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/src/be/ibridge/kettle/trans/step/mergerows/MergeRows.java b/src/be/ibridge/kettle/trans/step/mergerows/MergeRows.java
index 4a1bc4f0..82c38c12 100644
--- a/src/be/ibridge/kettle/trans/step/mergerows/MergeRows.java
+++ b/src/be/ibridge/kettle/trans/step/mergerows/MergeRows.java
@@ -1,206 +1,206 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.trans.step.mergerows;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.exception.KettleException;
import be.ibridge.kettle.core.exception.KettleStepException;
import be.ibridge.kettle.core.value.Value;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
import be.ibridge.kettle.trans.step.BaseStep;
import be.ibridge.kettle.trans.step.StepDataInterface;
import be.ibridge.kettle.trans.step.StepInterface;
import be.ibridge.kettle.trans.step.StepMeta;
import be.ibridge.kettle.trans.step.StepMetaInterface;
/**
* Merge rows from 2 sorted streams to detect changes.
* Use this as feed for a dimension in case you have no time stamps in your source system.
*
* @author Matt
* @since 19-dec-2005
*/
public class MergeRows extends BaseStep implements StepInterface
{
private static final Value VALUE_IDENTICAL = new Value("flag", "identical");
private static final Value VALUE_CHANGED = new Value("flag", "changed");
private static final Value VALUE_NEW = new Value("flag", "new");
private static final Value VALUE_DELETED = new Value("flag", "deleted");
private MergeRowsMeta meta;
private MergeRowsData data;
public MergeRows(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans)
{
super(stepMeta, stepDataInterface, copyNr, transMeta, trans);
}
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MergeRowsMeta)smi;
data=(MergeRowsData)sdi;
if (first)
{
first = false;
data.one=getRowFrom(meta.getReferenceStepName());
data.two=getRowFrom(meta.getCompareStepName());
// Find the key indexes:
data.keyNrs = new int[meta.getKeyFields().length];
data.keyAsc = new boolean[meta.getKeyFields().length];
for (int i=0;i<data.keyNrs.length;i++)
{
data.keyNrs[i] = data.one.searchValueIndex(meta.getKeyFields()[i]);
if (data.keyNrs[i]<0)
{
String message = "Unable to find field ["+meta.getKeyFields()[i]+"] in reference stream.";
logError(message);
throw new KettleStepException(message);
}
data.keyAsc[i] = true;
}
data.valueNrs = new int[meta.getValueFields().length];
data.valueAsc = new boolean[meta.getValueFields().length];
for (int i=0;i<data.valueNrs.length;i++)
{
data.valueNrs[i] = data.one.searchValueIndex(meta.getValueFields()[i]);
if (data.valueNrs[i]<0)
{
String message = "Unable to find field ["+meta.getValueFields()[i]+"] in reference stream.";
logError(message);
throw new KettleStepException(message);
}
data.valueAsc[i] = true;
}
}
logRowlevel("ONE: "+data.one+" / TWO: "+data.two);
if (data.one==null && data.two==null)
{
setOutputDone();
return false;
}
if (data.one==null && data.two!=null) // Record 2 is flagged as new!
{
data.two.addValue(VALUE_NEW);
putRow(data.two);
// Also get a next row from compare rowset...
data.two=getRowFrom(meta.getCompareStepName());
}
else
if (data.one!=null && data.two==null) // Record 1 is flagged as deleted!
{
data.one.addValue(VALUE_DELETED);
putRow(data.one);
// Also get a next row from reference rowset...
data.one=getRowFrom(meta.getReferenceStepName());
}
else // OK, Here is the real start of the compare code!
{
int compare = data.one.compare(data.two, data.keyNrs, data.keyAsc);
if (compare==0) // The Key matches, we CAN compare the two rows...
{
int compareValues = data.one.compare(data.two, data.valueNrs, data.valueAsc);
if (compareValues==0)
{
data.one.addValue(VALUE_IDENTICAL);
putRow(data.one);
}
else
{
data.two.addValue(VALUE_CHANGED);
putRow(data.two);
}
// Get a new row from both streams...
data.one=getRowFrom(meta.getReferenceStepName());
data.two=getRowFrom(meta.getCompareStepName());
}
else
{
if (compare<0) // one < two
{
data.one.addValue(VALUE_DELETED);
putRow(data.one);
data.one=getRowFrom(meta.getReferenceStepName());
}
else
{
data.two.addValue(VALUE_NEW);
putRow(data.two);
- data.two=getRowFrom(meta.getReferenceStepName());
+ data.two=getRowFrom(meta.getCompareStepName());
}
}
}
if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesRead);
return true;
}
/**
* @see StepInterface#init( be.ibridge.kettle.trans.step.StepMetaInterface , be.ibridge.kettle.trans.step.StepDataInterface)
*/
public boolean init(StepMetaInterface smi, StepDataInterface sdi)
{
meta=(MergeRowsMeta)smi;
data=(MergeRowsData)sdi;
if (super.init(smi, sdi))
{
if (meta.getReferenceStepName()!=null ^ meta.getCompareStepName()!=null)
{
logError("Both the 'true' and the 'false' steps need to be supplied, or neither");
}
else
{
return true;
}
}
return false;
}
//
// Run is were the action happens!
public void run()
{
try
{
logBasic("Starting to run...");
while (processRow(meta, data) && !isStopped());
}
catch(Exception e)
{
logError("Unexpected error in '"+debug+"' : "+e.toString());
setErrors(1);
stopAll();
}
finally
{
dispose(meta, data);
logSummary();
markStop();
}
}
}
| true | true | public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MergeRowsMeta)smi;
data=(MergeRowsData)sdi;
if (first)
{
first = false;
data.one=getRowFrom(meta.getReferenceStepName());
data.two=getRowFrom(meta.getCompareStepName());
// Find the key indexes:
data.keyNrs = new int[meta.getKeyFields().length];
data.keyAsc = new boolean[meta.getKeyFields().length];
for (int i=0;i<data.keyNrs.length;i++)
{
data.keyNrs[i] = data.one.searchValueIndex(meta.getKeyFields()[i]);
if (data.keyNrs[i]<0)
{
String message = "Unable to find field ["+meta.getKeyFields()[i]+"] in reference stream.";
logError(message);
throw new KettleStepException(message);
}
data.keyAsc[i] = true;
}
data.valueNrs = new int[meta.getValueFields().length];
data.valueAsc = new boolean[meta.getValueFields().length];
for (int i=0;i<data.valueNrs.length;i++)
{
data.valueNrs[i] = data.one.searchValueIndex(meta.getValueFields()[i]);
if (data.valueNrs[i]<0)
{
String message = "Unable to find field ["+meta.getValueFields()[i]+"] in reference stream.";
logError(message);
throw new KettleStepException(message);
}
data.valueAsc[i] = true;
}
}
logRowlevel("ONE: "+data.one+" / TWO: "+data.two);
if (data.one==null && data.two==null)
{
setOutputDone();
return false;
}
if (data.one==null && data.two!=null) // Record 2 is flagged as new!
{
data.two.addValue(VALUE_NEW);
putRow(data.two);
// Also get a next row from compare rowset...
data.two=getRowFrom(meta.getCompareStepName());
}
else
if (data.one!=null && data.two==null) // Record 1 is flagged as deleted!
{
data.one.addValue(VALUE_DELETED);
putRow(data.one);
// Also get a next row from reference rowset...
data.one=getRowFrom(meta.getReferenceStepName());
}
else // OK, Here is the real start of the compare code!
{
int compare = data.one.compare(data.two, data.keyNrs, data.keyAsc);
if (compare==0) // The Key matches, we CAN compare the two rows...
{
int compareValues = data.one.compare(data.two, data.valueNrs, data.valueAsc);
if (compareValues==0)
{
data.one.addValue(VALUE_IDENTICAL);
putRow(data.one);
}
else
{
data.two.addValue(VALUE_CHANGED);
putRow(data.two);
}
// Get a new row from both streams...
data.one=getRowFrom(meta.getReferenceStepName());
data.two=getRowFrom(meta.getCompareStepName());
}
else
{
if (compare<0) // one < two
{
data.one.addValue(VALUE_DELETED);
putRow(data.one);
data.one=getRowFrom(meta.getReferenceStepName());
}
else
{
data.two.addValue(VALUE_NEW);
putRow(data.two);
data.two=getRowFrom(meta.getReferenceStepName());
}
}
}
if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesRead);
return true;
}
| public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
meta=(MergeRowsMeta)smi;
data=(MergeRowsData)sdi;
if (first)
{
first = false;
data.one=getRowFrom(meta.getReferenceStepName());
data.two=getRowFrom(meta.getCompareStepName());
// Find the key indexes:
data.keyNrs = new int[meta.getKeyFields().length];
data.keyAsc = new boolean[meta.getKeyFields().length];
for (int i=0;i<data.keyNrs.length;i++)
{
data.keyNrs[i] = data.one.searchValueIndex(meta.getKeyFields()[i]);
if (data.keyNrs[i]<0)
{
String message = "Unable to find field ["+meta.getKeyFields()[i]+"] in reference stream.";
logError(message);
throw new KettleStepException(message);
}
data.keyAsc[i] = true;
}
data.valueNrs = new int[meta.getValueFields().length];
data.valueAsc = new boolean[meta.getValueFields().length];
for (int i=0;i<data.valueNrs.length;i++)
{
data.valueNrs[i] = data.one.searchValueIndex(meta.getValueFields()[i]);
if (data.valueNrs[i]<0)
{
String message = "Unable to find field ["+meta.getValueFields()[i]+"] in reference stream.";
logError(message);
throw new KettleStepException(message);
}
data.valueAsc[i] = true;
}
}
logRowlevel("ONE: "+data.one+" / TWO: "+data.two);
if (data.one==null && data.two==null)
{
setOutputDone();
return false;
}
if (data.one==null && data.two!=null) // Record 2 is flagged as new!
{
data.two.addValue(VALUE_NEW);
putRow(data.two);
// Also get a next row from compare rowset...
data.two=getRowFrom(meta.getCompareStepName());
}
else
if (data.one!=null && data.two==null) // Record 1 is flagged as deleted!
{
data.one.addValue(VALUE_DELETED);
putRow(data.one);
// Also get a next row from reference rowset...
data.one=getRowFrom(meta.getReferenceStepName());
}
else // OK, Here is the real start of the compare code!
{
int compare = data.one.compare(data.two, data.keyNrs, data.keyAsc);
if (compare==0) // The Key matches, we CAN compare the two rows...
{
int compareValues = data.one.compare(data.two, data.valueNrs, data.valueAsc);
if (compareValues==0)
{
data.one.addValue(VALUE_IDENTICAL);
putRow(data.one);
}
else
{
data.two.addValue(VALUE_CHANGED);
putRow(data.two);
}
// Get a new row from both streams...
data.one=getRowFrom(meta.getReferenceStepName());
data.two=getRowFrom(meta.getCompareStepName());
}
else
{
if (compare<0) // one < two
{
data.one.addValue(VALUE_DELETED);
putRow(data.one);
data.one=getRowFrom(meta.getReferenceStepName());
}
else
{
data.two.addValue(VALUE_NEW);
putRow(data.two);
data.two=getRowFrom(meta.getCompareStepName());
}
}
}
if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesRead);
return true;
}
|
diff --git a/src/com/android/exchange/adapter/FolderSyncParser.java b/src/com/android/exchange/adapter/FolderSyncParser.java
index f2e5d61..2f7cdd0 100644
--- a/src/com/android/exchange/adapter/FolderSyncParser.java
+++ b/src/com/android/exchange/adapter/FolderSyncParser.java
@@ -1,428 +1,428 @@
/*
* 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.exchange.adapter;
import com.android.email.Email;
import com.android.email.provider.AttachmentProvider;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailProvider;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.AccountColumns;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.MailboxColumns;
import com.android.exchange.Eas;
import com.android.exchange.MockParserStream;
import com.android.exchange.SyncManager;
import android.content.ContentProviderOperation;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.Calendar.Calendars;
import android.text.format.Time;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Parse the result of a FolderSync command
*
* Handles the addition, deletion, and changes to folders in the user's Exchange account.
**/
public class FolderSyncParser extends AbstractSyncParser {
public static final String TAG = "FolderSyncParser";
// These are defined by the EAS protocol
public static final int USER_FOLDER_TYPE = 1;
public static final int INBOX_TYPE = 2;
public static final int DRAFTS_TYPE = 3;
public static final int DELETED_TYPE = 4;
public static final int SENT_TYPE = 5;
public static final int OUTBOX_TYPE = 6;
public static final int TASKS_TYPE = 7;
public static final int CALENDAR_TYPE = 8;
public static final int CONTACTS_TYPE = 9;
public static final int NOTES_TYPE = 10;
public static final int JOURNAL_TYPE = 11;
public static final int USER_MAILBOX_TYPE = 12;
public static final List<Integer> mValidFolderTypes = Arrays.asList(INBOX_TYPE, DRAFTS_TYPE,
DELETED_TYPE, SENT_TYPE, OUTBOX_TYPE, USER_MAILBOX_TYPE, CALENDAR_TYPE, CONTACTS_TYPE);
public static final String ALL_BUT_ACCOUNT_MAILBOX = MailboxColumns.ACCOUNT_KEY + "=? and " +
MailboxColumns.TYPE + "!=" + Mailbox.TYPE_EAS_ACCOUNT_MAILBOX;
private static final String WHERE_SERVER_ID_AND_ACCOUNT = MailboxColumns.SERVER_ID + "=? and " +
MailboxColumns.ACCOUNT_KEY + "=?";
private static final String WHERE_DISPLAY_NAME_AND_ACCOUNT = MailboxColumns.DISPLAY_NAME +
"=? and " + MailboxColumns.ACCOUNT_KEY + "=?";
private static final String WHERE_PARENT_SERVER_ID_AND_ACCOUNT =
MailboxColumns.PARENT_SERVER_ID +"=? and " + MailboxColumns.ACCOUNT_KEY + "=?";
private static final String[] MAILBOX_ID_COLUMNS_PROJECTION =
new String[] {MailboxColumns.ID, MailboxColumns.SERVER_ID};
private long mAccountId;
private String mAccountIdAsString;
private MockParserStream mMock = null;
private String[] mBindArguments = new String[2];
public FolderSyncParser(InputStream in, AbstractSyncAdapter adapter) throws IOException {
super(in, adapter);
mAccountId = mAccount.mId;
mAccountIdAsString = Long.toString(mAccountId);
if (in instanceof MockParserStream) {
mMock = (MockParserStream)in;
}
}
@Override
public boolean parse() throws IOException {
int status;
boolean res = false;
boolean resetFolders = false;
if (nextTag(START_DOCUMENT) != Tags.FOLDER_FOLDER_SYNC)
throw new EasParserException();
while (nextTag(START_DOCUMENT) != END_DOCUMENT) {
if (tag == Tags.FOLDER_STATUS) {
status = getValueInt();
if (status != Eas.FOLDER_STATUS_OK) {
mService.errorLog("FolderSync failed: " + status);
if (status == Eas.FOLDER_STATUS_INVALID_KEY) {
mAccount.mSyncKey = "0";
mService.errorLog("Bad sync key; RESET and delete all folders");
mContentResolver.delete(Mailbox.CONTENT_URI, ALL_BUT_ACCOUNT_MAILBOX,
new String[] {Long.toString(mAccountId)});
// Stop existing syncs and reconstruct _main
SyncManager.folderListReloaded(mAccountId);
res = true;
resetFolders = true;
} else {
// Other errors are at the server, so let's throw an error that will
// cause this sync to be retried at a later time
mService.errorLog("Throwing IOException; will retry later");
throw new EasParserException("Folder status error");
}
}
} else if (tag == Tags.FOLDER_SYNC_KEY) {
mAccount.mSyncKey = getValue();
userLog("New Account SyncKey: ", mAccount.mSyncKey);
} else if (tag == Tags.FOLDER_CHANGES) {
changesParser();
} else
skipTag();
}
synchronized (mService.getSynchronizer()) {
if (!mService.isStopped() || resetFolders) {
ContentValues cv = new ContentValues();
cv.put(AccountColumns.SYNC_KEY, mAccount.mSyncKey);
mAccount.update(mContext, cv);
userLog("Leaving FolderSyncParser with Account syncKey=", mAccount.mSyncKey);
}
}
return res;
}
private Cursor getServerIdCursor(String serverId) {
mBindArguments[0] = serverId;
mBindArguments[1] = mAccountIdAsString;
return mContentResolver.query(Mailbox.CONTENT_URI, EmailContent.ID_PROJECTION,
WHERE_SERVER_ID_AND_ACCOUNT, mBindArguments, null);
}
public void deleteParser(ArrayList<ContentProviderOperation> ops) throws IOException {
while (nextTag(Tags.FOLDER_DELETE) != END) {
switch (tag) {
case Tags.FOLDER_SERVER_ID:
String serverId = getValue();
// Find the mailbox in this account with the given serverId
Cursor c = getServerIdCursor(serverId);
try {
if (c.moveToFirst()) {
userLog("Deleting ", serverId);
ops.add(ContentProviderOperation.newDelete(
ContentUris.withAppendedId(Mailbox.CONTENT_URI,
c.getLong(0))).build());
AttachmentProvider.deleteAllMailboxAttachmentFiles(mContext,
mAccountId, mMailbox.mId);
}
} finally {
c.close();
}
break;
default:
skipTag();
}
}
}
public void addParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String name = null;
String serverId = null;
String parentId = null;
int type = 0;
while (nextTag(Tags.FOLDER_ADD) != END) {
switch (tag) {
case Tags.FOLDER_DISPLAY_NAME: {
name = getValue();
break;
}
case Tags.FOLDER_TYPE: {
type = getValueInt();
break;
}
case Tags.FOLDER_PARENT_ID: {
parentId = getValue();
break;
}
case Tags.FOLDER_SERVER_ID: {
serverId = getValue();
break;
}
default:
skipTag();
}
}
if (mValidFolderTypes.contains(type)) {
Mailbox m = new Mailbox();
m.mDisplayName = name;
m.mServerId = serverId;
m.mAccountKey = mAccountId;
m.mType = Mailbox.TYPE_MAIL;
// Note that all mailboxes default to checking "never" (i.e. manual sync only)
// We set specific intervals for inbox, contacts, and (eventually) calendar
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
switch (type) {
case INBOX_TYPE:
m.mType = Mailbox.TYPE_INBOX;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case CONTACTS_TYPE:
m.mType = Mailbox.TYPE_CONTACTS;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case OUTBOX_TYPE:
// TYPE_OUTBOX mailboxes are known by SyncManager to sync whenever they aren't
// empty. The value of mSyncFrequency is ignored for this kind of mailbox.
m.mType = Mailbox.TYPE_OUTBOX;
break;
case SENT_TYPE:
m.mType = Mailbox.TYPE_SENT;
break;
case DRAFTS_TYPE:
m.mType = Mailbox.TYPE_DRAFTS;
break;
case DELETED_TYPE:
m.mType = Mailbox.TYPE_TRASH;
break;
case CALENDAR_TYPE:
m.mType = Mailbox.TYPE_CALENDAR;
m.mSyncInterval = mAccount.mSyncInterval;
// Create a Calendar object
ContentValues cv = new ContentValues();
// TODO How will this change if the user changes his account display name?
cv.put(Calendars.DISPLAY_NAME, mAccount.mDisplayName);
cv.put(Calendars._SYNC_ACCOUNT, mAccount.mEmailAddress);
cv.put(Calendars._SYNC_ACCOUNT_TYPE, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cv.put(Calendars.SYNC_EVENTS, 1);
cv.put(Calendars.SELECTED, 1);
cv.put(Calendars.HIDDEN, 0);
// TODO Find out how to set color!!
- cv.put(Calendars.COLOR, Email.getAccountColor(mAccountId));
+ cv.put(Calendars.COLOR, 0xFF000000 | Email.getAccountColor(mAccountId));
cv.put(Calendars.TIMEZONE, Time.getCurrentTimezone());
cv.put(Calendars.ACCESS_LEVEL, Calendars.OWNER_ACCESS);
cv.put(Calendars.OWNER_ACCOUNT, mAccount.mEmailAddress);
Uri uri = mService.mContentResolver.insert(Calendars.CONTENT_URI, cv);
// We save the id of the calendar into mSyncStatus
if (uri != null) {
m.mSyncStatus = uri.getPathSegments().get(1);
}
break;
}
// Make boxes like Contacts and Calendar invisible in the folder list
m.mFlagVisible = (m.mType < Mailbox.TYPE_NOT_EMAIL);
if (!parentId.equals("0")) {
m.mParentServerId = parentId;
}
userLog("Adding mailbox: ", m.mDisplayName);
ops.add(ContentProviderOperation
.newInsert(Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
}
return;
}
public void updateParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String serverId = null;
String displayName = null;
String parentId = null;
while (nextTag(Tags.FOLDER_UPDATE) != END) {
switch (tag) {
case Tags.FOLDER_SERVER_ID:
serverId = getValue();
break;
case Tags.FOLDER_DISPLAY_NAME:
displayName = getValue();
break;
case Tags.FOLDER_PARENT_ID:
parentId = getValue();
break;
default:
skipTag();
break;
}
}
// We'll make a change if one of parentId or displayName are specified
// serverId is required, but let's be careful just the same
if (serverId != null && (displayName != null || parentId != null)) {
Cursor c = getServerIdCursor(serverId);
try {
// If we find the mailbox (using serverId), make the change
if (c.moveToFirst()) {
userLog("Updating ", serverId);
ContentValues cv = new ContentValues();
if (displayName != null) {
cv.put(Mailbox.DISPLAY_NAME, displayName);
}
if (parentId != null) {
cv.put(Mailbox.PARENT_SERVER_ID, parentId);
}
ops.add(ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(Mailbox.CONTENT_URI,
c.getLong(0))).withValues(cv).build());
}
} finally {
c.close();
}
}
}
public void changesParser() throws IOException {
// Keep track of new boxes, deleted boxes, updated boxes
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
while (nextTag(Tags.FOLDER_CHANGES) != END) {
if (tag == Tags.FOLDER_ADD) {
addParser(ops);
} else if (tag == Tags.FOLDER_DELETE) {
deleteParser(ops);
} else if (tag == Tags.FOLDER_UPDATE) {
updateParser(ops);
} else if (tag == Tags.FOLDER_COUNT) {
getValueInt();
} else
skipTag();
}
// The mock stream is used for junit tests, so that the parsing code can be tested
// separately from the provider code.
// TODO Change tests to not require this; remove references to the mock stream
if (mMock != null) {
mMock.setResult(null);
return;
}
// Create the new mailboxes in a single batch operation
// Don't save any data if the service has been stopped
synchronized (mService.getSynchronizer()) {
if (!ops.isEmpty() && !mService.isStopped()) {
userLog("Applying ", ops.size(), " mailbox operations.");
// Then, we create an update for the account (most importantly, updating the syncKey)
ops.add(ContentProviderOperation.newUpdate(
ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId)).withValues(
mAccount.toContentValues()).build());
// Finally, we execute the batch
try {
mContentResolver.applyBatch(EmailProvider.EMAIL_AUTHORITY, ops);
userLog("New Account SyncKey: ", mAccount.mSyncKey);
} catch (RemoteException e) {
// There is nothing to be done here; fail by returning null
} catch (OperationApplicationException e) {
// There is nothing to be done here; fail by returning null
}
// Look for sync issues and its children and delete them
// I'm not aware of any other way to deal with this properly
mBindArguments[0] = "Sync Issues";
mBindArguments[1] = mAccountIdAsString;
Cursor c = mContentResolver.query(Mailbox.CONTENT_URI,
MAILBOX_ID_COLUMNS_PROJECTION, WHERE_DISPLAY_NAME_AND_ACCOUNT,
mBindArguments, null);
String parentServerId = null;
long id = 0;
try {
if (c.moveToFirst()) {
id = c.getLong(0);
parentServerId = c.getString(1);
}
} finally {
c.close();
}
if (parentServerId != null) {
mContentResolver.delete(ContentUris.withAppendedId(Mailbox.CONTENT_URI, id),
null, null);
mBindArguments[0] = parentServerId;
mContentResolver.delete(Mailbox.CONTENT_URI, WHERE_PARENT_SERVER_ID_AND_ACCOUNT,
mBindArguments);
}
}
}
}
/**
* Not needed for FolderSync parsing; everything is done within changesParser
*/
@Override
public void commandsParser() throws IOException {
}
/**
* We don't need to implement commit() because all operations take place atomically within
* changesParser
*/
@Override
public void commit() throws IOException {
}
@Override
public void wipe() {
}
@Override
public void responsesParser() throws IOException {
}
}
| true | true | public void addParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String name = null;
String serverId = null;
String parentId = null;
int type = 0;
while (nextTag(Tags.FOLDER_ADD) != END) {
switch (tag) {
case Tags.FOLDER_DISPLAY_NAME: {
name = getValue();
break;
}
case Tags.FOLDER_TYPE: {
type = getValueInt();
break;
}
case Tags.FOLDER_PARENT_ID: {
parentId = getValue();
break;
}
case Tags.FOLDER_SERVER_ID: {
serverId = getValue();
break;
}
default:
skipTag();
}
}
if (mValidFolderTypes.contains(type)) {
Mailbox m = new Mailbox();
m.mDisplayName = name;
m.mServerId = serverId;
m.mAccountKey = mAccountId;
m.mType = Mailbox.TYPE_MAIL;
// Note that all mailboxes default to checking "never" (i.e. manual sync only)
// We set specific intervals for inbox, contacts, and (eventually) calendar
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
switch (type) {
case INBOX_TYPE:
m.mType = Mailbox.TYPE_INBOX;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case CONTACTS_TYPE:
m.mType = Mailbox.TYPE_CONTACTS;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case OUTBOX_TYPE:
// TYPE_OUTBOX mailboxes are known by SyncManager to sync whenever they aren't
// empty. The value of mSyncFrequency is ignored for this kind of mailbox.
m.mType = Mailbox.TYPE_OUTBOX;
break;
case SENT_TYPE:
m.mType = Mailbox.TYPE_SENT;
break;
case DRAFTS_TYPE:
m.mType = Mailbox.TYPE_DRAFTS;
break;
case DELETED_TYPE:
m.mType = Mailbox.TYPE_TRASH;
break;
case CALENDAR_TYPE:
m.mType = Mailbox.TYPE_CALENDAR;
m.mSyncInterval = mAccount.mSyncInterval;
// Create a Calendar object
ContentValues cv = new ContentValues();
// TODO How will this change if the user changes his account display name?
cv.put(Calendars.DISPLAY_NAME, mAccount.mDisplayName);
cv.put(Calendars._SYNC_ACCOUNT, mAccount.mEmailAddress);
cv.put(Calendars._SYNC_ACCOUNT_TYPE, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cv.put(Calendars.SYNC_EVENTS, 1);
cv.put(Calendars.SELECTED, 1);
cv.put(Calendars.HIDDEN, 0);
// TODO Find out how to set color!!
cv.put(Calendars.COLOR, Email.getAccountColor(mAccountId));
cv.put(Calendars.TIMEZONE, Time.getCurrentTimezone());
cv.put(Calendars.ACCESS_LEVEL, Calendars.OWNER_ACCESS);
cv.put(Calendars.OWNER_ACCOUNT, mAccount.mEmailAddress);
Uri uri = mService.mContentResolver.insert(Calendars.CONTENT_URI, cv);
// We save the id of the calendar into mSyncStatus
if (uri != null) {
m.mSyncStatus = uri.getPathSegments().get(1);
}
break;
}
// Make boxes like Contacts and Calendar invisible in the folder list
m.mFlagVisible = (m.mType < Mailbox.TYPE_NOT_EMAIL);
if (!parentId.equals("0")) {
m.mParentServerId = parentId;
}
userLog("Adding mailbox: ", m.mDisplayName);
ops.add(ContentProviderOperation
.newInsert(Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
}
return;
}
| public void addParser(ArrayList<ContentProviderOperation> ops) throws IOException {
String name = null;
String serverId = null;
String parentId = null;
int type = 0;
while (nextTag(Tags.FOLDER_ADD) != END) {
switch (tag) {
case Tags.FOLDER_DISPLAY_NAME: {
name = getValue();
break;
}
case Tags.FOLDER_TYPE: {
type = getValueInt();
break;
}
case Tags.FOLDER_PARENT_ID: {
parentId = getValue();
break;
}
case Tags.FOLDER_SERVER_ID: {
serverId = getValue();
break;
}
default:
skipTag();
}
}
if (mValidFolderTypes.contains(type)) {
Mailbox m = new Mailbox();
m.mDisplayName = name;
m.mServerId = serverId;
m.mAccountKey = mAccountId;
m.mType = Mailbox.TYPE_MAIL;
// Note that all mailboxes default to checking "never" (i.e. manual sync only)
// We set specific intervals for inbox, contacts, and (eventually) calendar
m.mSyncInterval = Mailbox.CHECK_INTERVAL_NEVER;
switch (type) {
case INBOX_TYPE:
m.mType = Mailbox.TYPE_INBOX;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case CONTACTS_TYPE:
m.mType = Mailbox.TYPE_CONTACTS;
m.mSyncInterval = mAccount.mSyncInterval;
break;
case OUTBOX_TYPE:
// TYPE_OUTBOX mailboxes are known by SyncManager to sync whenever they aren't
// empty. The value of mSyncFrequency is ignored for this kind of mailbox.
m.mType = Mailbox.TYPE_OUTBOX;
break;
case SENT_TYPE:
m.mType = Mailbox.TYPE_SENT;
break;
case DRAFTS_TYPE:
m.mType = Mailbox.TYPE_DRAFTS;
break;
case DELETED_TYPE:
m.mType = Mailbox.TYPE_TRASH;
break;
case CALENDAR_TYPE:
m.mType = Mailbox.TYPE_CALENDAR;
m.mSyncInterval = mAccount.mSyncInterval;
// Create a Calendar object
ContentValues cv = new ContentValues();
// TODO How will this change if the user changes his account display name?
cv.put(Calendars.DISPLAY_NAME, mAccount.mDisplayName);
cv.put(Calendars._SYNC_ACCOUNT, mAccount.mEmailAddress);
cv.put(Calendars._SYNC_ACCOUNT_TYPE, Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
cv.put(Calendars.SYNC_EVENTS, 1);
cv.put(Calendars.SELECTED, 1);
cv.put(Calendars.HIDDEN, 0);
// TODO Find out how to set color!!
cv.put(Calendars.COLOR, 0xFF000000 | Email.getAccountColor(mAccountId));
cv.put(Calendars.TIMEZONE, Time.getCurrentTimezone());
cv.put(Calendars.ACCESS_LEVEL, Calendars.OWNER_ACCESS);
cv.put(Calendars.OWNER_ACCOUNT, mAccount.mEmailAddress);
Uri uri = mService.mContentResolver.insert(Calendars.CONTENT_URI, cv);
// We save the id of the calendar into mSyncStatus
if (uri != null) {
m.mSyncStatus = uri.getPathSegments().get(1);
}
break;
}
// Make boxes like Contacts and Calendar invisible in the folder list
m.mFlagVisible = (m.mType < Mailbox.TYPE_NOT_EMAIL);
if (!parentId.equals("0")) {
m.mParentServerId = parentId;
}
userLog("Adding mailbox: ", m.mDisplayName);
ops.add(ContentProviderOperation
.newInsert(Mailbox.CONTENT_URI).withValues(m.toContentValues()).build());
}
return;
}
|
diff --git a/geotools2/geotools-src/defaultcore/tests/unit/org/geotools/data/VeryBasicDataSource.java b/geotools2/geotools-src/defaultcore/tests/unit/org/geotools/data/VeryBasicDataSource.java
index 391fc2125..4708aed42 100644
--- a/geotools2/geotools-src/defaultcore/tests/unit/org/geotools/data/VeryBasicDataSource.java
+++ b/geotools2/geotools-src/defaultcore/tests/unit/org/geotools/data/VeryBasicDataSource.java
@@ -1,143 +1,144 @@
package org.geotools.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.Vector;
import org.geotools.feature.AttributeType;
import org.geotools.feature.AttributeTypeFactory;
import org.geotools.feature.Feature;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureType;
import org.geotools.feature.FeatureTypeFactory;
import org.geotools.filter.Filter;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.geotools.feature.DefaultFeatureType;
public class VeryBasicDataSource extends AbstractDataSource
implements DataSource {
String [] sColumnNames = null;
volatile boolean stopped = false;
GeometryFactory geomFac = new GeometryFactory();
URL url;
public VeryBasicDataSource(URL url) throws IOException {
this.url = url;
url.openStream().close();
}
/** Loads features from the datasource into the returned collection, based on
* the passed filter.
*
* @param filter An OpenGIS filter; specifies which features to retrieve.
* @return Collection The collection to put the features into.
* @throws DataSourceException For all data source errors.
*/
public void getFeatures(FeatureCollection ft, Query query) throws DataSourceException {
Filter filter = null;
if (query != null) {
filter = query.getFilter();
}
//FeatureCollectionDefault ft = (FeatureCollectionDefault)collection;
Vector Features = new Vector();
// Open file
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer sb = new StringBuffer();
while (reader.ready() && !stopped) {
- sb.append(reader.readLine()).append('\n');
+ sb.append(reader.readLine());
+ sb.append('\n');
}
if (stopped) return;
// Split up the string into rows
StringTokenizer st = new StringTokenizer(sb.toString(), "\n");
Vector rows = new Vector();
while (st.hasMoreElements()) {
String sRow = (String)st.nextElement();
sRow = sRow.trim();
System.out.println("Reading row : "+sRow);
// Split up into columns
Vector columns = new Vector();
columns.addElement("PRIMARY"); // The primary position
StringTokenizer stc = new StringTokenizer(sRow, ",");
while (stc.hasMoreElements())
columns.addElement(stc.nextElement());
rows.addElement((String[])columns.toArray(new String[columns.size()]));
System.out.println("read row:"+rows.size()+" with "+columns.size()+" elements");
}
// Get the first row (column names)
sColumnNames = (String[])rows.elementAt(0);
// Get each Feature - as a GeoPoint + attribs
for (int i=1;i<rows.size() && !stopped;i++) {
Coordinate p = new Coordinate();
Object [] objrow = (Object[])rows.elementAt(i);
// Create now Object[] for the row
Object [] row = new Object[objrow.length];
for (int t=0;t<row.length;t++)
row[t] = objrow[t];
for (int j=0;j<sColumnNames.length;j++) {
if (sColumnNames[j].equals("LONGITUDE"))
p.x = (new Double(row[j].toString())).doubleValue();
if (sColumnNames[j].equals("LATITUDE"))
p.y = (new Double(row[j].toString())).doubleValue();
}
AttributeType geometryAttribute = AttributeTypeFactory.newAttributeType("theGeometry", geomFac.createPoint(p).getClass());
AttributeType[] attDefs = new AttributeType[row.length];
attDefs[0] = geometryAttribute;
for(int att=1;att<row.length;att++){
attDefs[att] = AttributeTypeFactory.newAttributeType(sColumnNames[att],String.class);
}
FeatureType testType = FeatureTypeFactory.newFeatureType(attDefs,"test");
//FeatureType testType = new FeatureTypeFlat(geometryAttribute);
System.out.println("adding P "+p);
row[0] = geomFac.createPoint(p);
System.out.println("as Point "+(Point)row[0]);
for(int val=0;val<row.length;val++){
System.out.println("attribue "+val+" is "+row[val].getClass().getName());
}
System.out.println("Test Type is "+testType);
Feature feat = testType.create(row);
// Filter Feature Feature Filter
System.out.println("filter test "+filter.toString()+" -> "+filter.contains(feat));
if (filter.contains(feat)){
System.out.println("Adding feature");
ft.add(feat);
}
}
}
catch(Exception exp) {
System.out.println("Exception loading data");
exp.printStackTrace();
throw new DataSourceException("Exception loading data : "+exp.getMessage(),exp);
}
}
/**
* Retrieves the featureType that features extracted from this datasource
* will be created with.
* @tasks TODO: implement this method.
*/
public FeatureType getSchema(){
return DefaultFeatureType.EMPTY;
}
}
| true | true | public void getFeatures(FeatureCollection ft, Query query) throws DataSourceException {
Filter filter = null;
if (query != null) {
filter = query.getFilter();
}
//FeatureCollectionDefault ft = (FeatureCollectionDefault)collection;
Vector Features = new Vector();
// Open file
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer sb = new StringBuffer();
while (reader.ready() && !stopped) {
sb.append(reader.readLine()).append('\n');
}
if (stopped) return;
// Split up the string into rows
StringTokenizer st = new StringTokenizer(sb.toString(), "\n");
Vector rows = new Vector();
while (st.hasMoreElements()) {
String sRow = (String)st.nextElement();
sRow = sRow.trim();
System.out.println("Reading row : "+sRow);
// Split up into columns
Vector columns = new Vector();
columns.addElement("PRIMARY"); // The primary position
StringTokenizer stc = new StringTokenizer(sRow, ",");
while (stc.hasMoreElements())
columns.addElement(stc.nextElement());
rows.addElement((String[])columns.toArray(new String[columns.size()]));
System.out.println("read row:"+rows.size()+" with "+columns.size()+" elements");
}
// Get the first row (column names)
sColumnNames = (String[])rows.elementAt(0);
// Get each Feature - as a GeoPoint + attribs
for (int i=1;i<rows.size() && !stopped;i++) {
Coordinate p = new Coordinate();
Object [] objrow = (Object[])rows.elementAt(i);
// Create now Object[] for the row
Object [] row = new Object[objrow.length];
for (int t=0;t<row.length;t++)
row[t] = objrow[t];
for (int j=0;j<sColumnNames.length;j++) {
if (sColumnNames[j].equals("LONGITUDE"))
p.x = (new Double(row[j].toString())).doubleValue();
if (sColumnNames[j].equals("LATITUDE"))
p.y = (new Double(row[j].toString())).doubleValue();
}
AttributeType geometryAttribute = AttributeTypeFactory.newAttributeType("theGeometry", geomFac.createPoint(p).getClass());
AttributeType[] attDefs = new AttributeType[row.length];
attDefs[0] = geometryAttribute;
for(int att=1;att<row.length;att++){
attDefs[att] = AttributeTypeFactory.newAttributeType(sColumnNames[att],String.class);
}
FeatureType testType = FeatureTypeFactory.newFeatureType(attDefs,"test");
//FeatureType testType = new FeatureTypeFlat(geometryAttribute);
System.out.println("adding P "+p);
row[0] = geomFac.createPoint(p);
System.out.println("as Point "+(Point)row[0]);
for(int val=0;val<row.length;val++){
System.out.println("attribue "+val+" is "+row[val].getClass().getName());
}
System.out.println("Test Type is "+testType);
Feature feat = testType.create(row);
// Filter Feature Feature Filter
System.out.println("filter test "+filter.toString()+" -> "+filter.contains(feat));
if (filter.contains(feat)){
System.out.println("Adding feature");
ft.add(feat);
}
}
}
catch(Exception exp) {
System.out.println("Exception loading data");
exp.printStackTrace();
throw new DataSourceException("Exception loading data : "+exp.getMessage(),exp);
}
}
| public void getFeatures(FeatureCollection ft, Query query) throws DataSourceException {
Filter filter = null;
if (query != null) {
filter = query.getFilter();
}
//FeatureCollectionDefault ft = (FeatureCollectionDefault)collection;
Vector Features = new Vector();
// Open file
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer sb = new StringBuffer();
while (reader.ready() && !stopped) {
sb.append(reader.readLine());
sb.append('\n');
}
if (stopped) return;
// Split up the string into rows
StringTokenizer st = new StringTokenizer(sb.toString(), "\n");
Vector rows = new Vector();
while (st.hasMoreElements()) {
String sRow = (String)st.nextElement();
sRow = sRow.trim();
System.out.println("Reading row : "+sRow);
// Split up into columns
Vector columns = new Vector();
columns.addElement("PRIMARY"); // The primary position
StringTokenizer stc = new StringTokenizer(sRow, ",");
while (stc.hasMoreElements())
columns.addElement(stc.nextElement());
rows.addElement((String[])columns.toArray(new String[columns.size()]));
System.out.println("read row:"+rows.size()+" with "+columns.size()+" elements");
}
// Get the first row (column names)
sColumnNames = (String[])rows.elementAt(0);
// Get each Feature - as a GeoPoint + attribs
for (int i=1;i<rows.size() && !stopped;i++) {
Coordinate p = new Coordinate();
Object [] objrow = (Object[])rows.elementAt(i);
// Create now Object[] for the row
Object [] row = new Object[objrow.length];
for (int t=0;t<row.length;t++)
row[t] = objrow[t];
for (int j=0;j<sColumnNames.length;j++) {
if (sColumnNames[j].equals("LONGITUDE"))
p.x = (new Double(row[j].toString())).doubleValue();
if (sColumnNames[j].equals("LATITUDE"))
p.y = (new Double(row[j].toString())).doubleValue();
}
AttributeType geometryAttribute = AttributeTypeFactory.newAttributeType("theGeometry", geomFac.createPoint(p).getClass());
AttributeType[] attDefs = new AttributeType[row.length];
attDefs[0] = geometryAttribute;
for(int att=1;att<row.length;att++){
attDefs[att] = AttributeTypeFactory.newAttributeType(sColumnNames[att],String.class);
}
FeatureType testType = FeatureTypeFactory.newFeatureType(attDefs,"test");
//FeatureType testType = new FeatureTypeFlat(geometryAttribute);
System.out.println("adding P "+p);
row[0] = geomFac.createPoint(p);
System.out.println("as Point "+(Point)row[0]);
for(int val=0;val<row.length;val++){
System.out.println("attribue "+val+" is "+row[val].getClass().getName());
}
System.out.println("Test Type is "+testType);
Feature feat = testType.create(row);
// Filter Feature Feature Filter
System.out.println("filter test "+filter.toString()+" -> "+filter.contains(feat));
if (filter.contains(feat)){
System.out.println("Adding feature");
ft.add(feat);
}
}
}
catch(Exception exp) {
System.out.println("Exception loading data");
exp.printStackTrace();
throw new DataSourceException("Exception loading data : "+exp.getMessage(),exp);
}
}
|
diff --git a/same/src/main/java/com/orbekk/same/SameController.java b/same/src/main/java/com/orbekk/same/SameController.java
index 9b8abde..b75de96 100644
--- a/same/src/main/java/com/orbekk/same/SameController.java
+++ b/same/src/main/java/com/orbekk/same/SameController.java
@@ -1,134 +1,135 @@
package com.orbekk.same;
import org.eclipse.jetty.server.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.googlecode.jsonrpc4j.JsonRpcServer;
import com.orbekk.net.HttpUtil;
import com.orbekk.paxos.PaxosService;
import com.orbekk.paxos.PaxosServiceImpl;
public class SameController implements UrlReceiver {
private Logger logger = LoggerFactory.getLogger(getClass());
private int port;
private Server server;
private MasterServiceImpl master;
private ClientServiceImpl client;
private PaxosServiceImpl paxos;
/**
* Timeout for remote operations in milliseconds.
*/
private static final int timeout = 10000;
public static SameController create(int port) {
ConnectionManagerImpl connections = new ConnectionManagerImpl(
timeout, timeout);
State state = new State("Default");
Broadcaster broadcaster = BroadcasterImpl.getDefaultBroadcastRunner();
MasterServiceImpl master = new MasterServiceImpl(state, connections,
broadcaster);
JsonRpcServer jsonMaster = new JsonRpcServer(master, MasterService.class);
ClientServiceImpl client = new ClientServiceImpl(state, connections);
- JsonRpcServer jsonClient = new JsonRpcServer(client, ClientService.class);
+ JsonRpcServer jsonClient = new JsonRpcServer(client.getService(),
+ ClientService.class);
PaxosServiceImpl paxos = new PaxosServiceImpl("");
JsonRpcServer jsonPaxos = new JsonRpcServer(paxos, PaxosService.class);
Server server = new Server(port);
SameController controller = new SameController(port, server, master, client,
paxos);
RpcHandler rpcHandler = new RpcHandler(null);
rpcHandler.addRpcServer("/MasterService.json", jsonMaster);
rpcHandler.addRpcServer("/ClientService.json", jsonClient);
rpcHandler.addRpcServer("/PaxosService.json", jsonPaxos);
server.setHandler(rpcHandler);
return controller;
}
public SameController(
int port,
Server server,
MasterServiceImpl master,
ClientServiceImpl client,
PaxosServiceImpl paxos) {
this.port = port;
this.server = server;
this.master = master;
this.client = client;
this.paxos = paxos;
}
public void start() throws Exception {
server.start();
master.start();
client.start();
}
public void stop() {
try {
client.interrupt();
master.interrupt();
server.stop();
} catch (Exception e) {
logger.error("Failed to stop webserver", e);
}
}
public void join() {
try {
server.join();
master.join();
} catch (InterruptedException e) {
master.interrupt();
try {
server.stop();
} catch (Exception e1) {
logger.error("Failed to stop server", e);
}
}
}
public boolean tryGetUrl(String serverUrl) {
int retries = 100;
while (client.getUrl() == null && retries > 0) {
HttpUtil.sendHttpRequest(serverUrl + "ping?port=" +
port);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
return false;
}
retries -= 1;
}
return client.getUrl() != null;
}
public void joinNetwork(String url) {
boolean hasUrl = tryGetUrl(url);
if (hasUrl) {
client.joinNetwork(url + "MasterService.json");
}
}
@Override
public void setUrl(String url) {
if (master != null) {
master.setUrl(url);
}
if (client != null) {
client.setUrl(url);
}
}
public ClientServiceImpl getClient() {
return client;
}
public MasterServiceImpl getMaster() {
return master;
}
}
| true | true | public static SameController create(int port) {
ConnectionManagerImpl connections = new ConnectionManagerImpl(
timeout, timeout);
State state = new State("Default");
Broadcaster broadcaster = BroadcasterImpl.getDefaultBroadcastRunner();
MasterServiceImpl master = new MasterServiceImpl(state, connections,
broadcaster);
JsonRpcServer jsonMaster = new JsonRpcServer(master, MasterService.class);
ClientServiceImpl client = new ClientServiceImpl(state, connections);
JsonRpcServer jsonClient = new JsonRpcServer(client, ClientService.class);
PaxosServiceImpl paxos = new PaxosServiceImpl("");
JsonRpcServer jsonPaxos = new JsonRpcServer(paxos, PaxosService.class);
Server server = new Server(port);
SameController controller = new SameController(port, server, master, client,
paxos);
RpcHandler rpcHandler = new RpcHandler(null);
rpcHandler.addRpcServer("/MasterService.json", jsonMaster);
rpcHandler.addRpcServer("/ClientService.json", jsonClient);
rpcHandler.addRpcServer("/PaxosService.json", jsonPaxos);
server.setHandler(rpcHandler);
return controller;
}
| public static SameController create(int port) {
ConnectionManagerImpl connections = new ConnectionManagerImpl(
timeout, timeout);
State state = new State("Default");
Broadcaster broadcaster = BroadcasterImpl.getDefaultBroadcastRunner();
MasterServiceImpl master = new MasterServiceImpl(state, connections,
broadcaster);
JsonRpcServer jsonMaster = new JsonRpcServer(master, MasterService.class);
ClientServiceImpl client = new ClientServiceImpl(state, connections);
JsonRpcServer jsonClient = new JsonRpcServer(client.getService(),
ClientService.class);
PaxosServiceImpl paxos = new PaxosServiceImpl("");
JsonRpcServer jsonPaxos = new JsonRpcServer(paxos, PaxosService.class);
Server server = new Server(port);
SameController controller = new SameController(port, server, master, client,
paxos);
RpcHandler rpcHandler = new RpcHandler(null);
rpcHandler.addRpcServer("/MasterService.json", jsonMaster);
rpcHandler.addRpcServer("/ClientService.json", jsonClient);
rpcHandler.addRpcServer("/PaxosService.json", jsonPaxos);
server.setHandler(rpcHandler);
return controller;
}
|
diff --git a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java
index a1f4221db..646dc711b 100644
--- a/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java
+++ b/src/test/com/jogamp/opengl/test/junit/newt/TestFocus02SwingAWTRobot.java
@@ -1,309 +1,315 @@
/**
* Copyright 2010 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY JogAmp Community ``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 JogAmp Community 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.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of JogAmp Community.
*/
package com.jogamp.opengl.test.junit.newt;
import java.lang.reflect.*;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import java.awt.AWTException;
import java.awt.Button;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Robot;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.ArrayList;
import javax.media.opengl.*;
import com.jogamp.opengl.util.Animator;
import com.jogamp.newt.opengl.*;
import com.jogamp.newt.awt.NewtCanvasAWT;
import java.io.IOException;
import com.jogamp.opengl.test.junit.util.*;
import com.jogamp.opengl.test.junit.jogl.demos.es2.GearsES2;
/**
* Testing focus traversal of an AWT component tree with {@link NewtCanvasAWT} attached.
* <p>
* {@link JFrame} . {@link JPanel}+ . {@link Container} . {@link NewtCanvasAWT} . {@link GLWindow}
* </p>
* <p>
* <i>+ JPanel is set as JFrame's root content pane</i><br/>
* </p>
*/
public class TestFocus02SwingAWTRobot extends UITestCase {
static int width, height;
static long durationPerTest = 10;
static long awtWaitTimeout = 1000;
static GLCapabilities glCaps;
@BeforeClass
public static void initClass() throws AWTException, InterruptedException, InvocationTargetException {
width = 640;
height = 480;
final JFrame f = new JFrame();
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
f.setSize(100,100);
f.setVisible(true);
} } );
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
f.dispose();
} } );
glCaps = new GLCapabilities(null);
}
@AfterClass
public static void release() {
}
private void testFocus01ProgrFocusImpl(Robot robot)
throws AWTException, InterruptedException, InvocationTargetException {
ArrayList<EventCountAdapter> eventCountAdapters = new ArrayList<EventCountAdapter>();
GLWindow glWindow1 = GLWindow.create(glCaps);
glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy");
GLEventListener demo1 = new GearsES2();
glWindow1.addGLEventListener(demo1);
NEWTFocusAdapter glWindow1FA = new NEWTFocusAdapter("GLWindow1");
glWindow1.addWindowListener(glWindow1FA);
NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1");
glWindow1.addKeyListener(glWindow1KA);
eventCountAdapters.add(glWindow1KA);
NEWTMouseAdapter glWindow1MA = new NEWTMouseAdapter("GLWindow1");
glWindow1.addMouseListener(glWindow1MA);
eventCountAdapters.add(glWindow1MA);
NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1);
AWTFocusAdapter newtCanvasAWTFA = new AWTFocusAdapter("NewtCanvasAWT");
newtCanvasAWT.addFocusListener(newtCanvasAWTFA);
AWTKeyAdapter newtCanvasAWTKA = new AWTKeyAdapter("NewtCanvasAWT");
newtCanvasAWT.addKeyListener(newtCanvasAWTKA);
eventCountAdapters.add(newtCanvasAWTKA);
AWTMouseAdapter newtCanvasAWTMA = new AWTMouseAdapter("NewtCanvasAWT");
newtCanvasAWT.addMouseListener(newtCanvasAWTMA);
eventCountAdapters.add(newtCanvasAWTMA);
Button buttonNorthInner = new Button("north");
AWTFocusAdapter buttonNorthInnerFA = new AWTFocusAdapter("ButtonNorthInner");
buttonNorthInner.addFocusListener(buttonNorthInnerFA);
AWTKeyAdapter buttonNorthInnerKA = new AWTKeyAdapter("ButtonNorthInner");
buttonNorthInner.addKeyListener(buttonNorthInnerKA);
eventCountAdapters.add(buttonNorthInnerKA);
AWTMouseAdapter buttonNorthInnerMA = new AWTMouseAdapter("ButtonNorthInner");
buttonNorthInner.addMouseListener(buttonNorthInnerMA);
eventCountAdapters.add(buttonNorthInnerMA);
final Container container1 = new Container();
container1.setLayout(new BorderLayout());
container1.add(buttonNorthInner, BorderLayout.NORTH);
container1.add(new Button("south"), BorderLayout.SOUTH);
container1.add(new Button("east"), BorderLayout.EAST);
container1.add(new Button("west"), BorderLayout.WEST);
container1.add(newtCanvasAWT, BorderLayout.CENTER);
Button buttonNorthOuter = new Button("north");
AWTFocusAdapter buttonNorthOuterFA = new AWTFocusAdapter("ButtonNorthOuter");
buttonNorthOuter.addFocusListener(buttonNorthOuterFA);
AWTKeyAdapter buttonNorthOuterKA = new AWTKeyAdapter("ButtonNorthOuter");
buttonNorthOuter.addKeyListener(buttonNorthOuterKA);
eventCountAdapters.add(buttonNorthOuterKA);
AWTMouseAdapter buttonNorthOuterMA = new AWTMouseAdapter("ButtonNorthOuter");
buttonNorthOuter.addMouseListener(buttonNorthOuterMA);
eventCountAdapters.add(buttonNorthOuterMA);
final JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
jPanel1.add(buttonNorthOuter, BorderLayout.NORTH);
jPanel1.add(new Button("south"), BorderLayout.SOUTH);
jPanel1.add(new Button("east"), BorderLayout.EAST);
jPanel1.add(new Button("west"), BorderLayout.WEST);
jPanel1.add(container1, BorderLayout.CENTER);
final JFrame jFrame1 = new JFrame("Swing Parent JFrame");
// jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event!
jFrame1.setContentPane(jPanel1);
jFrame1.setSize(width, height);
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
jFrame1.setVisible(true);
} } );
Assert.assertEquals(true, AWTRobotUtil.waitForVisible(jFrame1, true));
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, true));
AWTRobotUtil.clearAWTFocus(robot);
Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1));
int wait=0;
while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; }
System.err.println("Frames for initial setVisible(true): "+glWindow1.getTotalFPSFrames());
Assert.assertTrue(glWindow1.isVisible());
Assert.assertTrue(0 < glWindow1.getTotalFPSFrames());
// Continuous animation ..
Animator animator1 = new Animator(glWindow1);
animator1.start();
Thread.sleep(durationPerTest); // manual testing
// Button Outer Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS AWT Button Outer request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, null); // OSX sporadically buttonNorthOuter did not gain - major UI failure
Assert.assertEquals(false, glWindow1FA.focusGained());
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
System.err.println("FOCUS AWT Button Outer sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA); // OSX sporadically won't receive the keyboard input - major UI failure
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
buttonNorthOuter, buttonNorthOuterMA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
buttonNorthOuter, buttonNorthOuterMA);
// NEWT Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS NEWT Canvas/GLWindow request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA);
- Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
+ // Manually tested on Java7/[Linux,Windows] (where this assertion failed),
+ // Should be OK to have the AWT component assume it also has the focus.
+ // Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA,
+ // AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA));
+ if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) {
+ System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA);
+ }
Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
System.err.println("FOCUS NEWT Canvas/GLWindow sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount());
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
glWindow1, glWindow1MA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
glWindow1, glWindow1MA);
Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount());
// Button Inner Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS AWT Button request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA);
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
System.err.println("FOCUS AWT Button sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthInner, buttonNorthInnerKA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
buttonNorthInner, buttonNorthInnerMA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
buttonNorthInner, buttonNorthInnerMA);
// NEWT Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS NEWT Canvas/GLWindow request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA);
// Manually tested on Java7/[Linux,Windows] (where this assertion failed),
// Should be OK to have the AWT component assume it also has the focus.
// Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA,
// AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA));
if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) {
System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA);
}
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
System.err.println("FOCUS NEWT Canvas/GLWindow sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount());
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
glWindow1, glWindow1MA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
glWindow1, glWindow1MA);
Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount());
animator1.stop();
Assert.assertEquals(false, animator1.isAnimating());
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
jFrame1.setVisible(false);
jPanel1.remove(container1);
jFrame1.dispose();
} });
glWindow1.destroy();
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, false));
}
@Test
public void testFocus01ProgrFocus() throws AWTException, InterruptedException, InvocationTargetException {
testFocus01ProgrFocusImpl(null);
}
@Test
public void testFocus02RobotFocus() throws AWTException, InterruptedException, InvocationTargetException {
Robot robot = new Robot();
robot.setAutoWaitForIdle(true);
testFocus01ProgrFocusImpl(robot);
}
static int atoi(String a) {
int i=0;
try {
i = Integer.parseInt(a);
} catch (Exception ex) { ex.printStackTrace(); }
return i;
}
@SuppressWarnings("unused")
public static void main(String args[])
throws IOException, AWTException, InterruptedException, InvocationTargetException
{
for(int i=0; i<args.length; i++) {
if(args[i].equals("-time")) {
durationPerTest = atoi(args[++i]);
}
}
if(true) {
String tstname = TestFocus02SwingAWTRobot.class.getName();
org.junit.runner.JUnitCore.main(tstname);
} else {
TestFocus02SwingAWTRobot.initClass();
TestFocus02SwingAWTRobot test = new TestFocus02SwingAWTRobot();
test.testFocus01ProgrFocus();
test.testFocus02RobotFocus();
TestFocus02SwingAWTRobot.release();
}
}
}
| true | true | private void testFocus01ProgrFocusImpl(Robot robot)
throws AWTException, InterruptedException, InvocationTargetException {
ArrayList<EventCountAdapter> eventCountAdapters = new ArrayList<EventCountAdapter>();
GLWindow glWindow1 = GLWindow.create(glCaps);
glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy");
GLEventListener demo1 = new GearsES2();
glWindow1.addGLEventListener(demo1);
NEWTFocusAdapter glWindow1FA = new NEWTFocusAdapter("GLWindow1");
glWindow1.addWindowListener(glWindow1FA);
NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1");
glWindow1.addKeyListener(glWindow1KA);
eventCountAdapters.add(glWindow1KA);
NEWTMouseAdapter glWindow1MA = new NEWTMouseAdapter("GLWindow1");
glWindow1.addMouseListener(glWindow1MA);
eventCountAdapters.add(glWindow1MA);
NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1);
AWTFocusAdapter newtCanvasAWTFA = new AWTFocusAdapter("NewtCanvasAWT");
newtCanvasAWT.addFocusListener(newtCanvasAWTFA);
AWTKeyAdapter newtCanvasAWTKA = new AWTKeyAdapter("NewtCanvasAWT");
newtCanvasAWT.addKeyListener(newtCanvasAWTKA);
eventCountAdapters.add(newtCanvasAWTKA);
AWTMouseAdapter newtCanvasAWTMA = new AWTMouseAdapter("NewtCanvasAWT");
newtCanvasAWT.addMouseListener(newtCanvasAWTMA);
eventCountAdapters.add(newtCanvasAWTMA);
Button buttonNorthInner = new Button("north");
AWTFocusAdapter buttonNorthInnerFA = new AWTFocusAdapter("ButtonNorthInner");
buttonNorthInner.addFocusListener(buttonNorthInnerFA);
AWTKeyAdapter buttonNorthInnerKA = new AWTKeyAdapter("ButtonNorthInner");
buttonNorthInner.addKeyListener(buttonNorthInnerKA);
eventCountAdapters.add(buttonNorthInnerKA);
AWTMouseAdapter buttonNorthInnerMA = new AWTMouseAdapter("ButtonNorthInner");
buttonNorthInner.addMouseListener(buttonNorthInnerMA);
eventCountAdapters.add(buttonNorthInnerMA);
final Container container1 = new Container();
container1.setLayout(new BorderLayout());
container1.add(buttonNorthInner, BorderLayout.NORTH);
container1.add(new Button("south"), BorderLayout.SOUTH);
container1.add(new Button("east"), BorderLayout.EAST);
container1.add(new Button("west"), BorderLayout.WEST);
container1.add(newtCanvasAWT, BorderLayout.CENTER);
Button buttonNorthOuter = new Button("north");
AWTFocusAdapter buttonNorthOuterFA = new AWTFocusAdapter("ButtonNorthOuter");
buttonNorthOuter.addFocusListener(buttonNorthOuterFA);
AWTKeyAdapter buttonNorthOuterKA = new AWTKeyAdapter("ButtonNorthOuter");
buttonNorthOuter.addKeyListener(buttonNorthOuterKA);
eventCountAdapters.add(buttonNorthOuterKA);
AWTMouseAdapter buttonNorthOuterMA = new AWTMouseAdapter("ButtonNorthOuter");
buttonNorthOuter.addMouseListener(buttonNorthOuterMA);
eventCountAdapters.add(buttonNorthOuterMA);
final JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
jPanel1.add(buttonNorthOuter, BorderLayout.NORTH);
jPanel1.add(new Button("south"), BorderLayout.SOUTH);
jPanel1.add(new Button("east"), BorderLayout.EAST);
jPanel1.add(new Button("west"), BorderLayout.WEST);
jPanel1.add(container1, BorderLayout.CENTER);
final JFrame jFrame1 = new JFrame("Swing Parent JFrame");
// jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event!
jFrame1.setContentPane(jPanel1);
jFrame1.setSize(width, height);
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
jFrame1.setVisible(true);
} } );
Assert.assertEquals(true, AWTRobotUtil.waitForVisible(jFrame1, true));
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, true));
AWTRobotUtil.clearAWTFocus(robot);
Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1));
int wait=0;
while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; }
System.err.println("Frames for initial setVisible(true): "+glWindow1.getTotalFPSFrames());
Assert.assertTrue(glWindow1.isVisible());
Assert.assertTrue(0 < glWindow1.getTotalFPSFrames());
// Continuous animation ..
Animator animator1 = new Animator(glWindow1);
animator1.start();
Thread.sleep(durationPerTest); // manual testing
// Button Outer Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS AWT Button Outer request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, null); // OSX sporadically buttonNorthOuter did not gain - major UI failure
Assert.assertEquals(false, glWindow1FA.focusGained());
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
System.err.println("FOCUS AWT Button Outer sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA); // OSX sporadically won't receive the keyboard input - major UI failure
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
buttonNorthOuter, buttonNorthOuterMA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
buttonNorthOuter, buttonNorthOuterMA);
// NEWT Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS NEWT Canvas/GLWindow request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA);
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
System.err.println("FOCUS NEWT Canvas/GLWindow sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount());
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
glWindow1, glWindow1MA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
glWindow1, glWindow1MA);
Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount());
// Button Inner Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS AWT Button request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA);
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
System.err.println("FOCUS AWT Button sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthInner, buttonNorthInnerKA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
buttonNorthInner, buttonNorthInnerMA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
buttonNorthInner, buttonNorthInnerMA);
// NEWT Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS NEWT Canvas/GLWindow request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA);
// Manually tested on Java7/[Linux,Windows] (where this assertion failed),
// Should be OK to have the AWT component assume it also has the focus.
// Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA,
// AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA));
if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) {
System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA);
}
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
System.err.println("FOCUS NEWT Canvas/GLWindow sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount());
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
glWindow1, glWindow1MA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
glWindow1, glWindow1MA);
Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount());
animator1.stop();
Assert.assertEquals(false, animator1.isAnimating());
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
jFrame1.setVisible(false);
jPanel1.remove(container1);
jFrame1.dispose();
} });
glWindow1.destroy();
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, false));
}
| private void testFocus01ProgrFocusImpl(Robot robot)
throws AWTException, InterruptedException, InvocationTargetException {
ArrayList<EventCountAdapter> eventCountAdapters = new ArrayList<EventCountAdapter>();
GLWindow glWindow1 = GLWindow.create(glCaps);
glWindow1.setTitle("testWindowParenting01CreateVisibleDestroy");
GLEventListener demo1 = new GearsES2();
glWindow1.addGLEventListener(demo1);
NEWTFocusAdapter glWindow1FA = new NEWTFocusAdapter("GLWindow1");
glWindow1.addWindowListener(glWindow1FA);
NEWTKeyAdapter glWindow1KA = new NEWTKeyAdapter("GLWindow1");
glWindow1.addKeyListener(glWindow1KA);
eventCountAdapters.add(glWindow1KA);
NEWTMouseAdapter glWindow1MA = new NEWTMouseAdapter("GLWindow1");
glWindow1.addMouseListener(glWindow1MA);
eventCountAdapters.add(glWindow1MA);
NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1);
AWTFocusAdapter newtCanvasAWTFA = new AWTFocusAdapter("NewtCanvasAWT");
newtCanvasAWT.addFocusListener(newtCanvasAWTFA);
AWTKeyAdapter newtCanvasAWTKA = new AWTKeyAdapter("NewtCanvasAWT");
newtCanvasAWT.addKeyListener(newtCanvasAWTKA);
eventCountAdapters.add(newtCanvasAWTKA);
AWTMouseAdapter newtCanvasAWTMA = new AWTMouseAdapter("NewtCanvasAWT");
newtCanvasAWT.addMouseListener(newtCanvasAWTMA);
eventCountAdapters.add(newtCanvasAWTMA);
Button buttonNorthInner = new Button("north");
AWTFocusAdapter buttonNorthInnerFA = new AWTFocusAdapter("ButtonNorthInner");
buttonNorthInner.addFocusListener(buttonNorthInnerFA);
AWTKeyAdapter buttonNorthInnerKA = new AWTKeyAdapter("ButtonNorthInner");
buttonNorthInner.addKeyListener(buttonNorthInnerKA);
eventCountAdapters.add(buttonNorthInnerKA);
AWTMouseAdapter buttonNorthInnerMA = new AWTMouseAdapter("ButtonNorthInner");
buttonNorthInner.addMouseListener(buttonNorthInnerMA);
eventCountAdapters.add(buttonNorthInnerMA);
final Container container1 = new Container();
container1.setLayout(new BorderLayout());
container1.add(buttonNorthInner, BorderLayout.NORTH);
container1.add(new Button("south"), BorderLayout.SOUTH);
container1.add(new Button("east"), BorderLayout.EAST);
container1.add(new Button("west"), BorderLayout.WEST);
container1.add(newtCanvasAWT, BorderLayout.CENTER);
Button buttonNorthOuter = new Button("north");
AWTFocusAdapter buttonNorthOuterFA = new AWTFocusAdapter("ButtonNorthOuter");
buttonNorthOuter.addFocusListener(buttonNorthOuterFA);
AWTKeyAdapter buttonNorthOuterKA = new AWTKeyAdapter("ButtonNorthOuter");
buttonNorthOuter.addKeyListener(buttonNorthOuterKA);
eventCountAdapters.add(buttonNorthOuterKA);
AWTMouseAdapter buttonNorthOuterMA = new AWTMouseAdapter("ButtonNorthOuter");
buttonNorthOuter.addMouseListener(buttonNorthOuterMA);
eventCountAdapters.add(buttonNorthOuterMA);
final JPanel jPanel1 = new JPanel();
jPanel1.setLayout(new BorderLayout());
jPanel1.add(buttonNorthOuter, BorderLayout.NORTH);
jPanel1.add(new Button("south"), BorderLayout.SOUTH);
jPanel1.add(new Button("east"), BorderLayout.EAST);
jPanel1.add(new Button("west"), BorderLayout.WEST);
jPanel1.add(container1, BorderLayout.CENTER);
final JFrame jFrame1 = new JFrame("Swing Parent JFrame");
// jFrame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // equivalent to Frame, use windowClosing event!
jFrame1.setContentPane(jPanel1);
jFrame1.setSize(width, height);
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
jFrame1.setVisible(true);
} } );
Assert.assertEquals(true, AWTRobotUtil.waitForVisible(jFrame1, true));
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, true));
AWTRobotUtil.clearAWTFocus(robot);
Assert.assertTrue(AWTRobotUtil.toFrontAndRequestFocus(robot, jFrame1));
int wait=0;
while(wait<awtWaitTimeout/10 && glWindow1.getTotalFPSFrames()<1) { Thread.sleep(awtWaitTimeout/100); wait++; }
System.err.println("Frames for initial setVisible(true): "+glWindow1.getTotalFPSFrames());
Assert.assertTrue(glWindow1.isVisible());
Assert.assertTrue(0 < glWindow1.getTotalFPSFrames());
// Continuous animation ..
Animator animator1 = new Animator(glWindow1);
animator1.start();
Thread.sleep(durationPerTest); // manual testing
// Button Outer Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS AWT Button Outer request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthOuter, buttonNorthOuter, buttonNorthOuterFA, null); // OSX sporadically buttonNorthOuter did not gain - major UI failure
Assert.assertEquals(false, glWindow1FA.focusGained());
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
System.err.println("FOCUS AWT Button Outer sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthOuter, buttonNorthOuterKA); // OSX sporadically won't receive the keyboard input - major UI failure
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
buttonNorthOuter, buttonNorthOuterMA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
buttonNorthOuter, buttonNorthOuterMA);
// NEWT Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS NEWT Canvas/GLWindow request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthOuterFA);
// Manually tested on Java7/[Linux,Windows] (where this assertion failed),
// Should be OK to have the AWT component assume it also has the focus.
// Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA,
// AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA));
if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) {
System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA);
}
Assert.assertEquals(false, buttonNorthInnerFA.focusGained());
System.err.println("FOCUS NEWT Canvas/GLWindow sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount());
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
glWindow1, glWindow1MA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
glWindow1, glWindow1MA);
Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount());
// Button Inner Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS AWT Button request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, buttonNorthInner, buttonNorthInner, buttonNorthInnerFA, glWindow1FA);
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
System.err.println("FOCUS AWT Button sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, buttonNorthInner, buttonNorthInnerKA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
buttonNorthInner, buttonNorthInnerMA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
buttonNorthInner, buttonNorthInnerMA);
// NEWT Focus
Thread.sleep(100); // allow event sync
System.err.println("FOCUS NEWT Canvas/GLWindow request");
EventCountAdapterUtil.reset(eventCountAdapters);
AWTRobotUtil.assertRequestFocusAndWait(robot, newtCanvasAWT, newtCanvasAWT.getNEWTChild(), glWindow1FA, buttonNorthInnerFA);
// Manually tested on Java7/[Linux,Windows] (where this assertion failed),
// Should be OK to have the AWT component assume it also has the focus.
// Assert.assertTrue("Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA,
// AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA));
if( !AWTRobotUtil.waitForFocus(glWindow1FA, newtCanvasAWTFA) ) {
System.err.println("Info: Focus prev. gained, but NewtCanvasAWT didn't loose it. Gainer: "+glWindow1FA+"; Looser "+newtCanvasAWTFA);
}
Assert.assertEquals(false, newtCanvasAWTFA.focusGained());
Assert.assertEquals(false, buttonNorthOuterFA.focusGained());
System.err.println("FOCUS NEWT Canvas/GLWindow sync");
AWTRobotUtil.assertKeyType(robot, java.awt.event.KeyEvent.VK_A, 2, glWindow1, glWindow1KA);
Assert.assertEquals("AWT parent canvas received keyboard events", 0, newtCanvasAWTKA.getCount());
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 1,
glWindow1, glWindow1MA);
AWTRobotUtil.assertMouseClick(robot, java.awt.event.InputEvent.BUTTON1_MASK, 2,
glWindow1, glWindow1MA);
Assert.assertEquals("AWT parent canvas received mouse events", 0, newtCanvasAWTMA.getCount());
animator1.stop();
Assert.assertEquals(false, animator1.isAnimating());
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
jFrame1.setVisible(false);
jPanel1.remove(container1);
jFrame1.dispose();
} });
glWindow1.destroy();
Assert.assertEquals(true, AWTRobotUtil.waitForRealized(glWindow1, false));
}
|
diff --git a/core/src/test/java/org/apache/mahout/cf/taste/hadoop/similarity/item/ItemSimilarityTest.java b/core/src/test/java/org/apache/mahout/cf/taste/hadoop/similarity/item/ItemSimilarityTest.java
index 4ef979ecb..1205b4272 100644
--- a/core/src/test/java/org/apache/mahout/cf/taste/hadoop/similarity/item/ItemSimilarityTest.java
+++ b/core/src/test/java/org/apache/mahout/cf/taste/hadoop/similarity/item/ItemSimilarityTest.java
@@ -1,314 +1,313 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.mahout.cf.taste.hadoop.similarity.item;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.OutputCollector;
import org.easymock.classextension.EasyMock;
import org.easymock.IArgumentMatcher;
import org.apache.mahout.cf.taste.hadoop.EntityPrefWritable;
import org.apache.mahout.cf.taste.hadoop.EntityPrefWritableArrayWritable;
import org.apache.mahout.cf.taste.hadoop.EntityEntityWritable;
import org.apache.mahout.cf.taste.hadoop.ToUserPrefsMapper;
import org.apache.mahout.common.MahoutTestCase;
/**
* Unit tests for the mappers and reducers in org.apache.mahout.cf.taste.hadoop.similarity
* Integration test with a mini-file at the end
*
*/
public class ItemSimilarityTest extends MahoutTestCase {
public void testUserPrefsPerItemMapper() throws Exception {
OutputCollector<LongWritable,LongWritable> output =
EasyMock.createMock(OutputCollector.class);
output.collect(new LongWritable(34L), new EntityPrefWritable(12L, 2.3f));
EasyMock.replay(output);
new ToUserPrefsMapper().map(new LongWritable(), new Text("12,34,2.3"), output, null);
EasyMock.verify(output);
}
public void testToItemVectorReducer() throws Exception {
List<EntityPrefWritable> userPrefs = Arrays.asList(
new EntityPrefWritable(34L, 1.0f), new EntityPrefWritable(56L, 2.0f));
OutputCollector<LongWritable,EntityPrefWritableArrayWritable> output =
EasyMock.createMock(OutputCollector.class);
output.collect(EasyMock.eq(new LongWritable(12L)), equalToUserPrefs(userPrefs));
EasyMock.replay(output);
new ToItemVectorReducer().reduce(new LongWritable(12L), userPrefs.iterator(), output, null);
EasyMock.verify(output);
}
static EntityPrefWritableArrayWritable equalToUserPrefs(
final Collection<EntityPrefWritable> prefsToCheck) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object argument) {
if (argument instanceof EntityPrefWritableArrayWritable) {
EntityPrefWritableArrayWritable userPrefArray =
(EntityPrefWritableArrayWritable) argument;
Set<EntityPrefWritable> set = new HashSet<EntityPrefWritable>();
set.addAll(Arrays.asList(userPrefArray.getPrefs()));
if (set.size() != prefsToCheck.size()) {
return false;
}
for (EntityPrefWritable prefToCheck : prefsToCheck) {
if (!set.contains(prefToCheck)) {
return false;
}
}
return true;
}
return false;
}
@Override
public void appendTo(StringBuffer buffer) {}
});
return null;
}
public void testPreferredItemsPerUserMapper() throws Exception {
OutputCollector<LongWritable,ItemPrefWithLengthWritable> output =
EasyMock.createMock(OutputCollector.class);
EntityPrefWritableArrayWritable userPrefs =
EasyMock.createMock(EntityPrefWritableArrayWritable.class);
EasyMock.expect(userPrefs.getPrefs()).andReturn(
new EntityPrefWritable[] {
new EntityPrefWritable(12L, 2.0f),
new EntityPrefWritable(56L, 3.0f) });
double length = Math.sqrt(Math.pow(2.0f, 2) + Math.pow(3.0f, 2));
output.collect(new LongWritable(12L), new ItemPrefWithLengthWritable(34L, length, 2.0f));
output.collect(new LongWritable(56L), new ItemPrefWithLengthWritable(34L, length, 3.0f));
EasyMock.replay(output, userPrefs);
new PreferredItemsPerUserMapper().map(new LongWritable(34L), userPrefs, output, null);
EasyMock.verify(output, userPrefs);
}
public void testPreferredItemsPerUserReducer() throws Exception {
List<ItemPrefWithLengthWritable> itemPrefs =
Arrays.asList(new ItemPrefWithLengthWritable(34L, 5.0, 1.0f),
new ItemPrefWithLengthWritable(56L, 7.0, 2.0f));
OutputCollector<LongWritable,ItemPrefWithLengthArrayWritable> output =
EasyMock.createMock(OutputCollector.class);
output.collect(EasyMock.eq(new LongWritable(12L)), equalToItemPrefs(itemPrefs));
EasyMock.replay(output);
new PreferredItemsPerUserReducer().reduce(
new LongWritable(12L), itemPrefs.iterator(), output, null);
EasyMock.verify(output);
}
static ItemPrefWithLengthArrayWritable equalToItemPrefs(
final Collection<ItemPrefWithLengthWritable> prefsToCheck) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object argument) {
if (argument instanceof ItemPrefWithLengthArrayWritable) {
ItemPrefWithLengthArrayWritable itemPrefArray = (ItemPrefWithLengthArrayWritable) argument;
Collection<ItemPrefWithLengthWritable> set = new HashSet<ItemPrefWithLengthWritable>();
set.addAll(Arrays.asList(itemPrefArray.getItemPrefs()));
if (set.size() != prefsToCheck.size()) {
return false;
}
for (ItemPrefWithLengthWritable prefToCheck : prefsToCheck) {
if (!set.contains(prefToCheck)) {
return false;
}
}
return true;
}
return false;
}
@Override
public void appendTo(StringBuffer buffer) {}
});
return null;
}
public void testCopreferredItemsMapper() throws Exception {
OutputCollector<ItemPairWritable,FloatWritable> output =
EasyMock.createMock(OutputCollector.class);
ItemPrefWithLengthArrayWritable itemPrefs =
EasyMock.createMock(ItemPrefWithLengthArrayWritable.class);
EasyMock.expect(itemPrefs.getItemPrefs()).andReturn(new ItemPrefWithLengthWritable[] {
new ItemPrefWithLengthWritable(34L, 2.0, 1.0f), new ItemPrefWithLengthWritable(56L, 3.0, 2.0f),
new ItemPrefWithLengthWritable(78L, 4.0, 3.0f) });
output.collect(new ItemPairWritable(34L, 56L, 6.0), new FloatWritable(2.0f));
output.collect(new ItemPairWritable(34L, 78L, 8.0), new FloatWritable(3.0f));
output.collect(new ItemPairWritable(56L, 78L, 12.0), new FloatWritable(6.0f));
EasyMock.replay(output, itemPrefs);
new CopreferredItemsMapper().map(new LongWritable(), itemPrefs, output, null);
EasyMock.verify(output, itemPrefs);
}
public void testCosineSimilarityReducer() throws Exception {
OutputCollector<EntityEntityWritable,DoubleWritable> output =
EasyMock.createMock(OutputCollector.class);
output.collect(new EntityEntityWritable(12L, 34L), new DoubleWritable(0.5d));
EasyMock.replay(output);
new CosineSimilarityReducer().reduce(new ItemPairWritable(12L, 34L, 20.0),
Arrays.asList(new FloatWritable(5.0f),
new FloatWritable(5.0f)).iterator(), output, null);
EasyMock.verify(output);
}
public void testCompleteJob() throws Exception {
String tmpDirProp = System.getProperty("java.io.tmpdir");
if (!tmpDirProp.endsWith("/")) {
tmpDirProp += "/";
}
String tmpDirPath = tmpDirProp + ItemSimilarityTest.class.getCanonicalName();
File tmpDir = new File(tmpDirPath);
try {
if (tmpDir.exists()) {
recursiveDelete(tmpDir);
- } else {
- tmpDir.mkdirs();
}
+ tmpDir.mkdirs();
/* user-item-matrix
Game Mouse PC Disk
Jane 0 1 2 0
Paul 1 0 1 0
Fred 0 0 0 1
*/
BufferedWriter writer = new BufferedWriter(new FileWriter(tmpDirPath+"/prefs.txt"));
try {
writer.write("1,2,1\n" +
"1,3,2\n" +
"2,1,1\n" +
"2,3,1\n" +
"3,4,1\n");
} finally {
writer.close();
}
ItemSimilarityJob similarityJob = new ItemSimilarityJob();
Configuration conf = new Configuration();
conf.set("mapred.input.dir", tmpDirPath+"/prefs.txt");
conf.set("mapred.output.dir", tmpDirPath+"/output");
conf.set("mapred.output.compress", Boolean.FALSE.toString());
similarityJob.setConf(conf);
similarityJob.run(new String[] { "--tempDir", tmpDirPath+"/tmp"});
String filePath = tmpDirPath+"/output/part-00000";
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
int currentLine = 1;
while ( (line = reader.readLine()) != null) {
String[] tokens = line.split("\t");
long itemAID = Long.parseLong(tokens[0]);
long itemBID = Long.parseLong(tokens[1]);
double similarity = Double.parseDouble(tokens[2]);
if (currentLine == 1) {
assertEquals(1L, itemAID);
assertEquals(3L, itemBID);
assertEquals(0.45, similarity, 0.01);
}
if (currentLine == 2) {
assertEquals(2L, itemAID);
assertEquals(3L, itemBID);
assertEquals(0.89, similarity, 0.01);
}
currentLine++;
}
int linesWritten = currentLine-1;
assertEquals(2, linesWritten);
} finally {
recursiveDelete(tmpDir);
}
}
static void recursiveDelete(File fileOrDir) {
if (fileOrDir.isDirectory()) {
for (File innerFile : fileOrDir.listFiles()) {
recursiveDelete(innerFile);
}
}
fileOrDir.delete();
}
}
| false | true | public void testCompleteJob() throws Exception {
String tmpDirProp = System.getProperty("java.io.tmpdir");
if (!tmpDirProp.endsWith("/")) {
tmpDirProp += "/";
}
String tmpDirPath = tmpDirProp + ItemSimilarityTest.class.getCanonicalName();
File tmpDir = new File(tmpDirPath);
try {
if (tmpDir.exists()) {
recursiveDelete(tmpDir);
} else {
tmpDir.mkdirs();
}
/* user-item-matrix
Game Mouse PC Disk
Jane 0 1 2 0
Paul 1 0 1 0
Fred 0 0 0 1
*/
BufferedWriter writer = new BufferedWriter(new FileWriter(tmpDirPath+"/prefs.txt"));
try {
writer.write("1,2,1\n" +
"1,3,2\n" +
"2,1,1\n" +
"2,3,1\n" +
"3,4,1\n");
} finally {
writer.close();
}
ItemSimilarityJob similarityJob = new ItemSimilarityJob();
Configuration conf = new Configuration();
conf.set("mapred.input.dir", tmpDirPath+"/prefs.txt");
conf.set("mapred.output.dir", tmpDirPath+"/output");
conf.set("mapred.output.compress", Boolean.FALSE.toString());
similarityJob.setConf(conf);
similarityJob.run(new String[] { "--tempDir", tmpDirPath+"/tmp"});
String filePath = tmpDirPath+"/output/part-00000";
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
int currentLine = 1;
while ( (line = reader.readLine()) != null) {
String[] tokens = line.split("\t");
long itemAID = Long.parseLong(tokens[0]);
long itemBID = Long.parseLong(tokens[1]);
double similarity = Double.parseDouble(tokens[2]);
if (currentLine == 1) {
assertEquals(1L, itemAID);
assertEquals(3L, itemBID);
assertEquals(0.45, similarity, 0.01);
}
if (currentLine == 2) {
assertEquals(2L, itemAID);
assertEquals(3L, itemBID);
assertEquals(0.89, similarity, 0.01);
}
currentLine++;
}
int linesWritten = currentLine-1;
assertEquals(2, linesWritten);
} finally {
recursiveDelete(tmpDir);
}
}
| public void testCompleteJob() throws Exception {
String tmpDirProp = System.getProperty("java.io.tmpdir");
if (!tmpDirProp.endsWith("/")) {
tmpDirProp += "/";
}
String tmpDirPath = tmpDirProp + ItemSimilarityTest.class.getCanonicalName();
File tmpDir = new File(tmpDirPath);
try {
if (tmpDir.exists()) {
recursiveDelete(tmpDir);
}
tmpDir.mkdirs();
/* user-item-matrix
Game Mouse PC Disk
Jane 0 1 2 0
Paul 1 0 1 0
Fred 0 0 0 1
*/
BufferedWriter writer = new BufferedWriter(new FileWriter(tmpDirPath+"/prefs.txt"));
try {
writer.write("1,2,1\n" +
"1,3,2\n" +
"2,1,1\n" +
"2,3,1\n" +
"3,4,1\n");
} finally {
writer.close();
}
ItemSimilarityJob similarityJob = new ItemSimilarityJob();
Configuration conf = new Configuration();
conf.set("mapred.input.dir", tmpDirPath+"/prefs.txt");
conf.set("mapred.output.dir", tmpDirPath+"/output");
conf.set("mapred.output.compress", Boolean.FALSE.toString());
similarityJob.setConf(conf);
similarityJob.run(new String[] { "--tempDir", tmpDirPath+"/tmp"});
String filePath = tmpDirPath+"/output/part-00000";
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
int currentLine = 1;
while ( (line = reader.readLine()) != null) {
String[] tokens = line.split("\t");
long itemAID = Long.parseLong(tokens[0]);
long itemBID = Long.parseLong(tokens[1]);
double similarity = Double.parseDouble(tokens[2]);
if (currentLine == 1) {
assertEquals(1L, itemAID);
assertEquals(3L, itemBID);
assertEquals(0.45, similarity, 0.01);
}
if (currentLine == 2) {
assertEquals(2L, itemAID);
assertEquals(3L, itemBID);
assertEquals(0.89, similarity, 0.01);
}
currentLine++;
}
int linesWritten = currentLine-1;
assertEquals(2, linesWritten);
} finally {
recursiveDelete(tmpDir);
}
}
|
diff --git a/src/org/siraya/rent/user/service/UserService.java b/src/org/siraya/rent/user/service/UserService.java
index 71747c6..61be808 100755
--- a/src/org/siraya/rent/user/service/UserService.java
+++ b/src/org/siraya/rent/user/service/UserService.java
@@ -1,507 +1,507 @@
package org.siraya.rent.user.service;
import org.siraya.rent.pojo.MobileAuthRequest;
import org.siraya.rent.pojo.User;
import org.siraya.rent.pojo.VerifyEvent;
import org.siraya.rent.pojo.MobileAuthResponse;
import org.siraya.rent.user.dao.IUserDAO;
import org.siraya.rent.user.dao.IVerifyEventDao;
import org.siraya.rent.user.dao.IMobileAuthRequestDao;
import org.siraya.rent.user.dao.IMobileAuthResponseDao;
import org.siraya.rent.utils.EncodeUtility;
import org.siraya.rent.utils.IApplicationConfig;
import org.siraya.rent.utils.RentException;
import org.siraya.rent.utils.RentException.RentErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
import java.util.Map;
import org.siraya.rent.pojo.Device;
import org.siraya.rent.user.dao.IDeviceDao;
import java.util.List;
@Service("userService")
public class UserService implements IUserService {
@Autowired
private IUserDAO userDao;
@Autowired
private IApplicationConfig applicationConfig;
@Autowired
private IDeviceDao deviceDao;
@Autowired
private IMobileAuthRequestDao mobileAuthRequestDao;
@Autowired
private IMobileAuthResponseDao mobileAuthResponsetDao;
@Autowired
private IVerifyEventDao verifyEventDao;
@Autowired
private EncodeUtility encodeUtility;
private static Logger logger = LoggerFactory.getLogger(UserService.class);
@Transactional(value = "rentTxManager", propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = java.lang.Throwable.class)
public void removeDevice (Device device) throws Exception{
logger.debug("remove device ");
int ret =deviceDao.updateRemovedDeviceStatus(device.getId(),device.getUserId(),
device.getModified());
if (ret != 1) {
throw new RentException(RentErrorCode.ErrorStatusViolate, "update count is not 1");
}
}
/**
* get device info, only can get information with correct device id and user id
* @param device
*/
@Transactional(value = "rentTxManager", propagation = Propagation.SUPPORTS, readOnly = true)
public Device getDevice(Device device){
String userId = device.getUserId();
logger.debug("get device from database user id "+userId+" device id "+device.getId());
Device tmp = deviceDao.getDeviceByDeviceIdAndUserId(device.getId(), userId);
if (tmp == null) {
throw new RentException(RentErrorCode.ErrorNotFound, "device id not exist in database");
} else {
device = tmp;
}
if (device.getStatus() == DeviceStatus.Removed.getStatus()) {
throw new RentException(RentErrorCode.ErrorRemoved, "device status is removed");
}
logger.debug("device status is "+device.getStatus());
if (device.getStatus() == DeviceStatus.Authed.getStatus()) {
//
// only authed device can get user info
//
logger.debug("get user from database");
User user = userDao.getUserByUserId(userId);
if (user == null ) {
throw new RentException(RentException.RentErrorCode.ErrorNotFound, "user "+userId+" not found");
}
logger.debug("mobile phone is "+user.getMobilePhone());
device.setUser(user);
}
return device;
}
/**
* new user mobile number
*
* @param cc country code
* @param moblie phone number
* @exception DuplicateKeyException duplicate mobile number
*/
@Transactional(value = "rentTxManager", propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = java.lang.Throwable.class)
public User newUserByMobileNumber(int cc,String mobilePhone) {
//
// verify format
//
String ccString = Integer.toString(cc);
logger.debug("check cc code");
mobilePhone = mobilePhone.trim();
Map<String, Object> mobileCountryCode = applicationConfig.get("mobile_country_code");
if (!mobileCountryCode.containsKey(ccString)) {
throw new RentException(RentErrorCode.ErrorCountryNotSupport, "cc not exist in mobile country code " + cc);
}
if (!mobilePhone.startsWith(ccString)) {
throw new RentException(RentErrorCode.ErrorInvalidParameter,"cc code not start with "+cc);
}
//
// setup user object
//
Map<String, Object> map = (Map<String, Object>) mobileCountryCode
.get(ccString);
User user = new User();
String id = java.util.UUID.randomUUID().toString();
user.setId(id);
user.setMobilePhone(encodeUtility.encrypt(mobilePhone, User.ENCRYPT_KEY));
user.setCc((String) map.get("country"));
user.setLang((String) map.get("lang"));
user.setTimezone((String) map.get("timezone"));
user.setStatus(UserStatus.Init.getStatus());
try{
//
// insert into database.
//
userDao.newUser(user);
logger.info("create new user id is " + id);
return user;
}catch(org.springframework.dao.DuplicateKeyException e){
logger.debug("phone number "+mobilePhone+" have been exist in database.");
return userDao.getUserByMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY));
}
}
/**
* create new device
*
* 1.check max device number.
* 2.create new record in database.
* 3.send auth code through mobile number.
*/
@Transactional(value = "rentTxManager", propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = java.lang.Throwable.class)
public Device newDevice(Device device) throws Exception {
User user = device.getUser();
Map<String,Object> generalSetting = applicationConfig.get("general");
//
// check device count.
//
int count=deviceDao.getDeviceCountByUserId(device.getUserId());
int maxDevice = ((Integer)generalSetting.get("max_device_count")).intValue();
logger.debug("user id is "+device.getUserId()+" device count is "+count+" max device is "+maxDevice);
if (count > maxDevice) {
throw new RentException(RentErrorCode.ErrorExceedLimit, "current user have too many device");
}
//
// check how many user in this device
//
count = deviceDao.getDeviceCountByDeviceId(device.getId());
maxDevice = ((Integer)generalSetting.get("max_user_per_device")).intValue();
logger.debug("device id is "+device.getId()+" user count is "+count+" max user is "+maxDevice);
if (count > maxDevice) {
throw new RentException(RentErrorCode.ErrorExceedLimit, "current device have too many users");
}
//
// check user status
//
if (user.getStatus() == UserStatus.Remove.getStatus()) {
throw new RentException(RentErrorCode.ErrorRemoved, "user status is removed");
}
//
// generate new device id
//
if (device.getId() == null) {
String id = Device.genId();
device.setId(id);
}
Device oldDevice = deviceDao.getDeviceByDeviceIdAndUserId(
device.getId(), user.getId());
if (oldDevice != null) {
logger.debug("old device exist");
} else {
// old device not exist
device.setStatus(DeviceStatus.Init.getStatus());
device.setToken(this.encodeUtility.encrypt(device.genToken(), Device.ENCRYPT_KEY));
deviceDao.newDevice(device);
logger.debug("insert device");
}
return device;
}
/**
* set up email. only when email still not exist.
*
*/
@Transactional(value = "rentTxManager", propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = java.lang.Throwable.class)
public void setupEmail(User user) throws Exception {
String userId = user.getId();
String newEmail = user.getEmail();
logger.info("update email for user "+userId+ " new email "+newEmail);
VerifyEvent verifyEvent = null;
user = userDao.getUserByUserId(user.getId());
String oldEmail = user.getEmail();
if (oldEmail != null && !oldEmail.equals("")) {
logger.debug("old email exist");
if (oldEmail.equals(newEmail)) {
//
// same email.
//
throw new RentException(RentErrorCode.ErrorUpdateSameItem, "same email have been setted");
}
//
// if old email exist and already verified, then throw exception
// to prevent overwrite primary email
// change email must call by different process.
//
verifyEvent = verifyEventDao.getEventByVerifyDetailAndType(VerifyEvent.VerifyType.Email.getType(),
oldEmail);
if (verifyEvent != null
&& verifyEvent.getStatus() == VerifyEvent.VerifyStatus.Authed
.getStatus()) {
throw new RentException(RentErrorCode.ErrorStatusViolate, "old email have been verified. can't reset email");
}
}
user.setModified(new Long(0));
user.setEmail(newEmail);
logger.debug("insert verify event");
verifyEvent = new VerifyEvent();
verifyEvent.setUserId(userId);
verifyEvent.setStatus(VerifyEvent.VerifyStatus.Init.getStatus());
verifyEvent.setVerifyDetail(newEmail);
verifyEvent.setVerifyType(VerifyEvent.VerifyType.Email.getType());
verifyEventDao.newVerifyEvent(verifyEvent);
logger.debug("update email in database");
userDao.updateUserEmail(user);
}
/**
* update login id and password
*
*/
@Transactional(value = "rentTxManager", propagation = Propagation.SUPPORTS, readOnly = false, rollbackFor = java.lang.Throwable.class)
public void updateLoginIdAndPassowrd(User user) throws Exception{
String userId = user.getId();
User user2 = userDao.getUserByUserId(userId);
//
// check original login id must be null or empty
//
if (user2.getLoginId() != null && user2.getLoginId() != "") {
throw new Exception("can't reset login id");
}
user.setId(user2.getId());
user.setModified(new Long(0));
//
// sha1
//
user.setPassword(EncodeUtility.sha1(user.getPassword()));
logger.debug("update login id and password in database");
int ret =userDao.updateUserLoginIdAndPassword(user);
if (ret == 0 ) {
throw new RentException(RentErrorCode.ErrorCanNotOverwrite, "update cnt =0, only empty login id can be update");
}
}
public void nameDevice(Device device) {
int ret = this.deviceDao.nameDevice(device);
if (ret == 0 ) {
throw new RentException(RentErrorCode.ErrorCanNotOverwrite, "update cnt =0, only empty login id can be update");
}
}
/**
* get all user devies
* @param userId
* @return
*/
public List<Device> getUserDevices(String userId, int limit, int offset){
List<Device> ret = this.deviceDao.getUserDevices(userId, limit ,offset);
if (ret.size() == 0){
throw new RentException(RentErrorCode.ErrorNotFound,"no device found");
}
return ret;
}
public List<User> getDeviceUsers(String deviceId, int limit, int offset){
List<User> ret = this.deviceDao.getDeviceUsers(deviceId, limit ,offset);
if (ret.size() == 0){
throw new RentException(RentErrorCode.ErrorNotFound,"no device found");
}
return ret;
}
public String getSignatureOfMobileAuthRequest(MobileAuthRequest request){
String userId = request.getRequestFrom();
Device requestFrom = this.deviceDao.getDeviceByDeviceIdAndUserId(
SSO_DEVICE_ID, userId);
return this._getSignatureOfMobileAuthRequest(request, requestFrom);
}
private String _getSignatureOfMobileAuthRequest(MobileAuthRequest request,Device requestFrom) {
if (requestFrom == null) {
String userId = requestFrom.getUserId();
throw new RentException(RentErrorCode.ErrorUserExist,"request sso device user id:"+userId+" not exist");
}
if (requestFrom.getStatus() != DeviceStatus.ApiKeyOnly.getStatus()) {
throw new RentException(RentErrorCode.ErrorPermissionDeny,"request user not for apikey only");
}
String requestString = request.toString(requestFrom.getToken());
logger.debug("verify request sign "+requestString);
return EncodeUtility.sha1(requestString);
}
/**
* step1: check requestFrom
* step2: check sign
* step3: if auth user exist, fetch user id.
* if user not exist, create new user
* step4: check expire time.
* step4: authUser and mobilePhone can't have together.
* step5: save request into database.
*/
public MobileAuthResponse mobileAuthRequest( MobileAuthRequest request){
Device currentDevice = request.getDevice();
String userId = request.getRequestFrom();
Map<String,Object> generalSetting = applicationConfig.get("general");
Device requestFrom = this.deviceDao.getDeviceByDeviceIdAndUserId(
SSO_DEVICE_ID, userId);
- boolean debug = (boolean)generalSetting.get("debug");
+ boolean debug = (Boolean)generalSetting.get("debug");
String sign = this._getSignatureOfMobileAuthRequest(request, requestFrom);
if (!debug && !sign.equals(request.getSign())) {
throw new RentException(RentErrorCode.ErrorPermissionDeny,
"sign verify failed "+sign);
}
logger.debug("do verify expired");
long expire = 300;
long now = Calendar.getInstance().getTimeInMillis() / 1000;
if (request.getRequestTime() > now) {
throw new RentException(RentErrorCode.ErrorAuthExpired,
"request time is too after now " + request.getRequestTime()
+ " compare to " + now);
}
if (request.getRequestTime() < now - expire) {
throw new RentException(RentErrorCode.ErrorAuthExpired,
"request time is expired time is "
+ request.getRequestTime() + " compare to " + now);
}
//
// get autu user from friend
//
//
// get auth user from mobile phone
//
String mobilePhone = request.getMobilePhone();
User user = null;
if (mobilePhone != null) {
user = this.userDao.getUserByMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY));
if (user != null) {
logger.debug("current user exist");
} else {
logger.debug("this mobile phone's user not exist yet");
int cc = Integer.parseInt(request.getCountryCode());
user = this.newUserByMobileNumber(cc, mobilePhone);
}
request.setMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY)); // encrypt mobile phone
currentDevice.setUserId(user.getId());
//
// get device from deviceDao
//
try{
currentDevice = this.getDevice(currentDevice);
}catch(RentException e){
//
// skip device not found error and set as staus to removed.
//
if (e.getErrorCode() != RentException.RentErrorCode.ErrorNotFound) {
throw e;
}
currentDevice.setStatus(DeviceStatus.Authing.getStatus());
}
} else {
logger.debug("requset mobile phone is empty");
}
//
// save into database.
//
try {
logger.debug("save request into database");
request.genToken();
request.setToken(encodeUtility.encrypt(request.getToken(), Device.ENCRYPT_KEY));
mobileAuthRequestDao.newRequest(request);
}catch(Exception e){
logger.error("insert request into dao error",e);
throw new RentException(RentException.RentErrorCode.ErrorGeneral,"insert request into dao error");
}
//
// prepare response
//
MobileAuthResponse response = new MobileAuthResponse();
logger.debug("prepare response");
response.setRequestId(request.getRequestId());
response.setStatus(currentDevice.getStatus());
response.setResponseTime(java.util.Calendar.getInstance().getTimeInMillis()/1000);
response.setUser(user);
response.setDevice(currentDevice);
String responseSign = EncodeUtility.sha1(response.toString(requestFrom.getToken()));
response.setSign(responseSign);
if (currentDevice.getStatus() == DeviceStatus.Authed.getStatus()) {
logger.debug("update response into database");
this.mobileAuthResponsetDao.updateResponse(response);
}
return response;
}
public List<Device> getSsoDevices(){
return this.deviceDao.getSsoDevices();
}
public MobileAuthRequest getMobileAuthRequest(String requestId) {
MobileAuthRequest request = this.mobileAuthRequestDao.get(requestId);
if (request == null) {
throw new RentException(RentException.RentErrorCode.ErrorNotFound,
"request id "+requestId+" not found");
}
return request;
}
public IMobileAuthRequestDao getMobileAuthRequestDao() {
return mobileAuthRequestDao;
}
public void setMobileAuthRequestDao(IMobileAuthRequestDao mobileAuthRequestDao) {
this.mobileAuthRequestDao = mobileAuthRequestDao;
}
@Override
public void verifyEmail(String userId, String authCode) {
// TODO Auto-generated method stub
}
@Override
public void updateUserInfo(User user) {
// TODO Auto-generated method stub
}
public void setUserDao(IUserDAO userDao){
this.userDao = userDao;
}
public void setDeviceDao(IDeviceDao deviceDao){
this.deviceDao = deviceDao;
}
public IApplicationConfig getApplicationConfig() {
return applicationConfig;
}
public void setApplicationConfig(IApplicationConfig applicationConfig) {
this.applicationConfig = applicationConfig;
}
public IVerifyEventDao getVerifyEventDao() {
return verifyEventDao;
}
public void setVerifyEventDao(IVerifyEventDao verifyEventDao) {
this.verifyEventDao = verifyEventDao;
}
public EncodeUtility getEncodeUtility() {
return encodeUtility;
}
public void setEncodeUtility(EncodeUtility encodeUtility) {
this.encodeUtility = encodeUtility;
}
}
| true | true | public MobileAuthResponse mobileAuthRequest( MobileAuthRequest request){
Device currentDevice = request.getDevice();
String userId = request.getRequestFrom();
Map<String,Object> generalSetting = applicationConfig.get("general");
Device requestFrom = this.deviceDao.getDeviceByDeviceIdAndUserId(
SSO_DEVICE_ID, userId);
boolean debug = (boolean)generalSetting.get("debug");
String sign = this._getSignatureOfMobileAuthRequest(request, requestFrom);
if (!debug && !sign.equals(request.getSign())) {
throw new RentException(RentErrorCode.ErrorPermissionDeny,
"sign verify failed "+sign);
}
logger.debug("do verify expired");
long expire = 300;
long now = Calendar.getInstance().getTimeInMillis() / 1000;
if (request.getRequestTime() > now) {
throw new RentException(RentErrorCode.ErrorAuthExpired,
"request time is too after now " + request.getRequestTime()
+ " compare to " + now);
}
if (request.getRequestTime() < now - expire) {
throw new RentException(RentErrorCode.ErrorAuthExpired,
"request time is expired time is "
+ request.getRequestTime() + " compare to " + now);
}
//
// get autu user from friend
//
//
// get auth user from mobile phone
//
String mobilePhone = request.getMobilePhone();
User user = null;
if (mobilePhone != null) {
user = this.userDao.getUserByMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY));
if (user != null) {
logger.debug("current user exist");
} else {
logger.debug("this mobile phone's user not exist yet");
int cc = Integer.parseInt(request.getCountryCode());
user = this.newUserByMobileNumber(cc, mobilePhone);
}
request.setMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY)); // encrypt mobile phone
currentDevice.setUserId(user.getId());
//
// get device from deviceDao
//
try{
currentDevice = this.getDevice(currentDevice);
}catch(RentException e){
//
// skip device not found error and set as staus to removed.
//
if (e.getErrorCode() != RentException.RentErrorCode.ErrorNotFound) {
throw e;
}
currentDevice.setStatus(DeviceStatus.Authing.getStatus());
}
} else {
logger.debug("requset mobile phone is empty");
}
//
// save into database.
//
try {
logger.debug("save request into database");
request.genToken();
request.setToken(encodeUtility.encrypt(request.getToken(), Device.ENCRYPT_KEY));
mobileAuthRequestDao.newRequest(request);
}catch(Exception e){
logger.error("insert request into dao error",e);
throw new RentException(RentException.RentErrorCode.ErrorGeneral,"insert request into dao error");
}
//
// prepare response
//
MobileAuthResponse response = new MobileAuthResponse();
logger.debug("prepare response");
response.setRequestId(request.getRequestId());
response.setStatus(currentDevice.getStatus());
response.setResponseTime(java.util.Calendar.getInstance().getTimeInMillis()/1000);
response.setUser(user);
response.setDevice(currentDevice);
String responseSign = EncodeUtility.sha1(response.toString(requestFrom.getToken()));
response.setSign(responseSign);
if (currentDevice.getStatus() == DeviceStatus.Authed.getStatus()) {
logger.debug("update response into database");
this.mobileAuthResponsetDao.updateResponse(response);
}
return response;
}
| public MobileAuthResponse mobileAuthRequest( MobileAuthRequest request){
Device currentDevice = request.getDevice();
String userId = request.getRequestFrom();
Map<String,Object> generalSetting = applicationConfig.get("general");
Device requestFrom = this.deviceDao.getDeviceByDeviceIdAndUserId(
SSO_DEVICE_ID, userId);
boolean debug = (Boolean)generalSetting.get("debug");
String sign = this._getSignatureOfMobileAuthRequest(request, requestFrom);
if (!debug && !sign.equals(request.getSign())) {
throw new RentException(RentErrorCode.ErrorPermissionDeny,
"sign verify failed "+sign);
}
logger.debug("do verify expired");
long expire = 300;
long now = Calendar.getInstance().getTimeInMillis() / 1000;
if (request.getRequestTime() > now) {
throw new RentException(RentErrorCode.ErrorAuthExpired,
"request time is too after now " + request.getRequestTime()
+ " compare to " + now);
}
if (request.getRequestTime() < now - expire) {
throw new RentException(RentErrorCode.ErrorAuthExpired,
"request time is expired time is "
+ request.getRequestTime() + " compare to " + now);
}
//
// get autu user from friend
//
//
// get auth user from mobile phone
//
String mobilePhone = request.getMobilePhone();
User user = null;
if (mobilePhone != null) {
user = this.userDao.getUserByMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY));
if (user != null) {
logger.debug("current user exist");
} else {
logger.debug("this mobile phone's user not exist yet");
int cc = Integer.parseInt(request.getCountryCode());
user = this.newUserByMobileNumber(cc, mobilePhone);
}
request.setMobilePhone(this.encodeUtility.encrypt(mobilePhone,User.ENCRYPT_KEY)); // encrypt mobile phone
currentDevice.setUserId(user.getId());
//
// get device from deviceDao
//
try{
currentDevice = this.getDevice(currentDevice);
}catch(RentException e){
//
// skip device not found error and set as staus to removed.
//
if (e.getErrorCode() != RentException.RentErrorCode.ErrorNotFound) {
throw e;
}
currentDevice.setStatus(DeviceStatus.Authing.getStatus());
}
} else {
logger.debug("requset mobile phone is empty");
}
//
// save into database.
//
try {
logger.debug("save request into database");
request.genToken();
request.setToken(encodeUtility.encrypt(request.getToken(), Device.ENCRYPT_KEY));
mobileAuthRequestDao.newRequest(request);
}catch(Exception e){
logger.error("insert request into dao error",e);
throw new RentException(RentException.RentErrorCode.ErrorGeneral,"insert request into dao error");
}
//
// prepare response
//
MobileAuthResponse response = new MobileAuthResponse();
logger.debug("prepare response");
response.setRequestId(request.getRequestId());
response.setStatus(currentDevice.getStatus());
response.setResponseTime(java.util.Calendar.getInstance().getTimeInMillis()/1000);
response.setUser(user);
response.setDevice(currentDevice);
String responseSign = EncodeUtility.sha1(response.toString(requestFrom.getToken()));
response.setSign(responseSign);
if (currentDevice.getStatus() == DeviceStatus.Authed.getStatus()) {
logger.debug("update response into database");
this.mobileAuthResponsetDao.updateResponse(response);
}
return response;
}
|
diff --git a/src/servlets/Manager.java b/src/servlets/Manager.java
index 760b361..749f065 100644
--- a/src/servlets/Manager.java
+++ b/src/servlets/Manager.java
@@ -1,639 +1,647 @@
package servlets;
/*
* Shop.java
*
*/
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import beans.*;
/**
*
* @author Fredrik �lund, Olle Eriksson
* @version 1.0
*/
public class Manager extends HttpServlet {
private static String jdbcURL = null;
private static String manager_page = null;
private static String user_page = null;
private static String show_products_page = null;
private static String show_components_page = null;
private static String profile_page = null;
private static String detail_page = null;
private static String add_product_page = null;
private static String add_component_page = null;
private CompleteProductListBean productList = null;
private ComponentListBean componentList = null;
/**
* Initializes the servlet.
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
jdbcURL = config.getInitParameter("JDBC_URL");
manager_page = config.getInitParameter("MANAGER_PAGE");
user_page = config.getInitParameter("USER_PAGE");
show_products_page = config.getInitParameter("SHOW_PRODUCTS_PAGE");
show_components_page = config.getInitParameter("SHOW_COMPONENTS_PAGE");
profile_page = config.getInitParameter("PROFILE_PAGE");
detail_page = config.getInitParameter("DETAIL_PAGE");
add_product_page = config.getInitParameter("ADD_PRODUCT_PAGE");
add_component_page = config.getInitParameter("ADD_COMPONENT_PAGE");
// get the books from the database using a bean
try {
this.productList = new CompleteProductListBean(jdbcURL);
this.componentList = new ComponentListBean(jdbcURL);
} catch (Exception e) {
throw new ServletException(e);
}
// servletContext is the same as scope Application
// store the productList in application scope
ServletContext sc = getServletContext();
sc.setAttribute("productList", this.productList);
sc.setAttribute("componentList", this.componentList);
}
/**
* Destroys the servlet.
*/
public void destroy() {
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request
* servlet request
* @param response
* servlet response
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
HttpSession sess = request.getSession();
RequestDispatcher rd = null;
sess.setAttribute("currentUser", request.getRemoteUser());
sess.setAttribute("jdbcURL", jdbcURL);
sess.setAttribute("usertype", "manager");
// check if we should turn on debug
String debug = request.getParameter("debug");
if (debug != null && debug.equals("on"))
sess.setAttribute("debug", "on");
else if (debug != null && debug.equals("off"))
sess.removeAttribute("debug");
/************************************************************/
/* START PAGE */
/************************************************************/
if (request.getParameter("action") == null
|| request.getParameter("action").equals("manager")) {
if (sess.getAttribute("currentUser") != null) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
}
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* SHOW PAGE (COMPONENTs / PRODUCTs) */
/************************************************************/
else if(request.getParameter("action").equals("manage")) {
if(request.getParameter("type") == null ||
request.getParameter("type").equals("product")) {
rd = request.getRequestDispatcher(show_products_page);
rd.forward(request, response);
}
else if(request.getParameter("type").equals("components")) {
rd = request.getRequestDispatcher(show_components_page);
rd.forward(request, response);
}
else
throw new ServletException("Trying to access something not existing.");
}
/************************************************************/
/* ADD PRODUCT */
/************************************************************/
else if (request.getParameter("action").equals("addProduct")) {
if(request.getParameter("save") != null &&
request.getParameter("save").equals("true")) {
CompleteProductBean bb = new CompleteProductBean();
bb.setDescription(request.getParameter("description"));
bb.setProduct(request.getParameter("product"));
bb.setVisbile(false);
bb.setProfit(Integer.valueOf(request.getParameter("profit")));
bb.setPrice(Integer.valueOf(request.getParameter("profit")));
bb.add(jdbcURL);
}
rd = request.getRequestDispatcher(add_product_page);
rd.forward(request, response);
}
/************************************************************/
/* ADD COMPONENT */
/************************************************************/
else if(request.getParameter("action").equals("addComponent")) {
+ try {
+ this.componentList = null;
+ this.componentList = new ComponentListBean(jdbcURL);
+ ServletContext sc = getServletContext();
+ sc.setAttribute("componentList", this.componentList);
+ } catch (Exception e) {
+ throw new ServletException(e);
+ }
if(request.getParameter("save") != null &&
request.getParameter("save").equals("true")) {
// DUMMY
ComponentBean cb = new ComponentBean();
cb.setManufacturer(request.getParameter("manufacturer"));
cb.setType(request.getParameter("type"));
cb.setPrice(Integer.parseInt(request.getParameter("price")));
cb.setQuantity(Integer.parseInt(request.getParameter("quantity")));
cb.add(jdbcURL);
this.componentList = null;
try {
- componentList = new ComponentListBean(jdbcURL);
+ this.componentList = new ComponentListBean(jdbcURL);
ServletContext sc = getServletContext();
sc.setAttribute("componentList", this.componentList);
} catch (Exception e) {
throw new ServletException(e);
}
}
rd = request.getRequestDispatcher(add_component_page);
rd.forward(request, response);
}
/************************************************************/
/* UPDATE PRODUCT / COMPONENT */
/************************************************************/
else if (request.getParameter("action").equals("update")) {
if(request.getParameter("productid") != null
&& request.getParameter("product") != null
&& request.getParameter("description") != null
&& request.getParameter("profit") != null) {
String product = request.getParameter("product");
String description = request.getParameter("description");
boolean visible = false;
if(request.getParameter("visible") != null
&& request.getParameter("visible").equals("true")) {
visible = true;
}
int profit = 0;
try {
profit = Integer.parseInt(request.getParameter("profit"));
} catch (NumberFormatException e) {
throw new ServletException("Illegal profit specified");
}
try {
this.productList.updateProduct(
Integer.parseInt(request.getParameter("productid")),
product, description, visible, profit);
} catch (Exception e) {
throw new ServletException(e);
}
rd = request.getRequestDispatcher(show_products_page);
rd.forward(request, response);
}
else if (request.getParameter("componentid") != null
&& request.getParameter("manufacturer") != null
&& request.getParameter("type") != null
&& request.getParameter("price") != null
&& request.getParameter("quantity") != null) {
String manufacturer = request.getParameter("manufacturer");
String type = request.getParameter("type");
int price = Integer.parseInt(request.getParameter("price"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
int id = Integer.parseInt(request.getParameter("componentid"));
try {
this.componentList.updateComponent(
id, manufacturer, type, price, quantity);
} catch (Exception e) {
throw new ServletException(e);
}
rd = request.getRequestDispatcher(show_components_page);
rd.forward(request, response);
}
else {
throw new ServletException("False update request");
}
}
/************************************************************/
/* ADD COMPONENT TO PRODUCT */
/************************************************************/
else if(request.getParameter("action").equals("addComp")) {
if(request.getParameter("productid") != null
&& request.getParameter("componentid") != null
&& request.getParameter("quantity") != null) {
int q = Integer.parseInt(request.getParameter("quantity"));
int pid = Integer.parseInt(request.getParameter("productid"));
int cid = Integer.parseInt(request.getParameter("componentid"));
try {
this.productList.addComponent(pid, cid, q);
} catch(Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException(
"No productid, componentid or quantity when add component to product");
}
rd = request.getRequestDispatcher(
"manager?action=detail&productid=" + request.getParameter("productid"));
rd.forward(request, response);
}
/************************************************************/
/* REMOVE COMPONENT FROM PRODUCT */
/************************************************************/
else if (request.getParameter("action").equals("removeComponent")) {
if (request.getParameter("productid") != null
&& request.getParameter("quantity") != null
&& request.getParameter("componentid") != null) {
int q = Integer.parseInt(request.getParameter("quantity"));
int pid = Integer.parseInt(request.getParameter("productid"));
int cid = Integer.parseInt(request.getParameter("componentid"));
try {
this.productList.removeComponent(pid, cid, q);
} catch (Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException(
"No productid, componentid or quantity when removing component from product");
}
rd = request.getRequestDispatcher(
"manager?action=detail&productid=" + request.getParameter("productid"));
rd.forward(request, response);
}
/************************************************************/
/* PRODUCT DETAILS */
/************************************************************/
else if (request.getParameter("action").equals("detail")) {
if (request.getParameter("productid") != null) {
CompleteProductBean cpb = this.productList.getById(
Integer.parseInt(request.getParameter("productid")));
request.setAttribute("product", cpb);
} else {
throw new ServletException("No productid when viewing detail");
}
rd = request.getRequestDispatcher(detail_page);
rd.forward(request, response);
}
/************************************************************/
/* SAVE PRODUCT / COMPONENT */
/************************************************************/
else if (request.getParameter("action").equals("save")) {
// if we have a shoppingcart, verify that we have
// valid userdata, then create an orderbean and
// save the order in the database
/*
* if (shoppingCart != null && request.getParameter("shipping_name")
* != null && request.getParameter("shipping_city") != null &&
* request.getParameter("shipping_zipcode") != null &&
* request.getParameter("shipping_address") != null){ OrderBean ob =
* new OrderBean(jdbcURL, shoppingCart,
* request.getParameter("shipping_name").trim(),
* request.getParameter("shipping_address").trim(),
* request.getParameter("shipping_zipcode").trim(),
* request.getParameter("shipping_city").trim()); try{ String check
* = ob.saveOrder(); if (!check.equals("")) throw new
* ServletException(check, new Exception()); } catch(Exception e){
* throw new ServletException("Error saving order", e); } } else{
* throw new ServletException(
* "Not all parameters are present or no " +
* " shopping cart when saving book"); }
*/
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* CHECKOUT */
/************************************************************/
else if (request.getParameter("action").equals("checkout")) {
if (sess.getAttribute("currentUser") != null) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
}
response.sendRedirect(manager_page);
}
/************************************************************/
/* LOGOUT */
/************************************************************/
else if (request.getParameter("action").equals("logout")) {
sess.invalidate();
response.sendRedirect("manager");
}
/************************************************************/
/* PROFILE PAGE */
/************************************************************/
else if (request.getParameter("action").equals("profile")) {
HashMap<String, Boolean> role = null;
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
role = p.getRoles();
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
Set<String> k = role.keySet();
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = i.next();
if (request.isUserInRole(st))
role.put(st, true);
}
p.setRole(role);
sess.setAttribute("roles", role);
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* UPDATE PROFILE */
/************************************************************/
else if (request.getParameter("action").equals("profilechange")
|| request.getParameter("action").equals("usercreate")) {
ProfileBean pb = (ProfileBean) sess.getAttribute("profile");
String u;
if (request.getParameter("action").equals("profilechange"))
u = (String) sess.getAttribute("currentUser");
else
u = request.getParameter("user");
String p1 = request.getParameter("password");
String p2 = request.getParameter("password2");
String name = request.getParameter("name");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String country = request.getParameter("country");
pb.setUser(u);
pb.setPassword(p1);
pb.setName(name);
pb.setStreet(street);
pb.setZip(zip);
pb.setCity(city);
pb.setCountry(country);
HashMap<String, Boolean> r =
(HashMap<String, Boolean>) sess.getAttribute("roles");
Set<String> k = r.keySet();
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = i.next();
String res = request.getParameter(st);
if (res != null)
r.put(st, true);
else
r.put(st, false);
}
pb.setRole(r);
// if this a new user, try to add him to the database
if (request.getParameter("action").equals("usercreate")) {
boolean b;
// make sure the the username is not used already
try {
b = pb.testUser(u);
} catch (Exception e) {
throw new ServletException("Error loading user table", e);
}
if (b) {
sess.setAttribute("passwordInvalid",
"User name already in use");
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
// note that a return is needed here because forward
// will not cause our servlet to stop execution, just
// forward the request processing
return;
}
}
// now we know that we have a valid user name
// validate all data,
boolean b = profileValidate(request, sess);
if (!b && request.getParameter("action").equals("profilechange")) {
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
} else if (!b) {
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
// validated OK, update the database
else {
ProfileUpdateBean pu = new ProfileUpdateBean(jdbcURL);
if (request.getParameter("action").equals("profilechange")) {
try {
pu.setProfile(pb);
} catch (Exception e) {
throw new ServletException("Error saving profile", e);
}
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
} else {
try {
pu.setUser(pb);
} catch (Exception e) {
throw new ServletException("Error saving profile", e);
}
response.sendRedirect(manager_page);
}
}
}
/************************************************************/
/* CREATE USER */
/************************************************************/
else if (request.getParameter("action").equals("newuser")) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
HashMap<String, Boolean> role = p.getRoles();
sess.setAttribute("roles", role);
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
}
// valide a profile
private boolean profileValidate(HttpServletRequest request, HttpSession sess) {
// use the attribute "passwordInvalid" as error messages
sess.setAttribute("passwordInvalid", null);
String u;
// get all data
if (request.getParameter("action").equals("profilechange"))
u = (String) sess.getAttribute("currentUser");
else
u = request.getParameter("user");
String p1 = request.getParameter("password");
String p2 = request.getParameter("password2");
String name = request.getParameter("name");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String country = request.getParameter("country");
HashMap<String, Boolean> r =
(HashMap<String, Boolean>) sess.getAttribute("roles");
Set<String> k = r.keySet();
int count = 0;
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = request.getParameter(i.next());
if (st != null)
count++;
}
// validate
if (count == 0) {
sess.setAttribute("passwordInvalid",
"You must select at least one role");
return false;
} else if (u == null || u.length() < 1) {
sess.setAttribute("passwordInvalid",
"User name must not be empty, retry!");
return false;
}
if (!request.isUserInRole("admin")
&& request.getParameter("admin") != null) {
sess.setAttribute("passwordInvalid",
"You must be in role admin to set role admin");
return false;
}
if (p1 == null || p2 == null || p1.length() < 1) {
sess.setAttribute("passwordInvalid",
"Password must not be empty, retry!");
return false;
} else if (!(p1.equals(p2))) {
sess.setAttribute("passwordInvalid",
"Passwords do not match, retry!");
return false;
} else if (name == null || name.length() < 1) {
sess.setAttribute("passwordInvalid",
"Name must not be empty, retry!");
return false;
} else if (street == null || street.length() < 1) {
sess.setAttribute("passwordInvalid",
"Street must no be empty, retry!");
return false;
} else if (zip == null || zip.length() < 1) {
sess.setAttribute("passwordInvalid",
"Zip code must not be empty, retry!");
return false;
} else if (city == null || city.length() < 1) {
sess.setAttribute("passwordInvalid",
"City must not be empty, retry!");
return false;
} else if (country == null || country.length() < 1) {
sess.setAttribute("passwordInvalid",
"County must not be empty, retry!");
return false;
}
// validation OK
return true;
}
// get the shoppingcart, create it if needed
private ShoppingBean getCart(HttpServletRequest request) {
HttpSession se = null;
se = request.getSession();
ShoppingBean sb = null;
sb = (ShoppingBean) se.getAttribute("shoppingCart");
if (sb == null) {
sb = new ShoppingBean();
se.setAttribute("shoppingCart", sb);
}
return sb;
}
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request
* servlet request
* @param response
* servlet response
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "The main BookShop";
}
}
| false | true | protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
HttpSession sess = request.getSession();
RequestDispatcher rd = null;
sess.setAttribute("currentUser", request.getRemoteUser());
sess.setAttribute("jdbcURL", jdbcURL);
sess.setAttribute("usertype", "manager");
// check if we should turn on debug
String debug = request.getParameter("debug");
if (debug != null && debug.equals("on"))
sess.setAttribute("debug", "on");
else if (debug != null && debug.equals("off"))
sess.removeAttribute("debug");
/************************************************************/
/* START PAGE */
/************************************************************/
if (request.getParameter("action") == null
|| request.getParameter("action").equals("manager")) {
if (sess.getAttribute("currentUser") != null) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
}
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* SHOW PAGE (COMPONENTs / PRODUCTs) */
/************************************************************/
else if(request.getParameter("action").equals("manage")) {
if(request.getParameter("type") == null ||
request.getParameter("type").equals("product")) {
rd = request.getRequestDispatcher(show_products_page);
rd.forward(request, response);
}
else if(request.getParameter("type").equals("components")) {
rd = request.getRequestDispatcher(show_components_page);
rd.forward(request, response);
}
else
throw new ServletException("Trying to access something not existing.");
}
/************************************************************/
/* ADD PRODUCT */
/************************************************************/
else if (request.getParameter("action").equals("addProduct")) {
if(request.getParameter("save") != null &&
request.getParameter("save").equals("true")) {
CompleteProductBean bb = new CompleteProductBean();
bb.setDescription(request.getParameter("description"));
bb.setProduct(request.getParameter("product"));
bb.setVisbile(false);
bb.setProfit(Integer.valueOf(request.getParameter("profit")));
bb.setPrice(Integer.valueOf(request.getParameter("profit")));
bb.add(jdbcURL);
}
rd = request.getRequestDispatcher(add_product_page);
rd.forward(request, response);
}
/************************************************************/
/* ADD COMPONENT */
/************************************************************/
else if(request.getParameter("action").equals("addComponent")) {
if(request.getParameter("save") != null &&
request.getParameter("save").equals("true")) {
// DUMMY
ComponentBean cb = new ComponentBean();
cb.setManufacturer(request.getParameter("manufacturer"));
cb.setType(request.getParameter("type"));
cb.setPrice(Integer.parseInt(request.getParameter("price")));
cb.setQuantity(Integer.parseInt(request.getParameter("quantity")));
cb.add(jdbcURL);
this.componentList = null;
try {
componentList = new ComponentListBean(jdbcURL);
ServletContext sc = getServletContext();
sc.setAttribute("componentList", this.componentList);
} catch (Exception e) {
throw new ServletException(e);
}
}
rd = request.getRequestDispatcher(add_component_page);
rd.forward(request, response);
}
/************************************************************/
/* UPDATE PRODUCT / COMPONENT */
/************************************************************/
else if (request.getParameter("action").equals("update")) {
if(request.getParameter("productid") != null
&& request.getParameter("product") != null
&& request.getParameter("description") != null
&& request.getParameter("profit") != null) {
String product = request.getParameter("product");
String description = request.getParameter("description");
boolean visible = false;
if(request.getParameter("visible") != null
&& request.getParameter("visible").equals("true")) {
visible = true;
}
int profit = 0;
try {
profit = Integer.parseInt(request.getParameter("profit"));
} catch (NumberFormatException e) {
throw new ServletException("Illegal profit specified");
}
try {
this.productList.updateProduct(
Integer.parseInt(request.getParameter("productid")),
product, description, visible, profit);
} catch (Exception e) {
throw new ServletException(e);
}
rd = request.getRequestDispatcher(show_products_page);
rd.forward(request, response);
}
else if (request.getParameter("componentid") != null
&& request.getParameter("manufacturer") != null
&& request.getParameter("type") != null
&& request.getParameter("price") != null
&& request.getParameter("quantity") != null) {
String manufacturer = request.getParameter("manufacturer");
String type = request.getParameter("type");
int price = Integer.parseInt(request.getParameter("price"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
int id = Integer.parseInt(request.getParameter("componentid"));
try {
this.componentList.updateComponent(
id, manufacturer, type, price, quantity);
} catch (Exception e) {
throw new ServletException(e);
}
rd = request.getRequestDispatcher(show_components_page);
rd.forward(request, response);
}
else {
throw new ServletException("False update request");
}
}
/************************************************************/
/* ADD COMPONENT TO PRODUCT */
/************************************************************/
else if(request.getParameter("action").equals("addComp")) {
if(request.getParameter("productid") != null
&& request.getParameter("componentid") != null
&& request.getParameter("quantity") != null) {
int q = Integer.parseInt(request.getParameter("quantity"));
int pid = Integer.parseInt(request.getParameter("productid"));
int cid = Integer.parseInt(request.getParameter("componentid"));
try {
this.productList.addComponent(pid, cid, q);
} catch(Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException(
"No productid, componentid or quantity when add component to product");
}
rd = request.getRequestDispatcher(
"manager?action=detail&productid=" + request.getParameter("productid"));
rd.forward(request, response);
}
/************************************************************/
/* REMOVE COMPONENT FROM PRODUCT */
/************************************************************/
else if (request.getParameter("action").equals("removeComponent")) {
if (request.getParameter("productid") != null
&& request.getParameter("quantity") != null
&& request.getParameter("componentid") != null) {
int q = Integer.parseInt(request.getParameter("quantity"));
int pid = Integer.parseInt(request.getParameter("productid"));
int cid = Integer.parseInt(request.getParameter("componentid"));
try {
this.productList.removeComponent(pid, cid, q);
} catch (Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException(
"No productid, componentid or quantity when removing component from product");
}
rd = request.getRequestDispatcher(
"manager?action=detail&productid=" + request.getParameter("productid"));
rd.forward(request, response);
}
/************************************************************/
/* PRODUCT DETAILS */
/************************************************************/
else if (request.getParameter("action").equals("detail")) {
if (request.getParameter("productid") != null) {
CompleteProductBean cpb = this.productList.getById(
Integer.parseInt(request.getParameter("productid")));
request.setAttribute("product", cpb);
} else {
throw new ServletException("No productid when viewing detail");
}
rd = request.getRequestDispatcher(detail_page);
rd.forward(request, response);
}
/************************************************************/
/* SAVE PRODUCT / COMPONENT */
/************************************************************/
else if (request.getParameter("action").equals("save")) {
// if we have a shoppingcart, verify that we have
// valid userdata, then create an orderbean and
// save the order in the database
/*
* if (shoppingCart != null && request.getParameter("shipping_name")
* != null && request.getParameter("shipping_city") != null &&
* request.getParameter("shipping_zipcode") != null &&
* request.getParameter("shipping_address") != null){ OrderBean ob =
* new OrderBean(jdbcURL, shoppingCart,
* request.getParameter("shipping_name").trim(),
* request.getParameter("shipping_address").trim(),
* request.getParameter("shipping_zipcode").trim(),
* request.getParameter("shipping_city").trim()); try{ String check
* = ob.saveOrder(); if (!check.equals("")) throw new
* ServletException(check, new Exception()); } catch(Exception e){
* throw new ServletException("Error saving order", e); } } else{
* throw new ServletException(
* "Not all parameters are present or no " +
* " shopping cart when saving book"); }
*/
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* CHECKOUT */
/************************************************************/
else if (request.getParameter("action").equals("checkout")) {
if (sess.getAttribute("currentUser") != null) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
}
response.sendRedirect(manager_page);
}
/************************************************************/
/* LOGOUT */
/************************************************************/
else if (request.getParameter("action").equals("logout")) {
sess.invalidate();
response.sendRedirect("manager");
}
/************************************************************/
/* PROFILE PAGE */
/************************************************************/
else if (request.getParameter("action").equals("profile")) {
HashMap<String, Boolean> role = null;
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
role = p.getRoles();
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
Set<String> k = role.keySet();
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = i.next();
if (request.isUserInRole(st))
role.put(st, true);
}
p.setRole(role);
sess.setAttribute("roles", role);
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* UPDATE PROFILE */
/************************************************************/
else if (request.getParameter("action").equals("profilechange")
|| request.getParameter("action").equals("usercreate")) {
ProfileBean pb = (ProfileBean) sess.getAttribute("profile");
String u;
if (request.getParameter("action").equals("profilechange"))
u = (String) sess.getAttribute("currentUser");
else
u = request.getParameter("user");
String p1 = request.getParameter("password");
String p2 = request.getParameter("password2");
String name = request.getParameter("name");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String country = request.getParameter("country");
pb.setUser(u);
pb.setPassword(p1);
pb.setName(name);
pb.setStreet(street);
pb.setZip(zip);
pb.setCity(city);
pb.setCountry(country);
HashMap<String, Boolean> r =
(HashMap<String, Boolean>) sess.getAttribute("roles");
Set<String> k = r.keySet();
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = i.next();
String res = request.getParameter(st);
if (res != null)
r.put(st, true);
else
r.put(st, false);
}
pb.setRole(r);
// if this a new user, try to add him to the database
if (request.getParameter("action").equals("usercreate")) {
boolean b;
// make sure the the username is not used already
try {
b = pb.testUser(u);
} catch (Exception e) {
throw new ServletException("Error loading user table", e);
}
if (b) {
sess.setAttribute("passwordInvalid",
"User name already in use");
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
// note that a return is needed here because forward
// will not cause our servlet to stop execution, just
// forward the request processing
return;
}
}
// now we know that we have a valid user name
// validate all data,
boolean b = profileValidate(request, sess);
if (!b && request.getParameter("action").equals("profilechange")) {
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
} else if (!b) {
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
// validated OK, update the database
else {
ProfileUpdateBean pu = new ProfileUpdateBean(jdbcURL);
if (request.getParameter("action").equals("profilechange")) {
try {
pu.setProfile(pb);
} catch (Exception e) {
throw new ServletException("Error saving profile", e);
}
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
} else {
try {
pu.setUser(pb);
} catch (Exception e) {
throw new ServletException("Error saving profile", e);
}
response.sendRedirect(manager_page);
}
}
}
/************************************************************/
/* CREATE USER */
/************************************************************/
else if (request.getParameter("action").equals("newuser")) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
HashMap<String, Boolean> role = p.getRoles();
sess.setAttribute("roles", role);
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
}
| protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
HttpSession sess = request.getSession();
RequestDispatcher rd = null;
sess.setAttribute("currentUser", request.getRemoteUser());
sess.setAttribute("jdbcURL", jdbcURL);
sess.setAttribute("usertype", "manager");
// check if we should turn on debug
String debug = request.getParameter("debug");
if (debug != null && debug.equals("on"))
sess.setAttribute("debug", "on");
else if (debug != null && debug.equals("off"))
sess.removeAttribute("debug");
/************************************************************/
/* START PAGE */
/************************************************************/
if (request.getParameter("action") == null
|| request.getParameter("action").equals("manager")) {
if (sess.getAttribute("currentUser") != null) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
}
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* SHOW PAGE (COMPONENTs / PRODUCTs) */
/************************************************************/
else if(request.getParameter("action").equals("manage")) {
if(request.getParameter("type") == null ||
request.getParameter("type").equals("product")) {
rd = request.getRequestDispatcher(show_products_page);
rd.forward(request, response);
}
else if(request.getParameter("type").equals("components")) {
rd = request.getRequestDispatcher(show_components_page);
rd.forward(request, response);
}
else
throw new ServletException("Trying to access something not existing.");
}
/************************************************************/
/* ADD PRODUCT */
/************************************************************/
else if (request.getParameter("action").equals("addProduct")) {
if(request.getParameter("save") != null &&
request.getParameter("save").equals("true")) {
CompleteProductBean bb = new CompleteProductBean();
bb.setDescription(request.getParameter("description"));
bb.setProduct(request.getParameter("product"));
bb.setVisbile(false);
bb.setProfit(Integer.valueOf(request.getParameter("profit")));
bb.setPrice(Integer.valueOf(request.getParameter("profit")));
bb.add(jdbcURL);
}
rd = request.getRequestDispatcher(add_product_page);
rd.forward(request, response);
}
/************************************************************/
/* ADD COMPONENT */
/************************************************************/
else if(request.getParameter("action").equals("addComponent")) {
try {
this.componentList = null;
this.componentList = new ComponentListBean(jdbcURL);
ServletContext sc = getServletContext();
sc.setAttribute("componentList", this.componentList);
} catch (Exception e) {
throw new ServletException(e);
}
if(request.getParameter("save") != null &&
request.getParameter("save").equals("true")) {
// DUMMY
ComponentBean cb = new ComponentBean();
cb.setManufacturer(request.getParameter("manufacturer"));
cb.setType(request.getParameter("type"));
cb.setPrice(Integer.parseInt(request.getParameter("price")));
cb.setQuantity(Integer.parseInt(request.getParameter("quantity")));
cb.add(jdbcURL);
this.componentList = null;
try {
this.componentList = new ComponentListBean(jdbcURL);
ServletContext sc = getServletContext();
sc.setAttribute("componentList", this.componentList);
} catch (Exception e) {
throw new ServletException(e);
}
}
rd = request.getRequestDispatcher(add_component_page);
rd.forward(request, response);
}
/************************************************************/
/* UPDATE PRODUCT / COMPONENT */
/************************************************************/
else if (request.getParameter("action").equals("update")) {
if(request.getParameter("productid") != null
&& request.getParameter("product") != null
&& request.getParameter("description") != null
&& request.getParameter("profit") != null) {
String product = request.getParameter("product");
String description = request.getParameter("description");
boolean visible = false;
if(request.getParameter("visible") != null
&& request.getParameter("visible").equals("true")) {
visible = true;
}
int profit = 0;
try {
profit = Integer.parseInt(request.getParameter("profit"));
} catch (NumberFormatException e) {
throw new ServletException("Illegal profit specified");
}
try {
this.productList.updateProduct(
Integer.parseInt(request.getParameter("productid")),
product, description, visible, profit);
} catch (Exception e) {
throw new ServletException(e);
}
rd = request.getRequestDispatcher(show_products_page);
rd.forward(request, response);
}
else if (request.getParameter("componentid") != null
&& request.getParameter("manufacturer") != null
&& request.getParameter("type") != null
&& request.getParameter("price") != null
&& request.getParameter("quantity") != null) {
String manufacturer = request.getParameter("manufacturer");
String type = request.getParameter("type");
int price = Integer.parseInt(request.getParameter("price"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
int id = Integer.parseInt(request.getParameter("componentid"));
try {
this.componentList.updateComponent(
id, manufacturer, type, price, quantity);
} catch (Exception e) {
throw new ServletException(e);
}
rd = request.getRequestDispatcher(show_components_page);
rd.forward(request, response);
}
else {
throw new ServletException("False update request");
}
}
/************************************************************/
/* ADD COMPONENT TO PRODUCT */
/************************************************************/
else if(request.getParameter("action").equals("addComp")) {
if(request.getParameter("productid") != null
&& request.getParameter("componentid") != null
&& request.getParameter("quantity") != null) {
int q = Integer.parseInt(request.getParameter("quantity"));
int pid = Integer.parseInt(request.getParameter("productid"));
int cid = Integer.parseInt(request.getParameter("componentid"));
try {
this.productList.addComponent(pid, cid, q);
} catch(Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException(
"No productid, componentid or quantity when add component to product");
}
rd = request.getRequestDispatcher(
"manager?action=detail&productid=" + request.getParameter("productid"));
rd.forward(request, response);
}
/************************************************************/
/* REMOVE COMPONENT FROM PRODUCT */
/************************************************************/
else if (request.getParameter("action").equals("removeComponent")) {
if (request.getParameter("productid") != null
&& request.getParameter("quantity") != null
&& request.getParameter("componentid") != null) {
int q = Integer.parseInt(request.getParameter("quantity"));
int pid = Integer.parseInt(request.getParameter("productid"));
int cid = Integer.parseInt(request.getParameter("componentid"));
try {
this.productList.removeComponent(pid, cid, q);
} catch (Exception e) {
throw new ServletException(e);
}
} else {
throw new ServletException(
"No productid, componentid or quantity when removing component from product");
}
rd = request.getRequestDispatcher(
"manager?action=detail&productid=" + request.getParameter("productid"));
rd.forward(request, response);
}
/************************************************************/
/* PRODUCT DETAILS */
/************************************************************/
else if (request.getParameter("action").equals("detail")) {
if (request.getParameter("productid") != null) {
CompleteProductBean cpb = this.productList.getById(
Integer.parseInt(request.getParameter("productid")));
request.setAttribute("product", cpb);
} else {
throw new ServletException("No productid when viewing detail");
}
rd = request.getRequestDispatcher(detail_page);
rd.forward(request, response);
}
/************************************************************/
/* SAVE PRODUCT / COMPONENT */
/************************************************************/
else if (request.getParameter("action").equals("save")) {
// if we have a shoppingcart, verify that we have
// valid userdata, then create an orderbean and
// save the order in the database
/*
* if (shoppingCart != null && request.getParameter("shipping_name")
* != null && request.getParameter("shipping_city") != null &&
* request.getParameter("shipping_zipcode") != null &&
* request.getParameter("shipping_address") != null){ OrderBean ob =
* new OrderBean(jdbcURL, shoppingCart,
* request.getParameter("shipping_name").trim(),
* request.getParameter("shipping_address").trim(),
* request.getParameter("shipping_zipcode").trim(),
* request.getParameter("shipping_city").trim()); try{ String check
* = ob.saveOrder(); if (!check.equals("")) throw new
* ServletException(check, new Exception()); } catch(Exception e){
* throw new ServletException("Error saving order", e); } } else{
* throw new ServletException(
* "Not all parameters are present or no " +
* " shopping cart when saving book"); }
*/
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* CHECKOUT */
/************************************************************/
else if (request.getParameter("action").equals("checkout")) {
if (sess.getAttribute("currentUser") != null) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
}
response.sendRedirect(manager_page);
}
/************************************************************/
/* LOGOUT */
/************************************************************/
else if (request.getParameter("action").equals("logout")) {
sess.invalidate();
response.sendRedirect("manager");
}
/************************************************************/
/* PROFILE PAGE */
/************************************************************/
else if (request.getParameter("action").equals("profile")) {
HashMap<String, Boolean> role = null;
ProfileBean p = new ProfileBean(jdbcURL);
try {
p.populate((String) sess.getAttribute("currentUser"));
role = p.getRoles();
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
Set<String> k = role.keySet();
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = i.next();
if (request.isUserInRole(st))
role.put(st, true);
}
p.setRole(role);
sess.setAttribute("roles", role);
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
/************************************************************/
/* UPDATE PROFILE */
/************************************************************/
else if (request.getParameter("action").equals("profilechange")
|| request.getParameter("action").equals("usercreate")) {
ProfileBean pb = (ProfileBean) sess.getAttribute("profile");
String u;
if (request.getParameter("action").equals("profilechange"))
u = (String) sess.getAttribute("currentUser");
else
u = request.getParameter("user");
String p1 = request.getParameter("password");
String p2 = request.getParameter("password2");
String name = request.getParameter("name");
String street = request.getParameter("street");
String zip = request.getParameter("zip");
String city = request.getParameter("city");
String country = request.getParameter("country");
pb.setUser(u);
pb.setPassword(p1);
pb.setName(name);
pb.setStreet(street);
pb.setZip(zip);
pb.setCity(city);
pb.setCountry(country);
HashMap<String, Boolean> r =
(HashMap<String, Boolean>) sess.getAttribute("roles");
Set<String> k = r.keySet();
Iterator<String> i = k.iterator();
while (i.hasNext()) {
String st = i.next();
String res = request.getParameter(st);
if (res != null)
r.put(st, true);
else
r.put(st, false);
}
pb.setRole(r);
// if this a new user, try to add him to the database
if (request.getParameter("action").equals("usercreate")) {
boolean b;
// make sure the the username is not used already
try {
b = pb.testUser(u);
} catch (Exception e) {
throw new ServletException("Error loading user table", e);
}
if (b) {
sess.setAttribute("passwordInvalid",
"User name already in use");
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
// note that a return is needed here because forward
// will not cause our servlet to stop execution, just
// forward the request processing
return;
}
}
// now we know that we have a valid user name
// validate all data,
boolean b = profileValidate(request, sess);
if (!b && request.getParameter("action").equals("profilechange")) {
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
} else if (!b) {
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
// validated OK, update the database
else {
ProfileUpdateBean pu = new ProfileUpdateBean(jdbcURL);
if (request.getParameter("action").equals("profilechange")) {
try {
pu.setProfile(pb);
} catch (Exception e) {
throw new ServletException("Error saving profile", e);
}
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
} else {
try {
pu.setUser(pb);
} catch (Exception e) {
throw new ServletException("Error saving profile", e);
}
response.sendRedirect(manager_page);
}
}
}
/************************************************************/
/* CREATE USER */
/************************************************************/
else if (request.getParameter("action").equals("newuser")) {
ProfileBean p = new ProfileBean(jdbcURL);
try {
HashMap<String, Boolean> role = p.getRoles();
sess.setAttribute("roles", role);
} catch (Exception e) {
throw new ServletException("Error loading profile", e);
}
sess.setAttribute("profile", p);
rd = request.getRequestDispatcher(manager_page);
rd.forward(request, response);
}
}
|
diff --git a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java
index 643d7ca9..cd3ca9ec 100644
--- a/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java
+++ b/bundles/org.eclipse.osgi/security/src/org/eclipse/osgi/internal/service/security/KeyStoreTrustEngine.java
@@ -1,291 +1,294 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.osgi.internal.service.security;
import java.io.*;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import org.eclipse.osgi.framework.log.FrameworkLogEntry;
import org.eclipse.osgi.internal.signedcontent.SignedBundleHook;
import org.eclipse.osgi.internal.signedcontent.SignedContentMessages;
import org.eclipse.osgi.service.security.TrustEngine;
import org.eclipse.osgi.util.NLS;
//*potential enhancements*
// 1. reloading from the backing file when it changes
// 3. methods to support lock/unlock
// 3a. Using a callback handler to collect the password
// 3b. managing lock/unlock between multiple threads. dealing with SWT UI thread
// 4. methods to support changing password, etc
// 5. methods to support export, etc
// 6. 'friendly-name' generator
// 7. Listeners for change events
public class KeyStoreTrustEngine extends TrustEngine {
private KeyStore keyStore;
private final String type;
private final String path;
private final char[] password;
private final String name;
/**
* Create a new KeyStoreTrustEngine that is backed by a KeyStore
* @param path - path to the keystore
* @param type - the type of keystore at the path location
* @param password - the password required to unlock the keystore
*/
public KeyStoreTrustEngine(String path, String type, char[] password, String name) { //TODO: This should be a *CallbackHandler*
this.path = path;
this.type = type;
this.password = password;
this.name = name;
}
/**
* Return the type
* @return type - the type for the KeyStore being managed
*/
private String getType() {
return type;
}
/**
* Return the path
* @return - the path for the KeyStore being managed
*/
private String getPath() {
return path;
}
/**
* Return the password
* @return password - the password as a char[]
*/
private char[] getPassword() {
return password;
}
/**
* Return the KeyStore managed
* @return keystore - the KeyStore instance, initialized and loaded
* @throws KeyStoreException
*/
private synchronized KeyStore getKeyStore() throws IOException, GeneralSecurityException {
if (null == keyStore) {
keyStore = KeyStore.getInstance(getType());
loadStore(keyStore, getInputStream());
}
if (keyStore == null)
throw new KeyStoreException(NLS.bind(SignedContentMessages.Default_Trust_Keystore_Load_Failed, getPath()));
return keyStore;
}
public Certificate findTrustAnchor(Certificate[] certChain) throws IOException {
if (certChain == null || certChain.length == 0)
throw new IllegalArgumentException("Certificate chain is required"); //$NON-NLS-1$
try {
Certificate rootCert = null;
KeyStore store = getKeyStore();
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
if (i == certChain.length - 1) { //this is the last certificate in the chain
X509Certificate cert = (X509Certificate) certChain[i];
if (cert.getSubjectDN().equals(cert.getIssuerDN())) {
certChain[i].verify(certChain[i].getPublicKey());
rootCert = certChain[i]; // this is a self-signed certificate
} else {
// try to find a parent, we have an incomplete chain
- for (Enumeration e = store.aliases(); e.hasMoreElements();) {
- Certificate nextCert = store.getCertificate((String) e.nextElement());
- if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) {
- cert.verify(nextCert.getPublicKey());
- rootCert = nextCert;
+ synchronized (store) {
+ for (Enumeration e = store.aliases(); e.hasMoreElements();) {
+ Certificate nextCert = store.getCertificate((String) e.nextElement());
+ if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) {
+ cert.verify(nextCert.getPublicKey());
+ rootCert = nextCert;
+ break;
+ }
}
}
}
} else {
X509Certificate nextX509Cert = (X509Certificate) certChain[i + 1];
certChain[i].verify(nextX509Cert.getPublicKey());
}
}
synchronized (store) {
String alias = rootCert == null ? null : store.getCertificateAlias(rootCert);
if (alias != null)
return store.getCertificate(alias);
else if (rootCert != certChain[i]) {
alias = store.getCertificateAlias(certChain[i]);
if (alias != null)
return store.getCertificate(alias);
}
}
}
} catch (KeyStoreException e) {
throw new IOException(e.getMessage());
} catch (GeneralSecurityException e) {
SignedBundleHook.log(e.getMessage(), FrameworkLogEntry.WARNING, e);
return null;
}
return null;
}
protected String doAddTrustAnchor(Certificate cert, String alias) throws IOException, GeneralSecurityException {
if (isReadOnly())
throw new IOException(SignedContentMessages.Default_Trust_Read_Only);
if (cert == null) {
throw new IllegalArgumentException("Certificate must be specified"); //$NON-NLS-1$
}
try {
KeyStore store = getKeyStore();
synchronized (store) {
String oldAlias = store.getCertificateAlias(cert);
if (null != oldAlias)
throw new CertificateException(SignedContentMessages.Default_Trust_Existing_Cert);
Certificate oldCert = store.getCertificate(alias);
if (null != oldCert)
throw new CertificateException(SignedContentMessages.Default_Trust_Existing_Alias);
store.setCertificateEntry(alias, cert);
saveStore(store, getOutputStream());
}
} catch (KeyStoreException ke) {
throw new CertificateException(ke.getMessage());
}
return alias;
}
protected void doRemoveTrustAnchor(Certificate cert) throws IOException, GeneralSecurityException {
if (isReadOnly())
throw new IOException(SignedContentMessages.Default_Trust_Read_Only);
if (cert == null) {
throw new IllegalArgumentException("Certificate must be specified"); //$NON-NLS-1$
}
try {
KeyStore store = getKeyStore();
synchronized (store) {
String alias = store.getCertificateAlias(cert);
if (alias == null) {
throw new CertificateException(SignedContentMessages.Default_Trust_Cert_Not_Found);
}
removeTrustAnchor(alias);
}
} catch (KeyStoreException ke) {
throw new CertificateException(ke.getMessage());
}
}
protected void doRemoveTrustAnchor(String alias) throws IOException, GeneralSecurityException {
if (alias == null) {
throw new IllegalArgumentException("Alias must be specified"); //$NON-NLS-1$
}
try {
KeyStore store = getKeyStore();
synchronized (store) {
Certificate oldCert = store.getCertificate(alias);
if (oldCert == null)
throw new CertificateException(SignedContentMessages.Default_Trust_Cert_Not_Found);
store.deleteEntry(alias);
saveStore(store, getOutputStream());
}
} catch (KeyStoreException ke) {
throw new CertificateException(ke.getMessage());
}
}
public Certificate getTrustAnchor(String alias) throws IOException, GeneralSecurityException {
if (alias == null) {
throw new IllegalArgumentException("Alias must be specified"); //$NON-NLS-1$
}
try {
KeyStore store = getKeyStore();
synchronized (store) {
return store.getCertificate(alias);
}
} catch (KeyStoreException ke) {
throw new CertificateException(ke.getMessage());
}
}
public String[] getAliases() throws IOException, GeneralSecurityException {
ArrayList returnList = new ArrayList();
try {
KeyStore store = getKeyStore();
synchronized (store) {
for (Enumeration aliases = store.aliases(); aliases.hasMoreElements();) {
String currentAlias = (String) aliases.nextElement();
if (store.isCertificateEntry(currentAlias)) {
returnList.add(currentAlias);
}
}
}
} catch (KeyStoreException ke) {
throw new CertificateException(ke.getMessage());
}
return (String[]) returnList.toArray(new String[] {});
}
/**
* Load using the current password
*/
private void loadStore(KeyStore store, InputStream is) throws IOException, GeneralSecurityException {
store.load(is, getPassword());
}
/**
* Save using the current password
*/
private void saveStore(KeyStore store, OutputStream os) throws IOException, GeneralSecurityException {
store.store(os, getPassword());
}
/**
* Get an input stream for the KeyStore managed
* @return inputstream - the stream
* @throws KeyStoreException
*/
private InputStream getInputStream() throws IOException {
return new FileInputStream(new File(getPath()));
}
/**
* Get an output stream for the KeyStore managed
* @return outputstream - the stream
* @throws KeyStoreException
*/
private OutputStream getOutputStream() throws IOException {
File file = new File(getPath());
if (!file.exists())
file.createNewFile();
return new FileOutputStream(file);
}
public boolean isReadOnly() {
return getPassword() == null || !(new File(path).canWrite());
}
public String getName() {
return name;
}
}
| true | true | public Certificate findTrustAnchor(Certificate[] certChain) throws IOException {
if (certChain == null || certChain.length == 0)
throw new IllegalArgumentException("Certificate chain is required"); //$NON-NLS-1$
try {
Certificate rootCert = null;
KeyStore store = getKeyStore();
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
if (i == certChain.length - 1) { //this is the last certificate in the chain
X509Certificate cert = (X509Certificate) certChain[i];
if (cert.getSubjectDN().equals(cert.getIssuerDN())) {
certChain[i].verify(certChain[i].getPublicKey());
rootCert = certChain[i]; // this is a self-signed certificate
} else {
// try to find a parent, we have an incomplete chain
for (Enumeration e = store.aliases(); e.hasMoreElements();) {
Certificate nextCert = store.getCertificate((String) e.nextElement());
if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) {
cert.verify(nextCert.getPublicKey());
rootCert = nextCert;
}
}
}
} else {
X509Certificate nextX509Cert = (X509Certificate) certChain[i + 1];
certChain[i].verify(nextX509Cert.getPublicKey());
}
}
synchronized (store) {
String alias = rootCert == null ? null : store.getCertificateAlias(rootCert);
if (alias != null)
return store.getCertificate(alias);
else if (rootCert != certChain[i]) {
alias = store.getCertificateAlias(certChain[i]);
if (alias != null)
return store.getCertificate(alias);
}
}
}
} catch (KeyStoreException e) {
throw new IOException(e.getMessage());
} catch (GeneralSecurityException e) {
SignedBundleHook.log(e.getMessage(), FrameworkLogEntry.WARNING, e);
return null;
}
return null;
}
| public Certificate findTrustAnchor(Certificate[] certChain) throws IOException {
if (certChain == null || certChain.length == 0)
throw new IllegalArgumentException("Certificate chain is required"); //$NON-NLS-1$
try {
Certificate rootCert = null;
KeyStore store = getKeyStore();
for (int i = 0; i < certChain.length; i++) {
if (certChain[i] instanceof X509Certificate) {
if (i == certChain.length - 1) { //this is the last certificate in the chain
X509Certificate cert = (X509Certificate) certChain[i];
if (cert.getSubjectDN().equals(cert.getIssuerDN())) {
certChain[i].verify(certChain[i].getPublicKey());
rootCert = certChain[i]; // this is a self-signed certificate
} else {
// try to find a parent, we have an incomplete chain
synchronized (store) {
for (Enumeration e = store.aliases(); e.hasMoreElements();) {
Certificate nextCert = store.getCertificate((String) e.nextElement());
if (nextCert instanceof X509Certificate && ((X509Certificate) nextCert).getSubjectDN().equals(cert.getIssuerDN())) {
cert.verify(nextCert.getPublicKey());
rootCert = nextCert;
break;
}
}
}
}
} else {
X509Certificate nextX509Cert = (X509Certificate) certChain[i + 1];
certChain[i].verify(nextX509Cert.getPublicKey());
}
}
synchronized (store) {
String alias = rootCert == null ? null : store.getCertificateAlias(rootCert);
if (alias != null)
return store.getCertificate(alias);
else if (rootCert != certChain[i]) {
alias = store.getCertificateAlias(certChain[i]);
if (alias != null)
return store.getCertificate(alias);
}
}
}
} catch (KeyStoreException e) {
throw new IOException(e.getMessage());
} catch (GeneralSecurityException e) {
SignedBundleHook.log(e.getMessage(), FrameworkLogEntry.WARNING, e);
return null;
}
return null;
}
|
diff --git a/src/main/java/biomesoplenty/world/WorldTypeSize.java b/src/main/java/biomesoplenty/world/WorldTypeSize.java
index 09d72b305..a17529b1b 100644
--- a/src/main/java/biomesoplenty/world/WorldTypeSize.java
+++ b/src/main/java/biomesoplenty/world/WorldTypeSize.java
@@ -1,35 +1,36 @@
package biomesoplenty.world;
import net.minecraft.world.WorldProviderHell;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.terraingen.WorldTypeEvent;
import biomesoplenty.configuration.BOPConfigurationTerrainGen;
public class WorldTypeSize
{
@ForgeSubscribe
public void BiomeSize(WorldTypeEvent.BiomeSize event)
{
- if (event.worldType.getWorldTypeName() == "BIOMESOP") {
+ if (event.worldType.getWorldTypeName() == "BIOMESOP" || event.worldType.getWorldTypeName() == "ATG")
+ {
event.newSize = (byte)BOPConfigurationTerrainGen.biomeSize;
if (BOPConfigurationTerrainGen.netherOverride)
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderBOPhell.class, true);
}
}
else if (BOPConfigurationTerrainGen.netherOverride && BOPConfigurationTerrainGen.addToDefault)
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderBOPhell.class, true);
}
else
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderHell.class, true);
}
}
}
| true | true | public void BiomeSize(WorldTypeEvent.BiomeSize event)
{
if (event.worldType.getWorldTypeName() == "BIOMESOP") {
event.newSize = (byte)BOPConfigurationTerrainGen.biomeSize;
if (BOPConfigurationTerrainGen.netherOverride)
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderBOPhell.class, true);
}
}
else if (BOPConfigurationTerrainGen.netherOverride && BOPConfigurationTerrainGen.addToDefault)
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderBOPhell.class, true);
}
else
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderHell.class, true);
}
}
| public void BiomeSize(WorldTypeEvent.BiomeSize event)
{
if (event.worldType.getWorldTypeName() == "BIOMESOP" || event.worldType.getWorldTypeName() == "ATG")
{
event.newSize = (byte)BOPConfigurationTerrainGen.biomeSize;
if (BOPConfigurationTerrainGen.netherOverride)
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderBOPhell.class, true);
}
}
else if (BOPConfigurationTerrainGen.netherOverride && BOPConfigurationTerrainGen.addToDefault)
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderBOPhell.class, true);
}
else
{
DimensionManager.unregisterProviderType(-1);
DimensionManager.registerProviderType(-1, WorldProviderHell.class, true);
}
}
|
diff --git a/mes-plugins/mes-plugins-technologies/src/test/java/com/qcadoo/mes/technologies/TechnologyServiceTest.java b/mes-plugins/mes-plugins-technologies/src/test/java/com/qcadoo/mes/technologies/TechnologyServiceTest.java
index f994409984..6c52a595bc 100644
--- a/mes-plugins/mes-plugins-technologies/src/test/java/com/qcadoo/mes/technologies/TechnologyServiceTest.java
+++ b/mes-plugins/mes-plugins-technologies/src/test/java/com/qcadoo/mes/technologies/TechnologyServiceTest.java
@@ -1,100 +1,100 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.1.2
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.technologies;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.math.BigDecimal;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.qcadoo.model.api.Entity;
import com.qcadoo.model.api.EntityList;
public class TechnologyServiceTest {
TechnologyService technologyService;
@Mock
Entity opComp1, opComp2;
@Mock
Entity product1, product2;
@Mock
Entity prodOutComp1, prodOutComp2;
@Mock
Entity prodInComp1;
private static EntityList mockEntityIterator(List<Entity> entities) {
EntityList entityList = mock(EntityList.class);
when(entityList.iterator()).thenReturn(entities.iterator());
return entityList;
}
@Before
public void init() {
technologyService = new TechnologyService();
MockitoAnnotations.initMocks(this);
- when(product1.getId()).thenReturn(1l);
- when(product2.getId()).thenReturn(2l);
+ when(product1.getId()).thenReturn(1L);
+ when(product2.getId()).thenReturn(2L);
when(opComp1.getBelongsToField("parent")).thenReturn(null);
when(opComp2.getBelongsToField("parent")).thenReturn(opComp1);
EntityList opComp1Children = mockEntityIterator(asList(opComp2));
when(opComp1.getHasManyField("children")).thenReturn(opComp1Children);
when(prodOutComp1.getBelongsToField("product")).thenReturn(product1);
when(prodOutComp2.getBelongsToField("product")).thenReturn(product2);
when(prodInComp1.getBelongsToField("product")).thenReturn(product1);
when(prodOutComp1.getField("quantity")).thenReturn(new BigDecimal(10));
EntityList opComp1prodIns = mockEntityIterator(asList(prodInComp1));
when(opComp1.getHasManyField("operationProductInComponents")).thenReturn(opComp1prodIns);
EntityList opComp2prodOuts = mockEntityIterator(asList(prodOutComp1, prodOutComp2));
when(opComp2.getHasManyField("operationProductOutComponents")).thenReturn(opComp2prodOuts);
}
@Test
public void shouldReturnOutputProductCountForOperationComponent() {
// when
BigDecimal count = technologyService.getProductCountForOperationComponent(opComp2);
// then
assertEquals(new BigDecimal(10), count);
}
}
| true | true | public void init() {
technologyService = new TechnologyService();
MockitoAnnotations.initMocks(this);
when(product1.getId()).thenReturn(1l);
when(product2.getId()).thenReturn(2l);
when(opComp1.getBelongsToField("parent")).thenReturn(null);
when(opComp2.getBelongsToField("parent")).thenReturn(opComp1);
EntityList opComp1Children = mockEntityIterator(asList(opComp2));
when(opComp1.getHasManyField("children")).thenReturn(opComp1Children);
when(prodOutComp1.getBelongsToField("product")).thenReturn(product1);
when(prodOutComp2.getBelongsToField("product")).thenReturn(product2);
when(prodInComp1.getBelongsToField("product")).thenReturn(product1);
when(prodOutComp1.getField("quantity")).thenReturn(new BigDecimal(10));
EntityList opComp1prodIns = mockEntityIterator(asList(prodInComp1));
when(opComp1.getHasManyField("operationProductInComponents")).thenReturn(opComp1prodIns);
EntityList opComp2prodOuts = mockEntityIterator(asList(prodOutComp1, prodOutComp2));
when(opComp2.getHasManyField("operationProductOutComponents")).thenReturn(opComp2prodOuts);
}
| public void init() {
technologyService = new TechnologyService();
MockitoAnnotations.initMocks(this);
when(product1.getId()).thenReturn(1L);
when(product2.getId()).thenReturn(2L);
when(opComp1.getBelongsToField("parent")).thenReturn(null);
when(opComp2.getBelongsToField("parent")).thenReturn(opComp1);
EntityList opComp1Children = mockEntityIterator(asList(opComp2));
when(opComp1.getHasManyField("children")).thenReturn(opComp1Children);
when(prodOutComp1.getBelongsToField("product")).thenReturn(product1);
when(prodOutComp2.getBelongsToField("product")).thenReturn(product2);
when(prodInComp1.getBelongsToField("product")).thenReturn(product1);
when(prodOutComp1.getField("quantity")).thenReturn(new BigDecimal(10));
EntityList opComp1prodIns = mockEntityIterator(asList(prodInComp1));
when(opComp1.getHasManyField("operationProductInComponents")).thenReturn(opComp1prodIns);
EntityList opComp2prodOuts = mockEntityIterator(asList(prodOutComp1, prodOutComp2));
when(opComp2.getHasManyField("operationProductOutComponents")).thenReturn(opComp2prodOuts);
}
|
diff --git a/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/WorkspaceMojo.java b/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/WorkspaceMojo.java
index 8efa8ed013..e7e52f19b6 100644
--- a/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/WorkspaceMojo.java
+++ b/deegree-misc/deegree-maven-plugin/src/main/java/org/deegree/maven/WorkspaceMojo.java
@@ -1,138 +1,139 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.maven;
import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.h2.util.IOUtils.copy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.artifact.AttachedArtifact;
/**
* @goal attach-workspace
* @phase package
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class WorkspaceMojo extends AbstractMojo {
/**
* @parameter default-value="${project}"
* @required
* @readonly
*/
private MavenProject project;
private void zip( File f, ZipOutputStream out, URI workspace )
throws IOException {
if ( f.getName().equalsIgnoreCase( ".svn" ) ) {
return;
}
String name = workspace.relativize( f.getAbsoluteFile().toURI() ).toString();
if ( f.isDirectory() ) {
ZipEntry e = new ZipEntry( name );
out.putNextEntry( e );
File[] fs = f.listFiles();
if ( fs != null ) {
for ( File f2 : fs ) {
zip( f2, out, workspace );
}
}
} else {
ZipEntry e = new ZipEntry( name );
out.putNextEntry( e );
InputStream is = null;
try {
is = new FileInputStream( f );
copy( is, out );
} finally {
closeQuietly( is );
}
}
}
public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
File dir = new File( project.getBasedir(), "src/main/webapp/WEB-INF/workspace" );
if ( !dir.isDirectory() ) {
dir = new File( project.getBasedir(), "src/main/webapp/WEB-INF/conf" );
}
ZipOutputStream out = null;
try {
- if ( !new File( project.getBasedir(), "target" ).mkdirs() ) {
+ File target = new File( project.getBasedir(), "target" );
+ if ( !target.exists() && !target.mkdirs() ) {
throw new MojoFailureException( "Could not create target directory!" );
}
File workspaceFile = new File( project.getBasedir(), "target/" + project.getArtifactId() + "-"
+ project.getVersion() + "-workspace.zip" );
OutputStream os = new FileOutputStream( workspaceFile );
out = new ZipOutputStream( os );
zip( dir, out, dir.getAbsoluteFile().toURI() );
log.info( "Attaching " + workspaceFile );
Artifact artifact = new AttachedArtifact( project.getArtifact(), "zip", "workspace",
new DefaultArtifactHandler( "zip" ) );
artifact.setFile( workspaceFile );
artifact.setResolved( true );
project.addAttachedArtifact( artifact );
} catch ( IOException e ) {
log.debug( e );
throw new MojoFailureException( "Could not create workspace zip artifact: " + e.getLocalizedMessage() );
} finally {
closeQuietly( out );
}
}
}
| true | true | public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
File dir = new File( project.getBasedir(), "src/main/webapp/WEB-INF/workspace" );
if ( !dir.isDirectory() ) {
dir = new File( project.getBasedir(), "src/main/webapp/WEB-INF/conf" );
}
ZipOutputStream out = null;
try {
if ( !new File( project.getBasedir(), "target" ).mkdirs() ) {
throw new MojoFailureException( "Could not create target directory!" );
}
File workspaceFile = new File( project.getBasedir(), "target/" + project.getArtifactId() + "-"
+ project.getVersion() + "-workspace.zip" );
OutputStream os = new FileOutputStream( workspaceFile );
out = new ZipOutputStream( os );
zip( dir, out, dir.getAbsoluteFile().toURI() );
log.info( "Attaching " + workspaceFile );
Artifact artifact = new AttachedArtifact( project.getArtifact(), "zip", "workspace",
new DefaultArtifactHandler( "zip" ) );
artifact.setFile( workspaceFile );
artifact.setResolved( true );
project.addAttachedArtifact( artifact );
} catch ( IOException e ) {
log.debug( e );
throw new MojoFailureException( "Could not create workspace zip artifact: " + e.getLocalizedMessage() );
} finally {
closeQuietly( out );
}
}
| public void execute()
throws MojoExecutionException, MojoFailureException {
Log log = getLog();
File dir = new File( project.getBasedir(), "src/main/webapp/WEB-INF/workspace" );
if ( !dir.isDirectory() ) {
dir = new File( project.getBasedir(), "src/main/webapp/WEB-INF/conf" );
}
ZipOutputStream out = null;
try {
File target = new File( project.getBasedir(), "target" );
if ( !target.exists() && !target.mkdirs() ) {
throw new MojoFailureException( "Could not create target directory!" );
}
File workspaceFile = new File( project.getBasedir(), "target/" + project.getArtifactId() + "-"
+ project.getVersion() + "-workspace.zip" );
OutputStream os = new FileOutputStream( workspaceFile );
out = new ZipOutputStream( os );
zip( dir, out, dir.getAbsoluteFile().toURI() );
log.info( "Attaching " + workspaceFile );
Artifact artifact = new AttachedArtifact( project.getArtifact(), "zip", "workspace",
new DefaultArtifactHandler( "zip" ) );
artifact.setFile( workspaceFile );
artifact.setResolved( true );
project.addAttachedArtifact( artifact );
} catch ( IOException e ) {
log.debug( e );
throw new MojoFailureException( "Could not create workspace zip artifact: " + e.getLocalizedMessage() );
} finally {
closeQuietly( out );
}
}
|
diff --git a/src/main/java/me/botsko/dhmcdeath/DeathConfig.java b/src/main/java/me/botsko/dhmcdeath/DeathConfig.java
index 7a21f16..1b3c1fc 100644
--- a/src/main/java/me/botsko/dhmcdeath/DeathConfig.java
+++ b/src/main/java/me/botsko/dhmcdeath/DeathConfig.java
@@ -1,192 +1,192 @@
package me.botsko.dhmcdeath;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.configuration.file.FileConfiguration;
public class DeathConfig {
/**
*
* @param plugin
*/
public static FileConfiguration init( DhmcDeath plugin ){
FileConfiguration config = plugin.getConfig();
// other configs
config.addDefault("debug", false );
// Base config
config.addDefault("messages.allow_cross_world", false );
config.addDefault("messages.hear_distance", 50 );
config.addDefault("messages.log_deaths", true );
config.addDefault("allow_deathpoint_tp_on_pvp", false );
// Set initial methods as enabled
config.addDefault("messages.custom.enabled", true );
config.addDefault("messages.cactus.enabled", true );
config.addDefault("messages.drowning.enabled", true );
config.addDefault("messages.fall.enabled", true );
config.addDefault("messages.fire.enabled", true );
config.addDefault("messages.lava.enabled", true );
config.addDefault("messages.lightning.enabled", true );
config.addDefault("messages.mob.enabled", true );
config.addDefault("messages.poison.enabled", true );
config.addDefault("messages.pvp.enabled", true );
config.addDefault("messages.starvation.enabled", true );
config.addDefault("messages.suffocation.enabled", true );
config.addDefault("messages.suicide.enabled", true );
config.addDefault("messages.tnt.enabled", true );
config.addDefault("messages.void.enabled", true );
config.addDefault("messages.default.enabled", true );
List<String> cactus=new ArrayList<String>();
cactus.add("&3%d &cdied from a cactus. We know, that's lame.");
cactus.add("&3%d &cpoked a cactus, but the cactus poked back.");
config.addDefault("messages.cactus.messages", cactus );
List<String> drowning=new ArrayList<String>();
drowning.add("&3%d &cdrowned.");
drowning.add("&3%d &cis swimming with the fishes.");
drowning.add("&3%d &ctook a long walk off a short pier.");
config.addDefault("messages.drowning.messages", drowning );
List<String> fall=new ArrayList<String>();
fall.add("&3%d &cfell to his ultimate demise.");
fall.add("&3%d &chit the ground too hard.");
fall.add("&3%d &cperished from a brutal fall.");
fall.add("&3%d &csuccumbed to gravity.");
fall.add("&3%d &cfinally experienced terminal velocity.");
fall.add("&3%d &cwent skydiving, forgot the parachute.");
fall.add("&cWe'll hold a moment of silence while we laugh at your falling death, &3%d.");
fall.add("&cAttempting a high-wire stunt yet again, &3%d &cslipped, and died.");
fall.add("&cSomehow tree tops are immune to gravity. &3%d &cis not.");
fall.add("&cNice going &3%d, &cyou've fallen. You're in a group that includes sand, and gravel - the losers of three.");
fall.add("&cWe're here today to mourn the loss of &3%d&c. He is survived by his Nyan Cat and Creeper statues.");
fall.add("&cLike everything in life, &3%d &cchose the most average, unexciting, unadventerous death - falling. Whoopie.");
fall.add("&cOh man that was hard fall &3%d&c! You ok? &3%d&c? How many fingers dude? Um, dude? Oh sh...");
fall.add("&3%d &chad a whoopsie-daisy!");
fall.add("&3%d &cwas testing gravity. Yup, still works.");
fall.add("&cAlthough &3%d's &cbody lies on the ground somewhere, the question stands. Will it blend?");
config.addDefault("messages.fall.messages", fall );
List<String> fire=new ArrayList<String>();
fire.add("&3%d &cburned to death.");
fire.add("&3%d &cforgot how to stop, drop and roll.");
fire.add("&3%d &cspontaneiously combusted, or possibly walked into fire.");
fire.add("&3%d &cbecame a human torch. Not a very long-lasting one either.");
fire.add("&cNot only did you burn up &3%d&c, but you may have started a forest fire. Nice going.");
fire.add("&cYou are not a replacement for coal, &3%d&c. I'm not sure that even death can teach you that lesson.");
fire.add("&cTaking himself out of the gene pool for us, &3%d &cburned to death. Good job!");
config.addDefault("messages.fire.messages", fire );
List<String> lava=new ArrayList<String>();
lava.add("&3%d &cwas killed by lava.");
lava.add("&3%d &cbecame obsidian.");
lava.add("&3%d &ctook a bath in a lake of fire.");
lava.add("&3%d &clost an entire inventory to lava. He died too, but man, loosing your stuff's a bummer!");
lava.add("&cI told you not to dig straight down &3%d&c. Now look what happened.");
lava.add("&cLook &3%d&c, I'm sorry I boiled you to death. I just wanted a friend. No one likes me. - Your Best Buddy, Lava.");
lava.add("&cThen &3%d &csaid \"Take my picture in front of this pit of boiling, killer lava.\"");
config.addDefault("messages.lava.messages", lava );
List<String> lightning=new ArrayList<String>();
lightning.add("%d was struck with a bolt of inspiration. Wait, nevermind. Lightning.");
config.addDefault("messages.lightning.messages", lightning );
List<String> mob=new ArrayList<String>();
mob.add("&3%d &cwas ravaged by &3%a&c.");
mob.add("&3%d &cdied after encountering the fierce &3%a&c.");
mob.add("&3%d &cwas killed by an angry &3%a&c.");
mob.add("&cIt was a horrible death for &3%d &c- ravaged by a &3%a&c.");
mob.add("&cDinner time for &3%a&c. Cooked pork for the main course, &3%d &cfor dessert.");
mob.add("&3%d &cwent off into the woods alone and shall never return. Until respawn.");
mob.add("&cWhile hunting, &3%d &cwas unaware that a &3%a &cwas hunting him. Rest in pieces.");
mob.add("&cWe have unconfirmed reports that &3%d &cwas attacked by an &3%a.");
mob.add("&cLook &3%d&c, I'm sorry I killed you. I just wanted a friend. No one likes me. - Your Best Buddy, &3%a&c.");
mob.add("&cSomething killed &3%d&c!");
mob.add("&cDear &3%d&c, good luck finding your stuff. - &3%a&c.");
mob.add("&3%d &cwas ravaged by &3%a&c.");
config.addDefault("messages.mob.messages", mob );
// MOB SPECIFIC TYPES
List<String> zombie=new ArrayList<String>();
zombie.add("&cHaving not seen the plethora of zombie movies, &3%d &cwas amazingly unaware of how to escape.");
zombie.add("&cPoor &3%d &c- that zombie only wanted a hug! That's why his arms were stretched out.");
config.addDefault("messages.mob.zombie.messages", zombie );
List<String> creeper=new ArrayList<String>();
creeper.add("&3%d &cwas creeper bombed.");
creeper.add("&3%d &chugged a creeper.");
creeper.add("&cSorry you died &3%d&c, a creeper's gonna creep!");
creeper.add("&3%d &cwas testing a new creeper-proof suit. It didn't work.");
creeper.add("&3%d &cwas not involved in any explosion, nor are we able to confirm the existence of the \"creeper\". Move along.");
creeper.add("&cDue to the laws of physics, the sound of a creeper explosion only reached &3%d &cafter he died from it.");
creeper.add("&cHell hath no fury like a creeper scorned. We drink to thy untimely end, lord &3%d&c.");
creeper.add("&cI'm sorry &3%d&c, that's the only birthday gift Creepers know how to give. ;(");
config.addDefault("messages.mob.creeper.messages", creeper );
// posion
List<String> pvp=new ArrayList<String>();
pvp.add("&3%d &cwas just murdered by &3%a&c, using &3%i&c.");
pvp.add("&3%d &cdied, by &3%a's %i.");
pvp.add("&3%a &ckilled &3%d &cwielding &3%i");
- pvp.add("&cYou think it was &3%a who &ckilled &3%d&c? Nope, Chuck Testa.");
+ pvp.add("&cYou think it was &3%a &cwho killed &3%d&c? Nope, Chuck Testa.");
pvp.add("&cIt was a bitter end for &3%d&c, but &3%a &cwon victoriously.");
pvp.add("&cEmbarrassingly, &3%d &cdied of fright before &3%a &ccould even raise his weapon.");
pvp.add("&3%a &cstruck the mighty blow and ended &3%d&c.");
pvp.add("&3%d &cnever saw &3%a &ccoming.");
pvp.add("&3%a &cdelivered the fatal blow on &3%d&c.");
pvp.add("&3%d's &cinventory now belongs to &3%a&c.");
pvp.add("&3%a &ctaught &3%d &cthe true meaning of PVP.");
pvp.add("&cIn the case of &3%d &cv. &3%a&c, &3%d &cis suing on charges of voluntary manslaughter. This judge finds &3%a &cguilty of BEING AWESOME!");
pvp.add("&cWhat is this, like death number ten for &3%d&c? Ask &3%a&c.");
config.addDefault("messages.pvp.messages", pvp );
List<String> starvation=new ArrayList<String>();
starvation.add("&3%d &cstarved to death.");
starvation.add("&3%d &cstarved to death. Because food is *so* hard to find.");
config.addDefault("messages.starvation.messages", starvation );
List<String> suffocation=new ArrayList<String>();
suffocation.add("&3%d &csuffocated.");
config.addDefault("messages.suffocation.messages",suffocation );
List<String> suicide=new ArrayList<String>();
suicide.add("&3%d &ckilled himself.");
suicide.add("&3%d &cended it all. Goodbye cruel world!");
config.addDefault("messages.suicide.messages", suicide );
List<String> tnt=new ArrayList<String>();
tnt.add("&3%d &cblew up.");
tnt.add("&3%d &cwas blown to tiny bits.");
config.addDefault("messages.tnt.messages", tnt );
List<String> thevoid=new ArrayList<String>();
thevoid.add("&3%d &cceased to exist. Thanks void!");
thevoid.add("&3%d &cpassed the event horizon.");
config.addDefault("messages.void.messages", thevoid );
List<String> defaultmsg=new ArrayList<String>();
defaultmsg.add("&3%d &cpossibly died - we're looking into it.");
defaultmsg.add("&cNothing happened. &3%d &cis totally ok. Why are you asking?");
config.addDefault("messages.default.messages",defaultmsg );
// Copy defaults
config.options().copyDefaults(true);
// save the defaults/config
plugin.saveConfig();
return config;
}
}
| true | true | public static FileConfiguration init( DhmcDeath plugin ){
FileConfiguration config = plugin.getConfig();
// other configs
config.addDefault("debug", false );
// Base config
config.addDefault("messages.allow_cross_world", false );
config.addDefault("messages.hear_distance", 50 );
config.addDefault("messages.log_deaths", true );
config.addDefault("allow_deathpoint_tp_on_pvp", false );
// Set initial methods as enabled
config.addDefault("messages.custom.enabled", true );
config.addDefault("messages.cactus.enabled", true );
config.addDefault("messages.drowning.enabled", true );
config.addDefault("messages.fall.enabled", true );
config.addDefault("messages.fire.enabled", true );
config.addDefault("messages.lava.enabled", true );
config.addDefault("messages.lightning.enabled", true );
config.addDefault("messages.mob.enabled", true );
config.addDefault("messages.poison.enabled", true );
config.addDefault("messages.pvp.enabled", true );
config.addDefault("messages.starvation.enabled", true );
config.addDefault("messages.suffocation.enabled", true );
config.addDefault("messages.suicide.enabled", true );
config.addDefault("messages.tnt.enabled", true );
config.addDefault("messages.void.enabled", true );
config.addDefault("messages.default.enabled", true );
List<String> cactus=new ArrayList<String>();
cactus.add("&3%d &cdied from a cactus. We know, that's lame.");
cactus.add("&3%d &cpoked a cactus, but the cactus poked back.");
config.addDefault("messages.cactus.messages", cactus );
List<String> drowning=new ArrayList<String>();
drowning.add("&3%d &cdrowned.");
drowning.add("&3%d &cis swimming with the fishes.");
drowning.add("&3%d &ctook a long walk off a short pier.");
config.addDefault("messages.drowning.messages", drowning );
List<String> fall=new ArrayList<String>();
fall.add("&3%d &cfell to his ultimate demise.");
fall.add("&3%d &chit the ground too hard.");
fall.add("&3%d &cperished from a brutal fall.");
fall.add("&3%d &csuccumbed to gravity.");
fall.add("&3%d &cfinally experienced terminal velocity.");
fall.add("&3%d &cwent skydiving, forgot the parachute.");
fall.add("&cWe'll hold a moment of silence while we laugh at your falling death, &3%d.");
fall.add("&cAttempting a high-wire stunt yet again, &3%d &cslipped, and died.");
fall.add("&cSomehow tree tops are immune to gravity. &3%d &cis not.");
fall.add("&cNice going &3%d, &cyou've fallen. You're in a group that includes sand, and gravel - the losers of three.");
fall.add("&cWe're here today to mourn the loss of &3%d&c. He is survived by his Nyan Cat and Creeper statues.");
fall.add("&cLike everything in life, &3%d &cchose the most average, unexciting, unadventerous death - falling. Whoopie.");
fall.add("&cOh man that was hard fall &3%d&c! You ok? &3%d&c? How many fingers dude? Um, dude? Oh sh...");
fall.add("&3%d &chad a whoopsie-daisy!");
fall.add("&3%d &cwas testing gravity. Yup, still works.");
fall.add("&cAlthough &3%d's &cbody lies on the ground somewhere, the question stands. Will it blend?");
config.addDefault("messages.fall.messages", fall );
List<String> fire=new ArrayList<String>();
fire.add("&3%d &cburned to death.");
fire.add("&3%d &cforgot how to stop, drop and roll.");
fire.add("&3%d &cspontaneiously combusted, or possibly walked into fire.");
fire.add("&3%d &cbecame a human torch. Not a very long-lasting one either.");
fire.add("&cNot only did you burn up &3%d&c, but you may have started a forest fire. Nice going.");
fire.add("&cYou are not a replacement for coal, &3%d&c. I'm not sure that even death can teach you that lesson.");
fire.add("&cTaking himself out of the gene pool for us, &3%d &cburned to death. Good job!");
config.addDefault("messages.fire.messages", fire );
List<String> lava=new ArrayList<String>();
lava.add("&3%d &cwas killed by lava.");
lava.add("&3%d &cbecame obsidian.");
lava.add("&3%d &ctook a bath in a lake of fire.");
lava.add("&3%d &clost an entire inventory to lava. He died too, but man, loosing your stuff's a bummer!");
lava.add("&cI told you not to dig straight down &3%d&c. Now look what happened.");
lava.add("&cLook &3%d&c, I'm sorry I boiled you to death. I just wanted a friend. No one likes me. - Your Best Buddy, Lava.");
lava.add("&cThen &3%d &csaid \"Take my picture in front of this pit of boiling, killer lava.\"");
config.addDefault("messages.lava.messages", lava );
List<String> lightning=new ArrayList<String>();
lightning.add("%d was struck with a bolt of inspiration. Wait, nevermind. Lightning.");
config.addDefault("messages.lightning.messages", lightning );
List<String> mob=new ArrayList<String>();
mob.add("&3%d &cwas ravaged by &3%a&c.");
mob.add("&3%d &cdied after encountering the fierce &3%a&c.");
mob.add("&3%d &cwas killed by an angry &3%a&c.");
mob.add("&cIt was a horrible death for &3%d &c- ravaged by a &3%a&c.");
mob.add("&cDinner time for &3%a&c. Cooked pork for the main course, &3%d &cfor dessert.");
mob.add("&3%d &cwent off into the woods alone and shall never return. Until respawn.");
mob.add("&cWhile hunting, &3%d &cwas unaware that a &3%a &cwas hunting him. Rest in pieces.");
mob.add("&cWe have unconfirmed reports that &3%d &cwas attacked by an &3%a.");
mob.add("&cLook &3%d&c, I'm sorry I killed you. I just wanted a friend. No one likes me. - Your Best Buddy, &3%a&c.");
mob.add("&cSomething killed &3%d&c!");
mob.add("&cDear &3%d&c, good luck finding your stuff. - &3%a&c.");
mob.add("&3%d &cwas ravaged by &3%a&c.");
config.addDefault("messages.mob.messages", mob );
// MOB SPECIFIC TYPES
List<String> zombie=new ArrayList<String>();
zombie.add("&cHaving not seen the plethora of zombie movies, &3%d &cwas amazingly unaware of how to escape.");
zombie.add("&cPoor &3%d &c- that zombie only wanted a hug! That's why his arms were stretched out.");
config.addDefault("messages.mob.zombie.messages", zombie );
List<String> creeper=new ArrayList<String>();
creeper.add("&3%d &cwas creeper bombed.");
creeper.add("&3%d &chugged a creeper.");
creeper.add("&cSorry you died &3%d&c, a creeper's gonna creep!");
creeper.add("&3%d &cwas testing a new creeper-proof suit. It didn't work.");
creeper.add("&3%d &cwas not involved in any explosion, nor are we able to confirm the existence of the \"creeper\". Move along.");
creeper.add("&cDue to the laws of physics, the sound of a creeper explosion only reached &3%d &cafter he died from it.");
creeper.add("&cHell hath no fury like a creeper scorned. We drink to thy untimely end, lord &3%d&c.");
creeper.add("&cI'm sorry &3%d&c, that's the only birthday gift Creepers know how to give. ;(");
config.addDefault("messages.mob.creeper.messages", creeper );
// posion
List<String> pvp=new ArrayList<String>();
pvp.add("&3%d &cwas just murdered by &3%a&c, using &3%i&c.");
pvp.add("&3%d &cdied, by &3%a's %i.");
pvp.add("&3%a &ckilled &3%d &cwielding &3%i");
pvp.add("&cYou think it was &3%a who &ckilled &3%d&c? Nope, Chuck Testa.");
pvp.add("&cIt was a bitter end for &3%d&c, but &3%a &cwon victoriously.");
pvp.add("&cEmbarrassingly, &3%d &cdied of fright before &3%a &ccould even raise his weapon.");
pvp.add("&3%a &cstruck the mighty blow and ended &3%d&c.");
pvp.add("&3%d &cnever saw &3%a &ccoming.");
pvp.add("&3%a &cdelivered the fatal blow on &3%d&c.");
pvp.add("&3%d's &cinventory now belongs to &3%a&c.");
pvp.add("&3%a &ctaught &3%d &cthe true meaning of PVP.");
pvp.add("&cIn the case of &3%d &cv. &3%a&c, &3%d &cis suing on charges of voluntary manslaughter. This judge finds &3%a &cguilty of BEING AWESOME!");
pvp.add("&cWhat is this, like death number ten for &3%d&c? Ask &3%a&c.");
config.addDefault("messages.pvp.messages", pvp );
List<String> starvation=new ArrayList<String>();
starvation.add("&3%d &cstarved to death.");
starvation.add("&3%d &cstarved to death. Because food is *so* hard to find.");
config.addDefault("messages.starvation.messages", starvation );
List<String> suffocation=new ArrayList<String>();
suffocation.add("&3%d &csuffocated.");
config.addDefault("messages.suffocation.messages",suffocation );
List<String> suicide=new ArrayList<String>();
suicide.add("&3%d &ckilled himself.");
suicide.add("&3%d &cended it all. Goodbye cruel world!");
config.addDefault("messages.suicide.messages", suicide );
List<String> tnt=new ArrayList<String>();
tnt.add("&3%d &cblew up.");
tnt.add("&3%d &cwas blown to tiny bits.");
config.addDefault("messages.tnt.messages", tnt );
List<String> thevoid=new ArrayList<String>();
thevoid.add("&3%d &cceased to exist. Thanks void!");
thevoid.add("&3%d &cpassed the event horizon.");
config.addDefault("messages.void.messages", thevoid );
List<String> defaultmsg=new ArrayList<String>();
defaultmsg.add("&3%d &cpossibly died - we're looking into it.");
defaultmsg.add("&cNothing happened. &3%d &cis totally ok. Why are you asking?");
config.addDefault("messages.default.messages",defaultmsg );
// Copy defaults
config.options().copyDefaults(true);
// save the defaults/config
plugin.saveConfig();
return config;
}
| public static FileConfiguration init( DhmcDeath plugin ){
FileConfiguration config = plugin.getConfig();
// other configs
config.addDefault("debug", false );
// Base config
config.addDefault("messages.allow_cross_world", false );
config.addDefault("messages.hear_distance", 50 );
config.addDefault("messages.log_deaths", true );
config.addDefault("allow_deathpoint_tp_on_pvp", false );
// Set initial methods as enabled
config.addDefault("messages.custom.enabled", true );
config.addDefault("messages.cactus.enabled", true );
config.addDefault("messages.drowning.enabled", true );
config.addDefault("messages.fall.enabled", true );
config.addDefault("messages.fire.enabled", true );
config.addDefault("messages.lava.enabled", true );
config.addDefault("messages.lightning.enabled", true );
config.addDefault("messages.mob.enabled", true );
config.addDefault("messages.poison.enabled", true );
config.addDefault("messages.pvp.enabled", true );
config.addDefault("messages.starvation.enabled", true );
config.addDefault("messages.suffocation.enabled", true );
config.addDefault("messages.suicide.enabled", true );
config.addDefault("messages.tnt.enabled", true );
config.addDefault("messages.void.enabled", true );
config.addDefault("messages.default.enabled", true );
List<String> cactus=new ArrayList<String>();
cactus.add("&3%d &cdied from a cactus. We know, that's lame.");
cactus.add("&3%d &cpoked a cactus, but the cactus poked back.");
config.addDefault("messages.cactus.messages", cactus );
List<String> drowning=new ArrayList<String>();
drowning.add("&3%d &cdrowned.");
drowning.add("&3%d &cis swimming with the fishes.");
drowning.add("&3%d &ctook a long walk off a short pier.");
config.addDefault("messages.drowning.messages", drowning );
List<String> fall=new ArrayList<String>();
fall.add("&3%d &cfell to his ultimate demise.");
fall.add("&3%d &chit the ground too hard.");
fall.add("&3%d &cperished from a brutal fall.");
fall.add("&3%d &csuccumbed to gravity.");
fall.add("&3%d &cfinally experienced terminal velocity.");
fall.add("&3%d &cwent skydiving, forgot the parachute.");
fall.add("&cWe'll hold a moment of silence while we laugh at your falling death, &3%d.");
fall.add("&cAttempting a high-wire stunt yet again, &3%d &cslipped, and died.");
fall.add("&cSomehow tree tops are immune to gravity. &3%d &cis not.");
fall.add("&cNice going &3%d, &cyou've fallen. You're in a group that includes sand, and gravel - the losers of three.");
fall.add("&cWe're here today to mourn the loss of &3%d&c. He is survived by his Nyan Cat and Creeper statues.");
fall.add("&cLike everything in life, &3%d &cchose the most average, unexciting, unadventerous death - falling. Whoopie.");
fall.add("&cOh man that was hard fall &3%d&c! You ok? &3%d&c? How many fingers dude? Um, dude? Oh sh...");
fall.add("&3%d &chad a whoopsie-daisy!");
fall.add("&3%d &cwas testing gravity. Yup, still works.");
fall.add("&cAlthough &3%d's &cbody lies on the ground somewhere, the question stands. Will it blend?");
config.addDefault("messages.fall.messages", fall );
List<String> fire=new ArrayList<String>();
fire.add("&3%d &cburned to death.");
fire.add("&3%d &cforgot how to stop, drop and roll.");
fire.add("&3%d &cspontaneiously combusted, or possibly walked into fire.");
fire.add("&3%d &cbecame a human torch. Not a very long-lasting one either.");
fire.add("&cNot only did you burn up &3%d&c, but you may have started a forest fire. Nice going.");
fire.add("&cYou are not a replacement for coal, &3%d&c. I'm not sure that even death can teach you that lesson.");
fire.add("&cTaking himself out of the gene pool for us, &3%d &cburned to death. Good job!");
config.addDefault("messages.fire.messages", fire );
List<String> lava=new ArrayList<String>();
lava.add("&3%d &cwas killed by lava.");
lava.add("&3%d &cbecame obsidian.");
lava.add("&3%d &ctook a bath in a lake of fire.");
lava.add("&3%d &clost an entire inventory to lava. He died too, but man, loosing your stuff's a bummer!");
lava.add("&cI told you not to dig straight down &3%d&c. Now look what happened.");
lava.add("&cLook &3%d&c, I'm sorry I boiled you to death. I just wanted a friend. No one likes me. - Your Best Buddy, Lava.");
lava.add("&cThen &3%d &csaid \"Take my picture in front of this pit of boiling, killer lava.\"");
config.addDefault("messages.lava.messages", lava );
List<String> lightning=new ArrayList<String>();
lightning.add("%d was struck with a bolt of inspiration. Wait, nevermind. Lightning.");
config.addDefault("messages.lightning.messages", lightning );
List<String> mob=new ArrayList<String>();
mob.add("&3%d &cwas ravaged by &3%a&c.");
mob.add("&3%d &cdied after encountering the fierce &3%a&c.");
mob.add("&3%d &cwas killed by an angry &3%a&c.");
mob.add("&cIt was a horrible death for &3%d &c- ravaged by a &3%a&c.");
mob.add("&cDinner time for &3%a&c. Cooked pork for the main course, &3%d &cfor dessert.");
mob.add("&3%d &cwent off into the woods alone and shall never return. Until respawn.");
mob.add("&cWhile hunting, &3%d &cwas unaware that a &3%a &cwas hunting him. Rest in pieces.");
mob.add("&cWe have unconfirmed reports that &3%d &cwas attacked by an &3%a.");
mob.add("&cLook &3%d&c, I'm sorry I killed you. I just wanted a friend. No one likes me. - Your Best Buddy, &3%a&c.");
mob.add("&cSomething killed &3%d&c!");
mob.add("&cDear &3%d&c, good luck finding your stuff. - &3%a&c.");
mob.add("&3%d &cwas ravaged by &3%a&c.");
config.addDefault("messages.mob.messages", mob );
// MOB SPECIFIC TYPES
List<String> zombie=new ArrayList<String>();
zombie.add("&cHaving not seen the plethora of zombie movies, &3%d &cwas amazingly unaware of how to escape.");
zombie.add("&cPoor &3%d &c- that zombie only wanted a hug! That's why his arms were stretched out.");
config.addDefault("messages.mob.zombie.messages", zombie );
List<String> creeper=new ArrayList<String>();
creeper.add("&3%d &cwas creeper bombed.");
creeper.add("&3%d &chugged a creeper.");
creeper.add("&cSorry you died &3%d&c, a creeper's gonna creep!");
creeper.add("&3%d &cwas testing a new creeper-proof suit. It didn't work.");
creeper.add("&3%d &cwas not involved in any explosion, nor are we able to confirm the existence of the \"creeper\". Move along.");
creeper.add("&cDue to the laws of physics, the sound of a creeper explosion only reached &3%d &cafter he died from it.");
creeper.add("&cHell hath no fury like a creeper scorned. We drink to thy untimely end, lord &3%d&c.");
creeper.add("&cI'm sorry &3%d&c, that's the only birthday gift Creepers know how to give. ;(");
config.addDefault("messages.mob.creeper.messages", creeper );
// posion
List<String> pvp=new ArrayList<String>();
pvp.add("&3%d &cwas just murdered by &3%a&c, using &3%i&c.");
pvp.add("&3%d &cdied, by &3%a's %i.");
pvp.add("&3%a &ckilled &3%d &cwielding &3%i");
pvp.add("&cYou think it was &3%a &cwho killed &3%d&c? Nope, Chuck Testa.");
pvp.add("&cIt was a bitter end for &3%d&c, but &3%a &cwon victoriously.");
pvp.add("&cEmbarrassingly, &3%d &cdied of fright before &3%a &ccould even raise his weapon.");
pvp.add("&3%a &cstruck the mighty blow and ended &3%d&c.");
pvp.add("&3%d &cnever saw &3%a &ccoming.");
pvp.add("&3%a &cdelivered the fatal blow on &3%d&c.");
pvp.add("&3%d's &cinventory now belongs to &3%a&c.");
pvp.add("&3%a &ctaught &3%d &cthe true meaning of PVP.");
pvp.add("&cIn the case of &3%d &cv. &3%a&c, &3%d &cis suing on charges of voluntary manslaughter. This judge finds &3%a &cguilty of BEING AWESOME!");
pvp.add("&cWhat is this, like death number ten for &3%d&c? Ask &3%a&c.");
config.addDefault("messages.pvp.messages", pvp );
List<String> starvation=new ArrayList<String>();
starvation.add("&3%d &cstarved to death.");
starvation.add("&3%d &cstarved to death. Because food is *so* hard to find.");
config.addDefault("messages.starvation.messages", starvation );
List<String> suffocation=new ArrayList<String>();
suffocation.add("&3%d &csuffocated.");
config.addDefault("messages.suffocation.messages",suffocation );
List<String> suicide=new ArrayList<String>();
suicide.add("&3%d &ckilled himself.");
suicide.add("&3%d &cended it all. Goodbye cruel world!");
config.addDefault("messages.suicide.messages", suicide );
List<String> tnt=new ArrayList<String>();
tnt.add("&3%d &cblew up.");
tnt.add("&3%d &cwas blown to tiny bits.");
config.addDefault("messages.tnt.messages", tnt );
List<String> thevoid=new ArrayList<String>();
thevoid.add("&3%d &cceased to exist. Thanks void!");
thevoid.add("&3%d &cpassed the event horizon.");
config.addDefault("messages.void.messages", thevoid );
List<String> defaultmsg=new ArrayList<String>();
defaultmsg.add("&3%d &cpossibly died - we're looking into it.");
defaultmsg.add("&cNothing happened. &3%d &cis totally ok. Why are you asking?");
config.addDefault("messages.default.messages",defaultmsg );
// Copy defaults
config.options().copyDefaults(true);
// save the defaults/config
plugin.saveConfig();
return config;
}
|
diff --git a/fabric/fabric-zookeeper-commands/src/main/java/org/fusesource/fabric/zookeeper/commands/List.java b/fabric/fabric-zookeeper-commands/src/main/java/org/fusesource/fabric/zookeeper/commands/List.java
index 0491a842e..1dc6ab6ab 100644
--- a/fabric/fabric-zookeeper-commands/src/main/java/org/fusesource/fabric/zookeeper/commands/List.java
+++ b/fabric/fabric-zookeeper-commands/src/main/java/org/fusesource/fabric/zookeeper/commands/List.java
@@ -1,76 +1,76 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* 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.fusesource.fabric.zookeeper.commands;
import org.apache.curator.framework.CuratorFramework;
import org.apache.felix.gogo.commands.Argument;
import org.apache.felix.gogo.commands.Command;
import org.apache.felix.gogo.commands.Option;
import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.getAllChildren;
import static org.fusesource.fabric.zookeeper.utils.ZooKeeperUtils.getChildren;
@Command(name = "list", scope = "zk", description = "List a znode's children", detailedDescription = "classpath:list.txt")
public class List extends ZooKeeperCommandSupport {
@Argument(description = "Path of the znode to list")
String path = "/";
@Option(name = "-r", aliases = {"--recursive"}, description = "List children recursively")
boolean recursive = false;
@Option(name="-d", aliases={"--display"}, description="Display a znode's value if set")
boolean display = false;
//TODO - Be good to also have an option to show other ZK attributes for a node similar to ls -la
@Override
protected void doExecute(CuratorFramework zk) throws Exception {
display(zk, path);
}
private java.util.List<String> getPaths(CuratorFramework zk) throws Exception {
if (recursive) {
return getAllChildren(zk, path);
} else {
return getChildren(zk, path);
}
}
protected void display(CuratorFramework curator, String path) throws Exception {
if (!path.endsWith("/")) {
path = path + "/";
}
if (!path.startsWith("/")) {
path = "/" + path;
}
java.util.List<String> paths = getPaths(curator);
for(String p : paths) {
if (display) {
- byte[] data = curator.getData().forPath(path + p);
+ byte[] data = curator.getData().forPath(recursive ? p : path + p);
if (data != null) {
System.out.printf("%s = %s\n", p, new String(data));
} else {
System.out.println(p);
}
} else {
System.out.println(p);
}
}
}
}
| true | true | protected void display(CuratorFramework curator, String path) throws Exception {
if (!path.endsWith("/")) {
path = path + "/";
}
if (!path.startsWith("/")) {
path = "/" + path;
}
java.util.List<String> paths = getPaths(curator);
for(String p : paths) {
if (display) {
byte[] data = curator.getData().forPath(path + p);
if (data != null) {
System.out.printf("%s = %s\n", p, new String(data));
} else {
System.out.println(p);
}
} else {
System.out.println(p);
}
}
}
| protected void display(CuratorFramework curator, String path) throws Exception {
if (!path.endsWith("/")) {
path = path + "/";
}
if (!path.startsWith("/")) {
path = "/" + path;
}
java.util.List<String> paths = getPaths(curator);
for(String p : paths) {
if (display) {
byte[] data = curator.getData().forPath(recursive ? p : path + p);
if (data != null) {
System.out.printf("%s = %s\n", p, new String(data));
} else {
System.out.println(p);
}
} else {
System.out.println(p);
}
}
}
|
diff --git a/src/com/github/zachuorice/brainfuh/Brainfuh.java b/src/com/github/zachuorice/brainfuh/Brainfuh.java
index 2c2d172..daed490 100644
--- a/src/com/github/zachuorice/brainfuh/Brainfuh.java
+++ b/src/com/github/zachuorice/brainfuh/Brainfuh.java
@@ -1,45 +1,48 @@
/*
* Copyright 2012 Zachary Richey <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* Useful static methods for using the library quickly. */
package com.github.zachuorice.brainfuh;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.github.zachuorice.brainfuh.*;
public class Brainfuh
{
static void executeFile(File code) throws IOException
{
if(!code.canRead() || !code.isFile())
throw new IOException();
FileReader code_reader = new FileReader(code);
int data = code_reader.read();
Interpreter interpreter = new Interpreter();
while(data != -1)
+ {
interpreter.feed((char ) data);
+ data = code_reader.read();
+ }
interpreter.execute();
}
static void executeString(String code)
{
Interpreter interpreter = new Interpreter();
interpreter.feed(code);
interpreter.execute();
}
}
| false | true | static void executeFile(File code) throws IOException
{
if(!code.canRead() || !code.isFile())
throw new IOException();
FileReader code_reader = new FileReader(code);
int data = code_reader.read();
Interpreter interpreter = new Interpreter();
while(data != -1)
interpreter.feed((char ) data);
interpreter.execute();
}
| static void executeFile(File code) throws IOException
{
if(!code.canRead() || !code.isFile())
throw new IOException();
FileReader code_reader = new FileReader(code);
int data = code_reader.read();
Interpreter interpreter = new Interpreter();
while(data != -1)
{
interpreter.feed((char ) data);
data = code_reader.read();
}
interpreter.execute();
}
|
diff --git a/dev/core/test/com/google/gwt/dev/shell/remoteui/MessageTransportTest.java b/dev/core/test/com/google/gwt/dev/shell/remoteui/MessageTransportTest.java
index 18647bde6..e5400c44e 100644
--- a/dev/core/test/com/google/gwt/dev/shell/remoteui/MessageTransportTest.java
+++ b/dev/core/test/com/google/gwt/dev/shell/remoteui/MessageTransportTest.java
@@ -1,483 +1,483 @@
package com.google.gwt.dev.shell.remoteui;
import com.google.gwt.dev.shell.remoteui.MessageTransport.RequestException;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message.Failure;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message.Request;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message.Response;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message.Request.DevModeRequest;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message.Request.DevModeRequest.RequestType;
import com.google.gwt.dev.shell.remoteui.RemoteMessageProto.Message.Response.DevModeResponse;
import junit.framework.TestCase;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class MessageTransportTest extends TestCase {
private static class MockNetwork {
private final Socket clientSocket;
private final Socket serverSocket;
private final ServerSocket listenSocket;
public MockNetwork(Socket clientSocket, Socket serverSocket,
ServerSocket listenSocket) {
this.clientSocket = clientSocket;
this.serverSocket = serverSocket;
this.listenSocket = listenSocket;
}
public Socket getClientSocket() {
return clientSocket;
}
public Socket getServerSocket() {
return serverSocket;
}
public void shutdown() {
try {
clientSocket.close();
} catch (IOException e) {
// Ignore
}
try {
serverSocket.close();
} catch (IOException e) {
// Ignore
}
try {
listenSocket.close();
} catch (IOException e) {
// Ignore
}
}
}
private static MockNetwork createMockNetwork() throws IOException,
InterruptedException, ExecutionException {
final ServerSocket listenSocket = new ServerSocket(0);
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<Socket> future = executorService.submit(new Callable<Socket>() {
public Socket call() throws Exception {
return listenSocket.accept();
}
});
Socket clientSocket = new Socket("localhost", listenSocket.getLocalPort());
Socket serverSocket = future.get();
return new MockNetwork(clientSocket, serverSocket, listenSocket);
}
/**
* Tests that sending an async request to a server when the sending stream is
* closed will result in:
*
* 1) A rejection of the request to the executor 2) An ExecutionException on a
* call to future.get()
*
* @throws ExecutionException
* @throws InterruptedException
* @throws IOException
*/
public void testExecuteAsyncRequestWithClosedSendStream() throws IOException,
InterruptedException, ExecutionException {
MockNetwork network = createMockNetwork();
/*
* Define a dummy request processor. The message transport is being set up
* on the client side, which means that it should not be receiving any
* requests (any responses).
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
fail("Should not reach here.");
return null;
}
};
// Set up a transport on the client side
MessageTransport messageTransport = new MessageTransport(
network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
Message.Request.Builder requestMessageBuilder = Message.Request.newBuilder();
requestMessageBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
Message.Request request = requestMessageBuilder.build();
// Close the server's input stream; that will close the client's output
// stream
network.getServerSocket().getInputStream().close();
Future<Response> responseFuture = null;
responseFuture = messageTransport.executeRequestAsync(request);
assertNotNull(responseFuture);
try {
responseFuture.get(2, TimeUnit.SECONDS);
fail("Should have thrown an exception");
} catch (TimeoutException te) {
fail("Should not have timed out");
} catch (ExecutionException e) {
assertTrue("Expected: IllegalStateException, actual:" + e.getCause(),
e.getCause() instanceof IllegalStateException);
} catch (Exception e) {
fail("Should not have thrown any other exception");
}
network.shutdown();
}
/**
* Tests that an async request to a remote server is successfully sent, and
* the server's response is successfully received.
*/
public void testExecuteRequestAsync() throws InterruptedException,
ExecutionException, IOException, TimeoutException {
MockNetwork network = createMockNetwork();
/*
* Define a dummy request processor. The message transport is being set up
* on the client side, which means that it should not be receiving any
* requests (any responses).
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
fail("Should not reach here.");
return null;
}
};
// Set up a transport on the client side
MessageTransport messageTransport = new MessageTransport(
network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor, null);
// Generate a new request
DevModeRequest.Builder devModeRequestBuilder = DevModeRequest.newBuilder();
devModeRequestBuilder.setRequestType(RequestType.CAPABILITY_EXCHANGE);
Message.Request.Builder requestMessageBuilder = Message.Request.newBuilder();
requestMessageBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
requestMessageBuilder.setDevModeRequest(devModeRequestBuilder);
Message.Request request = requestMessageBuilder.build();
// Execute the request on the remote server
Future<Response> responseFuture = messageTransport.executeRequestAsync(request);
assertNotNull(responseFuture);
// Get the request on the server side
Message receivedRequest = Message.parseDelimitedFrom(network.getServerSocket().getInputStream());
assertEquals(receivedRequest.getRequest(), request);
// Generate a response on the server
DevModeResponse.CapabilityExchange.Capability.Builder capabilityBuilder = DevModeResponse.CapabilityExchange.Capability.newBuilder();
capabilityBuilder.setCapability(DevModeRequest.RequestType.RESTART_WEB_SERVER);
DevModeResponse.CapabilityExchange.Builder capabilityExchangeResponseBuilder = DevModeResponse.CapabilityExchange.newBuilder();
capabilityExchangeResponseBuilder.addCapabilities(capabilityBuilder);
DevModeResponse.Builder devModeResponseBuilder = DevModeResponse.newBuilder();
devModeResponseBuilder.setResponseType(DevModeResponse.ResponseType.CAPABILITY_EXCHANGE);
devModeResponseBuilder.setCapabilityExchange(capabilityExchangeResponseBuilder);
Response.Builder responseBuilder = Response.newBuilder();
responseBuilder.setDevModeResponse(devModeResponseBuilder);
Response response = responseBuilder.build();
Message.Builder responseMsgBuilder = Message.newBuilder();
responseMsgBuilder.setMessageType(Message.MessageType.RESPONSE);
// Make sure we set the right message id
responseMsgBuilder.setMessageId(receivedRequest.getMessageId());
responseMsgBuilder.setResponse(response);
Message responseMsg = responseMsgBuilder.build();
// Send the response back to the client
responseMsg.writeDelimitedTo(network.getServerSocket().getOutputStream());
// Make sure that the response received on the client is identical to
// the response sent by the server
assertEquals(responseFuture.get(2, TimeUnit.SECONDS), response);
network.shutdown();
}
/**
* Tests that an async request to a remote server which ends up throwing an
* exception on the server side ends up throwing the proper exception via the
* future that the client is waiting on.
*/
public void testExecuteRequestAsyncServerThrowsException()
throws InterruptedException, ExecutionException, IOException,
TimeoutException {
MockNetwork network = createMockNetwork();
/*
* Define a dummy request processor. The message transport is being set up
* on the client side, which means that it should not be receiving any
* requests (any responses).
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
fail("Should not reach here.");
return null;
}
};
// Set up a message transport on the client side
MessageTransport messageTransport = new MessageTransport(
network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
// Generate a new request
Message.Request.Builder requestMessageBuilder = Message.Request.newBuilder();
requestMessageBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
Message.Request request = requestMessageBuilder.build();
// Execute the request on the remote server
Future<Response> responseFuture = messageTransport.executeRequestAsync(request);
assertNotNull(responseFuture);
// Get the request on the server side
Message receivedRequest = Message.parseDelimitedFrom(network.getServerSocket().getInputStream());
assertEquals(receivedRequest.getRequest(), request);
// Generate a failure response on the server
Failure.Builder failureBuilder = Failure.newBuilder();
failureBuilder.setMessage("Unable to process the request.");
Message.Builder messageBuilder = Message.newBuilder();
// Make sure that we set the matching message id
messageBuilder.setMessageId(receivedRequest.getMessageId());
messageBuilder.setMessageType(Message.MessageType.FAILURE);
messageBuilder.setFailure(failureBuilder);
Message failureMsg = messageBuilder.build();
// Send the failure message back to the client
failureMsg.writeDelimitedTo(network.getServerSocket().getOutputStream());
// Wait for the response on the client. This should result in a
// RequestException being thrown.
try {
responseFuture.get(2, TimeUnit.SECONDS);
fail("Should have thrown an exception");
} catch (TimeoutException te) {
fail("Should not have timed out");
} catch (ExecutionException e) {
// This is where we should hit
- assertTrue("Expected: IllegalStateException, actual:" + e.getCause(),
- e.getCause() instanceof IllegalStateException);
+ assertTrue("Expected: MessageTransport.RequestException, actual:"
+ + e.getCause(), e.getCause() instanceof RequestException);
RequestException re = (RequestException) e.getCause();
assertEquals(re.getMessage(), "Unable to process the request.");
} catch (Exception e) {
fail("Should not have thrown any other exception");
}
network.shutdown();
}
/**
* Tests that a future for an async request to a remote server will be
* interrupted if the server closes the connection before the response is
* received.
*/
public void testExecuteRequestAsyncWithClosedReceiveStreamBeforeResponse()
throws IOException, InterruptedException, ExecutionException,
TimeoutException {
MockNetwork network = createMockNetwork();
/*
* Define a dummy request processor. The message transport is being set up
* on the client side, which means that it should not be receiving any
* requests (any responses).
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
fail("Should not reach here.");
return null;
}
};
// Set up a message transport on the client side
MessageTransport messageTransport = new MessageTransport(
network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
Message.Request.Builder requestMessageBuilder = Message.Request.newBuilder();
requestMessageBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
Message.Request request = requestMessageBuilder.build();
// This will close the client's input stream
network.getServerSocket().getOutputStream().close();
try {
Future<Response> response = messageTransport.executeRequestAsync(request);
response.get(2, TimeUnit.SECONDS);
fail("Should have thrown an exception");
} catch (TimeoutException te) {
fail("Should not have timed out");
} catch (ExecutionException e) {
// This is where we should hit
assertTrue("Expected: IllegalStateException, actual:" + e.getCause(),
e.getCause() instanceof IllegalStateException);
} catch (Exception e) {
fail("Should not have thrown any other exception");
}
network.shutdown();
}
/**
* Tests that a client request is successfully received by the
* RequestProcessor, and the response generated by the RequestProcessor is
* successfully received by the client.
*
* @throws IOException
* @throws ExecutionException
* @throws InterruptedException
*/
public void testRequestProcessor() throws IOException, InterruptedException,
ExecutionException {
MockNetwork network = createMockNetwork();
// Create the request that will be sent to the server
DevModeRequest.Builder devModeRequestBuilder = DevModeRequest.newBuilder();
devModeRequestBuilder.setRequestType(DevModeRequest.RequestType.CAPABILITY_EXCHANGE);
Message.Request.Builder clientRequestBuilder = Message.Request.newBuilder();
clientRequestBuilder.setDevModeRequest(devModeRequestBuilder);
clientRequestBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
final Message.Request clientRequest = clientRequestBuilder.build();
// Create the response that will be sent back from the server
DevModeResponse.Builder devModeResponseBuilder = DevModeResponse.newBuilder();
devModeResponseBuilder.setResponseType(DevModeResponse.ResponseType.CAPABILITY_EXCHANGE);
Message.Response.Builder clientResponseBuilder = Message.Response.newBuilder();
clientResponseBuilder.setDevModeResponse(devModeResponseBuilder);
final Message.Response clientResponse = clientResponseBuilder.build();
/*
* Define a request processor, which will expect to receive the request that
* we've defined, and then return the response that we've defined.
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
assertEquals(clientRequest, request);
return clientResponse;
}
};
// Start up the message transport on the server side
new MessageTransport(network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
// Send the request from the client to the server
Message.Builder clientRequestMsgBuilder = Message.newBuilder();
clientRequestMsgBuilder.setMessageType(Message.MessageType.REQUEST);
clientRequestMsgBuilder.setMessageId(25);
clientRequestMsgBuilder.setRequest(clientRequest);
Message clientRequestMsg = clientRequestMsgBuilder.build();
clientRequestMsg.writeDelimitedTo(network.getServerSocket().getOutputStream());
// Receive the response on the client (which was returned by the
// RequestProcessor)
Message receivedResponseMsg = Message.parseDelimitedFrom(network.getServerSocket().getInputStream());
// Make sure the message ids match
assertEquals(receivedResponseMsg.getMessageId(), 25);
// Make sure that the response matches the one that was returned by the
// RequestProcessor
assertEquals(receivedResponseMsg.getResponse(), clientResponse);
network.shutdown();
}
/**
* Tests that a client request is successfully received by the
* RequestProcessor, and the exception thrown by the RequestProcessor is
* passed back in the form of an error response to the client.
*
* @throws IOException
* @throws ExecutionException
* @throws InterruptedException
*/
public void testRequestProcessorThrowsException() throws IOException,
InterruptedException, ExecutionException {
MockNetwork network = createMockNetwork();
/*
* Define a request processor that throws an exception when it receives the
* request. We'll expect to receive this exception as a failure message on
* the client side.
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
throw new Exception("There was an exception processing this request.");
}
};
// Start up the message transport on the server side
new MessageTransport(network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
// Send a request to the server
Message.Request.Builder clientRequestBuilder = Message.Request.newBuilder();
clientRequestBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
final Message.Request clientRequest = clientRequestBuilder.build();
Message.Builder clientRequestMsgBuilder = Message.newBuilder();
clientRequestMsgBuilder.setMessageType(Message.MessageType.REQUEST);
clientRequestMsgBuilder.setMessageId(25);
clientRequestMsgBuilder.setRequest(clientRequest);
Message clientRequestMsg = clientRequestMsgBuilder.build();
clientRequestMsg.writeDelimitedTo(network.getServerSocket().getOutputStream());
// Receive the response on the client (which was returned by the
// RequestProcessor)
Message receivedResponseMsg = Message.parseDelimitedFrom(network.getServerSocket().getInputStream());
// Make sure the message ids match
assertEquals(receivedResponseMsg.getMessageId(), 25);
// Verify that the message is of type FAILURE
assertEquals(receivedResponseMsg.getMessageType(),
Message.MessageType.FAILURE);
// Verify that the failure message field is set
assertNotNull(receivedResponseMsg.getFailure());
// Verify that the actual failure message is equal to the message
// set for the Exception in the RequestProcessor
assertEquals(receivedResponseMsg.getFailure().getMessage(),
"There was an exception processing this request.");
network.shutdown();
}
}
| true | true | public void testExecuteRequestAsyncServerThrowsException()
throws InterruptedException, ExecutionException, IOException,
TimeoutException {
MockNetwork network = createMockNetwork();
/*
* Define a dummy request processor. The message transport is being set up
* on the client side, which means that it should not be receiving any
* requests (any responses).
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
fail("Should not reach here.");
return null;
}
};
// Set up a message transport on the client side
MessageTransport messageTransport = new MessageTransport(
network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
// Generate a new request
Message.Request.Builder requestMessageBuilder = Message.Request.newBuilder();
requestMessageBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
Message.Request request = requestMessageBuilder.build();
// Execute the request on the remote server
Future<Response> responseFuture = messageTransport.executeRequestAsync(request);
assertNotNull(responseFuture);
// Get the request on the server side
Message receivedRequest = Message.parseDelimitedFrom(network.getServerSocket().getInputStream());
assertEquals(receivedRequest.getRequest(), request);
// Generate a failure response on the server
Failure.Builder failureBuilder = Failure.newBuilder();
failureBuilder.setMessage("Unable to process the request.");
Message.Builder messageBuilder = Message.newBuilder();
// Make sure that we set the matching message id
messageBuilder.setMessageId(receivedRequest.getMessageId());
messageBuilder.setMessageType(Message.MessageType.FAILURE);
messageBuilder.setFailure(failureBuilder);
Message failureMsg = messageBuilder.build();
// Send the failure message back to the client
failureMsg.writeDelimitedTo(network.getServerSocket().getOutputStream());
// Wait for the response on the client. This should result in a
// RequestException being thrown.
try {
responseFuture.get(2, TimeUnit.SECONDS);
fail("Should have thrown an exception");
} catch (TimeoutException te) {
fail("Should not have timed out");
} catch (ExecutionException e) {
// This is where we should hit
assertTrue("Expected: IllegalStateException, actual:" + e.getCause(),
e.getCause() instanceof IllegalStateException);
RequestException re = (RequestException) e.getCause();
assertEquals(re.getMessage(), "Unable to process the request.");
} catch (Exception e) {
fail("Should not have thrown any other exception");
}
network.shutdown();
}
| public void testExecuteRequestAsyncServerThrowsException()
throws InterruptedException, ExecutionException, IOException,
TimeoutException {
MockNetwork network = createMockNetwork();
/*
* Define a dummy request processor. The message transport is being set up
* on the client side, which means that it should not be receiving any
* requests (any responses).
*/
RequestProcessor requestProcessor = new RequestProcessor() {
public Response execute(Request request) throws Exception {
fail("Should not reach here.");
return null;
}
};
// Set up a message transport on the client side
MessageTransport messageTransport = new MessageTransport(
network.getClientSocket().getInputStream(),
network.getClientSocket().getOutputStream(), requestProcessor,
new MessageTransport.TerminationCallback() {
public void onTermination(Exception e) {
}
});
// Generate a new request
Message.Request.Builder requestMessageBuilder = Message.Request.newBuilder();
requestMessageBuilder.setServiceType(Message.Request.ServiceType.DEV_MODE);
Message.Request request = requestMessageBuilder.build();
// Execute the request on the remote server
Future<Response> responseFuture = messageTransport.executeRequestAsync(request);
assertNotNull(responseFuture);
// Get the request on the server side
Message receivedRequest = Message.parseDelimitedFrom(network.getServerSocket().getInputStream());
assertEquals(receivedRequest.getRequest(), request);
// Generate a failure response on the server
Failure.Builder failureBuilder = Failure.newBuilder();
failureBuilder.setMessage("Unable to process the request.");
Message.Builder messageBuilder = Message.newBuilder();
// Make sure that we set the matching message id
messageBuilder.setMessageId(receivedRequest.getMessageId());
messageBuilder.setMessageType(Message.MessageType.FAILURE);
messageBuilder.setFailure(failureBuilder);
Message failureMsg = messageBuilder.build();
// Send the failure message back to the client
failureMsg.writeDelimitedTo(network.getServerSocket().getOutputStream());
// Wait for the response on the client. This should result in a
// RequestException being thrown.
try {
responseFuture.get(2, TimeUnit.SECONDS);
fail("Should have thrown an exception");
} catch (TimeoutException te) {
fail("Should not have timed out");
} catch (ExecutionException e) {
// This is where we should hit
assertTrue("Expected: MessageTransport.RequestException, actual:"
+ e.getCause(), e.getCause() instanceof RequestException);
RequestException re = (RequestException) e.getCause();
assertEquals(re.getMessage(), "Unable to process the request.");
} catch (Exception e) {
fail("Should not have thrown any other exception");
}
network.shutdown();
}
|
diff --git a/maven-scm-test/src/main/java/org/apache/maven/scm/tck/command/update/UpdateCommandTckTest.java b/maven-scm-test/src/main/java/org/apache/maven/scm/tck/command/update/UpdateCommandTckTest.java
index eaaa8e35..31ad4bbd 100644
--- a/maven-scm-test/src/main/java/org/apache/maven/scm/tck/command/update/UpdateCommandTckTest.java
+++ b/maven-scm-test/src/main/java/org/apache/maven/scm/tck/command/update/UpdateCommandTckTest.java
@@ -1,185 +1,185 @@
package org.apache.maven.scm.tck.command.update;
/*
* 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 java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import org.apache.maven.scm.ChangeSet;
import org.apache.maven.scm.ScmFile;
import org.apache.maven.scm.ScmFileSet;
import org.apache.maven.scm.ScmFileStatus;
import org.apache.maven.scm.ScmTckTestCase;
import org.apache.maven.scm.ScmTestCase;
import org.apache.maven.scm.command.checkin.CheckInScmResult;
import org.apache.maven.scm.command.update.UpdateScmResult;
import org.apache.maven.scm.manager.ScmManager;
import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
/**
* This test tests the update command.
* <p/>
* It works like this:
* <p/>
* <ol>
* <li>Check out the files to directory getWorkingCopy().
* <li>Check out the files to directory getUpdatingCopy().
* <li>Change the files in getWorkingCopy().
* <li>Commit the files in getWorkingCopy(). Note that the provider <b>must</b> not
* use the check in command as it can be guaranteed to work as it's not yet tested.
* <li>Use the update command in getUpdatingCopy() to assert that the files
* that was supposed to be updated actually was updated.
* </ol>
*
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
*/
public abstract class UpdateCommandTckTest
extends ScmTckTestCase
{
private void commit( File workingDirectory, ScmRepository repository )
throws Exception
{
CheckInScmResult result = getScmManager().checkIn( repository, new ScmFileSet( workingDirectory ), "No msg" );
assertTrue( "Check result was successful, output: " + result.getCommandOutput(), result.isSuccess() );
List committedFiles = result.getCheckedInFiles();
assertEquals(
"Expected 3 files in the committed files list:\n " + StringUtils.join( committedFiles.iterator(), "\n " ),
3, committedFiles.size() );
}
public void testUpdateCommand()
throws Exception
{
FileUtils.deleteDirectory( getUpdatingCopy() );
assertFalse( getUpdatingCopy().exists() );
//FileUtils.deleteDirectory( getWorkingCopy() );
//assertFalse( getUpdatingCopy().exists() );
ScmRepository repository = makeScmRepository( getScmUrl() );
checkOut( getUpdatingCopy(), repository );
// ----------------------------------------------------------------------
// Change the files
// ----------------------------------------------------------------------
/*
* readme.txt is changed (changed file in the root directory)
* project.xml is added (added file in the root directory)
* src/test/resources is untouched (a empty directory is left untouched)
* src/test/java is untouched (a non empty directory is left untouched)
* src/test/java/org (a empty directory is added)
* src/main/java/org/Foo.java (a non empty directory is added)
*/
// /readme.txt
ScmTestCase.makeFile( getWorkingCopy(), "/readme.txt", "changed readme.txt" );
// /project.xml
ScmTestCase.makeFile( getWorkingCopy(), "/project.xml", "changed project.xml" );
addToWorkingTree( getWorkingCopy(), new File( "project.xml" ), repository );
// /src/test/java/org
ScmTestCase.makeDirectory( getWorkingCopy(), "/src/test/java/org" );
addToWorkingTree( getWorkingCopy(), new File( "src/test/java/org" ), repository );
// /src/main/java/org/Foo.java
ScmTestCase.makeFile( getWorkingCopy(), "/src/main/java/org/Foo.java" );
addToWorkingTree( getWorkingCopy(), new File( "src/main/java/org" ), repository );
// src/main/java/org/Foo.java
addToWorkingTree( getWorkingCopy(), new File( "src/main/java/org/Foo.java" ), repository );
ScmManager scmManager = getScmManager();
Date lastUpdate = new Date( System.currentTimeMillis() - 100000 );
- //Thread.sleep( 2000 );
+ Thread.sleep( 2000 );
commit( getWorkingCopy(), repository );
// ----------------------------------------------------------------------
// Update the project
// ----------------------------------------------------------------------
UpdateScmResult result = scmManager.update( repository, new ScmFileSet( getUpdatingCopy() ), lastUpdate );
assertNotNull( "The command returned a null result.", result );
assertResultIsSuccess( result );
List updatedFiles = result.getUpdatedFiles();
List changedSets = result.getChanges();
assertEquals( "Expected 3 files in the updated files list " + updatedFiles, 3, updatedFiles.size() );
assertNotNull( "The changed files list is null", changedSets );
assertFalse( "The changed files list is empty ", changedSets.isEmpty() );
for ( Iterator i = changedSets.iterator(); i.hasNext(); )
{
ChangeSet changeSet = (ChangeSet) i.next();
System.out.println( changeSet.toXML() );
}
// ----------------------------------------------------------------------
// Assert the files in the updated files list
// ----------------------------------------------------------------------
Iterator files = new TreeSet( updatedFiles ).iterator();
//Foo.java
ScmFile file = (ScmFile) files.next();
assertPath( "/src/main/java/org/Foo.java", file.getPath() );
//TODO : Consolidate file status so that we can remove "|| ADDED" term
assertTrue( file.getStatus().isUpdate() || file.getStatus() == ScmFileStatus.ADDED );
//readme.txt
file = (ScmFile) files.next();
assertPath( "/readme.txt", file.getPath() );
assertTrue( file.getStatus().isUpdate() );
//project.xml
file = (ScmFile) files.next();
assertPath( "/project.xml", file.getPath() );
//TODO : Consolidate file status so that we can remove "|| ADDED" term
assertTrue( file.getStatus().isUpdate() || file.getStatus() == ScmFileStatus.ADDED );
}
}
| true | true | public void testUpdateCommand()
throws Exception
{
FileUtils.deleteDirectory( getUpdatingCopy() );
assertFalse( getUpdatingCopy().exists() );
//FileUtils.deleteDirectory( getWorkingCopy() );
//assertFalse( getUpdatingCopy().exists() );
ScmRepository repository = makeScmRepository( getScmUrl() );
checkOut( getUpdatingCopy(), repository );
// ----------------------------------------------------------------------
// Change the files
// ----------------------------------------------------------------------
/*
* readme.txt is changed (changed file in the root directory)
* project.xml is added (added file in the root directory)
* src/test/resources is untouched (a empty directory is left untouched)
* src/test/java is untouched (a non empty directory is left untouched)
* src/test/java/org (a empty directory is added)
* src/main/java/org/Foo.java (a non empty directory is added)
*/
// /readme.txt
ScmTestCase.makeFile( getWorkingCopy(), "/readme.txt", "changed readme.txt" );
// /project.xml
ScmTestCase.makeFile( getWorkingCopy(), "/project.xml", "changed project.xml" );
addToWorkingTree( getWorkingCopy(), new File( "project.xml" ), repository );
// /src/test/java/org
ScmTestCase.makeDirectory( getWorkingCopy(), "/src/test/java/org" );
addToWorkingTree( getWorkingCopy(), new File( "src/test/java/org" ), repository );
// /src/main/java/org/Foo.java
ScmTestCase.makeFile( getWorkingCopy(), "/src/main/java/org/Foo.java" );
addToWorkingTree( getWorkingCopy(), new File( "src/main/java/org" ), repository );
// src/main/java/org/Foo.java
addToWorkingTree( getWorkingCopy(), new File( "src/main/java/org/Foo.java" ), repository );
ScmManager scmManager = getScmManager();
Date lastUpdate = new Date( System.currentTimeMillis() - 100000 );
//Thread.sleep( 2000 );
commit( getWorkingCopy(), repository );
// ----------------------------------------------------------------------
// Update the project
// ----------------------------------------------------------------------
UpdateScmResult result = scmManager.update( repository, new ScmFileSet( getUpdatingCopy() ), lastUpdate );
assertNotNull( "The command returned a null result.", result );
assertResultIsSuccess( result );
List updatedFiles = result.getUpdatedFiles();
List changedSets = result.getChanges();
assertEquals( "Expected 3 files in the updated files list " + updatedFiles, 3, updatedFiles.size() );
assertNotNull( "The changed files list is null", changedSets );
assertFalse( "The changed files list is empty ", changedSets.isEmpty() );
for ( Iterator i = changedSets.iterator(); i.hasNext(); )
{
ChangeSet changeSet = (ChangeSet) i.next();
System.out.println( changeSet.toXML() );
}
// ----------------------------------------------------------------------
// Assert the files in the updated files list
// ----------------------------------------------------------------------
Iterator files = new TreeSet( updatedFiles ).iterator();
//Foo.java
ScmFile file = (ScmFile) files.next();
assertPath( "/src/main/java/org/Foo.java", file.getPath() );
//TODO : Consolidate file status so that we can remove "|| ADDED" term
assertTrue( file.getStatus().isUpdate() || file.getStatus() == ScmFileStatus.ADDED );
//readme.txt
file = (ScmFile) files.next();
assertPath( "/readme.txt", file.getPath() );
assertTrue( file.getStatus().isUpdate() );
//project.xml
file = (ScmFile) files.next();
assertPath( "/project.xml", file.getPath() );
//TODO : Consolidate file status so that we can remove "|| ADDED" term
assertTrue( file.getStatus().isUpdate() || file.getStatus() == ScmFileStatus.ADDED );
}
| public void testUpdateCommand()
throws Exception
{
FileUtils.deleteDirectory( getUpdatingCopy() );
assertFalse( getUpdatingCopy().exists() );
//FileUtils.deleteDirectory( getWorkingCopy() );
//assertFalse( getUpdatingCopy().exists() );
ScmRepository repository = makeScmRepository( getScmUrl() );
checkOut( getUpdatingCopy(), repository );
// ----------------------------------------------------------------------
// Change the files
// ----------------------------------------------------------------------
/*
* readme.txt is changed (changed file in the root directory)
* project.xml is added (added file in the root directory)
* src/test/resources is untouched (a empty directory is left untouched)
* src/test/java is untouched (a non empty directory is left untouched)
* src/test/java/org (a empty directory is added)
* src/main/java/org/Foo.java (a non empty directory is added)
*/
// /readme.txt
ScmTestCase.makeFile( getWorkingCopy(), "/readme.txt", "changed readme.txt" );
// /project.xml
ScmTestCase.makeFile( getWorkingCopy(), "/project.xml", "changed project.xml" );
addToWorkingTree( getWorkingCopy(), new File( "project.xml" ), repository );
// /src/test/java/org
ScmTestCase.makeDirectory( getWorkingCopy(), "/src/test/java/org" );
addToWorkingTree( getWorkingCopy(), new File( "src/test/java/org" ), repository );
// /src/main/java/org/Foo.java
ScmTestCase.makeFile( getWorkingCopy(), "/src/main/java/org/Foo.java" );
addToWorkingTree( getWorkingCopy(), new File( "src/main/java/org" ), repository );
// src/main/java/org/Foo.java
addToWorkingTree( getWorkingCopy(), new File( "src/main/java/org/Foo.java" ), repository );
ScmManager scmManager = getScmManager();
Date lastUpdate = new Date( System.currentTimeMillis() - 100000 );
Thread.sleep( 2000 );
commit( getWorkingCopy(), repository );
// ----------------------------------------------------------------------
// Update the project
// ----------------------------------------------------------------------
UpdateScmResult result = scmManager.update( repository, new ScmFileSet( getUpdatingCopy() ), lastUpdate );
assertNotNull( "The command returned a null result.", result );
assertResultIsSuccess( result );
List updatedFiles = result.getUpdatedFiles();
List changedSets = result.getChanges();
assertEquals( "Expected 3 files in the updated files list " + updatedFiles, 3, updatedFiles.size() );
assertNotNull( "The changed files list is null", changedSets );
assertFalse( "The changed files list is empty ", changedSets.isEmpty() );
for ( Iterator i = changedSets.iterator(); i.hasNext(); )
{
ChangeSet changeSet = (ChangeSet) i.next();
System.out.println( changeSet.toXML() );
}
// ----------------------------------------------------------------------
// Assert the files in the updated files list
// ----------------------------------------------------------------------
Iterator files = new TreeSet( updatedFiles ).iterator();
//Foo.java
ScmFile file = (ScmFile) files.next();
assertPath( "/src/main/java/org/Foo.java", file.getPath() );
//TODO : Consolidate file status so that we can remove "|| ADDED" term
assertTrue( file.getStatus().isUpdate() || file.getStatus() == ScmFileStatus.ADDED );
//readme.txt
file = (ScmFile) files.next();
assertPath( "/readme.txt", file.getPath() );
assertTrue( file.getStatus().isUpdate() );
//project.xml
file = (ScmFile) files.next();
assertPath( "/project.xml", file.getPath() );
//TODO : Consolidate file status so that we can remove "|| ADDED" term
assertTrue( file.getStatus().isUpdate() || file.getStatus() == ScmFileStatus.ADDED );
}
|
diff --git a/raisavis/src/main/java/raisa/vis/VisualizerPanel.java b/raisavis/src/main/java/raisa/vis/VisualizerPanel.java
index 5df1cbf..df561e6 100644
--- a/raisavis/src/main/java/raisa/vis/VisualizerPanel.java
+++ b/raisavis/src/main/java/raisa/vis/VisualizerPanel.java
@@ -1,256 +1,256 @@
package raisa.vis;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D.Float;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JPanel;
public class VisualizerPanel extends JPanel {
private static final long serialVersionUID = 1L;
private Color measurementColor = new Color(0.4f, 0.4f, 0.4f);
private Float robot = new Float();
private Float camera = new Float();
private Float mouse = new Float();
private Float mouseDragStart = new Float();
private float scale = 1.0f;
private List<Sample> samples = new ArrayList<Sample>();
private List<Sample> latestIR = new ArrayList<Sample>();
private List<Sample> latestSR = new ArrayList<Sample>();
private Grid grid = new Grid();
public VisualizerPanel() {
setBackground(Color.gray);
setFocusable(true);
addHierarchyBoundsListener(new PanelSizeHandler());
addMouseMotionListener(new MouseMotionHandler());
addMouseListener(new MouseHandler());
addKeyListener(new KeyboardHandler());
}
public void update(List<Sample> samples) {
for (Sample sample : samples) {
if (sample.data.containsKey("ir") && sample.isSpot()) {
grid.addSpot(sample.getSpot());
latestIR.add(sample);
latestIR = takeLast(latestIR, 10);
}
if (sample.data.containsKey("sr") && sample.data.containsKey("sd")) {
latestSR.add(sample);
latestSR = takeLast(latestSR, 10);
}
}
synchronized (this.samples) {
this.samples.addAll(samples);
}
repaint();
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int screenWidth = getBounds().width;
int screenHeight = getBounds().height;
g.clearRect(0, 0, screenWidth, screenHeight);
Float tl = new Float(camera.x - screenWidth * 0.5f / scale, camera.y
- screenHeight * 0.5f / scale);
grid.draw(g2, new Rectangle2D.Float(tl.x * scale, tl.y * scale,
screenWidth * scale, screenHeight * scale), this);
g.setColor(Color.black);
/*
* synchronized (samples) { for (Sample sample : samples) { if
* (sample.isSpot()) { drawPoint(g, sample.getSpot()); } } }
*/
g.setColor(measurementColor);
drawMeasurementLine(g, robot, toWorld(mouse));
if (!latestSR.isEmpty()) {
float sonarWidth = 25.0f;
List<Sample> srs = new ArrayList<Sample>(latestSR);
Collections.reverse(srs);
float sr = 1.0f;
for (Sample sample : srs) {
Spot spot = sample.getSrSpot();
g.setColor(new Color(0.0f, 0.6f, 0.6f, sr));
if (sr >= 1.0f) {
- drawMeasurementLine(g, sample.getRobot(), sample.getSpot());
+ drawMeasurementLine(g, sample.getRobot(), spot);
g.setColor(new Color(0.0f, 0.6f, 0.6f, 0.05f));
drawSector(g, robot, spot, sonarWidth);
} else {
g.setColor(new Color(0.0f, 0.6f, 0.6f, 0.05f));
drawSector(g, robot, spot, sonarWidth);
}
g.setColor(new Color(0.0f, 0.6f, 0.6f, sr));
drawPoint(g, sample.getSpot());
sr *= 0.8f;
}
}
if (!latestIR.isEmpty()) {
List<Sample> irs = new ArrayList<Sample>(latestIR);
Collections.reverse(irs);
float ir = 1.0f;
for (Sample sample : irs) {
if (sample.isSpot()) {
g.setColor(new Color(1.0f, 0.0f, 0.0f, ir));
if (ir >= 1.0f) {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot());
} else {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot(), false);
}
drawPoint(g, sample.getSpot());
ir *= 0.8f;
}
}
}
}
private void drawSector(Graphics g, Float from, Float to, float sector) {
Float p1 = toScreen(from);
Float p2 = toScreen(to);
g.drawLine((int) p1.x, (int) p1.y, (int) p2.x, (int) p2.y);
float dx = (p2.x - p1.x);
float dy = (p2.y - p1.y);
float l = (float) Math.sqrt(dx * dx + dy * dy);
float a = (float) (Math.atan2(-dy, dx) / Math.PI * 180.0) - sector
* 0.5f;
g.fillArc((int) (p1.x - l), (int) (p1.y - l), (int) (2.0f * l),
(int) (2.0f * l), (int) a, (int) sector);
}
private void drawPoint(Graphics g, Float point) {
float w = 3.0f;
float h = 3.0f;
Float p = toScreen(point);
g.fillRect((int) (p.x - 0.5f * w), (int) (p.y - 0.5f * h), (int) w,
(int) h);
}
private void drawMeasurementLine(Graphics g, Float from, Float to) {
drawMeasurementLine(g, from, to, true);
}
private void drawMeasurementLine(Graphics g, Float from, Float to, boolean drawDistanceString) {
Float p1 = toScreen(from);
Float p2 = toScreen(to);
g.drawLine((int) p1.x, (int) p1.y, (int) p2.x, (int) p2.y);
if (drawDistanceString) {
float dx = (from.x - to.x);
float dy = (from.y - to.y);
float l = (float) Math.sqrt(dx * dx + dy * dy);
String distanceString = String.format("%3.1f cm", l);
g.drawString(distanceString, (int) (p2.x + 10), (int) p2.y);
}
}
public Float toWorld(Float screen) {
int screenWidth = getBounds().width;
int screenHeight = getBounds().height;
return new Float(camera.x + (screen.x - screenWidth * 0.5f) / scale,
camera.y + (screen.y - screenHeight * 0.5f) / scale);
}
public float toScreen(float size) {
return size * scale;
}
public Float toScreen(Float from) {
int screenWidth = getBounds().width;
int screenHeight = getBounds().height;
float x1 = (from.x - camera.x) * scale + 0.5f * screenWidth;
float y1 = (from.y - camera.y) * scale + 0.5f * screenHeight;
Float f = new Float(x1, y1);
return f;
}
private final class PanelSizeHandler implements HierarchyBoundsListener {
@Override
public void ancestorResized(HierarchyEvent arg0) {
resetMouseLocationLine();
repaint();
}
private void resetMouseLocationLine() {
mouse.x = camera.x;
mouse.y = camera.y;
}
@Override
public void ancestorMoved(HierarchyEvent arg0) {
}
}
private final class MouseMotionHandler extends MouseAdapter {
@Override
public void mouseMoved(MouseEvent mouseEvent) {
mouse.x = mouseEvent.getX();
mouse.y = mouseEvent.getY();
repaint();
}
@Override
public void mouseDragged(MouseEvent mouseEvent) {
mouse.x = mouseEvent.getX();
mouse.y = mouseEvent.getY();
camera.x += (mouseDragStart.x - mouse.x) / scale;
camera.y += (mouseDragStart.y - mouse.y) / scale;
mouseDragStart.x = mouse.x;
mouseDragStart.y = mouse.y;
repaint();
}
}
private final class MouseHandler extends MouseAdapter {
@Override
public void mousePressed(MouseEvent mouseEvent) {
mouseDragStart.x = mouseEvent.getX();
mouseDragStart.y = mouseEvent.getY();
}
}
private final class KeyboardHandler extends KeyAdapter {
@Override
public void keyReleased(KeyEvent arg0) {
int keyCode = arg0.getKeyCode();
if (keyCode == KeyEvent.VK_C) {
System.out.println("Cleared samples");
samples.clear();
repaint();
} else if (keyCode == KeyEvent.VK_H) {
System.out.println("Removed old samples");
samples = takeLast(samples, 1000);
repaint();
} else if (keyCode == KeyEvent.VK_PLUS) {
scale *= 1.25f;
repaint();
} else if (keyCode == KeyEvent.VK_MINUS) {
scale *= 0.8f;
repaint();
}
}
}
private List<Sample> takeLast(List<Sample> samples, int length) {
if (samples.size() > length) {
int fromIndex = Math.max(0, samples.size() - length);
int toIndex = samples.size();
List<Sample> newSamples = new ArrayList<Sample>();
newSamples.addAll(samples.subList(fromIndex, toIndex));
return newSamples;
}
return samples;
}
}
| true | true | public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int screenWidth = getBounds().width;
int screenHeight = getBounds().height;
g.clearRect(0, 0, screenWidth, screenHeight);
Float tl = new Float(camera.x - screenWidth * 0.5f / scale, camera.y
- screenHeight * 0.5f / scale);
grid.draw(g2, new Rectangle2D.Float(tl.x * scale, tl.y * scale,
screenWidth * scale, screenHeight * scale), this);
g.setColor(Color.black);
/*
* synchronized (samples) { for (Sample sample : samples) { if
* (sample.isSpot()) { drawPoint(g, sample.getSpot()); } } }
*/
g.setColor(measurementColor);
drawMeasurementLine(g, robot, toWorld(mouse));
if (!latestSR.isEmpty()) {
float sonarWidth = 25.0f;
List<Sample> srs = new ArrayList<Sample>(latestSR);
Collections.reverse(srs);
float sr = 1.0f;
for (Sample sample : srs) {
Spot spot = sample.getSrSpot();
g.setColor(new Color(0.0f, 0.6f, 0.6f, sr));
if (sr >= 1.0f) {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot());
g.setColor(new Color(0.0f, 0.6f, 0.6f, 0.05f));
drawSector(g, robot, spot, sonarWidth);
} else {
g.setColor(new Color(0.0f, 0.6f, 0.6f, 0.05f));
drawSector(g, robot, spot, sonarWidth);
}
g.setColor(new Color(0.0f, 0.6f, 0.6f, sr));
drawPoint(g, sample.getSpot());
sr *= 0.8f;
}
}
if (!latestIR.isEmpty()) {
List<Sample> irs = new ArrayList<Sample>(latestIR);
Collections.reverse(irs);
float ir = 1.0f;
for (Sample sample : irs) {
if (sample.isSpot()) {
g.setColor(new Color(1.0f, 0.0f, 0.0f, ir));
if (ir >= 1.0f) {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot());
} else {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot(), false);
}
drawPoint(g, sample.getSpot());
ir *= 0.8f;
}
}
}
}
| public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int screenWidth = getBounds().width;
int screenHeight = getBounds().height;
g.clearRect(0, 0, screenWidth, screenHeight);
Float tl = new Float(camera.x - screenWidth * 0.5f / scale, camera.y
- screenHeight * 0.5f / scale);
grid.draw(g2, new Rectangle2D.Float(tl.x * scale, tl.y * scale,
screenWidth * scale, screenHeight * scale), this);
g.setColor(Color.black);
/*
* synchronized (samples) { for (Sample sample : samples) { if
* (sample.isSpot()) { drawPoint(g, sample.getSpot()); } } }
*/
g.setColor(measurementColor);
drawMeasurementLine(g, robot, toWorld(mouse));
if (!latestSR.isEmpty()) {
float sonarWidth = 25.0f;
List<Sample> srs = new ArrayList<Sample>(latestSR);
Collections.reverse(srs);
float sr = 1.0f;
for (Sample sample : srs) {
Spot spot = sample.getSrSpot();
g.setColor(new Color(0.0f, 0.6f, 0.6f, sr));
if (sr >= 1.0f) {
drawMeasurementLine(g, sample.getRobot(), spot);
g.setColor(new Color(0.0f, 0.6f, 0.6f, 0.05f));
drawSector(g, robot, spot, sonarWidth);
} else {
g.setColor(new Color(0.0f, 0.6f, 0.6f, 0.05f));
drawSector(g, robot, spot, sonarWidth);
}
g.setColor(new Color(0.0f, 0.6f, 0.6f, sr));
drawPoint(g, sample.getSpot());
sr *= 0.8f;
}
}
if (!latestIR.isEmpty()) {
List<Sample> irs = new ArrayList<Sample>(latestIR);
Collections.reverse(irs);
float ir = 1.0f;
for (Sample sample : irs) {
if (sample.isSpot()) {
g.setColor(new Color(1.0f, 0.0f, 0.0f, ir));
if (ir >= 1.0f) {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot());
} else {
drawMeasurementLine(g, sample.getRobot(), sample.getSpot(), false);
}
drawPoint(g, sample.getSpot());
ir *= 0.8f;
}
}
}
}
|
diff --git a/araqne-logapi-nio/src/main/java/org/araqne/log/api/nio/RecursiveDirectoryWatchLoggerFactory.java b/araqne-logapi-nio/src/main/java/org/araqne/log/api/nio/RecursiveDirectoryWatchLoggerFactory.java
index 70e04da6..7be297bb 100644
--- a/araqne-logapi-nio/src/main/java/org/araqne/log/api/nio/RecursiveDirectoryWatchLoggerFactory.java
+++ b/araqne-logapi-nio/src/main/java/org/araqne/log/api/nio/RecursiveDirectoryWatchLoggerFactory.java
@@ -1,159 +1,159 @@
/**
* Copyright 2014 Eediom 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.araqne.log.api.nio;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Validate;
import org.araqne.log.api.AbstractLoggerFactory;
import org.araqne.log.api.Logger;
import org.araqne.log.api.LoggerConfigOption;
import org.araqne.log.api.LoggerSpecification;
import org.araqne.log.api.MutableStringConfigType;
@Component(name = "recursive-directory-watch-logger-factory")
@Provides
public class RecursiveDirectoryWatchLoggerFactory extends AbstractLoggerFactory {
private boolean useNio;
@Override
public String getName() {
return "recursive-dirwatch";
}
@Validate
public void start() {
// null -> nio
this.useNio = false;
String version = System.getProperty("java.version");
boolean isJdk7 = (version == null) ? false : version.compareTo("1.7") >= 0;
String useNaive = System.getProperty("araqne.logapi.watcher");
boolean isNaive = (useNaive == null) ? false : useNaive.equals("naive");
useNio = isJdk7 && !isNaive;
}
@Override
public String getDisplayName(Locale locale) {
if (locale != null && locale.equals(Locale.KOREAN))
return "리커시브 디렉터리 와처";
if (locale != null && locale.equals(Locale.JAPANESE))
return "再帰ディレクトリウォッチャー";
if (locale != null && locale.equals(Locale.CHINESE))
return "递归目录监控";
return "Recursive Directory Watcher";
}
@Override
public Collection<Locale> getDisplayNameLocales() {
return Arrays.asList(Locale.ENGLISH, Locale.KOREAN, Locale.JAPANESE, Locale.CHINESE);
}
@Override
public String getDescription(Locale locale) {
if (locale != null && locale.equals(Locale.KOREAN))
return "지정된 디렉터리에서 파일이름 패턴과 일치하는 모든 텍스트 로그 파일을 수집합니다.";
if (locale != null && locale.equals(Locale.JAPANESE))
return "指定されたディレクトリでファイル名パータンと一致するすべてのテキストログファイルを収集します。";
if (locale != null && locale.equals(Locale.CHINESE))
return "从指定目录(包括子目录)中采集所有文本文件。";
return "collect all text log files in specified directory";
}
@Override
public Collection<Locale> getDescriptionLocales() {
return Arrays.asList(Locale.ENGLISH, Locale.KOREAN, Locale.JAPANESE, Locale.CHINESE);
}
@Override
public Collection<LoggerConfigOption> getConfigOptions() {
LoggerConfigOption basePath = new MutableStringConfigType("base_path", t("Directory path", "디렉터리 경로", "ディレクトリ経路", "目录"),
t(
"Base log file directory path", "로그 파일을 수집할 대상 디렉터리 경로", "ログファイルを収集する対象ディレクトリ経路", "要采集的日志文件所在目录"), true);
LoggerConfigOption dirPathPattern = new MutableStringConfigType("dirpath_pattern", t("Directory Path pattern",
- "디렉토리 이름 패턴", "ディレクトリ経路パータン", "文件名模式"), t("Regular expression to match directory path",
+ "디렉토리 이름 패턴", "ディレクトリ経路パータン", "目录名称模式"), t("Regular expression to match directory path",
"대상 로그 파일이 있는 디렉토리를 선택하는데 사용할 정규표현식", "対象ログファイルがあるディレクトリを選ぶとき使う正規表現", "表示要采集的文件所在目录的正则表达式"), false);
LoggerConfigOption fileNamePattern = new MutableStringConfigType("filename_pattern", t("Filename pattern", "파일이름 패턴",
"ファイル名パータン", "文件名模式"), t("Regular expression to match log file name", "대상 로그 파일을 선택하는데 사용할 정규표현식",
"対象ログファイルを選ぶとき使う正規表現", "用于筛选文件的正则表达式"), true);
LoggerConfigOption datePattern = new MutableStringConfigType("date_pattern", t("Date pattern", "날짜 정규표현식", "日付正規表現",
"日期正则表达式"), t("Regular expression to match date and time strings", "날짜 및 시각을 추출하는데 사용할 정규표현식", "日付と時刻を解析する正規表現",
"用于提取日期及时间的正则表达式"), false);
LoggerConfigOption dateFormat = new MutableStringConfigType("date_format", t("Date format", "날짜 포맷", "日付フォーマット", "日期格式"),
t("date format to parse date and time strings. e.g. yyyy-MM-dd HH:mm:ss",
"날짜 및 시각 문자열을 파싱하는데 사용할 포맷. 예) yyyy-MM-dd HH:mm:ss", "日付と時刻を解析するフォーマット。例) yyyy-MM-dd HH:mm:ss",
"用于解析日期及时间字符串的格式。 示例) yyyy-MM-dd HH:mm:ss"), false);
LoggerConfigOption dateLocale = new MutableStringConfigType("date_locale", t("Date locale", "날짜 로케일", "日付ロケール", "日期区域"),
t("date locale, e.g. en", "날짜 로케일, 예를 들면 ko", "日付ロケール。例えばjp", "日期区域, 例如 zh"), false);
LoggerConfigOption timezone = new MutableStringConfigType("timezone", t("Time zone", "시간대", "時間帯", "时区"), t(
"time zone, e.g. EST or America/New_york ", "시간대, 예를 들면 KST 또는 Asia/Seoul", "時間帯。例えばJSTまたはAsia/Tokyo",
"时区, 例如 Asia/Beijing"), false);
LoggerConfigOption newlogRegex = new MutableStringConfigType("newlog_designator", t("Regex for first line", "로그 시작 정규식",
"ログ始め正規表現", "日志起始正则表达式"), t("Regular expression to determine whether the line is start of new log."
+ "(if a line does not matches, the line will be merged to prev line.).",
"새 로그의 시작을 인식하기 위한 정규식(매칭되지 않는 경우 이전 줄에 병합됨)", "新しいログの始まりを認識する正規表現 (マッチングされない場合は前のラインに繋げる)"
, "用于识别日志起始位置的正则表达式(如没有匹配项,则合并到之前日志)"), false);
LoggerConfigOption newlogEndRegex = new MutableStringConfigType("newlog_end_designator", t("Regex for last line",
"로그 끝 정규식", "ログ終わり正規表現", "日志结束正则表达式"), t("Regular expression to determine whether the line is end of new log."
+ "(if a line does not matches, the line will be merged to prev line.).",
"로그의 끝을 인식하기 위한 정규식(매칭되지 않는 경우 이전 줄에 병합됨)", "ログの終わりを認識する正規表現 (マッチングされない場合は前のラインに繋げる)"
, "用于识别日志结束位置地正则表达式(如没有匹配项,则合并到之前日志)"), false);
LoggerConfigOption charset = new MutableStringConfigType("charset", t("Charset", "문자 집합", "文字セット", "字符集"), t(
"charset encoding", "텍스트 파일의 문자 인코딩 방식", "テキストファイルの文字エンコーディング方式", "文本文件的字符编码方式"), false);
- LoggerConfigOption recursive = new MutableStringConfigType("recursive", t("Recursive", "하위 디렉터리 포함", "再帰", "包括下级目录"), t(
+ LoggerConfigOption recursive = new MutableStringConfigType("recursive", t("Recursive", "하위 디렉터리 포함", "再帰", "采集子目录"), t(
"Include sub-directories. default is false", "하위 디렉터리 포함 여부, 기본값 false", "下位ディレクトリを含む。基本値はfalse",
- "是否包换下级目录,默认值为false。"), false);
+ "true表示采集子目录,默认值为false。"), false);
- LoggerConfigOption fileTag = new MutableStringConfigType("file_tag", t("Filename Tag", "파일네임 태그", "ファイル名タグ", "文件标记"), t(
+ LoggerConfigOption fileTag = new MutableStringConfigType("file_tag", t("Filename Tag", "파일네임 태그", "ファイル名タグ", "文件名标记"), t(
"Field name for filename tagging", "파일명을 태깅할 필드 이름", "ファイル名をタギングするフィールド名", "要进行文件名标记的字段"), false);
return Arrays.asList(basePath, dirPathPattern, fileNamePattern, datePattern, dateFormat, dateLocale, timezone,
newlogRegex, newlogEndRegex, charset, recursive, fileTag);
}
private Map<Locale, String> t(String enText, String koText, String jpText, String cnText) {
Map<Locale, String> m = new HashMap<Locale, String>();
m.put(Locale.ENGLISH, enText);
m.put(Locale.KOREAN, koText);
m.put(Locale.JAPANESE, jpText);
m.put(Locale.CHINESE, cnText);
return m;
}
@Override
protected Logger createLogger(LoggerSpecification spec) {
if (!useNio)
return new NaiveRecursiveDirectoryWatchLogger(spec, this);
else
return new NioRecursiveDirectoryWatchLogger(spec, this);
}
}
| false | true | public Collection<LoggerConfigOption> getConfigOptions() {
LoggerConfigOption basePath = new MutableStringConfigType("base_path", t("Directory path", "디렉터리 경로", "ディレクトリ経路", "目录"),
t(
"Base log file directory path", "로그 파일을 수집할 대상 디렉터리 경로", "ログファイルを収集する対象ディレクトリ経路", "要采集的日志文件所在目录"), true);
LoggerConfigOption dirPathPattern = new MutableStringConfigType("dirpath_pattern", t("Directory Path pattern",
"디렉토리 이름 패턴", "ディレクトリ経路パータン", "文件名模式"), t("Regular expression to match directory path",
"대상 로그 파일이 있는 디렉토리를 선택하는데 사용할 정규표현식", "対象ログファイルがあるディレクトリを選ぶとき使う正規表現", "表示要采集的文件所在目录的正则表达式"), false);
LoggerConfigOption fileNamePattern = new MutableStringConfigType("filename_pattern", t("Filename pattern", "파일이름 패턴",
"ファイル名パータン", "文件名模式"), t("Regular expression to match log file name", "대상 로그 파일을 선택하는데 사용할 정규표현식",
"対象ログファイルを選ぶとき使う正規表現", "用于筛选文件的正则表达式"), true);
LoggerConfigOption datePattern = new MutableStringConfigType("date_pattern", t("Date pattern", "날짜 정규표현식", "日付正規表現",
"日期正则表达式"), t("Regular expression to match date and time strings", "날짜 및 시각을 추출하는데 사용할 정규표현식", "日付と時刻を解析する正規表現",
"用于提取日期及时间的正则表达式"), false);
LoggerConfigOption dateFormat = new MutableStringConfigType("date_format", t("Date format", "날짜 포맷", "日付フォーマット", "日期格式"),
t("date format to parse date and time strings. e.g. yyyy-MM-dd HH:mm:ss",
"날짜 및 시각 문자열을 파싱하는데 사용할 포맷. 예) yyyy-MM-dd HH:mm:ss", "日付と時刻を解析するフォーマット。例) yyyy-MM-dd HH:mm:ss",
"用于解析日期及时间字符串的格式。 示例) yyyy-MM-dd HH:mm:ss"), false);
LoggerConfigOption dateLocale = new MutableStringConfigType("date_locale", t("Date locale", "날짜 로케일", "日付ロケール", "日期区域"),
t("date locale, e.g. en", "날짜 로케일, 예를 들면 ko", "日付ロケール。例えばjp", "日期区域, 例如 zh"), false);
LoggerConfigOption timezone = new MutableStringConfigType("timezone", t("Time zone", "시간대", "時間帯", "时区"), t(
"time zone, e.g. EST or America/New_york ", "시간대, 예를 들면 KST 또는 Asia/Seoul", "時間帯。例えばJSTまたはAsia/Tokyo",
"时区, 例如 Asia/Beijing"), false);
LoggerConfigOption newlogRegex = new MutableStringConfigType("newlog_designator", t("Regex for first line", "로그 시작 정규식",
"ログ始め正規表現", "日志起始正则表达式"), t("Regular expression to determine whether the line is start of new log."
+ "(if a line does not matches, the line will be merged to prev line.).",
"새 로그의 시작을 인식하기 위한 정규식(매칭되지 않는 경우 이전 줄에 병합됨)", "新しいログの始まりを認識する正規表現 (マッチングされない場合は前のラインに繋げる)"
, "用于识别日志起始位置的正则表达式(如没有匹配项,则合并到之前日志)"), false);
LoggerConfigOption newlogEndRegex = new MutableStringConfigType("newlog_end_designator", t("Regex for last line",
"로그 끝 정규식", "ログ終わり正規表現", "日志结束正则表达式"), t("Regular expression to determine whether the line is end of new log."
+ "(if a line does not matches, the line will be merged to prev line.).",
"로그의 끝을 인식하기 위한 정규식(매칭되지 않는 경우 이전 줄에 병합됨)", "ログの終わりを認識する正規表現 (マッチングされない場合は前のラインに繋げる)"
, "用于识别日志结束位置地正则表达式(如没有匹配项,则合并到之前日志)"), false);
LoggerConfigOption charset = new MutableStringConfigType("charset", t("Charset", "문자 집합", "文字セット", "字符集"), t(
"charset encoding", "텍스트 파일의 문자 인코딩 방식", "テキストファイルの文字エンコーディング方式", "文本文件的字符编码方式"), false);
LoggerConfigOption recursive = new MutableStringConfigType("recursive", t("Recursive", "하위 디렉터리 포함", "再帰", "包括下级目录"), t(
"Include sub-directories. default is false", "하위 디렉터리 포함 여부, 기본값 false", "下位ディレクトリを含む。基本値はfalse",
"是否包换下级目录,默认值为false。"), false);
LoggerConfigOption fileTag = new MutableStringConfigType("file_tag", t("Filename Tag", "파일네임 태그", "ファイル名タグ", "文件标记"), t(
"Field name for filename tagging", "파일명을 태깅할 필드 이름", "ファイル名をタギングするフィールド名", "要进行文件名标记的字段"), false);
return Arrays.asList(basePath, dirPathPattern, fileNamePattern, datePattern, dateFormat, dateLocale, timezone,
newlogRegex, newlogEndRegex, charset, recursive, fileTag);
}
| public Collection<LoggerConfigOption> getConfigOptions() {
LoggerConfigOption basePath = new MutableStringConfigType("base_path", t("Directory path", "디렉터리 경로", "ディレクトリ経路", "目录"),
t(
"Base log file directory path", "로그 파일을 수집할 대상 디렉터리 경로", "ログファイルを収集する対象ディレクトリ経路", "要采集的日志文件所在目录"), true);
LoggerConfigOption dirPathPattern = new MutableStringConfigType("dirpath_pattern", t("Directory Path pattern",
"디렉토리 이름 패턴", "ディレクトリ経路パータン", "目录名称模式"), t("Regular expression to match directory path",
"대상 로그 파일이 있는 디렉토리를 선택하는데 사용할 정규표현식", "対象ログファイルがあるディレクトリを選ぶとき使う正規表現", "表示要采集的文件所在目录的正则表达式"), false);
LoggerConfigOption fileNamePattern = new MutableStringConfigType("filename_pattern", t("Filename pattern", "파일이름 패턴",
"ファイル名パータン", "文件名模式"), t("Regular expression to match log file name", "대상 로그 파일을 선택하는데 사용할 정규표현식",
"対象ログファイルを選ぶとき使う正規表現", "用于筛选文件的正则表达式"), true);
LoggerConfigOption datePattern = new MutableStringConfigType("date_pattern", t("Date pattern", "날짜 정규표현식", "日付正規表現",
"日期正则表达式"), t("Regular expression to match date and time strings", "날짜 및 시각을 추출하는데 사용할 정규표현식", "日付と時刻を解析する正規表現",
"用于提取日期及时间的正则表达式"), false);
LoggerConfigOption dateFormat = new MutableStringConfigType("date_format", t("Date format", "날짜 포맷", "日付フォーマット", "日期格式"),
t("date format to parse date and time strings. e.g. yyyy-MM-dd HH:mm:ss",
"날짜 및 시각 문자열을 파싱하는데 사용할 포맷. 예) yyyy-MM-dd HH:mm:ss", "日付と時刻を解析するフォーマット。例) yyyy-MM-dd HH:mm:ss",
"用于解析日期及时间字符串的格式。 示例) yyyy-MM-dd HH:mm:ss"), false);
LoggerConfigOption dateLocale = new MutableStringConfigType("date_locale", t("Date locale", "날짜 로케일", "日付ロケール", "日期区域"),
t("date locale, e.g. en", "날짜 로케일, 예를 들면 ko", "日付ロケール。例えばjp", "日期区域, 例如 zh"), false);
LoggerConfigOption timezone = new MutableStringConfigType("timezone", t("Time zone", "시간대", "時間帯", "时区"), t(
"time zone, e.g. EST or America/New_york ", "시간대, 예를 들면 KST 또는 Asia/Seoul", "時間帯。例えばJSTまたはAsia/Tokyo",
"时区, 例如 Asia/Beijing"), false);
LoggerConfigOption newlogRegex = new MutableStringConfigType("newlog_designator", t("Regex for first line", "로그 시작 정규식",
"ログ始め正規表現", "日志起始正则表达式"), t("Regular expression to determine whether the line is start of new log."
+ "(if a line does not matches, the line will be merged to prev line.).",
"새 로그의 시작을 인식하기 위한 정규식(매칭되지 않는 경우 이전 줄에 병합됨)", "新しいログの始まりを認識する正規表現 (マッチングされない場合は前のラインに繋げる)"
, "用于识别日志起始位置的正则表达式(如没有匹配项,则合并到之前日志)"), false);
LoggerConfigOption newlogEndRegex = new MutableStringConfigType("newlog_end_designator", t("Regex for last line",
"로그 끝 정규식", "ログ終わり正規表現", "日志结束正则表达式"), t("Regular expression to determine whether the line is end of new log."
+ "(if a line does not matches, the line will be merged to prev line.).",
"로그의 끝을 인식하기 위한 정규식(매칭되지 않는 경우 이전 줄에 병합됨)", "ログの終わりを認識する正規表現 (マッチングされない場合は前のラインに繋げる)"
, "用于识别日志结束位置地正则表达式(如没有匹配项,则合并到之前日志)"), false);
LoggerConfigOption charset = new MutableStringConfigType("charset", t("Charset", "문자 집합", "文字セット", "字符集"), t(
"charset encoding", "텍스트 파일의 문자 인코딩 방식", "テキストファイルの文字エンコーディング方式", "文本文件的字符编码方式"), false);
LoggerConfigOption recursive = new MutableStringConfigType("recursive", t("Recursive", "하위 디렉터리 포함", "再帰", "采集子目录"), t(
"Include sub-directories. default is false", "하위 디렉터리 포함 여부, 기본값 false", "下位ディレクトリを含む。基本値はfalse",
"true表示采集子目录,默认值为false。"), false);
LoggerConfigOption fileTag = new MutableStringConfigType("file_tag", t("Filename Tag", "파일네임 태그", "ファイル名タグ", "文件名标记"), t(
"Field name for filename tagging", "파일명을 태깅할 필드 이름", "ファイル名をタギングするフィールド名", "要进行文件名标记的字段"), false);
return Arrays.asList(basePath, dirPathPattern, fileNamePattern, datePattern, dateFormat, dateLocale, timezone,
newlogRegex, newlogEndRegex, charset, recursive, fileTag);
}
|
diff --git a/src/main/de/fzi/cjunit/jpf/exceptioninfo/ExceptionWrapper.java b/src/main/de/fzi/cjunit/jpf/exceptioninfo/ExceptionWrapper.java
index 08a8ed9..9b12bd6 100644
--- a/src/main/de/fzi/cjunit/jpf/exceptioninfo/ExceptionWrapper.java
+++ b/src/main/de/fzi/cjunit/jpf/exceptioninfo/ExceptionWrapper.java
@@ -1,81 +1,80 @@
/*
* This file is covered by the terms of the Common Public License v1.0.
*
* Copyright (c) SZEDER Gábor
*
* Parts of this software were developed within the JEOPARD research
* project, which received funding from the European Union's Seventh
* Framework Programme under grant agreement No. 216682.
*/
package de.fzi.cjunit.jpf.exceptioninfo;
import gov.nasa.jpf.jvm.ElementInfo;
public class ExceptionWrapper extends ElementInfoWrapper
implements ExceptionInfo {
StackTraceElementWrapper[] stackTrace;
ExceptionWrapper cause;
boolean causeInitialized;
public ExceptionWrapper(ElementInfo elementInfo) {
super(elementInfo, ExceptionInfoDefaultImpl.class);
}
@Override
public String getClassName() {
return getStringField("className");
}
@Override
public String getMessage() {
return getStringField("message");
}
public int getStackTraceDepth() {
return getArrayLength("stackTrace");
}
@Override
public StackTraceElementInfo[] getStackTrace() {
if (stackTrace != null) {
return stackTrace;
}
ElementInfo[] array = getReferenceArray("stackTrace");
- StackTraceElementWrapper[] stackTrace
- = new StackTraceElementWrapper[array.length];
+ stackTrace = new StackTraceElementWrapper[array.length];
int i = 0;
for (ElementInfo ei : array) {
stackTrace[i] = new StackTraceElementWrapper(ei);
i++;
}
return stackTrace;
}
@Override
public ExceptionInfo getCause() {
if (causeInitialized) {
return cause;
}
ElementInfo ei = getElementInfoForField("cause");
if (ei == null) {
cause = null;
} else {
cause = new ExceptionWrapper(ei);
}
causeInitialized = true;
return cause;
}
@Override
public boolean hasCause() {
return getCause() != null;
}
}
| true | true | public StackTraceElementInfo[] getStackTrace() {
if (stackTrace != null) {
return stackTrace;
}
ElementInfo[] array = getReferenceArray("stackTrace");
StackTraceElementWrapper[] stackTrace
= new StackTraceElementWrapper[array.length];
int i = 0;
for (ElementInfo ei : array) {
stackTrace[i] = new StackTraceElementWrapper(ei);
i++;
}
return stackTrace;
}
| public StackTraceElementInfo[] getStackTrace() {
if (stackTrace != null) {
return stackTrace;
}
ElementInfo[] array = getReferenceArray("stackTrace");
stackTrace = new StackTraceElementWrapper[array.length];
int i = 0;
for (ElementInfo ei : array) {
stackTrace[i] = new StackTraceElementWrapper(ei);
i++;
}
return stackTrace;
}
|
diff --git a/src/main/java/io/ReadStdinInt15.java b/src/main/java/io/ReadStdinInt15.java
index bd336390..e503b929 100644
--- a/src/main/java/io/ReadStdinInt15.java
+++ b/src/main/java/io/ReadStdinInt15.java
@@ -1,21 +1,16 @@
package io;
import java.util.Scanner;
/**
* Read an int from Standard Input, using 1.5
* @author Ian F. Darwin, http://www.darwinsys.com/
* @version $Id$
*/
public class ReadStdinInt15 {
public static void main(String[] ap) {
int val;
- try {
- Scanner sc = new Scanner(System.in); // Requires Java 5
- val = sc.nextInt();
- } catch (NumberFormatException ex) {
- System.err.println("Not a valid number: " + ex);
- return;
- }
+ Scanner sc = new Scanner(System.in); // Requires Java 5
+ val = sc.nextInt();
System.out.println("I read this number: " + val);
}
}
| true | true | public static void main(String[] ap) {
int val;
try {
Scanner sc = new Scanner(System.in); // Requires Java 5
val = sc.nextInt();
} catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + ex);
return;
}
System.out.println("I read this number: " + val);
}
| public static void main(String[] ap) {
int val;
Scanner sc = new Scanner(System.in); // Requires Java 5
val = sc.nextInt();
System.out.println("I read this number: " + val);
}
|
diff --git a/jvstm/src/jvstm/Transaction.java b/jvstm/src/jvstm/Transaction.java
index 4b8bb34..8e62a64 100644
--- a/jvstm/src/jvstm/Transaction.java
+++ b/jvstm/src/jvstm/Transaction.java
@@ -1,241 +1,241 @@
/*
* JVSTM: a Java library for Software Transactional Memory
* Copyright (C) 2005 INESC-ID Software Engineering Group
* http://www.esw.inesc-id.pt
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author's contact:
* INESC-ID Software Engineering Group
* Rua Alves Redol 9
* 1000 - 029 Lisboa
* Portugal
*/
package jvstm;
import java.util.concurrent.atomic.AtomicReference;
public abstract class Transaction implements Comparable<Transaction> {
// static part starts here
private static int commited = 0;
protected static final ActiveTransactionQueue ACTIVE_TXS = new ActiveTransactionQueue();
protected static final ThreadLocal<Transaction> current = new ThreadLocal<Transaction>();
private static TransactionFactory TRANSACTION_FACTORY = new TransactionFactory() {
public Transaction makeTopLevelTransaction(int txNumber) {
return new TopLevelTransaction(txNumber);
}
public Transaction makeReadOnlyTopLevelTransaction(int txNumber) {
return new ReadTransaction(txNumber);
}
};
public static void setTransactionFactory(TransactionFactory factory) {
TRANSACTION_FACTORY = factory;
}
public static Transaction current() {
return current.get();
}
public static synchronized int getCommitted() {
return commited;
}
public static synchronized void setCommitted(int number) {
commited = Math.max(number, commited);
}
public static void addTxQueueListener(TxQueueListener listener) {
ACTIVE_TXS.addListener(listener);
}
public static Transaction begin() {
return begin(false);
}
static int maxQSize = 0;
public static Transaction begin(boolean readOnly) {
Transaction parent = current.get();
Transaction tx = null;
// we need to synchronize on the queue LOCK to inhibit the queue clean-up because we
// don't want that a transaction that commits between we get the last committed number
// and we add the new transaction cleans up the version number that we got before
// the new transaction is added to the queue
ACTIVE_TXS.LOCK.lock();
try {
- int qSize = ACTIVE_TXS.getQueueSize() % 10;
+ int qSize = ACTIVE_TXS.getQueueSize() / 10;
if (qSize > maxQSize) {
maxQSize = qSize;
System.out.printf("# active transactions max is %d\n", maxQSize * 10);
}
if (parent == null) {
if (readOnly) {
tx = TRANSACTION_FACTORY.makeReadOnlyTopLevelTransaction(getCommitted());
} else {
tx = TRANSACTION_FACTORY.makeTopLevelTransaction(getCommitted());
}
} else {
tx = parent.makeNestedTransaction();
}
current.set(tx);
ACTIVE_TXS.add(tx);
} finally {
ACTIVE_TXS.LOCK.unlock();
}
return tx;
}
public static void abort() {
Transaction tx = current.get();
tx.abortTx();
}
public static void commit() {
Transaction tx = current.get();
tx.commitTx(true);
}
public static void checkpoint() {
Transaction tx = current.get();
tx.commitTx(false);
}
protected int number;
protected Transaction parent;
protected boolean finished = false;
protected volatile Thread thread = Thread.currentThread();
public Transaction(int number) {
this.number = number;
}
public Transaction(Transaction parent) {
this(parent.getNumber());
this.parent = parent;
}
public Thread getThread() {
return thread;
}
protected Transaction getParent() {
return parent;
}
public int getNumber() {
return number;
}
protected void setNumber(int number) {
this.number = number;
}
public int compareTo(Transaction o) {
return (this.getNumber() - o.getNumber());
}
protected void renumber(int txNumber) {
// To keep the queue ordered, we have to remove and reinsert the TX when it is renumbered
ACTIVE_TXS.renumberTransaction(this, txNumber);
}
protected void abortTx() {
finishTx();
}
protected void commitTx(boolean finishAlso) {
doCommit();
if (finishAlso) {
finishTx();
}
}
private void finishTx() {
// ensure that this method is called only by the thread "owning" the transaction,
// because, otherwise, we may not set the current ThreadLocal variable of the correct thread
if (Thread.currentThread() != this.thread) {
throw new Error("ERROR: Cannot finish a transaction from another thread than the one running it");
}
finish();
current.set(this.getParent());
// clean up the reference to the thread
this.thread = null;
this.finished = true;
// notify the active transaction's queue so that it may clean up
ACTIVE_TXS.noteTxFinished(this);
}
public boolean isFinished() {
return finished;
}
protected void finish() {
// intentionally empty
}
protected void gcTransaction() {
// by default, do nothing
}
protected abstract Transaction makeNestedTransaction();
protected abstract <T> void register(VBox<T> vbox, VBoxBody<T> body);
protected abstract <T> VBoxBody<T> getBodyForRead(VBox<T> vbox);
protected abstract <T> VBoxBody<T> getBodyForWrite(VBox<T> vbox);
protected abstract <T> T getPerTxValue(PerTxBox<T> box, T initial);
protected abstract <T> void setPerTxValue(PerTxBox<T> box, T value);
protected abstract void doCommit();
public static void transactionallyDo(TransactionalCommand command) {
while (true) {
Transaction tx = Transaction.begin();
try {
command.doIt();
tx.commit();
tx = null;
return;
} catch (CommitException ce) {
tx.abort();
tx = null;
} finally {
if (tx != null) {
tx.abort();
}
}
}
}
}
| true | true | public static Transaction begin(boolean readOnly) {
Transaction parent = current.get();
Transaction tx = null;
// we need to synchronize on the queue LOCK to inhibit the queue clean-up because we
// don't want that a transaction that commits between we get the last committed number
// and we add the new transaction cleans up the version number that we got before
// the new transaction is added to the queue
ACTIVE_TXS.LOCK.lock();
try {
int qSize = ACTIVE_TXS.getQueueSize() % 10;
if (qSize > maxQSize) {
maxQSize = qSize;
System.out.printf("# active transactions max is %d\n", maxQSize * 10);
}
if (parent == null) {
if (readOnly) {
tx = TRANSACTION_FACTORY.makeReadOnlyTopLevelTransaction(getCommitted());
} else {
tx = TRANSACTION_FACTORY.makeTopLevelTransaction(getCommitted());
}
} else {
tx = parent.makeNestedTransaction();
}
current.set(tx);
ACTIVE_TXS.add(tx);
} finally {
ACTIVE_TXS.LOCK.unlock();
}
return tx;
}
| public static Transaction begin(boolean readOnly) {
Transaction parent = current.get();
Transaction tx = null;
// we need to synchronize on the queue LOCK to inhibit the queue clean-up because we
// don't want that a transaction that commits between we get the last committed number
// and we add the new transaction cleans up the version number that we got before
// the new transaction is added to the queue
ACTIVE_TXS.LOCK.lock();
try {
int qSize = ACTIVE_TXS.getQueueSize() / 10;
if (qSize > maxQSize) {
maxQSize = qSize;
System.out.printf("# active transactions max is %d\n", maxQSize * 10);
}
if (parent == null) {
if (readOnly) {
tx = TRANSACTION_FACTORY.makeReadOnlyTopLevelTransaction(getCommitted());
} else {
tx = TRANSACTION_FACTORY.makeTopLevelTransaction(getCommitted());
}
} else {
tx = parent.makeNestedTransaction();
}
current.set(tx);
ACTIVE_TXS.add(tx);
} finally {
ACTIVE_TXS.LOCK.unlock();
}
return tx;
}
|
diff --git a/core/src/test/java/org/infinispan/distribution/SingleOwnerTest.java b/core/src/test/java/org/infinispan/distribution/SingleOwnerTest.java
index 5f0a1279b2..771ad7de1d 100644
--- a/core/src/test/java/org/infinispan/distribution/SingleOwnerTest.java
+++ b/core/src/test/java/org/infinispan/distribution/SingleOwnerTest.java
@@ -1,134 +1,134 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2009 Red Hat Inc. and/or its affiliates and other
* contributors as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a full listing of
* individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.infinispan.distribution;
import org.infinispan.Cache;
import org.infinispan.CacheException;
import org.infinispan.config.Configuration;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.util.concurrent.IsolationLevel;
import org.testng.annotations.Test;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
/**
* Test single owner distributed cache configurations.
*
* @author Galder Zamarreño
* @since 4.0
*/
@Test(groups = "functional", testName = "distribution.SingleOwnerTest")
public class SingleOwnerTest extends BaseDistFunctionalTest {
@Override
protected void createCacheManagers() throws Throwable {
cacheName = "dist";
configuration = getDefaultClusteredConfig(sync ? Configuration.CacheMode.DIST_SYNC : Configuration.CacheMode.DIST_ASYNC, tx);
if (!testRetVals) {
configuration.setUnsafeUnreliableReturnValues(true);
// we also need to use repeatable read for tests to work when we dont have reliable return values, since the
// tests repeatedly queries changes
configuration.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
}
configuration.setSyncReplTimeout(3, TimeUnit.SECONDS);
configuration.setNumOwners(1);
configuration.setLockAcquisitionTimeout(45, TimeUnit.SECONDS);
caches = createClusteredCaches(2, cacheName, configuration);
c1 = caches.get(0);
c2 = caches.get(1);
cacheAddresses = new ArrayList<Address>(2);
for (Cache cache : caches) {
EmbeddedCacheManager cacheManager = cache.getCacheManager();
cacheAddresses.add(cacheManager.getAddress());
}
waitForJoinTasksToComplete(60000, c1, c2);
}
public void testPutOnKeyOwner() {
Cache[] caches = getOwners("mykey", 1);
assert caches.length == 1;
Cache ownerCache = caches[0];
ownerCache.put("mykey", new Object());
}
public void testClearOnKeyOwner() {
Cache[] caches = getOwners("mykey", 1);
assert caches.length == 1;
Cache ownerCache = caches[0];
ownerCache.clear();
}
public void testRetrieveNonSerializableKeyFromNonOwner() {
Cache[] owners = getOwners("yourkey", 1);
Cache[] nonOwners = getNonOwners("yourkey", 1);
assert owners.length == 1;
assert nonOwners.length == 1;
Cache ownerCache = owners[0];
Cache nonOwnerCache = nonOwners[0];
ownerCache.put("yourkey", new Object());
try {
nonOwnerCache.get("yourkey");
assert false : "Should have failed with a org.infinispan.marshall.NotSerializableException";
} catch (org.infinispan.marshall.NotSerializableException e) {
}
}
public void testErrorWhenRetrievingKeyFromNonOwner() {
log.trace("Before test");
Cache[] owners = getOwners("diffkey", 1);
Cache[] nonOwners = getNonOwners("diffkey", 1);
assert owners.length == 1;
assert nonOwners.length == 1;
Cache ownerCache = owners[0];
Cache nonOwnerCache = nonOwners[0];
ownerCache.put("diffkey", new Externalizable() {
private static final long serialVersionUID = -483939825697574242L;
public void writeExternal(ObjectOutput out) throws IOException {
throw new UnknownError();
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
});
try {
nonOwnerCache.get("diffkey");
assert false : "Should have failed with a CacheException that contains an UnknownError";
} catch (CacheException e) {
if (e.getCause() != null) {
- assert e.getCause().getCause() instanceof UnknownError : e.getCause();
+ assert e.getCause() instanceof UnknownError : e.getCause();
} else {
throw e;
}
}
}
}
| true | true | public void testErrorWhenRetrievingKeyFromNonOwner() {
log.trace("Before test");
Cache[] owners = getOwners("diffkey", 1);
Cache[] nonOwners = getNonOwners("diffkey", 1);
assert owners.length == 1;
assert nonOwners.length == 1;
Cache ownerCache = owners[0];
Cache nonOwnerCache = nonOwners[0];
ownerCache.put("diffkey", new Externalizable() {
private static final long serialVersionUID = -483939825697574242L;
public void writeExternal(ObjectOutput out) throws IOException {
throw new UnknownError();
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
});
try {
nonOwnerCache.get("diffkey");
assert false : "Should have failed with a CacheException that contains an UnknownError";
} catch (CacheException e) {
if (e.getCause() != null) {
assert e.getCause().getCause() instanceof UnknownError : e.getCause();
} else {
throw e;
}
}
}
| public void testErrorWhenRetrievingKeyFromNonOwner() {
log.trace("Before test");
Cache[] owners = getOwners("diffkey", 1);
Cache[] nonOwners = getNonOwners("diffkey", 1);
assert owners.length == 1;
assert nonOwners.length == 1;
Cache ownerCache = owners[0];
Cache nonOwnerCache = nonOwners[0];
ownerCache.put("diffkey", new Externalizable() {
private static final long serialVersionUID = -483939825697574242L;
public void writeExternal(ObjectOutput out) throws IOException {
throw new UnknownError();
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
}
});
try {
nonOwnerCache.get("diffkey");
assert false : "Should have failed with a CacheException that contains an UnknownError";
} catch (CacheException e) {
if (e.getCause() != null) {
assert e.getCause() instanceof UnknownError : e.getCause();
} else {
throw e;
}
}
}
|
diff --git a/AngryUTBM/src/model/GameModel.java b/AngryUTBM/src/model/GameModel.java
index c8d61e1..344352e 100644
--- a/AngryUTBM/src/model/GameModel.java
+++ b/AngryUTBM/src/model/GameModel.java
@@ -1,324 +1,324 @@
package model;
import view.GameView;
import model.entities.Bird;
import model.entities.Egg;
import model.entities.Entity;
import model.entities.EntityThread;
import model.entities.Pig;
import java.util.ArrayList;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.event.EventListenerList;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class GameModel implements ActionListener {
private GameView angryView;
private Level level;
private ArrayList<Player> players;
private ArrayList<Entity> entities;
private Bird currentBird;
private Timer timer;
private EntityThread entityThread;
private EventListenerList listeners;
private Player currentPlayer;
private String difficulty;
private int currentLevel;
private int currentHighestScore;
public GameModel() {
entities = new ArrayList<Entity>();
players = new ArrayList<Player>();
// on parcourt tous les elements du repertoire
try{
File initial = new File ("save");
for (File f:initial.listFiles())
{
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
Player pl = (Player)ois.readObject();
players.add(pl);
}
}
catch(Exception e)
{
e.printStackTrace();
}
timer = new Timer(5, this);
timer.start();
listeners = new EventListenerList();
entityThread = new EntityThread(entities);
addListListener(entityThread);
}
public GameView getAngryView() {
return angryView;
}
public void setAngryView(GameView display) {
this.angryView = display;
}
public Level getMap() {
return level;
}
public ArrayList<Player> getPlayers(){
return players;
}
public void setMap(Level map) {
this.level = map;
entities = map.getEntityList();
for(Entity e : entities) {
if(e instanceof Bird) {
currentBird = (Bird) e;
break;
}
}
fireListChanged();
if (!entityThread.isAlive())
entityThread.start();
}
public ArrayList<Entity> getEntityList() {
return entities;
}
public void addEgg() {
int eggLeft = currentBird.getEggLeft();
if (eggLeft > 0) {
entities.add(new Egg((int)currentBird.getPosition().getX(), (int)currentBird.getPosition().getY()));
currentBird.setEggLeft(eggLeft-1);
}
else
System.out.println("Plus d'oeufs ! Fail !");
}
public void checkCollision() {
ArrayList<Entity> toRemove = new ArrayList<Entity>(); //On ne retire les entit�s de la liste qu'apr�s �tre sorti de la boucle
for(Entity entity : entities) {
int tabMap[][] = level.getTabMap();
if(entity instanceof Egg) {
Egg egg = (Egg) entity;
Rectangle hitBoxEgg = egg.getHitBox();
//Collisions oeuf/cochons
for(Entity entity2 : entities) {
if(entity2 instanceof Pig) {
Pig pig = (Pig) entity2;
Rectangle hitBoxPig = pig.getHitBox();
if(hitBoxPig.intersects(hitBoxEgg)) {
toRemove.add(egg);
toRemove.add(pig);
boolean win = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Pig) {
win = false;
break;
}
}
if(win) {
int score = 0;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird)
++score;
}
win(score);
}
}
}
}
//Collisions oeuf/d�cor
for(int x = 0; x < tabMap[0].length; ++x) {
for(int y = 0; y < tabMap.length; ++y) {
if(tabMap[y][x] != 0) {
Rectangle hitBoxScenery = new Rectangle(x*26,y*26,26,26);
if(hitBoxScenery.intersects(hitBoxEgg)) {
toRemove.add(egg);
if(tabMap[y][x] == 2)
tabMap[y][x] = 0;
level.setTabMap(tabMap);
}
}
}
}
}
if(entity instanceof Pig) {
Pig pig = (Pig) entity;
Rectangle hitBoxPig = pig.getHitBox();
//Collisions cochon/d�cor
for(int x = 0; x < tabMap[0].length; ++x) {
for(int y = 0; y < tabMap.length; ++y) {
if(tabMap[y][x] != 0) {
Rectangle hitBoxScenery = new Rectangle(x*26,y*26,25,25);
if(hitBoxScenery.intersects(hitBoxPig))
pig.changeDirection();
}
}
}
//On v�rifie que le cochon ne va pas marcher sur du vide
int casex = (hitBoxPig.x / 26);
int casey = (hitBoxPig.y / 26);
if(pig.goForward()) {
if(tabMap[casey+1][casex+1] == 0)
pig.changeDirection();
}
else {
if(tabMap[casey+1][casex] == 0)
pig.changeDirection();
}
//Collisions oiseaux/cochons
for(Entity entity2 : entities) {
if (entity2 instanceof Bird) {
Bird bird = (Bird) entity2;
Rectangle hitBoxBird = bird.getHitBox();
if(hitBoxBird.intersects(hitBoxPig)) {
toRemove.add(pig);
toRemove.add(bird);
boolean win = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Pig) {
win = false;
break;
}
}
if(win) {
int score = 0;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird)
++score;
}
win(score);
}
boolean lose = true;
for (Entity entity3 : entities) {
- if (entity3 instanceof Bird) {
+ if (entity3 instanceof Bird && !toRemove.contains(entity3)) {
currentBird = (Bird) entity3;
lose = false;
break;
}
}
if(lose) {
lose();
}
}
}
}
}
}
for(Entity entity : toRemove)
entities.remove(entity);
}
public boolean testCollision(Rectangle x, Rectangle y)
{
if(x.intersects(y))
return true;
return false;
}
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < entities.size(); ++i) {
if (entities.get(i) instanceof Egg) {
if (!entities.get(i).isVisible())
entities.remove(i);
}
if (entities.get(i) instanceof Bird) {
if (!entities.get(i).isVisible()) {
entities.remove(i);
boolean lose = true;
for (Entity entity : entities) {
if (entity instanceof Bird) {
currentBird = (Bird) entity;
lose = false;
break;
}
}
if(lose) {
lose();
}
}
}
}
checkCollision();
fireListChanged();
}
public void addListListener(ListListener listener) {
listeners.add(ListListener.class, listener);
}
public void removeListListener(ListListener l) {
listeners.remove(ListListener.class, l);
}
public void fireListChanged(){
ListListener[] listenerList = (ListListener[])listeners.getListeners(ListListener.class);
for(ListListener listener : listenerList){
listener.listChanged(new ListChangedEvent(this, getEntityList(), currentBird));
}
}
public void win(int score) {
javax.swing.JOptionPane.showMessageDialog(null, "Bravo, tu as gagné ! Ton score est " + score);
currentPlayer.finished(currentLevel, difficulty, score);
Level lvl = new Level("res/maps/lvl0" + (currentLevel+1) + ".txt");
if (lvl.isLoaded()) {
angryView.setMap(lvl);
this.setMap(lvl);
this.setCurrentLevel(currentLevel+1);
}
else {
javax.swing.JOptionPane.showMessageDialog(null, "Il n'y a aucun fichier map correspondant à ce niveau, tu peux insulter les développeurs");
}
}
public void lose() {
System.out.println("La lose! Vous avez perdu!");
}
public void setDifficulty(String dif) {
difficulty = dif;
}
public void setCurrentPlayer(Player p) {
currentPlayer = p;
}
public void setCurrentLevel(int l) {
currentLevel = l;
}
public void setCurrentHighScore() {
currentHighestScore = currentPlayer.getHighestScore(difficulty, currentLevel);
angryView.setCurrentHighestScore(currentHighestScore);
}
public Bird getCurrentBird() {
return currentBird;
}
}
| true | true | public void checkCollision() {
ArrayList<Entity> toRemove = new ArrayList<Entity>(); //On ne retire les entit�s de la liste qu'apr�s �tre sorti de la boucle
for(Entity entity : entities) {
int tabMap[][] = level.getTabMap();
if(entity instanceof Egg) {
Egg egg = (Egg) entity;
Rectangle hitBoxEgg = egg.getHitBox();
//Collisions oeuf/cochons
for(Entity entity2 : entities) {
if(entity2 instanceof Pig) {
Pig pig = (Pig) entity2;
Rectangle hitBoxPig = pig.getHitBox();
if(hitBoxPig.intersects(hitBoxEgg)) {
toRemove.add(egg);
toRemove.add(pig);
boolean win = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Pig) {
win = false;
break;
}
}
if(win) {
int score = 0;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird)
++score;
}
win(score);
}
}
}
}
//Collisions oeuf/d�cor
for(int x = 0; x < tabMap[0].length; ++x) {
for(int y = 0; y < tabMap.length; ++y) {
if(tabMap[y][x] != 0) {
Rectangle hitBoxScenery = new Rectangle(x*26,y*26,26,26);
if(hitBoxScenery.intersects(hitBoxEgg)) {
toRemove.add(egg);
if(tabMap[y][x] == 2)
tabMap[y][x] = 0;
level.setTabMap(tabMap);
}
}
}
}
}
if(entity instanceof Pig) {
Pig pig = (Pig) entity;
Rectangle hitBoxPig = pig.getHitBox();
//Collisions cochon/d�cor
for(int x = 0; x < tabMap[0].length; ++x) {
for(int y = 0; y < tabMap.length; ++y) {
if(tabMap[y][x] != 0) {
Rectangle hitBoxScenery = new Rectangle(x*26,y*26,25,25);
if(hitBoxScenery.intersects(hitBoxPig))
pig.changeDirection();
}
}
}
//On v�rifie que le cochon ne va pas marcher sur du vide
int casex = (hitBoxPig.x / 26);
int casey = (hitBoxPig.y / 26);
if(pig.goForward()) {
if(tabMap[casey+1][casex+1] == 0)
pig.changeDirection();
}
else {
if(tabMap[casey+1][casex] == 0)
pig.changeDirection();
}
//Collisions oiseaux/cochons
for(Entity entity2 : entities) {
if (entity2 instanceof Bird) {
Bird bird = (Bird) entity2;
Rectangle hitBoxBird = bird.getHitBox();
if(hitBoxBird.intersects(hitBoxPig)) {
toRemove.add(pig);
toRemove.add(bird);
boolean win = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Pig) {
win = false;
break;
}
}
if(win) {
int score = 0;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird)
++score;
}
win(score);
}
boolean lose = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird) {
currentBird = (Bird) entity3;
lose = false;
break;
}
}
if(lose) {
lose();
}
}
}
}
}
}
for(Entity entity : toRemove)
entities.remove(entity);
}
| public void checkCollision() {
ArrayList<Entity> toRemove = new ArrayList<Entity>(); //On ne retire les entit�s de la liste qu'apr�s �tre sorti de la boucle
for(Entity entity : entities) {
int tabMap[][] = level.getTabMap();
if(entity instanceof Egg) {
Egg egg = (Egg) entity;
Rectangle hitBoxEgg = egg.getHitBox();
//Collisions oeuf/cochons
for(Entity entity2 : entities) {
if(entity2 instanceof Pig) {
Pig pig = (Pig) entity2;
Rectangle hitBoxPig = pig.getHitBox();
if(hitBoxPig.intersects(hitBoxEgg)) {
toRemove.add(egg);
toRemove.add(pig);
boolean win = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Pig) {
win = false;
break;
}
}
if(win) {
int score = 0;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird)
++score;
}
win(score);
}
}
}
}
//Collisions oeuf/d�cor
for(int x = 0; x < tabMap[0].length; ++x) {
for(int y = 0; y < tabMap.length; ++y) {
if(tabMap[y][x] != 0) {
Rectangle hitBoxScenery = new Rectangle(x*26,y*26,26,26);
if(hitBoxScenery.intersects(hitBoxEgg)) {
toRemove.add(egg);
if(tabMap[y][x] == 2)
tabMap[y][x] = 0;
level.setTabMap(tabMap);
}
}
}
}
}
if(entity instanceof Pig) {
Pig pig = (Pig) entity;
Rectangle hitBoxPig = pig.getHitBox();
//Collisions cochon/d�cor
for(int x = 0; x < tabMap[0].length; ++x) {
for(int y = 0; y < tabMap.length; ++y) {
if(tabMap[y][x] != 0) {
Rectangle hitBoxScenery = new Rectangle(x*26,y*26,25,25);
if(hitBoxScenery.intersects(hitBoxPig))
pig.changeDirection();
}
}
}
//On v�rifie que le cochon ne va pas marcher sur du vide
int casex = (hitBoxPig.x / 26);
int casey = (hitBoxPig.y / 26);
if(pig.goForward()) {
if(tabMap[casey+1][casex+1] == 0)
pig.changeDirection();
}
else {
if(tabMap[casey+1][casex] == 0)
pig.changeDirection();
}
//Collisions oiseaux/cochons
for(Entity entity2 : entities) {
if (entity2 instanceof Bird) {
Bird bird = (Bird) entity2;
Rectangle hitBoxBird = bird.getHitBox();
if(hitBoxBird.intersects(hitBoxPig)) {
toRemove.add(pig);
toRemove.add(bird);
boolean win = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Pig) {
win = false;
break;
}
}
if(win) {
int score = 0;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird)
++score;
}
win(score);
}
boolean lose = true;
for (Entity entity3 : entities) {
if (entity3 instanceof Bird && !toRemove.contains(entity3)) {
currentBird = (Bird) entity3;
lose = false;
break;
}
}
if(lose) {
lose();
}
}
}
}
}
}
for(Entity entity : toRemove)
entities.remove(entity);
}
|
diff --git a/gis-metadata/gis-metadata/collection/src/main/java/org/fao/fi/gis/metadata/MetadataGenerator.java b/gis-metadata/gis-metadata/collection/src/main/java/org/fao/fi/gis/metadata/MetadataGenerator.java
index bc56c5d..f6a4aad 100644
--- a/gis-metadata/gis-metadata/collection/src/main/java/org/fao/fi/gis/metadata/MetadataGenerator.java
+++ b/gis-metadata/gis-metadata/collection/src/main/java/org/fao/fi/gis/metadata/MetadataGenerator.java
@@ -1,190 +1,190 @@
package org.fao.fi.gis.metadata;
import java.io.File;
import java.util.Arrays;
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 org.fao.fi.gis.metadata.association.GeographicMetaObject;
import org.fao.fi.gis.metadata.association.GeographicMetaObjectImpl;
import org.fao.fi.gis.metadata.collection.eez.EezEntity;
import org.fao.fi.gis.metadata.collection.eez.FLODEezEntity;
import org.fao.fi.gis.metadata.collection.rfb.FLODRfbEntity;
import org.fao.fi.gis.metadata.collection.rfb.RfbEntity;
import org.fao.fi.gis.metadata.collection.species.FLODSpeciesEntity;
import org.fao.fi.gis.metadata.collection.species.SpeciesEntity;
import org.fao.fi.gis.metadata.feature.FeatureTypeProperty;
import org.fao.fi.gis.metadata.entity.EntityAddin;
import org.fao.fi.gis.metadata.entity.GeographicEntity;
import org.fao.fi.gis.metadata.model.MetadataConfig;
import org.fao.fi.gis.metadata.publisher.Publisher;
import org.fao.fi.gis.metadata.util.FeatureTypeUtils;
import org.fao.fi.gis.metadata.utils.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
/**
* Main App to launch the batch data/metadata publication
*
*/
public class MetadataGenerator {
private static Logger LOGGER = LoggerFactory.getLogger(MetadataGenerator.class);
static Map<String, Map<EntityAddin, String>> set = null;
/**
* Main
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//Read the configuration
LOGGER.info("(1) Loading the configuration file");
- MetadataConfig config = MetadataConfig.fromXML(new File("c:/gis/metadata/config/species.xml"));
+ MetadataConfig config = MetadataConfig.fromXML(new File(args[0]));
//read the codelists
LOGGER.info("(2) Loading the reference list");
String collectionType = config.getSettings().getPublicationSettings().getCollectionType();
LOGGER.info("Collection type = "+collectionType);
if(collectionType.matches("species")){
set = CollectionUtils.parseSpeciesList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}else if(collectionType.matches("eez")){
set = CollectionUtils.parseEezList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}else if(collectionType.matches("rfb")){
set = CollectionUtils.parseRfbList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}
//only for test (apply to the first element)
if(config.getSettings().getPublicationSettings().isTest()){
String testCode = (String) set.keySet().toArray()[0];
Map<EntityAddin,String> addin = set.get(testCode);
set = new HashMap<String, Map<EntityAddin,String>>();
set.put(testCode, addin);
}
// configure the publisher
Publisher publisher = new Publisher(config);
int size = 0;
// UTILS
Set<String> metalist = new HashSet<String>();
List<String> existingLayers = publisher.getDataPublisher().GSReader
.getLayers().getNames(); // read once, improve performance
// iteration on the entities
LOGGER.info("(3) Start metadata creation & publication");
Iterator<String> entityIterator = set.keySet().iterator();
while (entityIterator.hasNext()) {
String code = entityIterator.next();
LOGGER.info("==============");
LOGGER.info("Publishing single layer & metadata for: "+code);
Map<FeatureTypeProperty, Object> geoproperties = null;
GeographicEntity entity = null;
boolean exist = existingLayers.contains(config.getSettings().getGeographicServerSettings().getTargetLayerPrefix() + "_" + code);
String action = config.getSettings().getPublicationSettings().getAction();
LOGGER.info("== ACTION: "+action+" == ");
//configure FLOD entity
JsonObject flodResponse = null;
if(collectionType.matches("species")){
FLODSpeciesEntity flodEntity = new FLODSpeciesEntity(code);
flodResponse = flodEntity.getFlodContent();
}else if(collectionType.matches("eez")){
FLODEezEntity flodEntity = new FLODEezEntity(code);
flodResponse = flodEntity.getFlodContent();
}else if(collectionType.matches("rfb")){
FLODRfbEntity flodEntity = new FLODRfbEntity(code);
flodResponse = flodEntity.getFlodContent();
}
//CHECK ACTION
if (action.matches("CHECK")) {
if (!exist) {
if (flodResponse != null) {
metalist.add(code);
}
}
} else{
// calculate geoproperties
if (action.matches("PUBLISH")){
while (geoproperties == null) {
geoproperties = FeatureTypeUtils
.computeFeatureTypeProperties(config.getSettings().getGeographicServerSettings(),
code, config.getSettings().getPublicationSettings().getBuffer());
}
}
//configure entity
if (flodResponse != null) {
if(collectionType.matches("species")){
entity = new SpeciesEntity(code, set.get(code), config);
}else if(collectionType.matches("eez")){
entity = new EezEntity(code, set.get(code), config);
}else if(collectionType.matches("rfb")){
entity = new RfbEntity(code, set.get(code), config);
}
boolean figis = config.getSettings().getPublicationSettings().isFigis();
GeographicMetaObject metaObject = new GeographicMetaObjectImpl(Arrays.asList(entity), geoproperties, null, set.get(code), config);
// PUBLISH ACTION
if (action.matches("PUBLISH")) {
String style = set.get(code).get(EntityAddin.Style);
LOGGER.debug(style);
publisher.publish(metaObject, style, exist);
size = size + 1;
LOGGER.info(size + " published metalayers");
// UNPUBLISH ACTION
}else if (action.matches("UNPUBLISH")) {
publisher.unpublish(metaObject, exist);
}
}else{
metalist.add(code);
}
}
}
// list all items for which the metadata production was not performed
if(metalist.size() > 0){
LOGGER.info("=======================================");
LOGGER.info("=========== NOT PRODUCED ==============");
LOGGER.info("==================|====================");
LOGGER.info("==================V====================");
LOGGER.info("=======================================");
Iterator<String> it2 = metalist.iterator();
while (it2.hasNext()) {
LOGGER.info(it2.next());
}
}
}
}
| true | true | public static void main(String[] args) throws Exception {
//Read the configuration
LOGGER.info("(1) Loading the configuration file");
MetadataConfig config = MetadataConfig.fromXML(new File("c:/gis/metadata/config/species.xml"));
//read the codelists
LOGGER.info("(2) Loading the reference list");
String collectionType = config.getSettings().getPublicationSettings().getCollectionType();
LOGGER.info("Collection type = "+collectionType);
if(collectionType.matches("species")){
set = CollectionUtils.parseSpeciesList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}else if(collectionType.matches("eez")){
set = CollectionUtils.parseEezList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}else if(collectionType.matches("rfb")){
set = CollectionUtils.parseRfbList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}
//only for test (apply to the first element)
if(config.getSettings().getPublicationSettings().isTest()){
String testCode = (String) set.keySet().toArray()[0];
Map<EntityAddin,String> addin = set.get(testCode);
set = new HashMap<String, Map<EntityAddin,String>>();
set.put(testCode, addin);
}
// configure the publisher
Publisher publisher = new Publisher(config);
int size = 0;
// UTILS
Set<String> metalist = new HashSet<String>();
List<String> existingLayers = publisher.getDataPublisher().GSReader
.getLayers().getNames(); // read once, improve performance
// iteration on the entities
LOGGER.info("(3) Start metadata creation & publication");
Iterator<String> entityIterator = set.keySet().iterator();
while (entityIterator.hasNext()) {
String code = entityIterator.next();
LOGGER.info("==============");
LOGGER.info("Publishing single layer & metadata for: "+code);
Map<FeatureTypeProperty, Object> geoproperties = null;
GeographicEntity entity = null;
boolean exist = existingLayers.contains(config.getSettings().getGeographicServerSettings().getTargetLayerPrefix() + "_" + code);
String action = config.getSettings().getPublicationSettings().getAction();
LOGGER.info("== ACTION: "+action+" == ");
//configure FLOD entity
JsonObject flodResponse = null;
if(collectionType.matches("species")){
FLODSpeciesEntity flodEntity = new FLODSpeciesEntity(code);
flodResponse = flodEntity.getFlodContent();
}else if(collectionType.matches("eez")){
FLODEezEntity flodEntity = new FLODEezEntity(code);
flodResponse = flodEntity.getFlodContent();
}else if(collectionType.matches("rfb")){
FLODRfbEntity flodEntity = new FLODRfbEntity(code);
flodResponse = flodEntity.getFlodContent();
}
//CHECK ACTION
if (action.matches("CHECK")) {
if (!exist) {
if (flodResponse != null) {
metalist.add(code);
}
}
} else{
// calculate geoproperties
if (action.matches("PUBLISH")){
while (geoproperties == null) {
geoproperties = FeatureTypeUtils
.computeFeatureTypeProperties(config.getSettings().getGeographicServerSettings(),
code, config.getSettings().getPublicationSettings().getBuffer());
}
}
//configure entity
if (flodResponse != null) {
if(collectionType.matches("species")){
entity = new SpeciesEntity(code, set.get(code), config);
}else if(collectionType.matches("eez")){
entity = new EezEntity(code, set.get(code), config);
}else if(collectionType.matches("rfb")){
entity = new RfbEntity(code, set.get(code), config);
}
boolean figis = config.getSettings().getPublicationSettings().isFigis();
GeographicMetaObject metaObject = new GeographicMetaObjectImpl(Arrays.asList(entity), geoproperties, null, set.get(code), config);
// PUBLISH ACTION
if (action.matches("PUBLISH")) {
String style = set.get(code).get(EntityAddin.Style);
LOGGER.debug(style);
publisher.publish(metaObject, style, exist);
size = size + 1;
LOGGER.info(size + " published metalayers");
// UNPUBLISH ACTION
}else if (action.matches("UNPUBLISH")) {
publisher.unpublish(metaObject, exist);
}
}else{
metalist.add(code);
}
}
}
// list all items for which the metadata production was not performed
if(metalist.size() > 0){
LOGGER.info("=======================================");
LOGGER.info("=========== NOT PRODUCED ==============");
LOGGER.info("==================|====================");
LOGGER.info("==================V====================");
LOGGER.info("=======================================");
Iterator<String> it2 = metalist.iterator();
while (it2.hasNext()) {
LOGGER.info(it2.next());
}
}
}
| public static void main(String[] args) throws Exception {
//Read the configuration
LOGGER.info("(1) Loading the configuration file");
MetadataConfig config = MetadataConfig.fromXML(new File(args[0]));
//read the codelists
LOGGER.info("(2) Loading the reference list");
String collectionType = config.getSettings().getPublicationSettings().getCollectionType();
LOGGER.info("Collection type = "+collectionType);
if(collectionType.matches("species")){
set = CollectionUtils.parseSpeciesList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}else if(collectionType.matches("eez")){
set = CollectionUtils.parseEezList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}else if(collectionType.matches("rfb")){
set = CollectionUtils.parseRfbList(config.getSettings()
.getPublicationSettings().getCodelistURL());
}
//only for test (apply to the first element)
if(config.getSettings().getPublicationSettings().isTest()){
String testCode = (String) set.keySet().toArray()[0];
Map<EntityAddin,String> addin = set.get(testCode);
set = new HashMap<String, Map<EntityAddin,String>>();
set.put(testCode, addin);
}
// configure the publisher
Publisher publisher = new Publisher(config);
int size = 0;
// UTILS
Set<String> metalist = new HashSet<String>();
List<String> existingLayers = publisher.getDataPublisher().GSReader
.getLayers().getNames(); // read once, improve performance
// iteration on the entities
LOGGER.info("(3) Start metadata creation & publication");
Iterator<String> entityIterator = set.keySet().iterator();
while (entityIterator.hasNext()) {
String code = entityIterator.next();
LOGGER.info("==============");
LOGGER.info("Publishing single layer & metadata for: "+code);
Map<FeatureTypeProperty, Object> geoproperties = null;
GeographicEntity entity = null;
boolean exist = existingLayers.contains(config.getSettings().getGeographicServerSettings().getTargetLayerPrefix() + "_" + code);
String action = config.getSettings().getPublicationSettings().getAction();
LOGGER.info("== ACTION: "+action+" == ");
//configure FLOD entity
JsonObject flodResponse = null;
if(collectionType.matches("species")){
FLODSpeciesEntity flodEntity = new FLODSpeciesEntity(code);
flodResponse = flodEntity.getFlodContent();
}else if(collectionType.matches("eez")){
FLODEezEntity flodEntity = new FLODEezEntity(code);
flodResponse = flodEntity.getFlodContent();
}else if(collectionType.matches("rfb")){
FLODRfbEntity flodEntity = new FLODRfbEntity(code);
flodResponse = flodEntity.getFlodContent();
}
//CHECK ACTION
if (action.matches("CHECK")) {
if (!exist) {
if (flodResponse != null) {
metalist.add(code);
}
}
} else{
// calculate geoproperties
if (action.matches("PUBLISH")){
while (geoproperties == null) {
geoproperties = FeatureTypeUtils
.computeFeatureTypeProperties(config.getSettings().getGeographicServerSettings(),
code, config.getSettings().getPublicationSettings().getBuffer());
}
}
//configure entity
if (flodResponse != null) {
if(collectionType.matches("species")){
entity = new SpeciesEntity(code, set.get(code), config);
}else if(collectionType.matches("eez")){
entity = new EezEntity(code, set.get(code), config);
}else if(collectionType.matches("rfb")){
entity = new RfbEntity(code, set.get(code), config);
}
boolean figis = config.getSettings().getPublicationSettings().isFigis();
GeographicMetaObject metaObject = new GeographicMetaObjectImpl(Arrays.asList(entity), geoproperties, null, set.get(code), config);
// PUBLISH ACTION
if (action.matches("PUBLISH")) {
String style = set.get(code).get(EntityAddin.Style);
LOGGER.debug(style);
publisher.publish(metaObject, style, exist);
size = size + 1;
LOGGER.info(size + " published metalayers");
// UNPUBLISH ACTION
}else if (action.matches("UNPUBLISH")) {
publisher.unpublish(metaObject, exist);
}
}else{
metalist.add(code);
}
}
}
// list all items for which the metadata production was not performed
if(metalist.size() > 0){
LOGGER.info("=======================================");
LOGGER.info("=========== NOT PRODUCED ==============");
LOGGER.info("==================|====================");
LOGGER.info("==================V====================");
LOGGER.info("=======================================");
Iterator<String> it2 = metalist.iterator();
while (it2.hasNext()) {
LOGGER.info(it2.next());
}
}
}
|
diff --git a/src/main/java/com/redhat/ceylon/compiler/js/CeylonCompileJsTool.java b/src/main/java/com/redhat/ceylon/compiler/js/CeylonCompileJsTool.java
index 58283f60..f94b681d 100644
--- a/src/main/java/com/redhat/ceylon/compiler/js/CeylonCompileJsTool.java
+++ b/src/main/java/com/redhat/ceylon/compiler/js/CeylonCompileJsTool.java
@@ -1,400 +1,400 @@
package com.redhat.ceylon.compiler.js;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.redhat.ceylon.cmr.api.RepositoryManager;
import com.redhat.ceylon.cmr.ceylon.CeylonUtils;
import com.redhat.ceylon.cmr.ceylon.RepoUsingTool;
import com.redhat.ceylon.common.tool.Argument;
import com.redhat.ceylon.common.tool.Description;
import com.redhat.ceylon.common.tool.Option;
import com.redhat.ceylon.common.tool.OptionArgument;
import com.redhat.ceylon.common.tool.Summary;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.loader.JsModuleManagerFactory;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.io.VirtualFile;
@Summary("Compiles Ceylon source code to JavaScript and directly produces " +
"module and source archives in a module repository")
public class CeylonCompileJsTool extends RepoUsingTool {
private boolean profile = false;
private boolean optimize = false;
private boolean modulify = true;
private boolean indent = true;
private boolean comments = false;
private boolean verbose = false;
private boolean skipSrc = false;
private String user = null;
private String pass = null;
private String out = "modules";
private String encoding;
private List<String> src = Collections.singletonList("source");
private List<String> files = Collections.emptyList();
public CeylonCompileJsTool() {
super(CeylonCompileJsMessages.RESOURCE_BUNDLE);
}
@OptionArgument(argumentName="encoding")
@Description("Sets the encoding used for reading source files (default: platform-specific)")
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getEncoding(){
return encoding;
}
public boolean isProfile() {
return profile;
}
@Option
@Description("Time the compilation phases (results are printed to standard error)")
public void setProfile(boolean profile) {
this.profile = profile;
}
public boolean isOptimize() {
return optimize;
}
@Option
@Description("Create prototype-style JS code")
public void setOptimize(boolean optimize) {
this.optimize = optimize;
}
public boolean isModulify() {
return modulify;
}
@Option(longName="no-module")
@Description("Do **not** wrap generated code as CommonJS module")
public void setNoModulify(boolean nomodulify) {
this.modulify = !nomodulify;
}
public boolean isIndent() {
return indent;
}
@Option
@Description("Do **not** indent code")
public void setNoIndent(boolean noindent) {
this.indent = !noindent;
}
@Option
@Description("Equivalent to `--no-indent` `--no-comments`")
public void setCompact(boolean compact) {
this.setNoIndent(compact);
this.setNoComments(compact);
}
public boolean isComments() {
return comments;
}
@Option
@Description("Do **not** generate any comments")
public void setNoComments(boolean nocomments) {
this.comments = !nocomments;
}
public boolean isVerbose() {
return verbose;
}
@Option
@Description("Print messages while compiling")
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public String getUser() {
return user;
}
@OptionArgument(argumentName="name")
@Description("Sets the user name for use with an authenticated output repository" +
"(no default).")
public void setUser(String user) {
this.user = user;
}
public String getPass() {
return pass;
}
@OptionArgument(argumentName="secret")
@Description("Sets the password for use with an authenticated output repository" +
"(no default).")
public void setPass(String pass) {
this.pass = pass;
}
public List<String> getRepos() {
return getRepositoryAsStrings();
}
public List<String> getSrc() {
return src;
}
@OptionArgument(longName="src", argumentName="dirs")
@Description("Path to source files. " +
"Can be specified multiple times; you can also specify several " +
"paths separated by your operating system's `PATH` separator." +
" (default: `./source`)")
public void setSrc(List<String> src) {
this.src = src;
}
public String getOut() {
return out;
}
@Option
@Description("Do **not** generate .src archive - useful when doing joint compilation")
public void setSkipSrcArchive(boolean skip) {
skipSrc = skip;
}
public boolean isSkipSrcArchive() {
return skipSrc;
}
@OptionArgument(argumentName="url")
@Description("Specifies the output module repository (which must be publishable). " +
"(default: `./modules`)")
public void setOut(String out) {
this.out = out;
}
@Argument(argumentName="moduleOrFile", multiplicity="+")
public void setModule(List<String> moduleOrFile) {
this.files = moduleOrFile;
}
@Override
public void run() throws Exception {
final Options opts = new Options(getRepos(), getSrc(), systemRepo, getOut(), getUser(), getPass(), isOptimize(),
isModulify(), isIndent(), isComments(), isVerbose(), isProfile(), false, !skipSrc, encoding, offline);
run(opts, files);
}
private static void addFilesToCompilationSet(File dir, List<String> onlyFiles, boolean verbose) {
for (File e : dir.listFiles()) {
String n = e.getName().toLowerCase();
if (e.isFile() && (n.endsWith(".ceylon") || n.endsWith(".js"))) {
if (verbose) {
System.out.println("Adding to compilation set: " + e.getPath());
}
if (!onlyFiles.contains(e.getPath())) {
onlyFiles.add(e.getPath());
}
} else if (e.isDirectory()) {
addFilesToCompilationSet(e, onlyFiles, verbose);
}
}
}
public static void run(Options opts, List<String> files) throws IOException {
final TypeChecker typeChecker;
if (opts.isVerbose()) {
System.out.printf("Using repositories: %s%n", opts.getRepos());
}
final RepositoryManager repoman = CeylonUtils.repoManager()
.systemRepo(opts.getSystemRepo())
.userRepos(opts.getRepos())
.outRepo(opts.getOutDir())
.offline(opts.getOffline())
.buildManager();
final List<String> onlyFiles = new ArrayList<String>();
long t0, t1, t2, t3, t4;
final TypeCheckerBuilder tcb;
if (opts.isStdin()) {
VirtualFile src = new VirtualFile() {
@Override
public boolean isFolder() {
return false;
}
@Override
public String getName() {
return "SCRIPT.ceylon";
}
@Override
public String getPath() {
return getName();
}
@Override
public InputStream getInputStream() {
return System.in;
}
@Override
public List<VirtualFile> getChildren() {
return new ArrayList<VirtualFile>(0);
}
@Override
public int hashCode() {
return getPath().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VirtualFile) {
return ((VirtualFile) obj).getPath().equals(getPath());
}
else {
return super.equals(obj);
}
}
};
t0 = System.nanoTime();
tcb = new TypeCheckerBuilder()
.addSrcDirectory(src);
} else {
t0=System.nanoTime();
tcb = new TypeCheckerBuilder();
final List<File> roots = new ArrayList<File>(opts.getSrcDirs().size());
for (String _srcdir : opts.getSrcDirs()) {
roots.add(new File(_srcdir));
}
final Set<String> modfilters = new HashSet<String>();
for (String filedir : files) {
File f = new File(filedir);
boolean once=false;
if (f.exists() && f.isFile()) {
for (File root : roots) {
- if (f.getAbsolutePath().startsWith(root.getAbsolutePath())) {
+ if (f.getAbsolutePath().startsWith(root.getAbsolutePath() + File.separatorChar)) {
if (opts.isVerbose()) {
System.out.printf("Adding %s to compilation set%n", filedir);
}
onlyFiles.add(filedir);
once=true;
break;
}
}
if (!once) {
throw new CompilerErrorException(String.format("%s is not in any source path: %n", f.getAbsolutePath()));
}
} else if ("default".equals(filedir)) {
//Default module: load every file in the source directories recursively,
//except any file that exists in directories and subdirectories where we find a module.ceylon file
//Typechecker takes care of all that if we add default to module filters
if (opts.isVerbose()) {
System.out.println("Adding default module filter");
}
modfilters.add("default");
f = null;
} else {
//Parse, may be a module name
String[] modpath = filedir.split("\\.");
f = null;
for (File root : roots) {
File _f = root;
for (String pe : modpath) {
_f = new File(_f, pe);
if (!(_f.exists() && _f.isDirectory())) {
System.err.printf("ceylonc-js: Could not find source files for module: %s%n", filedir);
_f=null;
break;
}
}
if (_f != null) {
f = _f;
}
}
if (f == null) {
throw new CompilerErrorException(String.format("ceylonc-js: file not found: %s%n", filedir));
} else {
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + filedir);
}
addFilesToCompilationSet(f, onlyFiles, opts.isVerbose());
modfilters.add(filedir);
f = null;
}
}
if (f != null) {
if ("module.ceylon".equals(f.getName().toLowerCase())) {
String _f = f.getParentFile().getAbsolutePath();
for (File root : roots) {
if (root.getAbsolutePath().startsWith(_f)) {
_f = _f.substring(root.getAbsolutePath().length()+1).replace(File.separator, ".");
modfilters.add(_f);
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + _f);
}
}
}
} else {
for (File root : roots) {
File middir = f.getParentFile();
while (middir != null && !middir.getAbsolutePath().equals(root.getAbsolutePath())) {
if (new File(middir, "module.ceylon").exists()) {
String _f = middir.getAbsolutePath().substring(root.getAbsolutePath().length()+1).replace(File.separator, ".");
modfilters.add(_f);
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + _f);
}
}
middir = middir.getParentFile();
}
}
}
}
}
for (File root : roots) {
tcb.addSrcDirectory(root);
}
if (!modfilters.isEmpty()) {
ArrayList<String> _modfilters = new ArrayList<String>();
_modfilters.addAll(modfilters);
tcb.setModuleFilters(_modfilters);
}
tcb.statistics(opts.isProfile());
JsModuleManagerFactory.setVerbose(opts.isVerbose());
tcb.moduleManagerFactory(new JsModuleManagerFactory(opts.getEncoding()));
}
//getting the type checker does process all types in the source directory
tcb.verbose(opts.isVerbose()).setRepositoryManager(repoman);
tcb.usageWarnings(false);
typeChecker = tcb.getTypeChecker();
t1=System.nanoTime();
typeChecker.process();
t2=System.nanoTime();
JsCompiler jsc = new JsCompiler(typeChecker, opts);
if (!onlyFiles.isEmpty()) { jsc.setFiles(onlyFiles); }
t3=System.nanoTime();
if (!jsc.generate()) {
int count = jsc.printErrors(System.out);
throw new CompilerErrorException(String.format("%d errors.", count));
}
t4=System.nanoTime();
if (opts.isProfile() || opts.isVerbose()) {
System.err.println("PROFILING INFORMATION");
System.err.printf("TypeChecker creation: %6d nanos%n", t1-t0);
System.err.printf("TypeChecker processing: %6d nanos%n", t2-t1);
System.err.printf("JS compiler creation: %6d nanos%n", t3-t2);
System.err.printf("JS compilation: %6d nanos%n", t4-t3);
System.out.println("Compilation finished.");
}
}
}
| true | true | public static void run(Options opts, List<String> files) throws IOException {
final TypeChecker typeChecker;
if (opts.isVerbose()) {
System.out.printf("Using repositories: %s%n", opts.getRepos());
}
final RepositoryManager repoman = CeylonUtils.repoManager()
.systemRepo(opts.getSystemRepo())
.userRepos(opts.getRepos())
.outRepo(opts.getOutDir())
.offline(opts.getOffline())
.buildManager();
final List<String> onlyFiles = new ArrayList<String>();
long t0, t1, t2, t3, t4;
final TypeCheckerBuilder tcb;
if (opts.isStdin()) {
VirtualFile src = new VirtualFile() {
@Override
public boolean isFolder() {
return false;
}
@Override
public String getName() {
return "SCRIPT.ceylon";
}
@Override
public String getPath() {
return getName();
}
@Override
public InputStream getInputStream() {
return System.in;
}
@Override
public List<VirtualFile> getChildren() {
return new ArrayList<VirtualFile>(0);
}
@Override
public int hashCode() {
return getPath().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VirtualFile) {
return ((VirtualFile) obj).getPath().equals(getPath());
}
else {
return super.equals(obj);
}
}
};
t0 = System.nanoTime();
tcb = new TypeCheckerBuilder()
.addSrcDirectory(src);
} else {
t0=System.nanoTime();
tcb = new TypeCheckerBuilder();
final List<File> roots = new ArrayList<File>(opts.getSrcDirs().size());
for (String _srcdir : opts.getSrcDirs()) {
roots.add(new File(_srcdir));
}
final Set<String> modfilters = new HashSet<String>();
for (String filedir : files) {
File f = new File(filedir);
boolean once=false;
if (f.exists() && f.isFile()) {
for (File root : roots) {
if (f.getAbsolutePath().startsWith(root.getAbsolutePath())) {
if (opts.isVerbose()) {
System.out.printf("Adding %s to compilation set%n", filedir);
}
onlyFiles.add(filedir);
once=true;
break;
}
}
if (!once) {
throw new CompilerErrorException(String.format("%s is not in any source path: %n", f.getAbsolutePath()));
}
} else if ("default".equals(filedir)) {
//Default module: load every file in the source directories recursively,
//except any file that exists in directories and subdirectories where we find a module.ceylon file
//Typechecker takes care of all that if we add default to module filters
if (opts.isVerbose()) {
System.out.println("Adding default module filter");
}
modfilters.add("default");
f = null;
} else {
//Parse, may be a module name
String[] modpath = filedir.split("\\.");
f = null;
for (File root : roots) {
File _f = root;
for (String pe : modpath) {
_f = new File(_f, pe);
if (!(_f.exists() && _f.isDirectory())) {
System.err.printf("ceylonc-js: Could not find source files for module: %s%n", filedir);
_f=null;
break;
}
}
if (_f != null) {
f = _f;
}
}
if (f == null) {
throw new CompilerErrorException(String.format("ceylonc-js: file not found: %s%n", filedir));
} else {
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + filedir);
}
addFilesToCompilationSet(f, onlyFiles, opts.isVerbose());
modfilters.add(filedir);
f = null;
}
}
if (f != null) {
if ("module.ceylon".equals(f.getName().toLowerCase())) {
String _f = f.getParentFile().getAbsolutePath();
for (File root : roots) {
if (root.getAbsolutePath().startsWith(_f)) {
_f = _f.substring(root.getAbsolutePath().length()+1).replace(File.separator, ".");
modfilters.add(_f);
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + _f);
}
}
}
} else {
for (File root : roots) {
File middir = f.getParentFile();
while (middir != null && !middir.getAbsolutePath().equals(root.getAbsolutePath())) {
if (new File(middir, "module.ceylon").exists()) {
String _f = middir.getAbsolutePath().substring(root.getAbsolutePath().length()+1).replace(File.separator, ".");
modfilters.add(_f);
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + _f);
}
}
middir = middir.getParentFile();
}
}
}
}
}
for (File root : roots) {
tcb.addSrcDirectory(root);
}
if (!modfilters.isEmpty()) {
ArrayList<String> _modfilters = new ArrayList<String>();
_modfilters.addAll(modfilters);
tcb.setModuleFilters(_modfilters);
}
tcb.statistics(opts.isProfile());
JsModuleManagerFactory.setVerbose(opts.isVerbose());
tcb.moduleManagerFactory(new JsModuleManagerFactory(opts.getEncoding()));
}
//getting the type checker does process all types in the source directory
tcb.verbose(opts.isVerbose()).setRepositoryManager(repoman);
tcb.usageWarnings(false);
typeChecker = tcb.getTypeChecker();
t1=System.nanoTime();
typeChecker.process();
t2=System.nanoTime();
JsCompiler jsc = new JsCompiler(typeChecker, opts);
if (!onlyFiles.isEmpty()) { jsc.setFiles(onlyFiles); }
t3=System.nanoTime();
if (!jsc.generate()) {
int count = jsc.printErrors(System.out);
throw new CompilerErrorException(String.format("%d errors.", count));
}
t4=System.nanoTime();
if (opts.isProfile() || opts.isVerbose()) {
System.err.println("PROFILING INFORMATION");
System.err.printf("TypeChecker creation: %6d nanos%n", t1-t0);
System.err.printf("TypeChecker processing: %6d nanos%n", t2-t1);
System.err.printf("JS compiler creation: %6d nanos%n", t3-t2);
System.err.printf("JS compilation: %6d nanos%n", t4-t3);
System.out.println("Compilation finished.");
}
}
| public static void run(Options opts, List<String> files) throws IOException {
final TypeChecker typeChecker;
if (opts.isVerbose()) {
System.out.printf("Using repositories: %s%n", opts.getRepos());
}
final RepositoryManager repoman = CeylonUtils.repoManager()
.systemRepo(opts.getSystemRepo())
.userRepos(opts.getRepos())
.outRepo(opts.getOutDir())
.offline(opts.getOffline())
.buildManager();
final List<String> onlyFiles = new ArrayList<String>();
long t0, t1, t2, t3, t4;
final TypeCheckerBuilder tcb;
if (opts.isStdin()) {
VirtualFile src = new VirtualFile() {
@Override
public boolean isFolder() {
return false;
}
@Override
public String getName() {
return "SCRIPT.ceylon";
}
@Override
public String getPath() {
return getName();
}
@Override
public InputStream getInputStream() {
return System.in;
}
@Override
public List<VirtualFile> getChildren() {
return new ArrayList<VirtualFile>(0);
}
@Override
public int hashCode() {
return getPath().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof VirtualFile) {
return ((VirtualFile) obj).getPath().equals(getPath());
}
else {
return super.equals(obj);
}
}
};
t0 = System.nanoTime();
tcb = new TypeCheckerBuilder()
.addSrcDirectory(src);
} else {
t0=System.nanoTime();
tcb = new TypeCheckerBuilder();
final List<File> roots = new ArrayList<File>(opts.getSrcDirs().size());
for (String _srcdir : opts.getSrcDirs()) {
roots.add(new File(_srcdir));
}
final Set<String> modfilters = new HashSet<String>();
for (String filedir : files) {
File f = new File(filedir);
boolean once=false;
if (f.exists() && f.isFile()) {
for (File root : roots) {
if (f.getAbsolutePath().startsWith(root.getAbsolutePath() + File.separatorChar)) {
if (opts.isVerbose()) {
System.out.printf("Adding %s to compilation set%n", filedir);
}
onlyFiles.add(filedir);
once=true;
break;
}
}
if (!once) {
throw new CompilerErrorException(String.format("%s is not in any source path: %n", f.getAbsolutePath()));
}
} else if ("default".equals(filedir)) {
//Default module: load every file in the source directories recursively,
//except any file that exists in directories and subdirectories where we find a module.ceylon file
//Typechecker takes care of all that if we add default to module filters
if (opts.isVerbose()) {
System.out.println("Adding default module filter");
}
modfilters.add("default");
f = null;
} else {
//Parse, may be a module name
String[] modpath = filedir.split("\\.");
f = null;
for (File root : roots) {
File _f = root;
for (String pe : modpath) {
_f = new File(_f, pe);
if (!(_f.exists() && _f.isDirectory())) {
System.err.printf("ceylonc-js: Could not find source files for module: %s%n", filedir);
_f=null;
break;
}
}
if (_f != null) {
f = _f;
}
}
if (f == null) {
throw new CompilerErrorException(String.format("ceylonc-js: file not found: %s%n", filedir));
} else {
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + filedir);
}
addFilesToCompilationSet(f, onlyFiles, opts.isVerbose());
modfilters.add(filedir);
f = null;
}
}
if (f != null) {
if ("module.ceylon".equals(f.getName().toLowerCase())) {
String _f = f.getParentFile().getAbsolutePath();
for (File root : roots) {
if (root.getAbsolutePath().startsWith(_f)) {
_f = _f.substring(root.getAbsolutePath().length()+1).replace(File.separator, ".");
modfilters.add(_f);
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + _f);
}
}
}
} else {
for (File root : roots) {
File middir = f.getParentFile();
while (middir != null && !middir.getAbsolutePath().equals(root.getAbsolutePath())) {
if (new File(middir, "module.ceylon").exists()) {
String _f = middir.getAbsolutePath().substring(root.getAbsolutePath().length()+1).replace(File.separator, ".");
modfilters.add(_f);
if (opts.isVerbose()) {
System.out.println("Adding to module filters: " + _f);
}
}
middir = middir.getParentFile();
}
}
}
}
}
for (File root : roots) {
tcb.addSrcDirectory(root);
}
if (!modfilters.isEmpty()) {
ArrayList<String> _modfilters = new ArrayList<String>();
_modfilters.addAll(modfilters);
tcb.setModuleFilters(_modfilters);
}
tcb.statistics(opts.isProfile());
JsModuleManagerFactory.setVerbose(opts.isVerbose());
tcb.moduleManagerFactory(new JsModuleManagerFactory(opts.getEncoding()));
}
//getting the type checker does process all types in the source directory
tcb.verbose(opts.isVerbose()).setRepositoryManager(repoman);
tcb.usageWarnings(false);
typeChecker = tcb.getTypeChecker();
t1=System.nanoTime();
typeChecker.process();
t2=System.nanoTime();
JsCompiler jsc = new JsCompiler(typeChecker, opts);
if (!onlyFiles.isEmpty()) { jsc.setFiles(onlyFiles); }
t3=System.nanoTime();
if (!jsc.generate()) {
int count = jsc.printErrors(System.out);
throw new CompilerErrorException(String.format("%d errors.", count));
}
t4=System.nanoTime();
if (opts.isProfile() || opts.isVerbose()) {
System.err.println("PROFILING INFORMATION");
System.err.printf("TypeChecker creation: %6d nanos%n", t1-t0);
System.err.printf("TypeChecker processing: %6d nanos%n", t2-t1);
System.err.printf("JS compiler creation: %6d nanos%n", t3-t2);
System.err.printf("JS compilation: %6d nanos%n", t4-t3);
System.out.println("Compilation finished.");
}
}
|
diff --git a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/trace/TraceView.java b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/trace/TraceView.java
index e1dea389b..1b987a3f2 100644
--- a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/trace/TraceView.java
+++ b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/trace/TraceView.java
@@ -1,466 +1,469 @@
/*******************************************************************************
* Copyright (c) 2007, 2010 Wind River Systems, Inc. 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.ui.trace;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.tcf.core.AbstractChannel;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.IPeer;
import org.eclipse.tcf.protocol.JSON;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.ui.part.ViewPart;
public class TraceView extends ViewPart implements Protocol.ChannelOpenListener {
private Composite parent;
private TabFolder tabs;
private Label no_data;
private final Map<TabItem,Page> tab2page = new HashMap<TabItem,Page>();
private class Page implements AbstractChannel.TraceListener {
final AbstractChannel channel;
private TabItem tab;
private Text text;
private final StringBuffer bf = new StringBuffer();
private int bf_line_cnt = 0;
private boolean closed;
private boolean scroll_locked;
private int key_pressed;
private int mouse_button_pressed;
private final Thread update_thread = new Thread() {
public void run() {
synchronized (Page.this) {
while (!closed) {
if (bf_line_cnt > 0 && (!scroll_locked || bf_line_cnt >= 5000)) {
Runnable r = new Runnable() {
public void run() {
String str = null;
int cnt = 0;
synchronized (Page.this) {
str = bf.toString();
cnt = bf_line_cnt;
bf.setLength(0);
bf_line_cnt = 0;
}
if (text == null) return;
if (text.getLineCount() > 1000 - cnt) {
String s = text.getText();
int n = 0;
int i = -1;
while (n < cnt) {
int j = s.indexOf('\n', i + 1);
if (j < 0) break;
i = j;
n++;
}
if (i >= 0) {
text.setText(s.substring(i + 1));
}
}
text.append(str);
}
};
getSite().getShell().getDisplay().asyncExec(r);
}
try {
Page.this.wait(1000);
}
catch (InterruptedException e) {
break;
}
}
}
}
};
Page(AbstractChannel channel) {
this.channel = channel;
update_thread.setName("TCF Trace View");
update_thread.start();
}
private void updateScrollLock() {
if (text == null) {
scroll_locked = false;
}
else {
scroll_locked = key_pressed > 0 || mouse_button_pressed > 0 || text.getSelectionCount() > 0;
}
}
public void dispose() {
if (closed) return;
Protocol.invokeAndWait(new Runnable() {
public void run() {
channel.removeTraceListener(Page.this);
}
});
synchronized (this) {
closed = true;
update_thread.interrupt();
}
try {
update_thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
tab2page.remove(tab);
tab.dispose();
tab = null;
text = null;
if (tab2page.isEmpty()) hideTabs();
}
public synchronized void onChannelClosed(Throwable error) {
if (error == null) {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
dispose();
}
});
}
else {
bf.append("Channel terminated: " + error);
bf_line_cnt++;
}
}
public synchronized void onMessageReceived(char type, String token,
String service, String name, byte[] data) {
try {
if ("Locator".equals(service) && "peerHeartBeat".equals(name)) return;
appendTime(bf);
bf.append("Inp: ");
bf.append(type);
if (token != null) {
bf.append(' ');
bf.append(token);
}
if (service != null) {
bf.append(' ');
bf.append(service);
}
if (name != null) {
bf.append(' ');
bf.append(name);
}
if (data != null) {
appendData(bf, data);
}
bf.append('\n');
bf_line_cnt++;
}
catch (UnsupportedEncodingException x) {
x.printStackTrace();
}
}
public synchronized void onMessageSent(char type, String token,
String service, String name, byte[] data) {
try {
if ("Locator".equals(service) && "peerHeartBeat".equals(name)) return;
appendTime(bf);
bf.append("Out: ");
bf.append(type);
if (token != null) {
bf.append(' ');
bf.append(token);
}
if (service != null) {
bf.append(' ');
bf.append(service);
}
if (name != null) {
bf.append(' ');
bf.append(name);
}
if (data != null) {
appendData(bf, data);
}
bf.append('\n');
bf_line_cnt++;
}
catch (UnsupportedEncodingException x) {
x.printStackTrace();
}
}
}
@Override
public void createPartControl(Composite parent) {
this.parent = parent;
Protocol.invokeAndWait(new Runnable() {
public void run() {
IChannel[] arr = Protocol.getOpenChannels();
for (IChannel c : arr) onChannelOpen(c);
Protocol.addChannelOpenListener(TraceView.this);
}
});
if (tab2page.size() == 0) hideTabs();
}
@Override
public void setFocus() {
if (tabs != null) tabs.setFocus();
}
@Override
public void dispose() {
final Page[] pages = tab2page.values().toArray(new Page[tab2page.size()]);
Protocol.invokeAndWait(new Runnable() {
public void run() {
Protocol.removeChannelOpenListener(TraceView.this);
}
});
for (Page p : pages) p.dispose();
assert tab2page.isEmpty();
if (tabs != null) {
tabs.dispose();
tabs = null;
}
if (no_data != null) {
no_data.dispose();
no_data = null;
}
super.dispose();
}
public void onChannelOpen(final IChannel channel) {
if (!(channel instanceof AbstractChannel)) return;
AbstractChannel c = (AbstractChannel)channel;
IPeer rp = c.getRemotePeer();
final String name = rp.getName();
final String host = rp.getAttributes().get(IPeer.ATTR_IP_HOST);
final String port = rp.getAttributes().get(IPeer.ATTR_IP_PORT);
final Page p = new Page(c);
c.addTraceListener(p);
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
showTabs();
p.tab = new TabItem(tabs, SWT.NONE);
tab2page.put(p.tab, p);
String title = name;
if (host != null) {
title += ", " + host;
if (port != null) {
title += ":" + port;
}
}
p.tab.setText(title);
p.text = new Text(tabs, SWT.H_SCROLL | SWT.V_SCROLL |
SWT.BORDER | SWT.READ_ONLY | SWT.MULTI);
p.tab.setControl(p.text);
p.text.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));
p.text.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
- p.key_pressed--;
+ if (p.key_pressed > 0) p.key_pressed--;
+ if (e.character == SWT.ESC) {
+ p.key_pressed = 0;
+ }
p.updateScrollLock();
}
public void keyPressed(KeyEvent e) {
p.key_pressed++;
p.updateScrollLock();
if (e.character == SWT.ESC) {
p.text.clearSelection();
}
}
});
p.text.addMouseListener(new MouseListener() {
public void mouseUp(MouseEvent e) {
p.mouse_button_pressed--;
p.updateScrollLock();
}
public void mouseDown(MouseEvent e) {
p.mouse_button_pressed++;
p.updateScrollLock();
}
public void mouseDoubleClick(MouseEvent e) {
}
});
}
});
}
private void appendTime(StringBuffer bf) {
String s = Long.toString(System.currentTimeMillis());
int l = s.length();
if (l < 6) return;
bf.append(s.charAt(l - 6));
bf.append(s.charAt(l - 5));
bf.append(s.charAt(l - 4));
bf.append('.');
bf.append(s.charAt(l - 3));
bf.append(s.charAt(l - 2));
bf.append(s.charAt(l - 1));
bf.append(' ');
}
private void appendData(StringBuffer bf, byte[] data) throws UnsupportedEncodingException {
int pos = bf.length();
try {
Object[] o = JSON.parseSequence(data);
for (int i = 0; i < o.length; i++) {
bf.append(' ');
appendJSON(bf, o[i]);
}
}
catch (Throwable z) {
bf.setLength(pos);
for (int i = 0; i < data.length; i++) {
bf.append(' ');
int x = (data[i] >> 4) & 0xf;
int y = data[i] & 0xf;
bf.append((char)(x < 10 ? '0' + x : 'a' + x - 10));
bf.append((char)(y < 10 ? '0' + y : 'a' + y - 10));
}
}
}
private void appendJSON(StringBuffer bf, Object o) {
if (o instanceof byte[]) {
int l = ((byte[])o).length;
bf.append('(');
bf.append(l);
bf.append(')');
}
else if (o instanceof Collection) {
int cnt = 0;
bf.append('[');
for (Object i : (Collection<?>)o) {
if (cnt > 0) bf.append(',');
appendJSON(bf, i);
cnt++;
}
bf.append(']');
}
else if (o instanceof Map) {
int cnt = 0;
bf.append('{');
for (Object k : ((Map<?,?>)o).keySet()) {
if (cnt > 0) bf.append(',');
bf.append(k.toString());
bf.append(':');
appendJSON(bf, ((Map<?,?>)o).get(k));
cnt++;
}
bf.append('}');
}
else if (o instanceof String) {
bf.append('"');
String s = (String)o;
int l = s.length();
for (int i = 0; i < l; i++) {
char ch = s.charAt(i);
if (ch < ' ') {
bf.append('\\');
bf.append('u');
for (int j = 0; j < 4; j++) {
int x = (ch >> (4 * (3 - j))) & 0xf;
bf.append((char)(x < 10 ? '0' + x : 'a' + x - 10));
}
}
else {
bf.append(ch);
}
}
bf.append('"');
}
else {
bf.append(o);
}
}
private void showTabs() {
boolean b = false;
if (no_data != null) {
no_data.dispose();
no_data = null;
b = true;
}
if (tabs == null) {
tabs = new TabFolder(parent, SWT.NONE);
Menu menu = new Menu(tabs);
MenuItem mi_close = new MenuItem(menu, SWT.NONE);
mi_close.setText("Close");
mi_close.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
if (tabs == null) return;
TabItem[] s = tabs.getSelection();
for (TabItem i : s) {
Page p = tab2page.get(i);
if (p != null) p.dispose();
else i.dispose();
}
}
});
MenuItem mi_close_all = new MenuItem(menu, SWT.NONE);
mi_close_all.setText("Close All");
mi_close_all.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
if (tabs == null) return;
TabItem[] s = tabs.getItems();
for (TabItem i : s) {
Page p = tab2page.get(i);
if (p != null) p.dispose();
else i.dispose();
}
}
});
tabs.setMenu(menu);
b = true;
}
if (b) parent.layout();
}
private void hideTabs() {
boolean b = false;
if (tabs != null) {
tabs.dispose();
tabs = null;
b = true;
}
if (!parent.isDisposed()) {
if (no_data == null) {
no_data = new Label(parent, SWT.NONE);
no_data.setText("No open communication channels at this time.");
b = true;
}
if (b) parent.layout();
}
}
}
| true | true | public void onChannelOpen(final IChannel channel) {
if (!(channel instanceof AbstractChannel)) return;
AbstractChannel c = (AbstractChannel)channel;
IPeer rp = c.getRemotePeer();
final String name = rp.getName();
final String host = rp.getAttributes().get(IPeer.ATTR_IP_HOST);
final String port = rp.getAttributes().get(IPeer.ATTR_IP_PORT);
final Page p = new Page(c);
c.addTraceListener(p);
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
showTabs();
p.tab = new TabItem(tabs, SWT.NONE);
tab2page.put(p.tab, p);
String title = name;
if (host != null) {
title += ", " + host;
if (port != null) {
title += ":" + port;
}
}
p.tab.setText(title);
p.text = new Text(tabs, SWT.H_SCROLL | SWT.V_SCROLL |
SWT.BORDER | SWT.READ_ONLY | SWT.MULTI);
p.tab.setControl(p.text);
p.text.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));
p.text.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
p.key_pressed--;
p.updateScrollLock();
}
public void keyPressed(KeyEvent e) {
p.key_pressed++;
p.updateScrollLock();
if (e.character == SWT.ESC) {
p.text.clearSelection();
}
}
});
p.text.addMouseListener(new MouseListener() {
public void mouseUp(MouseEvent e) {
p.mouse_button_pressed--;
p.updateScrollLock();
}
public void mouseDown(MouseEvent e) {
p.mouse_button_pressed++;
p.updateScrollLock();
}
public void mouseDoubleClick(MouseEvent e) {
}
});
}
});
}
| public void onChannelOpen(final IChannel channel) {
if (!(channel instanceof AbstractChannel)) return;
AbstractChannel c = (AbstractChannel)channel;
IPeer rp = c.getRemotePeer();
final String name = rp.getName();
final String host = rp.getAttributes().get(IPeer.ATTR_IP_HOST);
final String port = rp.getAttributes().get(IPeer.ATTR_IP_PORT);
final Page p = new Page(c);
c.addTraceListener(p);
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
showTabs();
p.tab = new TabItem(tabs, SWT.NONE);
tab2page.put(p.tab, p);
String title = name;
if (host != null) {
title += ", " + host;
if (port != null) {
title += ":" + port;
}
}
p.tab.setText(title);
p.text = new Text(tabs, SWT.H_SCROLL | SWT.V_SCROLL |
SWT.BORDER | SWT.READ_ONLY | SWT.MULTI);
p.tab.setControl(p.text);
p.text.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_WHITE));
p.text.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
if (p.key_pressed > 0) p.key_pressed--;
if (e.character == SWT.ESC) {
p.key_pressed = 0;
}
p.updateScrollLock();
}
public void keyPressed(KeyEvent e) {
p.key_pressed++;
p.updateScrollLock();
if (e.character == SWT.ESC) {
p.text.clearSelection();
}
}
});
p.text.addMouseListener(new MouseListener() {
public void mouseUp(MouseEvent e) {
p.mouse_button_pressed--;
p.updateScrollLock();
}
public void mouseDown(MouseEvent e) {
p.mouse_button_pressed++;
p.updateScrollLock();
}
public void mouseDoubleClick(MouseEvent e) {
}
});
}
});
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/myexpimport/pages/HomePage.java b/src/main/java/pl/psnc/dl/wf4ever/myexpimport/pages/HomePage.java
index 4694931..3deebae 100755
--- a/src/main/java/pl/psnc/dl/wf4ever/myexpimport/pages/HomePage.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/myexpimport/pages/HomePage.java
@@ -1,211 +1,217 @@
package pl.psnc.dl.wf4ever.myexpimport.pages;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.request.http.handler.RedirectRequestHandler;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import pl.psnc.dl.wf4ever.myexpimport.services.DlibraApi;
import pl.psnc.dl.wf4ever.myexpimport.services.MyExpApi;
import pl.psnc.dl.wf4ever.myexpimport.utils.Constants;
import pl.psnc.dl.wf4ever.myexpimport.utils.WicketUtils;
/**
*
* @author Piotr Hołubowicz
*
*/
public class HomePage
extends TemplatePage
{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(HomePage.class);
/**
* Default Constructor
*/
public HomePage()
{
this(new PageParameters());
}
@SuppressWarnings("serial")
public HomePage(PageParameters pageParameters)
{
super(pageParameters);
processOAuth(pageParameters);
Form< ? > form = new Form<Void>("form");
content.add(form);
final Button authMyExpButton = new Button("authMyExp") {
@Override
public void onSubmit()
{
Token at = tryLoadDlibraTestToken();
if (at == null) {
- startDlibraAuthorization();
+ startMyExpAuthorization();
+ } else {
+ setMyExpAccessToken(at);
+ goToPage(HomePage.class, null);
}
}
};
authMyExpButton.setEnabled(getMyExpAccessToken() == null);
form.add(authMyExpButton).setOutputMarkupId(true);
final Button authDlibraButton = new Button("authDlibra") {
@Override
public void onSubmit()
{
Token at = tryLoadMyExpTestToken();
if (at == null) {
- startMyExpAuthorization();
+ startDlibraAuthorization();
+ } else {
+ setDlibraAccessToken(at);
+ goToPage(HomePage.class, null);
}
}
};
authDlibraButton.setEnabled(getMyExpAccessToken() != null
&& getDlibraAccessToken() == null);
form.add(authDlibraButton).setOutputMarkupId(true);
final Button importButton = new Button("myExpImportButton") {
@Override
public void onSubmit()
{
goToPage(MyExpImportPage.class, null);
}
};
importButton.setEnabled(getMyExpAccessToken() != null
&& getDlibraAccessToken() != null);
form.add(importButton).setOutputMarkupId(true);
}
private void processOAuth(PageParameters pageParameters)
{
if (getMyExpAccessToken() == null) {
OAuthService service = MyExpApi.getOAuthService(WicketUtils
.getCompleteUrl(this, HomePage.class, true));
Token token = retrieveMyExpAccessToken(pageParameters, service);
setMyExpAccessToken(token);
}
else if (getDlibraAccessToken() == null) {
OAuthService service = DlibraApi.getOAuthService(WicketUtils
.getCompleteUrl(this, HomePage.class, true));
Token token = retrieveDlibraAccessToken(pageParameters, service);
setDlibraAccessToken(token);
}
}
protected void startDlibraAuthorization()
{
// TODO Auto-generated method stub
}
protected Token tryLoadDlibraTestToken()
{
Properties props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream(
"testToken.properties"));
String token = props.getProperty("dLibraToken");
if (token != null) {
return new Token(token, null);
}
}
catch (Exception e) {
log.debug("Failed to load properties: " + e.getMessage());
}
return null;
}
protected Token tryLoadMyExpTestToken()
{
Properties props = new Properties();
try {
props.load(getClass().getClassLoader().getResourceAsStream(
"testToken.properties"));
String token = props.getProperty("token");
String secret = props.getProperty("secret");
if (token != null && secret != null) {
return new Token(token, secret);
}
}
catch (Exception e) {
log.debug("Failed to load properties: " + e.getMessage());
}
return null;
}
private void startMyExpAuthorization()
{
String oauthCallbackURL = WicketUtils.getCompleteUrl(this,
HomePage.class, false);
OAuthService service = MyExpApi.getOAuthService(oauthCallbackURL);
Token requestToken = service.getRequestToken();
getSession()
.setAttribute(Constants.SESSION_REQUEST_TOKEN, requestToken);
String authorizationUrl = service.getAuthorizationUrl(requestToken);
log.debug("Request token: " + requestToken.toString() + " service: "
+ service.getAuthorizationUrl(requestToken));
getRequestCycle().scheduleRequestHandlerAfterCurrent(
new RedirectRequestHandler(authorizationUrl));
}
/**
* @param pageParameters
* @param service
* @return
*/
private Token retrieveMyExpAccessToken(PageParameters pageParameters,
OAuthService service)
{
Token accessToken = null;
if (!pageParameters.get(MyExpApi.OAUTH_VERIFIER).isEmpty()) {
Verifier verifier = new Verifier(pageParameters.get(
MyExpApi.OAUTH_VERIFIER).toString());
Token requestToken = (Token) getSession().getAttribute(
Constants.SESSION_REQUEST_TOKEN);
log.debug("Request token: " + requestToken.toString()
+ " verifier: " + verifier.getValue() + " service: "
+ service.getAuthorizationUrl(requestToken));
accessToken = service.getAccessToken(requestToken, verifier);
}
return accessToken;
}
/**
* @param pageParameters
* @param service
* @return
*/
private Token retrieveDlibraAccessToken(PageParameters pageParameters,
OAuthService service)
{
Token accessToken = null;
return accessToken;
}
}
| false | true | public HomePage(PageParameters pageParameters)
{
super(pageParameters);
processOAuth(pageParameters);
Form< ? > form = new Form<Void>("form");
content.add(form);
final Button authMyExpButton = new Button("authMyExp") {
@Override
public void onSubmit()
{
Token at = tryLoadDlibraTestToken();
if (at == null) {
startDlibraAuthorization();
}
}
};
authMyExpButton.setEnabled(getMyExpAccessToken() == null);
form.add(authMyExpButton).setOutputMarkupId(true);
final Button authDlibraButton = new Button("authDlibra") {
@Override
public void onSubmit()
{
Token at = tryLoadMyExpTestToken();
if (at == null) {
startMyExpAuthorization();
}
}
};
authDlibraButton.setEnabled(getMyExpAccessToken() != null
&& getDlibraAccessToken() == null);
form.add(authDlibraButton).setOutputMarkupId(true);
final Button importButton = new Button("myExpImportButton") {
@Override
public void onSubmit()
{
goToPage(MyExpImportPage.class, null);
}
};
importButton.setEnabled(getMyExpAccessToken() != null
&& getDlibraAccessToken() != null);
form.add(importButton).setOutputMarkupId(true);
}
| public HomePage(PageParameters pageParameters)
{
super(pageParameters);
processOAuth(pageParameters);
Form< ? > form = new Form<Void>("form");
content.add(form);
final Button authMyExpButton = new Button("authMyExp") {
@Override
public void onSubmit()
{
Token at = tryLoadDlibraTestToken();
if (at == null) {
startMyExpAuthorization();
} else {
setMyExpAccessToken(at);
goToPage(HomePage.class, null);
}
}
};
authMyExpButton.setEnabled(getMyExpAccessToken() == null);
form.add(authMyExpButton).setOutputMarkupId(true);
final Button authDlibraButton = new Button("authDlibra") {
@Override
public void onSubmit()
{
Token at = tryLoadMyExpTestToken();
if (at == null) {
startDlibraAuthorization();
} else {
setDlibraAccessToken(at);
goToPage(HomePage.class, null);
}
}
};
authDlibraButton.setEnabled(getMyExpAccessToken() != null
&& getDlibraAccessToken() == null);
form.add(authDlibraButton).setOutputMarkupId(true);
final Button importButton = new Button("myExpImportButton") {
@Override
public void onSubmit()
{
goToPage(MyExpImportPage.class, null);
}
};
importButton.setEnabled(getMyExpAccessToken() != null
&& getDlibraAccessToken() != null);
form.add(importButton).setOutputMarkupId(true);
}
|
diff --git a/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java b/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java
index 623aa173e9..3811a524e5 100644
--- a/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java
+++ b/core/testframework/src/main/java/org/overturetool/test/framework/ResultTestCase.java
@@ -1,166 +1,166 @@
/*******************************************************************************
* Copyright (c) 2009, 2011 Overture Team and others.
*
* Overture 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.
*
* Overture 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 Overture. If not, see <http://www.gnu.org/licenses/>.
*
* The Overture Tool web-site: http://overturetool.org/
*******************************************************************************/
package org.overturetool.test.framework;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.overturetool.test.framework.results.IMessage;
import org.overturetool.test.framework.results.IResultCombiner;
import org.overturetool.test.framework.results.Result;
import org.overturetool.test.util.MessageReaderWritter;
import org.overturetool.test.util.XmlResultReaderWritter;
public abstract class ResultTestCase extends BaseTestCase
{
public ResultTestCase()
{
super();
}
public ResultTestCase(File file)
{
super(file);
}
public ResultTestCase(String name, String content)
{
super(name,content);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void compareResults(Result result, String filename)
{
if(Properties.recordTestResults)
{
//MessageReaderWritter mrw = new MessageReaderWritter(createResultFile(filename));
//mrw.set(result);
//mrw.save();
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(createResultFile(filename));
xmlResult.setResult(result);
try {
xmlResult.saveInXml();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
File file = getResultFile(filename);
- assertNotNull("Result file " + filename + " was not found", file);
- assertTrue("Result file " + filename + " does not exist", file.exists());
+ assertNotNull("Result file " + file.getName() + " was not found", file);
+ assertTrue("Result file " + file.getName() + " does not exist", file.exists());
//MessageReaderWritter mrw = new MessageReaderWritter(file);
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(file);
boolean parsed = xmlResult.loadFromXml();
assertTrue("Could not read result file: " + file.getName(), parsed);
if (parsed)
{
if(file.getAbsolutePath().contains("SAFER"))
{//FIXME: remote this filter when SAFER is fixed in the warning reporting
return;
}
boolean errorsFound = checkMessages("warning", xmlResult.getWarnings(), result.warnings);
errorsFound = checkMessages("error", xmlResult.getErrors(), result.errors) || errorsFound;
assertFalse("Errors found in file \"" + filename + "\"", errorsFound);
}
}
protected abstract File createResultFile(String filename);
protected abstract File getResultFile(String filename);
public boolean checkMessages(String typeName, Set<IMessage> expectedList,
Set<IMessage> list)
{
String TypeName = typeName.toUpperCase().toCharArray()[0]
+ typeName.substring(1);
boolean errorFound = false;
for (IMessage w : list)
{
boolean isContainedIn = containedIn(expectedList, w);
if(!isContainedIn)
{
System.out.println(TypeName + " not expected: " + w);
errorFound = true;
}
// assertTrue(TypeName + " not expected: " + w, isContainedIn);
}
for (IMessage w : expectedList)
{
boolean isContainedIn = containedIn(list, w);
if(!isContainedIn)
{
System.out.println(TypeName + " expected but not found: " + w);
errorFound = true;
}
//assertTrue(TypeName + " expected but not found: " + w, isContainedIn);
}
return errorFound;
}
private static boolean containedIn(Set<IMessage> list, IMessage m)
{
for (IMessage m1 : list)
{
if (m1.equals(m))
{
return true;
}
}
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected <T> Result mergeResults(Set<? extends Result<T>> parse,
IResultCombiner<T> c)
{
Set<IMessage> warnings = new HashSet<IMessage>();
Set<IMessage> errors = new HashSet<IMessage>();
T result = null;
for (Result<T> r : parse)
{
warnings.addAll(r.warnings);
errors.addAll(r.errors);
result = c.combine(result, r.result);
}
return new Result(result, warnings, errors);
}
}
| true | true | protected void compareResults(Result result, String filename)
{
if(Properties.recordTestResults)
{
//MessageReaderWritter mrw = new MessageReaderWritter(createResultFile(filename));
//mrw.set(result);
//mrw.save();
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(createResultFile(filename));
xmlResult.setResult(result);
try {
xmlResult.saveInXml();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
File file = getResultFile(filename);
assertNotNull("Result file " + filename + " was not found", file);
assertTrue("Result file " + filename + " does not exist", file.exists());
//MessageReaderWritter mrw = new MessageReaderWritter(file);
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(file);
boolean parsed = xmlResult.loadFromXml();
assertTrue("Could not read result file: " + file.getName(), parsed);
if (parsed)
{
if(file.getAbsolutePath().contains("SAFER"))
{//FIXME: remote this filter when SAFER is fixed in the warning reporting
return;
}
boolean errorsFound = checkMessages("warning", xmlResult.getWarnings(), result.warnings);
errorsFound = checkMessages("error", xmlResult.getErrors(), result.errors) || errorsFound;
assertFalse("Errors found in file \"" + filename + "\"", errorsFound);
}
}
| protected void compareResults(Result result, String filename)
{
if(Properties.recordTestResults)
{
//MessageReaderWritter mrw = new MessageReaderWritter(createResultFile(filename));
//mrw.set(result);
//mrw.save();
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(createResultFile(filename));
xmlResult.setResult(result);
try {
xmlResult.saveInXml();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
File file = getResultFile(filename);
assertNotNull("Result file " + file.getName() + " was not found", file);
assertTrue("Result file " + file.getName() + " does not exist", file.exists());
//MessageReaderWritter mrw = new MessageReaderWritter(file);
XmlResultReaderWritter xmlResult = new XmlResultReaderWritter(file);
boolean parsed = xmlResult.loadFromXml();
assertTrue("Could not read result file: " + file.getName(), parsed);
if (parsed)
{
if(file.getAbsolutePath().contains("SAFER"))
{//FIXME: remote this filter when SAFER is fixed in the warning reporting
return;
}
boolean errorsFound = checkMessages("warning", xmlResult.getWarnings(), result.warnings);
errorsFound = checkMessages("error", xmlResult.getErrors(), result.errors) || errorsFound;
assertFalse("Errors found in file \"" + filename + "\"", errorsFound);
}
}
|
diff --git a/M4/src/edu/gatech/oad/antlab/person/Person5.java b/M4/src/edu/gatech/oad/antlab/person/Person5.java
index 4a08e36..bd23ec7 100755
--- a/M4/src/edu/gatech/oad/antlab/person/Person5.java
+++ b/M4/src/edu/gatech/oad/antlab/person/Person5.java
@@ -1,60 +1,60 @@
package edu.gatech.oad.antlab.person;
/**
* A simple class for person 5
* returns their name and a
* modified string
*
* @author Bob
* @version 1.1
*/
public class Person5 {
/** Holds the persons real name */
private String name;
/**
* The constructor, takes in the persons
* name
* @param pname the person's real name
*/
public Person5(String pname) {
name = pname;
}
/**
* This method should take the string
* input and return its characters rotated
* 3 positions.
* given "gtg123b" it should return
* "123bgtg".
*
* @param input the string to be modified
* @return the modified string
*/
private String calc(String input) {
- String output;
+ String output = "";
if(!input.equals(null)) {
if(input.length() < 3){
if(input.length() == 2){
- output = input.charAt(1) + input.charAt(0);
+ output = input.charAt(1) + "" + input.charAt(0);
} else {
output = input;
}
} else {
output = input.substring(3) + input.substring(0, 3);
}
}
return output;
}
/**
* Return a string rep of this object
* that varies with an input string
*
* @param input the varying string
* @return the string representing the
* object
*/
public String toString(String input) {
return name + calc(input);
}
}
| false | true | private String calc(String input) {
String output;
if(!input.equals(null)) {
if(input.length() < 3){
if(input.length() == 2){
output = input.charAt(1) + input.charAt(0);
} else {
output = input;
}
} else {
output = input.substring(3) + input.substring(0, 3);
}
}
return output;
}
| private String calc(String input) {
String output = "";
if(!input.equals(null)) {
if(input.length() < 3){
if(input.length() == 2){
output = input.charAt(1) + "" + input.charAt(0);
} else {
output = input;
}
} else {
output = input.substring(3) + input.substring(0, 3);
}
}
return output;
}
|
diff --git a/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java b/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java
index 56cf53a..808ec2b 100644
--- a/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java
+++ b/src/java/com/android/internal/telephony/gsm/GsmServiceStateTracker.java
@@ -1,1727 +1,1728 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony.gsm;
import com.android.internal.telephony.CommandException;
import com.android.internal.telephony.CommandsInterface;
import com.android.internal.telephony.DataConnectionTracker;
import com.android.internal.telephony.EventLogTags;
import com.android.internal.telephony.IccCard;
import com.android.internal.telephony.IccCardConstants;
import com.android.internal.telephony.IccCardStatus;
import com.android.internal.telephony.MccTable;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.RestrictedState;
import com.android.internal.telephony.RILConstants;
import com.android.internal.telephony.ServiceStateTracker;
import com.android.internal.telephony.TelephonyIntents;
import com.android.internal.telephony.TelephonyProperties;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.os.AsyncResult;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.Registrant;
import android.os.RegistrantList;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.ServiceState;
import android.telephony.SignalStrength;
import android.telephony.gsm.GsmCellLocation;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.util.TimeUtils;
import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.TimeZone;
/**
* {@hide}
*/
final class GsmServiceStateTracker extends ServiceStateTracker {
static final String LOG_TAG = "GSM";
static final boolean DBG = true;
GSMPhone phone;
GsmCellLocation cellLoc;
GsmCellLocation newCellLoc;
int mPreferredNetworkType;
private int gprsState = ServiceState.STATE_OUT_OF_SERVICE;
private int newGPRSState = ServiceState.STATE_OUT_OF_SERVICE;
private int mMaxDataCalls = 1;
private int mNewMaxDataCalls = 1;
private int mReasonDataDenied = -1;
private int mNewReasonDataDenied = -1;
/**
* GSM roaming status solely based on TS 27.007 7.2 CREG. Only used by
* handlePollStateResult to store CREG roaming result.
*/
private boolean mGsmRoaming = false;
/**
* Data roaming status solely based on TS 27.007 10.1.19 CGREG. Only used by
* handlePollStateResult to store CGREG roaming result.
*/
private boolean mDataRoaming = false;
/**
* Mark when service state is in emergency call only mode
*/
private boolean mEmergencyOnly = false;
/**
* Sometimes we get the NITZ time before we know what country we
* are in. Keep the time zone information from the NITZ string so
* we can fix the time zone once know the country.
*/
private boolean mNeedFixZoneAfterNitz = false;
private int mZoneOffset;
private boolean mZoneDst;
private long mZoneTime;
private boolean mGotCountryCode = false;
private ContentResolver cr;
/** Boolean is true is setTimeFromNITZString was called */
private boolean mNitzUpdatedTime = false;
String mSavedTimeZone;
long mSavedTime;
long mSavedAtTime;
/**
* We can't register for SIM_RECORDS_LOADED immediately because the
* SIMRecords object may not be instantiated yet.
*/
private boolean mNeedToRegForSimLoaded;
/** Started the recheck process after finding gprs should registered but not. */
private boolean mStartedGprsRegCheck = false;
/** Already sent the event-log for no gprs register. */
private boolean mReportedGprsNoReg = false;
/**
* The Notification object given to the NotificationManager.
*/
private Notification mNotification;
/** Wake lock used while setting time of day. */
private PowerManager.WakeLock mWakeLock;
private static final String WAKELOCK_TAG = "ServiceStateTracker";
/** Keep track of SPN display rules, so we only broadcast intent if something changes. */
private String curSpn = null;
private String curPlmn = null;
private int curSpnRule = 0;
/** waiting period before recheck gprs and voice registration. */
static final int DEFAULT_GPRS_CHECK_PERIOD_MILLIS = 60 * 1000;
/** Notification type. */
static final int PS_ENABLED = 1001; // Access Control blocks data service
static final int PS_DISABLED = 1002; // Access Control enables data service
static final int CS_ENABLED = 1003; // Access Control blocks all voice/sms service
static final int CS_DISABLED = 1004; // Access Control enables all voice/sms service
static final int CS_NORMAL_ENABLED = 1005; // Access Control blocks normal voice/sms service
static final int CS_EMERGENCY_ENABLED = 1006; // Access Control blocks emergency call service
/** Notification id. */
static final int PS_NOTIFICATION = 888; // Id to update and cancel PS restricted
static final int CS_NOTIFICATION = 999; // Id to update and cancel CS restricted
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED)) {
// update emergency string whenever locale changed
updateSpnDisplay();
}
}
};
private ContentObserver mAutoTimeObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
Log.i("GsmServiceStateTracker", "Auto time state changed");
revertToNitzTime();
}
};
private ContentObserver mAutoTimeZoneObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
Log.i("GsmServiceStateTracker", "Auto time zone state changed");
revertToNitzTimeZone();
}
};
public GsmServiceStateTracker(GSMPhone phone) {
super();
this.phone = phone;
cm = phone.mCM;
ss = new ServiceState();
newSS = new ServiceState();
cellLoc = new GsmCellLocation();
newCellLoc = new GsmCellLocation();
mSignalStrength = new SignalStrength();
PowerManager powerManager =
(PowerManager)phone.getContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);
cm.registerForAvailable(this, EVENT_RADIO_AVAILABLE, null);
cm.registerForRadioStateChanged(this, EVENT_RADIO_STATE_CHANGED, null);
cm.registerForVoiceNetworkStateChanged(this, EVENT_NETWORK_STATE_CHANGED, null);
cm.setOnNITZTime(this, EVENT_NITZ_TIME, null);
cm.setOnSignalStrengthUpdate(this, EVENT_SIGNAL_STRENGTH_UPDATE, null);
cm.setOnRestrictedStateChanged(this, EVENT_RESTRICTED_STATE_CHANGED, null);
phone.getIccCard().registerForReady(this, EVENT_SIM_READY, null);
// system setting property AIRPLANE_MODE_ON is set in Settings.
int airplaneMode = Settings.System.getInt(
phone.getContext().getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0);
mDesiredPowerState = ! (airplaneMode > 0);
cr = phone.getContext().getContentResolver();
cr.registerContentObserver(
Settings.System.getUriFor(Settings.System.AUTO_TIME), true,
mAutoTimeObserver);
cr.registerContentObserver(
Settings.System.getUriFor(Settings.System.AUTO_TIME_ZONE), true,
mAutoTimeZoneObserver);
setSignalStrengthDefaultValues();
mNeedToRegForSimLoaded = true;
// Monitor locale change
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_LOCALE_CHANGED);
phone.getContext().registerReceiver(mIntentReceiver, filter);
// Gsm doesn't support OTASP so its not needed
phone.notifyOtaspChanged(OTASP_NOT_NEEDED);
}
public void dispose() {
// Unregister for all events.
cm.unregisterForAvailable(this);
cm.unregisterForRadioStateChanged(this);
cm.unregisterForVoiceNetworkStateChanged(this);
phone.getIccCard().unregisterForReady(this);
phone.mIccRecords.unregisterForRecordsLoaded(this);
cm.unSetOnSignalStrengthUpdate(this);
cm.unSetOnRestrictedStateChanged(this);
cm.unSetOnNITZTime(this);
cr.unregisterContentObserver(this.mAutoTimeObserver);
cr.unregisterContentObserver(this.mAutoTimeZoneObserver);
}
protected void finalize() {
if(DBG) log("finalize");
}
@Override
protected Phone getPhone() {
return phone;
}
public void handleMessage (Message msg) {
AsyncResult ar;
int[] ints;
String[] strings;
Message message;
if (!phone.mIsTheCurrentActivePhone) {
Log.e(LOG_TAG, "Received message " + msg +
"[" + msg.what + "] while being destroyed. Ignoring.");
return;
}
switch (msg.what) {
case EVENT_RADIO_AVAILABLE:
//this is unnecessary
//setPowerStateToDesired();
break;
case EVENT_SIM_READY:
// Set the network type, in case the radio does not restore it.
cm.setCurrentPreferredNetworkType();
// The SIM is now ready i.e if it was locked
// it has been unlocked. At this stage, the radio is already
// powered on.
if (mNeedToRegForSimLoaded) {
phone.mIccRecords.registerForRecordsLoaded(this,
EVENT_SIM_RECORDS_LOADED, null);
mNeedToRegForSimLoaded = false;
}
boolean skipRestoringSelection = phone.getContext().getResources().getBoolean(
com.android.internal.R.bool.skip_restoring_network_selection);
if (!skipRestoringSelection) {
// restore the previous network selection.
phone.restoreSavedNetworkSelection(null);
}
pollState();
// Signal strength polling stops when radio is off
queueNextSignalStrengthPoll();
break;
case EVENT_RADIO_STATE_CHANGED:
// This will do nothing in the radio not
// available case
setPowerStateToDesired();
pollState();
break;
case EVENT_NETWORK_STATE_CHANGED:
pollState();
break;
case EVENT_GET_SIGNAL_STRENGTH:
// This callback is called when signal strength is polled
// all by itself
if (!(cm.getRadioState().isOn())) {
// Polling will continue when radio turns back on
return;
}
ar = (AsyncResult) msg.obj;
onSignalStrengthResult(ar);
queueNextSignalStrengthPoll();
break;
case EVENT_GET_LOC_DONE:
ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
String states[] = (String[])ar.result;
int lac = -1;
int cid = -1;
if (states.length >= 3) {
try {
if (states[1] != null && states[1].length() > 0) {
lac = Integer.parseInt(states[1], 16);
}
if (states[2] != null && states[2].length() > 0) {
cid = Integer.parseInt(states[2], 16);
}
} catch (NumberFormatException ex) {
Log.w(LOG_TAG, "error parsing location: " + ex);
}
}
cellLoc.setLacAndCid(lac, cid);
phone.notifyLocationChanged();
}
// Release any temporary cell lock, which could have been
// acquired to allow a single-shot location update.
disableSingleLocationUpdate();
break;
case EVENT_POLL_STATE_REGISTRATION:
case EVENT_POLL_STATE_GPRS:
case EVENT_POLL_STATE_OPERATOR:
case EVENT_POLL_STATE_NETWORK_SELECTION_MODE:
ar = (AsyncResult) msg.obj;
handlePollStateResult(msg.what, ar);
break;
case EVENT_POLL_SIGNAL_STRENGTH:
// Just poll signal strength...not part of pollState()
cm.getSignalStrength(obtainMessage(EVENT_GET_SIGNAL_STRENGTH));
break;
case EVENT_NITZ_TIME:
ar = (AsyncResult) msg.obj;
String nitzString = (String)((Object[])ar.result)[0];
long nitzReceiveTime = ((Long)((Object[])ar.result)[1]).longValue();
setTimeFromNITZString(nitzString, nitzReceiveTime);
break;
case EVENT_SIGNAL_STRENGTH_UPDATE:
// This is a notification from
// CommandsInterface.setOnSignalStrengthUpdate
ar = (AsyncResult) msg.obj;
// The radio is telling us about signal strength changes
// we don't have to ask it
dontPollSignalStrength = true;
onSignalStrengthResult(ar);
break;
case EVENT_SIM_RECORDS_LOADED:
updateSpnDisplay();
break;
case EVENT_LOCATION_UPDATES_ENABLED:
ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
cm.getVoiceRegistrationState(obtainMessage(EVENT_GET_LOC_DONE, null));
}
break;
case EVENT_SET_PREFERRED_NETWORK_TYPE:
ar = (AsyncResult) msg.obj;
// Don't care the result, only use for dereg network (COPS=2)
message = obtainMessage(EVENT_RESET_PREFERRED_NETWORK_TYPE, ar.userObj);
cm.setPreferredNetworkType(mPreferredNetworkType, message);
break;
case EVENT_RESET_PREFERRED_NETWORK_TYPE:
ar = (AsyncResult) msg.obj;
if (ar.userObj != null) {
AsyncResult.forMessage(((Message) ar.userObj)).exception
= ar.exception;
((Message) ar.userObj).sendToTarget();
}
break;
case EVENT_GET_PREFERRED_NETWORK_TYPE:
ar = (AsyncResult) msg.obj;
if (ar.exception == null) {
mPreferredNetworkType = ((int[])ar.result)[0];
} else {
mPreferredNetworkType = RILConstants.NETWORK_MODE_GLOBAL;
}
message = obtainMessage(EVENT_SET_PREFERRED_NETWORK_TYPE, ar.userObj);
int toggledNetworkType = RILConstants.NETWORK_MODE_GLOBAL;
cm.setPreferredNetworkType(toggledNetworkType, message);
break;
case EVENT_CHECK_REPORT_GPRS:
if (ss != null && !isGprsConsistent(gprsState, ss.getState())) {
// Can't register data service while voice service is ok
// i.e. CREG is ok while CGREG is not
// possible a network or baseband side error
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
EventLog.writeEvent(EventLogTags.DATA_NETWORK_REGISTRATION_FAIL,
ss.getOperatorNumeric(), loc != null ? loc.getCid() : -1);
mReportedGprsNoReg = true;
}
mStartedGprsRegCheck = false;
break;
case EVENT_RESTRICTED_STATE_CHANGED:
// This is a notification from
// CommandsInterface.setOnRestrictedStateChanged
if (DBG) log("EVENT_RESTRICTED_STATE_CHANGED");
ar = (AsyncResult) msg.obj;
onRestrictedStateChanged(ar);
break;
default:
super.handleMessage(msg);
break;
}
}
protected void setPowerStateToDesired() {
// If we want it on and it's off, turn it on
if (mDesiredPowerState
&& cm.getRadioState() == CommandsInterface.RadioState.RADIO_OFF) {
cm.setRadioPower(true, null);
} else if (!mDesiredPowerState && cm.getRadioState().isOn()) {
// If it's on and available and we want it off gracefully
DataConnectionTracker dcTracker = phone.mDataConnectionTracker;
powerOffRadioSafely(dcTracker);
} // Otherwise, we're in the desired state
}
@Override
protected void hangupAndPowerOff() {
// hang up all active voice calls
if (phone.isInCall()) {
phone.mCT.ringingCall.hangupIfAlive();
phone.mCT.backgroundCall.hangupIfAlive();
phone.mCT.foregroundCall.hangupIfAlive();
}
cm.setRadioPower(false, null);
}
protected void updateSpnDisplay() {
int rule = phone.mIccRecords.getDisplayRule(ss.getOperatorNumeric());
String spn = phone.mIccRecords.getServiceProviderName();
String plmn = ss.getOperatorAlphaLong();
// For emergency calls only, pass the EmergencyCallsOnly string via EXTRA_PLMN
if (mEmergencyOnly && cm.getRadioState().isOn()) {
plmn = Resources.getSystem().
getText(com.android.internal.R.string.emergency_calls_only).toString();
if (DBG) log("updateSpnDisplay: emergency only and radio is on plmn='" + plmn + "'");
}
if (rule != curSpnRule
|| !TextUtils.equals(spn, curSpn)
|| !TextUtils.equals(plmn, curPlmn)) {
boolean showSpn = !mEmergencyOnly && !TextUtils.isEmpty(spn)
&& (rule & SIMRecords.SPN_RULE_SHOW_SPN) == SIMRecords.SPN_RULE_SHOW_SPN;
boolean showPlmn = !TextUtils.isEmpty(plmn) &&
(rule & SIMRecords.SPN_RULE_SHOW_PLMN) == SIMRecords.SPN_RULE_SHOW_PLMN;
if (DBG) {
log(String.format("updateSpnDisplay: changed sending intent" + " rule=" + rule +
" showPlmn='%b' plmn='%s' showSpn='%b' spn='%s'",
showPlmn, plmn, showSpn, spn));
}
Intent intent = new Intent(TelephonyIntents.SPN_STRINGS_UPDATED_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra(TelephonyIntents.EXTRA_SHOW_SPN, showSpn);
intent.putExtra(TelephonyIntents.EXTRA_SPN, spn);
intent.putExtra(TelephonyIntents.EXTRA_SHOW_PLMN, showPlmn);
intent.putExtra(TelephonyIntents.EXTRA_PLMN, plmn);
phone.getContext().sendStickyBroadcast(intent);
}
curSpnRule = rule;
curSpn = spn;
curPlmn = plmn;
}
/**
* Handle the result of one of the pollState()-related requests
*/
protected void handlePollStateResult (int what, AsyncResult ar) {
int ints[];
String states[];
// Ignore stale requests from last poll
if (ar.userObj != pollingContext) return;
if (ar.exception != null) {
CommandException.Error err=null;
if (ar.exception instanceof CommandException) {
err = ((CommandException)(ar.exception)).getCommandError();
}
if (err == CommandException.Error.RADIO_NOT_AVAILABLE) {
// Radio has crashed or turned off
cancelPollState();
return;
}
if (!cm.getRadioState().isOn()) {
// Radio has crashed or turned off
cancelPollState();
return;
}
if (err != CommandException.Error.OP_NOT_ALLOWED_BEFORE_REG_NW) {
loge("RIL implementation has returned an error where it must succeed" +
ar.exception);
}
} else try {
switch (what) {
case EVENT_POLL_STATE_REGISTRATION:
states = (String[])ar.result;
int lac = -1;
int cid = -1;
int regState = -1;
int reasonRegStateDenied = -1;
int psc = -1;
if (states.length > 0) {
try {
regState = Integer.parseInt(states[0]);
if (states.length >= 3) {
if (states[1] != null && states[1].length() > 0) {
lac = Integer.parseInt(states[1], 16);
}
if (states[2] != null && states[2].length() > 0) {
cid = Integer.parseInt(states[2], 16);
}
}
if (states.length > 14) {
if (states[14] != null && states[14].length() > 0) {
psc = Integer.parseInt(states[14], 16);
}
}
} catch (NumberFormatException ex) {
loge("error parsing RegistrationState: " + ex);
}
}
mGsmRoaming = regCodeIsRoaming(regState);
newSS.setState (regCodeToServiceState(regState));
if (regState == 10 || regState == 12 || regState == 13 || regState == 14) {
mEmergencyOnly = true;
} else {
mEmergencyOnly = false;
}
// LAC and CID are -1 if not avail
newCellLoc.setLacAndCid(lac, cid);
newCellLoc.setPsc(psc);
break;
case EVENT_POLL_STATE_GPRS:
states = (String[])ar.result;
int type = 0;
regState = -1;
mNewReasonDataDenied = -1;
mNewMaxDataCalls = 1;
if (states.length > 0) {
try {
regState = Integer.parseInt(states[0]);
// states[3] (if present) is the current radio technology
if (states.length >= 4 && states[3] != null) {
type = Integer.parseInt(states[3]);
}
if ((states.length >= 5 ) && (regState == 3)) {
mNewReasonDataDenied = Integer.parseInt(states[4]);
}
if (states.length >= 6) {
mNewMaxDataCalls = Integer.parseInt(states[5]);
}
} catch (NumberFormatException ex) {
loge("error parsing GprsRegistrationState: " + ex);
}
}
newGPRSState = regCodeToServiceState(regState);
mDataRoaming = regCodeIsRoaming(regState);
mNewRilRadioTechnology = type;
newSS.setRadioTechnology(type);
break;
case EVENT_POLL_STATE_OPERATOR:
String opNames[] = (String[])ar.result;
if (opNames != null && opNames.length >= 3) {
newSS.setOperatorName (opNames[0], opNames[1], opNames[2]);
}
break;
case EVENT_POLL_STATE_NETWORK_SELECTION_MODE:
ints = (int[])ar.result;
newSS.setIsManualSelection(ints[0] == 1);
break;
}
} catch (RuntimeException ex) {
loge("Exception while polling service state. Probably malformed RIL response." + ex);
}
pollingContext[0]--;
if (pollingContext[0] == 0) {
/**
* Since the roaming states of gsm service (from +CREG) and
* data service (from +CGREG) could be different, the new SS
* is set roaming while either one is roaming.
*
* There is an exception for the above rule. The new SS is not set
* as roaming while gsm service reports roaming but indeed it is
* not roaming between operators.
*/
boolean roaming = (mGsmRoaming || mDataRoaming);
if (mGsmRoaming && !isRoamingBetweenOperators(mGsmRoaming, newSS)) {
roaming = false;
}
newSS.setRoaming(roaming);
newSS.setEmergencyOnly(mEmergencyOnly);
pollStateDone();
}
}
private void setSignalStrengthDefaultValues() {
// TODO Make a constructor only has boolean gsm as parameter
mSignalStrength = new SignalStrength(99, -1, -1, -1, -1, -1, -1,
-1, -1, -1, SignalStrength.INVALID_SNR, -1, true);
}
/**
* A complete "service state" from our perspective is
* composed of a handful of separate requests to the radio.
*
* We make all of these requests at once, but then abandon them
* and start over again if the radio notifies us that some
* event has changed
*/
private void pollState() {
pollingContext = new int[1];
pollingContext[0] = 0;
switch (cm.getRadioState()) {
case RADIO_UNAVAILABLE:
newSS.setStateOutOfService();
newCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
mNitzUpdatedTime = false;
pollStateDone();
break;
case RADIO_OFF:
newSS.setStateOff();
newCellLoc.setStateInvalid();
setSignalStrengthDefaultValues();
mGotCountryCode = false;
mNitzUpdatedTime = false;
pollStateDone();
break;
default:
// Issue all poll-related commands at once
// then count down the responses, which
// are allowed to arrive out-of-order
pollingContext[0]++;
cm.getOperator(
obtainMessage(
EVENT_POLL_STATE_OPERATOR, pollingContext));
pollingContext[0]++;
cm.getDataRegistrationState(
obtainMessage(
EVENT_POLL_STATE_GPRS, pollingContext));
pollingContext[0]++;
cm.getVoiceRegistrationState(
obtainMessage(
EVENT_POLL_STATE_REGISTRATION, pollingContext));
pollingContext[0]++;
cm.getNetworkSelectionMode(
obtainMessage(
EVENT_POLL_STATE_NETWORK_SELECTION_MODE, pollingContext));
break;
}
}
private void pollStateDone() {
if (DBG) {
log("Poll ServiceState done: " +
" oldSS=[" + ss + "] newSS=[" + newSS +
"] oldGprs=" + gprsState + " newData=" + newGPRSState +
" oldMaxDataCalls=" + mMaxDataCalls +
" mNewMaxDataCalls=" + mNewMaxDataCalls +
" oldReasonDataDenied=" + mReasonDataDenied +
" mNewReasonDataDenied=" + mNewReasonDataDenied +
" oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
}
boolean hasRegistered =
ss.getState() != ServiceState.STATE_IN_SERVICE
&& newSS.getState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered =
ss.getState() == ServiceState.STATE_IN_SERVICE
&& newSS.getState() != ServiceState.STATE_IN_SERVICE;
boolean hasGprsAttached =
gprsState != ServiceState.STATE_IN_SERVICE
&& newGPRSState == ServiceState.STATE_IN_SERVICE;
boolean hasGprsDetached =
gprsState == ServiceState.STATE_IN_SERVICE
&& newGPRSState != ServiceState.STATE_IN_SERVICE;
boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
boolean hasChanged = !newSS.equals(ss);
boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
// Add an event log when connection state changes
if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
ss.getState(), gprsState, newSS.getState(), newGPRSState);
}
ServiceState tss;
tss = ss;
ss = newSS;
newSS = tss;
// clean slate for next time
newSS.setStateOutOfService();
GsmCellLocation tcl = cellLoc;
cellLoc = newCellLoc;
newCellLoc = tcl;
// Add an event log when network type switched
// TODO: we may add filtering to reduce the event logged,
// i.e. check preferred network setting, only switch to 2G, etc
if (hasRadioTechnologyChanged) {
int cid = -1;
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
if (loc != null) cid = loc.getCid();
EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
mNewRilRadioTechnology);
if (DBG) {
log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
" at cell " + cid);
}
}
gprsState = newGPRSState;
mReasonDataDenied = mNewReasonDataDenied;
mMaxDataCalls = mNewMaxDataCalls;
mRilRadioTechnology = mNewRilRadioTechnology;
// this new state has been applied - forget it until we get a new new state
mNewRilRadioTechnology = 0;
newSS.setStateOutOfService(); // clean slate for next time
if (hasRadioTechnologyChanged) {
phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
if (DBG) {
log("pollStateDone: registering current mNitzUpdatedTime=" +
mNitzUpdatedTime + " changing to false");
}
mNitzUpdatedTime = false;
}
if (hasChanged) {
String operatorNumeric;
updateSpnDisplay();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
ss.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = ss.getOperatorNumeric();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
mNitzUpdatedTime = false;
} else {
String iso = "";
- String mcc = operatorNumeric.substring(0, 3);
+ String mcc = "";
try{
+ mcc = operatorNumeric.substring(0, 3);
iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
} catch ( NumberFormatException ex){
loge("pollStateDone: countryCodeForMcc error" + ex);
} catch ( StringIndexOutOfBoundsException ex) {
loge("pollStateDone: countryCodeForMcc error" + ex);
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
mGotCountryCode = true;
TimeZone zone = null;
if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
getAutoTimeZone()) {
// Test both paths if ignore nitz is true
boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
((SystemClock.uptimeMillis() & 1) == 0);
ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
zone = uniqueZones.get(0);
if (DBG) {
log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
" with zone.getID=" + zone.getID() +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
}
setAndBroadcastNetworkSetTimeZone(zone.getID());
} else {
if (DBG) {
log("pollStateDone: there are " + uniqueZones.size() +
" unique offsets for iso-cc='" + iso +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
"', do nothing");
}
}
}
if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
mNeedFixZoneAfterNitz)) {
// If the offset is (0, false) and the timezone property
// is set, use the timezone property rather than
// GMT.
String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
if (DBG) {
log("pollStateDone: fix time zone zoneName='" + zoneName +
"' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
" iso-cc='" + iso +
"' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
}
// "(mZoneOffset == 0) && (mZoneDst == false) &&
// (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
// means that we received a NITZ string telling
// it is in GMT+0 w/ DST time zone
// BUT iso tells is NOT, e.g, a wrong NITZ reporting
// local time w/ 0 offset.
if ((mZoneOffset == 0) && (mZoneDst == false) &&
(zoneName != null) && (zoneName.length() > 0) &&
(Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
zone = TimeZone.getDefault();
if (mNeedFixZoneAfterNitz) {
// For wrong NITZ reporting local time w/ 0 offset,
// need adjust time to reflect default timezone setting
long ctm = System.currentTimeMillis();
long tzOffset = zone.getOffset(ctm);
if (DBG) {
log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
TimeUtils.logTimeOfDay(ctm));
}
if (getAutoTime()) {
long adj = ctm - tzOffset;
if (DBG) log("pollStateDone: adj ltod=" +
TimeUtils.logTimeOfDay(adj));
setAndBroadcastNetworkSetTime(adj);
} else {
// Adjust the saved NITZ time to account for tzOffset.
mSavedTime = mSavedTime - tzOffset;
}
}
if (DBG) log("pollStateDone: using default TimeZone");
} else if (iso.equals("")){
// Country code not found. This is likely a test network.
// Get a TimeZone based only on the NITZ parameters (best guess).
zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
if (DBG) log("pollStateDone: using NITZ TimeZone");
} else {
zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
}
mNeedFixZoneAfterNitz = false;
if (zone != null) {
log("pollStateDone: zone != null zone.getID=" + zone.getID());
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
} else {
log("pollStateDone: zone == null");
}
}
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
ss.getRoaming() ? "true" : "false");
phone.notifyServiceStateChanged(ss);
}
if (hasGprsAttached) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasGprsDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if (hasRadioTechnologyChanged) {
phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
phone.notifyLocationChanged();
}
if (! isGprsConsistent(gprsState, ss.getState())) {
if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
mStartedGprsRegCheck = true;
int check_period = Settings.Secure.getInt(
phone.getContext().getContentResolver(),
Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
check_period);
}
} else {
mReportedGprsNoReg = false;
}
}
/**
* Check if GPRS got registered while voice is registered.
*
* @param gprsState for GPRS registration state, i.e. CGREG in GSM
* @param serviceState for voice registration state, i.e. CREG in GSM
* @return false if device only register to voice but not gprs
*/
private boolean isGprsConsistent(int gprsState, int serviceState) {
return !((serviceState == ServiceState.STATE_IN_SERVICE) &&
(gprsState != ServiceState.STATE_IN_SERVICE));
}
/**
* Returns a TimeZone object based only on parameters from the NITZ string.
*/
private TimeZone getNitzTimeZone(int offset, boolean dst, long when) {
TimeZone guess = findTimeZone(offset, dst, when);
if (guess == null) {
// Couldn't find a proper timezone. Perhaps the DST data is wrong.
guess = findTimeZone(offset, !dst, when);
}
if (DBG) log("getNitzTimeZone returning " + (guess == null ? guess : guess.getID()));
return guess;
}
private TimeZone findTimeZone(int offset, boolean dst, long when) {
int rawOffset = offset;
if (dst) {
rawOffset -= 3600000;
}
String[] zones = TimeZone.getAvailableIDs(rawOffset);
TimeZone guess = null;
Date d = new Date(when);
for (String zone : zones) {
TimeZone tz = TimeZone.getTimeZone(zone);
if (tz.getOffset(when) == offset &&
tz.inDaylightTime(d) == dst) {
guess = tz;
break;
}
}
return guess;
}
private void queueNextSignalStrengthPoll() {
if (dontPollSignalStrength) {
// The radio is telling us about signal strength changes
// we don't have to ask it
return;
}
Message msg;
msg = obtainMessage();
msg.what = EVENT_POLL_SIGNAL_STRENGTH;
long nextTime;
// TODO Don't poll signal strength if screen is off
sendMessageDelayed(msg, POLL_PERIOD_MILLIS);
}
/**
* Send signal-strength-changed notification if changed.
* Called both for solicited and unsolicited signal strength updates.
*/
private void onSignalStrengthResult(AsyncResult ar) {
SignalStrength oldSignalStrength = mSignalStrength;
int rssi = 99;
int lteSignalStrength = -1;
int lteRsrp = -1;
int lteRsrq = -1;
int lteRssnr = SignalStrength.INVALID_SNR;
int lteCqi = -1;
if (ar.exception != null) {
// -1 = unknown
// most likely radio is resetting/disconnected
setSignalStrengthDefaultValues();
} else {
int[] ints = (int[])ar.result;
// bug 658816 seems to be a case where the result is 0-length
if (ints.length != 0) {
rssi = ints[0];
lteSignalStrength = ints[7];
lteRsrp = ints[8];
lteRsrq = ints[9];
lteRssnr = ints[10];
lteCqi = ints[11];
} else {
loge("Bogus signal strength response");
rssi = 99;
}
}
mSignalStrength = new SignalStrength(rssi, -1, -1, -1,
-1, -1, -1, lteSignalStrength, lteRsrp, lteRsrq, lteRssnr, lteCqi, true);
if (!mSignalStrength.equals(oldSignalStrength)) {
try { // This takes care of delayed EVENT_POLL_SIGNAL_STRENGTH (scheduled after
// POLL_PERIOD_MILLIS) during Radio Technology Change)
phone.notifySignalStrength();
} catch (NullPointerException ex) {
log("onSignalStrengthResult() Phone already destroyed: " + ex
+ "SignalStrength not notified");
}
}
}
/**
* Set restricted state based on the OnRestrictedStateChanged notification
* If any voice or packet restricted state changes, trigger a UI
* notification and notify registrants when sim is ready.
*
* @param ar an int value of RIL_RESTRICTED_STATE_*
*/
private void onRestrictedStateChanged(AsyncResult ar) {
RestrictedState newRs = new RestrictedState();
if (DBG) log("onRestrictedStateChanged: E rs "+ mRestrictedState);
if (ar.exception == null) {
int[] ints = (int[])ar.result;
int state = ints[0];
newRs.setCsEmergencyRestricted(
((state & RILConstants.RIL_RESTRICTED_STATE_CS_EMERGENCY) != 0) ||
((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) );
//ignore the normal call and data restricted state before SIM READY
if (phone.getIccCard().getState() == IccCardConstants.State.READY) {
newRs.setCsNormalRestricted(
((state & RILConstants.RIL_RESTRICTED_STATE_CS_NORMAL) != 0) ||
((state & RILConstants.RIL_RESTRICTED_STATE_CS_ALL) != 0) );
newRs.setPsRestricted(
(state & RILConstants.RIL_RESTRICTED_STATE_PS_ALL)!= 0);
}
if (DBG) log("onRestrictedStateChanged: new rs "+ newRs);
if (!mRestrictedState.isPsRestricted() && newRs.isPsRestricted()) {
mPsRestrictEnabledRegistrants.notifyRegistrants();
setNotification(PS_ENABLED);
} else if (mRestrictedState.isPsRestricted() && !newRs.isPsRestricted()) {
mPsRestrictDisabledRegistrants.notifyRegistrants();
setNotification(PS_DISABLED);
}
/**
* There are two kind of cs restriction, normal and emergency. So
* there are 4 x 4 combinations in current and new restricted states
* and we only need to notify when state is changed.
*/
if (mRestrictedState.isCsRestricted()) {
if (!newRs.isCsRestricted()) {
// remove all restriction
setNotification(CS_DISABLED);
} else if (!newRs.isCsNormalRestricted()) {
// remove normal restriction
setNotification(CS_EMERGENCY_ENABLED);
} else if (!newRs.isCsEmergencyRestricted()) {
// remove emergency restriction
setNotification(CS_NORMAL_ENABLED);
}
} else if (mRestrictedState.isCsEmergencyRestricted() &&
!mRestrictedState.isCsNormalRestricted()) {
if (!newRs.isCsRestricted()) {
// remove all restriction
setNotification(CS_DISABLED);
} else if (newRs.isCsRestricted()) {
// enable all restriction
setNotification(CS_ENABLED);
} else if (newRs.isCsNormalRestricted()) {
// remove emergency restriction and enable normal restriction
setNotification(CS_NORMAL_ENABLED);
}
} else if (!mRestrictedState.isCsEmergencyRestricted() &&
mRestrictedState.isCsNormalRestricted()) {
if (!newRs.isCsRestricted()) {
// remove all restriction
setNotification(CS_DISABLED);
} else if (newRs.isCsRestricted()) {
// enable all restriction
setNotification(CS_ENABLED);
} else if (newRs.isCsEmergencyRestricted()) {
// remove normal restriction and enable emergency restriction
setNotification(CS_EMERGENCY_ENABLED);
}
} else {
if (newRs.isCsRestricted()) {
// enable all restriction
setNotification(CS_ENABLED);
} else if (newRs.isCsEmergencyRestricted()) {
// enable emergency restriction
setNotification(CS_EMERGENCY_ENABLED);
} else if (newRs.isCsNormalRestricted()) {
// enable normal restriction
setNotification(CS_NORMAL_ENABLED);
}
}
mRestrictedState = newRs;
}
log("onRestrictedStateChanged: X rs "+ mRestrictedState);
}
/** code is registration state 0-5 from TS 27.007 7.2 */
private int regCodeToServiceState(int code) {
switch (code) {
case 0:
case 2: // 2 is "searching"
case 3: // 3 is "registration denied"
case 4: // 4 is "unknown" no vaild in current baseband
case 10:// same as 0, but indicates that emergency call is possible.
case 12:// same as 2, but indicates that emergency call is possible.
case 13:// same as 3, but indicates that emergency call is possible.
case 14:// same as 4, but indicates that emergency call is possible.
return ServiceState.STATE_OUT_OF_SERVICE;
case 1:
return ServiceState.STATE_IN_SERVICE;
case 5:
// in service, roam
return ServiceState.STATE_IN_SERVICE;
default:
loge("regCodeToServiceState: unexpected service state " + code);
return ServiceState.STATE_OUT_OF_SERVICE;
}
}
/**
* code is registration state 0-5 from TS 27.007 7.2
* returns true if registered roam, false otherwise
*/
private boolean regCodeIsRoaming (int code) {
// 5 is "in service -- roam"
return 5 == code;
}
/**
* Set roaming state when gsmRoaming is true and, if operator mcc is the
* same as sim mcc, ons is different from spn
* @param gsmRoaming TS 27.007 7.2 CREG registered roaming
* @param s ServiceState hold current ons
* @return true for roaming state set
*/
private boolean isRoamingBetweenOperators(boolean gsmRoaming, ServiceState s) {
String spn = SystemProperties.get(TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA, "empty");
String onsl = s.getOperatorAlphaLong();
String onss = s.getOperatorAlphaShort();
boolean equalsOnsl = onsl != null && spn.equals(onsl);
boolean equalsOnss = onss != null && spn.equals(onss);
String simNumeric = SystemProperties.get(
TelephonyProperties.PROPERTY_ICC_OPERATOR_NUMERIC, "");
String operatorNumeric = s.getOperatorNumeric();
boolean equalsMcc = true;
try {
equalsMcc = simNumeric.substring(0, 3).
equals(operatorNumeric.substring(0, 3));
} catch (Exception e){
}
return gsmRoaming && !(equalsMcc && (equalsOnsl || equalsOnss));
}
private static int twoDigitsAt(String s, int offset) {
int a, b;
a = Character.digit(s.charAt(offset), 10);
b = Character.digit(s.charAt(offset+1), 10);
if (a < 0 || b < 0) {
throw new RuntimeException("invalid format");
}
return a*10 + b;
}
/**
* @return The current GPRS state. IN_SERVICE is the same as "attached"
* and OUT_OF_SERVICE is the same as detached.
*/
int getCurrentGprsState() {
return gprsState;
}
public int getCurrentDataConnectionState() {
return gprsState;
}
/**
* @return true if phone is camping on a technology (eg UMTS)
* that could support voice and data simultaneously.
*/
public boolean isConcurrentVoiceAndDataAllowed() {
return (mRilRadioTechnology >= ServiceState.RIL_RADIO_TECHNOLOGY_UMTS);
}
/**
* Provides the name of the algorithmic time zone for the specified
* offset. Taken from TimeZone.java.
*/
private static String displayNameFor(int off) {
off = off / 1000 / 60;
char[] buf = new char[9];
buf[0] = 'G';
buf[1] = 'M';
buf[2] = 'T';
if (off < 0) {
buf[3] = '-';
off = -off;
} else {
buf[3] = '+';
}
int hours = off / 60;
int minutes = off % 60;
buf[4] = (char) ('0' + hours / 10);
buf[5] = (char) ('0' + hours % 10);
buf[6] = ':';
buf[7] = (char) ('0' + minutes / 10);
buf[8] = (char) ('0' + minutes % 10);
return new String(buf);
}
/**
* nitzReceiveTime is time_t that the NITZ time was posted
*/
private void setTimeFromNITZString (String nitz, long nitzReceiveTime) {
// "yy/mm/dd,hh:mm:ss(+/-)tz"
// tz is in number of quarter-hours
long start = SystemClock.elapsedRealtime();
if (DBG) {log("NITZ: " + nitz + "," + nitzReceiveTime +
" start=" + start + " delay=" + (start - nitzReceiveTime));
}
try {
/* NITZ time (hour:min:sec) will be in UTC but it supplies the timezone
* offset as well (which we won't worry about until later) */
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.clear();
c.set(Calendar.DST_OFFSET, 0);
String[] nitzSubs = nitz.split("[/:,+-]");
int year = 2000 + Integer.parseInt(nitzSubs[0]);
c.set(Calendar.YEAR, year);
// month is 0 based!
int month = Integer.parseInt(nitzSubs[1]) - 1;
c.set(Calendar.MONTH, month);
int date = Integer.parseInt(nitzSubs[2]);
c.set(Calendar.DATE, date);
int hour = Integer.parseInt(nitzSubs[3]);
c.set(Calendar.HOUR, hour);
int minute = Integer.parseInt(nitzSubs[4]);
c.set(Calendar.MINUTE, minute);
int second = Integer.parseInt(nitzSubs[5]);
c.set(Calendar.SECOND, second);
boolean sign = (nitz.indexOf('-') == -1);
int tzOffset = Integer.parseInt(nitzSubs[6]);
int dst = (nitzSubs.length >= 8 ) ? Integer.parseInt(nitzSubs[7])
: 0;
// The zone offset received from NITZ is for current local time,
// so DST correction is already applied. Don't add it again.
//
// tzOffset += dst * 4;
//
// We could unapply it if we wanted the raw offset.
tzOffset = (sign ? 1 : -1) * tzOffset * 15 * 60 * 1000;
TimeZone zone = null;
// As a special extension, the Android emulator appends the name of
// the host computer's timezone to the nitz string. this is zoneinfo
// timezone name of the form Area!Location or Area!Location!SubLocation
// so we need to convert the ! into /
if (nitzSubs.length >= 9) {
String tzname = nitzSubs[8].replace('!','/');
zone = TimeZone.getTimeZone( tzname );
}
String iso = SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY);
if (zone == null) {
if (mGotCountryCode) {
if (iso != null && iso.length() > 0) {
zone = TimeUtils.getTimeZone(tzOffset, dst != 0,
c.getTimeInMillis(),
iso);
} else {
// We don't have a valid iso country code. This is
// most likely because we're on a test network that's
// using a bogus MCC (eg, "001"), so get a TimeZone
// based only on the NITZ parameters.
zone = getNitzTimeZone(tzOffset, (dst != 0), c.getTimeInMillis());
}
}
}
if ((zone == null) || (mZoneOffset != tzOffset) || (mZoneDst != (dst != 0))){
// We got the time before the country or the zone has changed
// so we don't know how to identify the DST rules yet. Save
// the information and hope to fix it up later.
mNeedFixZoneAfterNitz = true;
mZoneOffset = tzOffset;
mZoneDst = dst != 0;
mZoneTime = c.getTimeInMillis();
}
if (zone != null) {
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
}
String ignore = SystemProperties.get("gsm.ignore-nitz");
if (ignore != null && ignore.equals("yes")) {
log("NITZ: Not setting clock because gsm.ignore-nitz is set");
return;
}
try {
mWakeLock.acquire();
if (getAutoTime()) {
long millisSinceNitzReceived
= SystemClock.elapsedRealtime() - nitzReceiveTime;
if (millisSinceNitzReceived < 0) {
// Sanity check: something is wrong
if (DBG) {
log("NITZ: not setting time, clock has rolled "
+ "backwards since NITZ time was received, "
+ nitz);
}
return;
}
if (millisSinceNitzReceived > Integer.MAX_VALUE) {
// If the time is this far off, something is wrong > 24 days!
if (DBG) {
log("NITZ: not setting time, processing has taken "
+ (millisSinceNitzReceived / (1000 * 60 * 60 * 24))
+ " days");
}
return;
}
// Note: with range checks above, cast to int is safe
c.add(Calendar.MILLISECOND, (int)millisSinceNitzReceived);
if (DBG) {
log("NITZ: Setting time of day to " + c.getTime()
+ " NITZ receive delay(ms): " + millisSinceNitzReceived
+ " gained(ms): "
+ (c.getTimeInMillis() - System.currentTimeMillis())
+ " from " + nitz);
}
setAndBroadcastNetworkSetTime(c.getTimeInMillis());
Log.i(LOG_TAG, "NITZ: after Setting time of day");
}
SystemProperties.set("gsm.nitz.time", String.valueOf(c.getTimeInMillis()));
saveNitzTime(c.getTimeInMillis());
if (false) {
long end = SystemClock.elapsedRealtime();
log("NITZ: end=" + end + " dur=" + (end - start));
}
mNitzUpdatedTime = true;
} finally {
mWakeLock.release();
}
} catch (RuntimeException ex) {
loge("NITZ: Parsing NITZ time " + nitz + " ex=" + ex);
}
}
private boolean getAutoTime() {
try {
return Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME) > 0;
} catch (SettingNotFoundException snfe) {
return true;
}
}
private boolean getAutoTimeZone() {
try {
return Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME_ZONE) > 0;
} catch (SettingNotFoundException snfe) {
return true;
}
}
private void saveNitzTimeZone(String zoneId) {
mSavedTimeZone = zoneId;
}
private void saveNitzTime(long time) {
mSavedTime = time;
mSavedAtTime = SystemClock.elapsedRealtime();
}
/**
* Set the timezone and send out a sticky broadcast so the system can
* determine if the timezone was set by the carrier.
*
* @param zoneId timezone set by carrier
*/
private void setAndBroadcastNetworkSetTimeZone(String zoneId) {
if (DBG) log("setAndBroadcastNetworkSetTimeZone: setTimeZone=" + zoneId);
AlarmManager alarm =
(AlarmManager) phone.getContext().getSystemService(Context.ALARM_SERVICE);
alarm.setTimeZone(zoneId);
Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra("time-zone", zoneId);
phone.getContext().sendStickyBroadcast(intent);
if (DBG) {
log("setAndBroadcastNetworkSetTimeZone: call alarm.setTimeZone and broadcast zoneId=" +
zoneId);
}
}
/**
* Set the time and Send out a sticky broadcast so the system can determine
* if the time was set by the carrier.
*
* @param time time set by network
*/
private void setAndBroadcastNetworkSetTime(long time) {
if (DBG) log("setAndBroadcastNetworkSetTime: time=" + time + "ms");
SystemClock.setCurrentTimeMillis(time);
Intent intent = new Intent(TelephonyIntents.ACTION_NETWORK_SET_TIME);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
intent.putExtra("time", time);
phone.getContext().sendStickyBroadcast(intent);
}
private void revertToNitzTime() {
if (Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME, 0) == 0) {
return;
}
if (DBG) {
log("Reverting to NITZ Time: mSavedTime=" + mSavedTime
+ " mSavedAtTime=" + mSavedAtTime);
}
if (mSavedTime != 0 && mSavedAtTime != 0) {
setAndBroadcastNetworkSetTime(mSavedTime
+ (SystemClock.elapsedRealtime() - mSavedAtTime));
}
}
private void revertToNitzTimeZone() {
if (Settings.System.getInt(phone.getContext().getContentResolver(),
Settings.System.AUTO_TIME_ZONE, 0) == 0) {
return;
}
if (DBG) log("Reverting to NITZ TimeZone: tz='" + mSavedTimeZone);
if (mSavedTimeZone != null) {
setAndBroadcastNetworkSetTimeZone(mSavedTimeZone);
}
}
/**
* Post a notification to NotificationManager for restricted state
*
* @param notifyType is one state of PS/CS_*_ENABLE/DISABLE
*/
private void setNotification(int notifyType) {
if (DBG) log("setNotification: create notification " + notifyType);
Context context = phone.getContext();
mNotification = new Notification();
mNotification.when = System.currentTimeMillis();
mNotification.flags = Notification.FLAG_AUTO_CANCEL;
mNotification.icon = com.android.internal.R.drawable.stat_sys_warning;
Intent intent = new Intent();
mNotification.contentIntent = PendingIntent
.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
CharSequence details = "";
CharSequence title = context.getText(com.android.internal.R.string.RestrictedChangedTitle);
int notificationId = CS_NOTIFICATION;
switch (notifyType) {
case PS_ENABLED:
notificationId = PS_NOTIFICATION;
details = context.getText(com.android.internal.R.string.RestrictedOnData);;
break;
case PS_DISABLED:
notificationId = PS_NOTIFICATION;
break;
case CS_ENABLED:
details = context.getText(com.android.internal.R.string.RestrictedOnAllVoice);;
break;
case CS_NORMAL_ENABLED:
details = context.getText(com.android.internal.R.string.RestrictedOnNormal);;
break;
case CS_EMERGENCY_ENABLED:
details = context.getText(com.android.internal.R.string.RestrictedOnEmergency);;
break;
case CS_DISABLED:
// do nothing and cancel the notification later
break;
}
if (DBG) log("setNotification: put notification " + title + " / " +details);
mNotification.tickerText = title;
mNotification.setLatestEventInfo(context, title, details,
mNotification.contentIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notifyType == PS_DISABLED || notifyType == CS_DISABLED) {
// cancel previous post notification
notificationManager.cancel(notificationId);
} else {
// update restricted state notification
notificationManager.notify(notificationId, mNotification);
}
}
@Override
protected void log(String s) {
Log.d(LOG_TAG, "[GsmSST] " + s);
}
@Override
protected void loge(String s) {
Log.e(LOG_TAG, "[GsmSST] " + s);
}
private static void sloge(String s) {
Log.e(LOG_TAG, "[GsmSST] " + s);
}
@Override
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("GsmServiceStateTracker extends:");
super.dump(fd, pw, args);
pw.println(" phone=" + phone);
pw.println(" cellLoc=" + cellLoc);
pw.println(" newCellLoc=" + newCellLoc);
pw.println(" mPreferredNetworkType=" + mPreferredNetworkType);
pw.println(" gprsState=" + gprsState);
pw.println(" newGPRSState=" + newGPRSState);
pw.println(" mMaxDataCalls=" + mMaxDataCalls);
pw.println(" mNewMaxDataCalls=" + mNewMaxDataCalls);
pw.println(" mReasonDataDenied=" + mReasonDataDenied);
pw.println(" mNewReasonDataDenied=" + mNewReasonDataDenied);
pw.println(" mGsmRoaming=" + mGsmRoaming);
pw.println(" mDataRoaming=" + mDataRoaming);
pw.println(" mEmergencyOnly=" + mEmergencyOnly);
pw.println(" mNeedFixZoneAfterNitz=" + mNeedFixZoneAfterNitz);
pw.println(" mZoneOffset=" + mZoneOffset);
pw.println(" mZoneDst=" + mZoneDst);
pw.println(" mZoneTime=" + mZoneTime);
pw.println(" mGotCountryCode=" + mGotCountryCode);
pw.println(" mNitzUpdatedTime=" + mNitzUpdatedTime);
pw.println(" mSavedTimeZone=" + mSavedTimeZone);
pw.println(" mSavedTime=" + mSavedTime);
pw.println(" mSavedAtTime=" + mSavedAtTime);
pw.println(" mNeedToRegForSimLoaded=" + mNeedToRegForSimLoaded);
pw.println(" mStartedGprsRegCheck=" + mStartedGprsRegCheck);
pw.println(" mReportedGprsNoReg=" + mReportedGprsNoReg);
pw.println(" mNotification=" + mNotification);
pw.println(" mWakeLock=" + mWakeLock);
pw.println(" curSpn=" + curSpn);
pw.println(" curPlmn=" + curPlmn);
pw.println(" curSpnRule=" + curSpnRule);
}
}
| false | true | private void pollStateDone() {
if (DBG) {
log("Poll ServiceState done: " +
" oldSS=[" + ss + "] newSS=[" + newSS +
"] oldGprs=" + gprsState + " newData=" + newGPRSState +
" oldMaxDataCalls=" + mMaxDataCalls +
" mNewMaxDataCalls=" + mNewMaxDataCalls +
" oldReasonDataDenied=" + mReasonDataDenied +
" mNewReasonDataDenied=" + mNewReasonDataDenied +
" oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
}
boolean hasRegistered =
ss.getState() != ServiceState.STATE_IN_SERVICE
&& newSS.getState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered =
ss.getState() == ServiceState.STATE_IN_SERVICE
&& newSS.getState() != ServiceState.STATE_IN_SERVICE;
boolean hasGprsAttached =
gprsState != ServiceState.STATE_IN_SERVICE
&& newGPRSState == ServiceState.STATE_IN_SERVICE;
boolean hasGprsDetached =
gprsState == ServiceState.STATE_IN_SERVICE
&& newGPRSState != ServiceState.STATE_IN_SERVICE;
boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
boolean hasChanged = !newSS.equals(ss);
boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
// Add an event log when connection state changes
if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
ss.getState(), gprsState, newSS.getState(), newGPRSState);
}
ServiceState tss;
tss = ss;
ss = newSS;
newSS = tss;
// clean slate for next time
newSS.setStateOutOfService();
GsmCellLocation tcl = cellLoc;
cellLoc = newCellLoc;
newCellLoc = tcl;
// Add an event log when network type switched
// TODO: we may add filtering to reduce the event logged,
// i.e. check preferred network setting, only switch to 2G, etc
if (hasRadioTechnologyChanged) {
int cid = -1;
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
if (loc != null) cid = loc.getCid();
EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
mNewRilRadioTechnology);
if (DBG) {
log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
" at cell " + cid);
}
}
gprsState = newGPRSState;
mReasonDataDenied = mNewReasonDataDenied;
mMaxDataCalls = mNewMaxDataCalls;
mRilRadioTechnology = mNewRilRadioTechnology;
// this new state has been applied - forget it until we get a new new state
mNewRilRadioTechnology = 0;
newSS.setStateOutOfService(); // clean slate for next time
if (hasRadioTechnologyChanged) {
phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
if (DBG) {
log("pollStateDone: registering current mNitzUpdatedTime=" +
mNitzUpdatedTime + " changing to false");
}
mNitzUpdatedTime = false;
}
if (hasChanged) {
String operatorNumeric;
updateSpnDisplay();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
ss.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = ss.getOperatorNumeric();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
mNitzUpdatedTime = false;
} else {
String iso = "";
String mcc = operatorNumeric.substring(0, 3);
try{
iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
} catch ( NumberFormatException ex){
loge("pollStateDone: countryCodeForMcc error" + ex);
} catch ( StringIndexOutOfBoundsException ex) {
loge("pollStateDone: countryCodeForMcc error" + ex);
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
mGotCountryCode = true;
TimeZone zone = null;
if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
getAutoTimeZone()) {
// Test both paths if ignore nitz is true
boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
((SystemClock.uptimeMillis() & 1) == 0);
ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
zone = uniqueZones.get(0);
if (DBG) {
log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
" with zone.getID=" + zone.getID() +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
}
setAndBroadcastNetworkSetTimeZone(zone.getID());
} else {
if (DBG) {
log("pollStateDone: there are " + uniqueZones.size() +
" unique offsets for iso-cc='" + iso +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
"', do nothing");
}
}
}
if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
mNeedFixZoneAfterNitz)) {
// If the offset is (0, false) and the timezone property
// is set, use the timezone property rather than
// GMT.
String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
if (DBG) {
log("pollStateDone: fix time zone zoneName='" + zoneName +
"' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
" iso-cc='" + iso +
"' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
}
// "(mZoneOffset == 0) && (mZoneDst == false) &&
// (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
// means that we received a NITZ string telling
// it is in GMT+0 w/ DST time zone
// BUT iso tells is NOT, e.g, a wrong NITZ reporting
// local time w/ 0 offset.
if ((mZoneOffset == 0) && (mZoneDst == false) &&
(zoneName != null) && (zoneName.length() > 0) &&
(Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
zone = TimeZone.getDefault();
if (mNeedFixZoneAfterNitz) {
// For wrong NITZ reporting local time w/ 0 offset,
// need adjust time to reflect default timezone setting
long ctm = System.currentTimeMillis();
long tzOffset = zone.getOffset(ctm);
if (DBG) {
log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
TimeUtils.logTimeOfDay(ctm));
}
if (getAutoTime()) {
long adj = ctm - tzOffset;
if (DBG) log("pollStateDone: adj ltod=" +
TimeUtils.logTimeOfDay(adj));
setAndBroadcastNetworkSetTime(adj);
} else {
// Adjust the saved NITZ time to account for tzOffset.
mSavedTime = mSavedTime - tzOffset;
}
}
if (DBG) log("pollStateDone: using default TimeZone");
} else if (iso.equals("")){
// Country code not found. This is likely a test network.
// Get a TimeZone based only on the NITZ parameters (best guess).
zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
if (DBG) log("pollStateDone: using NITZ TimeZone");
} else {
zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
}
mNeedFixZoneAfterNitz = false;
if (zone != null) {
log("pollStateDone: zone != null zone.getID=" + zone.getID());
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
} else {
log("pollStateDone: zone == null");
}
}
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
ss.getRoaming() ? "true" : "false");
phone.notifyServiceStateChanged(ss);
}
if (hasGprsAttached) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasGprsDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if (hasRadioTechnologyChanged) {
phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
phone.notifyLocationChanged();
}
if (! isGprsConsistent(gprsState, ss.getState())) {
if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
mStartedGprsRegCheck = true;
int check_period = Settings.Secure.getInt(
phone.getContext().getContentResolver(),
Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
check_period);
}
} else {
mReportedGprsNoReg = false;
}
}
| private void pollStateDone() {
if (DBG) {
log("Poll ServiceState done: " +
" oldSS=[" + ss + "] newSS=[" + newSS +
"] oldGprs=" + gprsState + " newData=" + newGPRSState +
" oldMaxDataCalls=" + mMaxDataCalls +
" mNewMaxDataCalls=" + mNewMaxDataCalls +
" oldReasonDataDenied=" + mReasonDataDenied +
" mNewReasonDataDenied=" + mNewReasonDataDenied +
" oldType=" + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" newType=" + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology));
}
boolean hasRegistered =
ss.getState() != ServiceState.STATE_IN_SERVICE
&& newSS.getState() == ServiceState.STATE_IN_SERVICE;
boolean hasDeregistered =
ss.getState() == ServiceState.STATE_IN_SERVICE
&& newSS.getState() != ServiceState.STATE_IN_SERVICE;
boolean hasGprsAttached =
gprsState != ServiceState.STATE_IN_SERVICE
&& newGPRSState == ServiceState.STATE_IN_SERVICE;
boolean hasGprsDetached =
gprsState == ServiceState.STATE_IN_SERVICE
&& newGPRSState != ServiceState.STATE_IN_SERVICE;
boolean hasRadioTechnologyChanged = mRilRadioTechnology != mNewRilRadioTechnology;
boolean hasChanged = !newSS.equals(ss);
boolean hasRoamingOn = !ss.getRoaming() && newSS.getRoaming();
boolean hasRoamingOff = ss.getRoaming() && !newSS.getRoaming();
boolean hasLocationChanged = !newCellLoc.equals(cellLoc);
// Add an event log when connection state changes
if (ss.getState() != newSS.getState() || gprsState != newGPRSState) {
EventLog.writeEvent(EventLogTags.GSM_SERVICE_STATE_CHANGE,
ss.getState(), gprsState, newSS.getState(), newGPRSState);
}
ServiceState tss;
tss = ss;
ss = newSS;
newSS = tss;
// clean slate for next time
newSS.setStateOutOfService();
GsmCellLocation tcl = cellLoc;
cellLoc = newCellLoc;
newCellLoc = tcl;
// Add an event log when network type switched
// TODO: we may add filtering to reduce the event logged,
// i.e. check preferred network setting, only switch to 2G, etc
if (hasRadioTechnologyChanged) {
int cid = -1;
GsmCellLocation loc = ((GsmCellLocation)phone.getCellLocation());
if (loc != null) cid = loc.getCid();
EventLog.writeEvent(EventLogTags.GSM_RAT_SWITCHED, cid, mRilRadioTechnology,
mNewRilRadioTechnology);
if (DBG) {
log("RAT switched " + ServiceState.rilRadioTechnologyToString(mRilRadioTechnology) +
" -> " + ServiceState.rilRadioTechnologyToString(mNewRilRadioTechnology) +
" at cell " + cid);
}
}
gprsState = newGPRSState;
mReasonDataDenied = mNewReasonDataDenied;
mMaxDataCalls = mNewMaxDataCalls;
mRilRadioTechnology = mNewRilRadioTechnology;
// this new state has been applied - forget it until we get a new new state
mNewRilRadioTechnology = 0;
newSS.setStateOutOfService(); // clean slate for next time
if (hasRadioTechnologyChanged) {
phone.setSystemProperty(TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE,
ServiceState.rilRadioTechnologyToString(mRilRadioTechnology));
}
if (hasRegistered) {
mNetworkAttachedRegistrants.notifyRegistrants();
if (DBG) {
log("pollStateDone: registering current mNitzUpdatedTime=" +
mNitzUpdatedTime + " changing to false");
}
mNitzUpdatedTime = false;
}
if (hasChanged) {
String operatorNumeric;
updateSpnDisplay();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ALPHA,
ss.getOperatorAlphaLong());
String prevOperatorNumeric =
SystemProperties.get(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
operatorNumeric = ss.getOperatorNumeric();
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, operatorNumeric);
if (operatorNumeric == null) {
if (DBG) log("operatorNumeric is null");
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, "");
mGotCountryCode = false;
mNitzUpdatedTime = false;
} else {
String iso = "";
String mcc = "";
try{
mcc = operatorNumeric.substring(0, 3);
iso = MccTable.countryCodeForMcc(Integer.parseInt(mcc));
} catch ( NumberFormatException ex){
loge("pollStateDone: countryCodeForMcc error" + ex);
} catch ( StringIndexOutOfBoundsException ex) {
loge("pollStateDone: countryCodeForMcc error" + ex);
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISO_COUNTRY, iso);
mGotCountryCode = true;
TimeZone zone = null;
if (!mNitzUpdatedTime && !mcc.equals("000") && !TextUtils.isEmpty(iso) &&
getAutoTimeZone()) {
// Test both paths if ignore nitz is true
boolean testOneUniqueOffsetPath = SystemProperties.getBoolean(
TelephonyProperties.PROPERTY_IGNORE_NITZ, false) &&
((SystemClock.uptimeMillis() & 1) == 0);
ArrayList<TimeZone> uniqueZones = TimeUtils.getTimeZonesWithUniqueOffsets(iso);
if ((uniqueZones.size() == 1) || testOneUniqueOffsetPath) {
zone = uniqueZones.get(0);
if (DBG) {
log("pollStateDone: no nitz but one TZ for iso-cc=" + iso +
" with zone.getID=" + zone.getID() +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath);
}
setAndBroadcastNetworkSetTimeZone(zone.getID());
} else {
if (DBG) {
log("pollStateDone: there are " + uniqueZones.size() +
" unique offsets for iso-cc='" + iso +
" testOneUniqueOffsetPath=" + testOneUniqueOffsetPath +
"', do nothing");
}
}
}
if (shouldFixTimeZoneNow(phone, operatorNumeric, prevOperatorNumeric,
mNeedFixZoneAfterNitz)) {
// If the offset is (0, false) and the timezone property
// is set, use the timezone property rather than
// GMT.
String zoneName = SystemProperties.get(TIMEZONE_PROPERTY);
if (DBG) {
log("pollStateDone: fix time zone zoneName='" + zoneName +
"' mZoneOffset=" + mZoneOffset + " mZoneDst=" + mZoneDst +
" iso-cc='" + iso +
"' iso-cc-idx=" + Arrays.binarySearch(GMT_COUNTRY_CODES, iso));
}
// "(mZoneOffset == 0) && (mZoneDst == false) &&
// (Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)"
// means that we received a NITZ string telling
// it is in GMT+0 w/ DST time zone
// BUT iso tells is NOT, e.g, a wrong NITZ reporting
// local time w/ 0 offset.
if ((mZoneOffset == 0) && (mZoneDst == false) &&
(zoneName != null) && (zoneName.length() > 0) &&
(Arrays.binarySearch(GMT_COUNTRY_CODES, iso) < 0)) {
zone = TimeZone.getDefault();
if (mNeedFixZoneAfterNitz) {
// For wrong NITZ reporting local time w/ 0 offset,
// need adjust time to reflect default timezone setting
long ctm = System.currentTimeMillis();
long tzOffset = zone.getOffset(ctm);
if (DBG) {
log("pollStateDone: tzOffset=" + tzOffset + " ltod=" +
TimeUtils.logTimeOfDay(ctm));
}
if (getAutoTime()) {
long adj = ctm - tzOffset;
if (DBG) log("pollStateDone: adj ltod=" +
TimeUtils.logTimeOfDay(adj));
setAndBroadcastNetworkSetTime(adj);
} else {
// Adjust the saved NITZ time to account for tzOffset.
mSavedTime = mSavedTime - tzOffset;
}
}
if (DBG) log("pollStateDone: using default TimeZone");
} else if (iso.equals("")){
// Country code not found. This is likely a test network.
// Get a TimeZone based only on the NITZ parameters (best guess).
zone = getNitzTimeZone(mZoneOffset, mZoneDst, mZoneTime);
if (DBG) log("pollStateDone: using NITZ TimeZone");
} else {
zone = TimeUtils.getTimeZone(mZoneOffset, mZoneDst, mZoneTime, iso);
if (DBG) log("pollStateDone: using getTimeZone(off, dst, time, iso)");
}
mNeedFixZoneAfterNitz = false;
if (zone != null) {
log("pollStateDone: zone != null zone.getID=" + zone.getID());
if (getAutoTimeZone()) {
setAndBroadcastNetworkSetTimeZone(zone.getID());
}
saveNitzTimeZone(zone.getID());
} else {
log("pollStateDone: zone == null");
}
}
}
phone.setSystemProperty(TelephonyProperties.PROPERTY_OPERATOR_ISROAMING,
ss.getRoaming() ? "true" : "false");
phone.notifyServiceStateChanged(ss);
}
if (hasGprsAttached) {
mAttachedRegistrants.notifyRegistrants();
}
if (hasGprsDetached) {
mDetachedRegistrants.notifyRegistrants();
}
if (hasRadioTechnologyChanged) {
phone.notifyDataConnection(Phone.REASON_NW_TYPE_CHANGED);
}
if (hasRoamingOn) {
mRoamingOnRegistrants.notifyRegistrants();
}
if (hasRoamingOff) {
mRoamingOffRegistrants.notifyRegistrants();
}
if (hasLocationChanged) {
phone.notifyLocationChanged();
}
if (! isGprsConsistent(gprsState, ss.getState())) {
if (!mStartedGprsRegCheck && !mReportedGprsNoReg) {
mStartedGprsRegCheck = true;
int check_period = Settings.Secure.getInt(
phone.getContext().getContentResolver(),
Settings.Secure.GPRS_REGISTER_CHECK_PERIOD_MS,
DEFAULT_GPRS_CHECK_PERIOD_MILLIS);
sendMessageDelayed(obtainMessage(EVENT_CHECK_REPORT_GPRS),
check_period);
}
} else {
mReportedGprsNoReg = false;
}
}
|
diff --git a/org.maven.ide.eclipse.editor.xml/src/main/java/org/maven/ide/eclipse/editor/xml/PomTemplateContext.java b/org.maven.ide.eclipse.editor.xml/src/main/java/org/maven/ide/eclipse/editor/xml/PomTemplateContext.java
index 9947349f..b09fec98 100644
--- a/org.maven.ide.eclipse.editor.xml/src/main/java/org/maven/ide/eclipse/editor/xml/PomTemplateContext.java
+++ b/org.maven.ide.eclipse.editor.xml/src/main/java/org/maven/ide/eclipse/editor/xml/PomTemplateContext.java
@@ -1,512 +1,512 @@
/*******************************************************************************
* Copyright (c) 2008 Sonatype, Inc.
* 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.maven.ide.eclipse.editor.xml;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.AbstractArtifactResolutionException;
import org.apache.maven.embedder.MavenEmbedder;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.Parameter;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder;
import org.codehaus.plexus.util.IOUtil;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.persistence.TemplateStore;
import org.maven.ide.eclipse.MavenPlugin;
import org.maven.ide.eclipse.core.MavenConsole;
import org.maven.ide.eclipse.core.MavenLogger;
import org.maven.ide.eclipse.editor.xml.search.ArtifactInfo;
import org.maven.ide.eclipse.editor.xml.search.Packaging;
import org.maven.ide.eclipse.editor.xml.search.SearchEngine;
import org.maven.ide.eclipse.embedder.IMaven;
import org.maven.ide.eclipse.index.IndexManager;
/**
* Context types.
*
* @author Lukas Krecan
* @author Eugene Kuleshov
*/
public enum PomTemplateContext {
UNKNOWN("unknown"), //
DOCUMENT("#document"), //
PROJECT("project"), //
PARENT("parent"), //
PROPERTIES("properties"), //
DEPENDENCIES("dependencies"), //
EXCLUSIONS("exclusions"), //
PLUGINS("plugins"), //
PLUGIN("plugin"), //
EXECUTIONS("executions"), //
PROFILES("profiles"), //
REPOSITORIES("repositories"), //
CONFIGURATION("configuration") {
private final Map<String, PluginDescriptor> descriptors = new HashMap<String, PluginDescriptor>();
@Override
protected void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String groupId = getGroupId(node);
if(groupId==null) {
groupId = "org.apache.maven.plugins"; // TODO support other default groups
}
String artifactId = getArtifactId(node);
String version = getVersion(node);
if(version==null) {
Collection<String> versions = getSearchEngine().findVersions(groupId, artifactId, "", Packaging.PLUGIN);
if(versions.isEmpty()) {
return;
}
version = versions.iterator().next();
}
PluginDescriptor descriptor = getPluginDescriptor(groupId, artifactId, version);
if(descriptor!=null) {
@SuppressWarnings("unchecked")
List<MojoDescriptor> mojos = descriptor.getMojos();
HashSet<String> params = new HashSet<String>();
for(MojoDescriptor mojo : mojos) {
@SuppressWarnings("unchecked")
List<Parameter> parameters = (List<Parameter>) mojo.getParameters();
for(Parameter parameter : parameters) {
boolean editable = parameter.isEditable();
if(editable) {
String name = parameter.getName();
if(!params.contains(name)) {
params.add(name);
String text = "<b>required:</b> " + parameter.isRequired() + "<br>" //
+ "<b>type:</b> " + parameter.getType() + "<br>";
String expression = parameter.getExpression();
if(expression!=null) {
text += "expression: " + expression + "<br>";
}
String defaultValue = parameter.getDefaultValue();
if(defaultValue!=null) {
text += "default: " + defaultValue + "<br>";
}
String desc = parameter.getDescription().trim();
text += desc.startsWith("<p>") ? desc : "<br>" + desc;
proposals.add(new Template(name, text, getContextTypeId(), //
"<" + name + ">${cursor}</" + name + ">", false));
}
}
}
}
}
}
private PluginDescriptor getPluginDescriptor(String groupId, String artifactId, String version) {
String name = groupId + ":" + artifactId + ":" + version;
PluginDescriptor descriptor = descriptors.get(name);
if(descriptor!=null) {
return descriptor;
}
MavenPlugin plugin = MavenPlugin.getDefault();
MavenConsole console = plugin.getConsole();
try {
IMaven embedder = MavenPlugin.lookup(IMaven.class);
IndexManager indexManager = MavenPlugin.getDefault().getIndexManager();
List<ArtifactRepository> repositories = indexManager.getArtifactRepositories(null, null);
- Artifact artifact = embedder.resolve(groupId, artifactId, version, null, "maven-plugin", repositories, null);
+ Artifact artifact = embedder.resolve(groupId, artifactId, version, "maven-plugin", null, repositories, null);
File file = artifact.getFile();
if(file == null) {
String msg = "Can't resolve plugin " + name;
console.logError(msg);
} else {
InputStream is = null;
ZipFile zf = null;
try {
zf = new ZipFile(file);
ZipEntry entry = zf.getEntry("META-INF/maven/plugin.xml");
if(entry != null) {
is = zf.getInputStream(entry);
PluginDescriptorBuilder builder = new PluginDescriptorBuilder();
descriptor = builder.build(new InputStreamReader(is));
descriptors.put(name, descriptor);
return descriptor;
}
} catch(Exception ex) {
String msg = "Can't read configuration for " + name;
console.logError(msg);
MavenLogger.log(msg, ex);
} finally {
IOUtil.close(is);
try {
zf.close();
} catch(IOException ex) {
// ignore
}
}
}
} catch(CoreException ex) {
IStatus status = ex.getStatus();
console.logError(status.getMessage() + "; " + status.getException().getMessage());
MavenLogger.log(ex);
}
return null;
}
},
GROUP_ID("groupId") {
@Override
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String contextTypeId = getContextTypeId();
for(String groupId : getSearchEngine().findGroupIds(prefix, getPackaging(node), getContainingArtifact(node))) {
add(proposals, contextTypeId, groupId);
}
}
},
ARTIFACT_ID("artifactId") {
@Override
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String groupId = getGroupId(node);
if(groupId != null) {
String contextTypeId = getContextTypeId();
for(String artifactId : getSearchEngine().findArtifactIds(groupId, prefix, getPackaging(node),
getContainingArtifact(node))) {
add(proposals, contextTypeId, artifactId, groupId + ":" + artifactId);
}
}
}
},
VERSION("version") {
@Override
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String groupId = getGroupId(node);
String artifactId = getArtifactId(node);
if(groupId != null && artifactId != null) {
String contextTypeId = getContextTypeId();
for(String version : getSearchEngine().findVersions(groupId, artifactId, prefix, getPackaging(node))) {
add(proposals, contextTypeId, version, groupId + ":" + artifactId + ":" + version);
}
}
}
},
CLASSIFIER("classifier") {
@Override
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String groupId = getGroupId(node);
String artifactId = getArtifactId(node);
String version = getVersion(node);
if(groupId != null && artifactId != null && version != null) {
String contextTypeId = getContextTypeId();
for(String classifier : getSearchEngine().findClassifiers(groupId, artifactId, version, prefix,
getPackaging(node))) {
add(proposals, contextTypeId, classifier, groupId + ":" + artifactId + ":" + version + ":" + classifier);
}
}
}
},
TYPE("type") {
@Override
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String groupId = getGroupId(node);
String artifactId = getArtifactId(node);
String version = getVersion(node);
String contextTypeId = getContextTypeId();
if(groupId != null && artifactId != null && version != null) {
for(String type : getSearchEngine().findTypes(groupId, artifactId, version, prefix, getPackaging(node))) {
add(proposals, contextTypeId, type, groupId + ":" + artifactId + ":" + version + ":" + type);
}
}
}
},
PACKAGING("packaging") {
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String contextTypeId = getContextTypeId();
// TODO only show "pom" packaging in root section
add(proposals, contextTypeId, "pom");
add(proposals, contextTypeId, "jar");
add(proposals, contextTypeId, "war");
add(proposals, contextTypeId, "ear");
add(proposals, contextTypeId, "ejb");
add(proposals, contextTypeId, "eclipse-plugin");
add(proposals, contextTypeId, "eclipse-feature");
add(proposals, contextTypeId, "eclipse-update-site");
add(proposals, contextTypeId, "maven-plugin");
add(proposals, contextTypeId, "maven-archetype");
}
},
SCOPE("scope") {
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
String contextTypeId = getContextTypeId();
add(proposals, contextTypeId, "compile");
add(proposals, contextTypeId, "test");
add(proposals, contextTypeId, "provided");
add(proposals, contextTypeId, "runtime");
add(proposals, contextTypeId, "system");
// TODO only show "import" scope in <dependencyManagement>
add(proposals, contextTypeId, "import");
}
},
SYSTEM_PATH("systemPath"),
PHASE("phase") {
@Override
public void addTemplates(Collection<Template> proposals, Node node, String prefix) {
// TODO the following list should be derived from the packaging handler (the actual lifecycle)
// Clean Lifecycle
add(proposals, "pre-clean", "Executes processes needed prior to the actual project cleaning");
add(proposals, "clean", "Removes all files generated by the previous build");
add(proposals, "post-clean", "Executes processes needed to finalize the project cleaning");
// Default Lifecycle
add(proposals, "validate", "Validate the project is correct and all necessary information is available");
add(proposals, "generate-sources", "Generate any source code for inclusion in compilation");
add(proposals, "process-sources", "Process the source code, for example to filter any values");
add(proposals, "generate-resources", "Generate resources for inclusion in the package");
add(proposals, "process-resources", "Copy and process the resources into the destination directory, ready for packaging");
add(proposals, "compile", "Compile the source code of the project");
add(proposals, "process-classes", "Post-process the generated files from compilation, for example to do bytecode enhancement on Java classes");
add(proposals, "generate-test-sources", "Generate any test source code for inclusion in compilation");
add(proposals, "process-test-sources", "Process the test source code, for example to filter any values");
add(proposals, "generate-test-resources", "Create resources for testing");
add(proposals, "process-test-resources", "Copy and process the resources into the test destination directory");
add(proposals, "test-compile", "Compile the test source code into the test destination directory");
add(proposals, "process-test-classes", "Post-process the generated files from test compilation, for example to do bytecode enhancement on Java classes. For Maven 2.0.5 and above");
add(proposals, "test", "Run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed");
add(proposals, "prepare-package", "Perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package. (Maven 2.1 and above)");
add(proposals, "package", "Take the compiled code and package it in its distributable format, such as a JAR");
add(proposals, "pre-integration-test", "Perform actions required before integration tests are executed. This may involve things such as setting up the required environment");
add(proposals, "integration-test", "Process and deploy the package if necessary into an environment where integration tests can be run");
add(proposals, "post-integration-test", "Perform actions required after integration tests have been executed. This may including cleaning up the environment");
add(proposals, "verify", "Run any checks to verify the package is valid and meets quality criteria");
add(proposals, "install", "Install the package into the local repository, for use as a dependency in other projects locally");
add(proposals, "deploy", "Done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects");
// Site Lifecycle
add(proposals, "pre-site", "Executes processes needed prior to the actual project site generation");
add(proposals, "site", "Generates the project's site documentation");
add(proposals, "post-site", "Executes processes needed to finalize the site generation, and to prepare for site deployment");
add(proposals, "site-deploy", "Deploys the generated site documentation to the specified web server");
}
};
private static final String PREFIX = MvnIndexPlugin.PLUGIN_ID + ".templates.contextType.";
private final String nodeName;
private PomTemplateContext(String nodeName) {
this.nodeName = nodeName;
}
/**
* Return templates depending on the context type.
*/
public Template[] getTemplates(Node node, String prefix) {
Collection<Template> templates = new ArrayList<Template>();
addTemplates(templates, node, prefix);
TemplateStore store = MvnIndexPlugin.getDefault().getTemplateStore();
if(store != null) {
templates.addAll(Arrays.asList(store.getTemplates(getContextTypeId())));
}
return templates.toArray(new Template[templates.size()]);
}
protected void addTemplates(Collection<Template> templates, Node currentNode, String prefix) {
}
protected String getNodeName() {
return nodeName;
}
public String getContextTypeId() {
return PREFIX + nodeName;
}
public static PomTemplateContext fromId(String contextTypeId) {
for(PomTemplateContext context : values()) {
if(context.getContextTypeId().equals(contextTypeId)) {
return context;
}
}
return UNKNOWN;
}
public static PomTemplateContext fromNodeName(String idSuffix) {
for(PomTemplateContext context : values()) {
if(context.getNodeName().equals(idSuffix)) {
return context;
}
}
return UNKNOWN;
}
private static SearchEngine getSearchEngine() {
return MvnIndexPlugin.getDefault().getSearchEngine();
}
///
/**
* Returns containing artifactInfo for exclusions. Otherwise returns null.
*/
protected ArtifactInfo getContainingArtifact(Node currentNode) {
if(isExclusion(currentNode)) {
Node node = currentNode.getParentNode().getParentNode();
return getArtifactInfo(node);
}
return null;
}
/**
* Returns artifact info from siblings of given node.
*/
private ArtifactInfo getArtifactInfo(Node node) {
return new ArtifactInfo(getGroupId(node), getArtifactId(node), getVersion(node), //
getSiblingTextValue(node, "classifier"), getSiblingTextValue(node, "type"));
}
/**
* Returns required packaging.
*/
protected Packaging getPackaging(Node currentNode) {
if(isPlugin(currentNode)) {
return Packaging.PLUGIN;
} else if(isParent(currentNode)) {
return Packaging.POM;
}
return Packaging.ALL;
}
/**
* Returns true if user is editing plugin dependency.
*/
private boolean isPlugin(Node currentNode) {
return "plugin".equals(currentNode.getParentNode().getNodeName());
}
/**
* Returns true if user is editing plugin dependency exclusion.
*/
private boolean isExclusion(Node currentNode) {
return "exclusion".equals(currentNode.getParentNode().getNodeName());
}
/**
* Returns true if user is editing parent dependency.
*/
private boolean isParent(Node currentNode) {
return "parent".equals(currentNode.getParentNode().getNodeName());
}
protected String getGroupId(Node currentNode) {
return getSiblingTextValue(currentNode, "groupId");
}
protected static String getArtifactId(Node currentNode) {
return getSiblingTextValue(currentNode, "artifactId");
}
protected static String getVersion(Node currentNode) {
return getSiblingTextValue(currentNode, "version");
}
private static String getSiblingTextValue(Node sibling, String name) {
Node node = getSiblingWithName(sibling, name);
return getNodeTextValue(node);
}
/**
* Returns sibling with given name.
*/
private static Node getSiblingWithName(Node node, String name) {
NodeList nodeList = node.getParentNode().getChildNodes();
for(int i = 0; i < nodeList.getLength(); i++ ) {
if(name.equals(nodeList.item(i).getNodeName())) {
return nodeList.item(i);
}
}
return null;
}
/**
* Returns text value of the node.
*/
private static String getNodeTextValue(Node node) {
if(node != null && hasOneNode(node.getChildNodes())) {
return ((Text) node.getChildNodes().item(0)).getData().trim();
}
return null;
}
/**
* Returns true if there is only one node in the nodeList.
*/
private static boolean hasOneNode(NodeList nodeList) {
return nodeList != null && nodeList.getLength() == 1;
}
private static void add(Collection<Template> proposals, String contextTypeId, String name) {
add(proposals, contextTypeId, name, name);
}
private static void add(Collection<Template> proposals, String contextTypeId, String name, String description) {
proposals.add(new Template(name, description, contextTypeId, name, false));
}
}
| true | true | private PluginDescriptor getPluginDescriptor(String groupId, String artifactId, String version) {
String name = groupId + ":" + artifactId + ":" + version;
PluginDescriptor descriptor = descriptors.get(name);
if(descriptor!=null) {
return descriptor;
}
MavenPlugin plugin = MavenPlugin.getDefault();
MavenConsole console = plugin.getConsole();
try {
IMaven embedder = MavenPlugin.lookup(IMaven.class);
IndexManager indexManager = MavenPlugin.getDefault().getIndexManager();
List<ArtifactRepository> repositories = indexManager.getArtifactRepositories(null, null);
Artifact artifact = embedder.resolve(groupId, artifactId, version, null, "maven-plugin", repositories, null);
File file = artifact.getFile();
if(file == null) {
String msg = "Can't resolve plugin " + name;
console.logError(msg);
} else {
InputStream is = null;
ZipFile zf = null;
try {
zf = new ZipFile(file);
ZipEntry entry = zf.getEntry("META-INF/maven/plugin.xml");
if(entry != null) {
is = zf.getInputStream(entry);
PluginDescriptorBuilder builder = new PluginDescriptorBuilder();
descriptor = builder.build(new InputStreamReader(is));
descriptors.put(name, descriptor);
return descriptor;
}
} catch(Exception ex) {
String msg = "Can't read configuration for " + name;
console.logError(msg);
MavenLogger.log(msg, ex);
} finally {
IOUtil.close(is);
try {
zf.close();
} catch(IOException ex) {
// ignore
}
}
}
} catch(CoreException ex) {
IStatus status = ex.getStatus();
console.logError(status.getMessage() + "; " + status.getException().getMessage());
MavenLogger.log(ex);
}
return null;
}
| private PluginDescriptor getPluginDescriptor(String groupId, String artifactId, String version) {
String name = groupId + ":" + artifactId + ":" + version;
PluginDescriptor descriptor = descriptors.get(name);
if(descriptor!=null) {
return descriptor;
}
MavenPlugin plugin = MavenPlugin.getDefault();
MavenConsole console = plugin.getConsole();
try {
IMaven embedder = MavenPlugin.lookup(IMaven.class);
IndexManager indexManager = MavenPlugin.getDefault().getIndexManager();
List<ArtifactRepository> repositories = indexManager.getArtifactRepositories(null, null);
Artifact artifact = embedder.resolve(groupId, artifactId, version, "maven-plugin", null, repositories, null);
File file = artifact.getFile();
if(file == null) {
String msg = "Can't resolve plugin " + name;
console.logError(msg);
} else {
InputStream is = null;
ZipFile zf = null;
try {
zf = new ZipFile(file);
ZipEntry entry = zf.getEntry("META-INF/maven/plugin.xml");
if(entry != null) {
is = zf.getInputStream(entry);
PluginDescriptorBuilder builder = new PluginDescriptorBuilder();
descriptor = builder.build(new InputStreamReader(is));
descriptors.put(name, descriptor);
return descriptor;
}
} catch(Exception ex) {
String msg = "Can't read configuration for " + name;
console.logError(msg);
MavenLogger.log(msg, ex);
} finally {
IOUtil.close(is);
try {
zf.close();
} catch(IOException ex) {
// ignore
}
}
}
} catch(CoreException ex) {
IStatus status = ex.getStatus();
console.logError(status.getMessage() + "; " + status.getException().getMessage());
MavenLogger.log(ex);
}
return null;
}
|
diff --git a/core/src/visad/trunk/DataRenderer.java b/core/src/visad/trunk/DataRenderer.java
index c2207534a..b22b3f63a 100644
--- a/core/src/visad/trunk/DataRenderer.java
+++ b/core/src/visad/trunk/DataRenderer.java
@@ -1,2187 +1,2189 @@
//
// DataRenderer.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2001 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
import java.util.*;
import java.rmi.*;
/**
DataRenderer is the VisAD abstract super-class for graphics rendering
algorithms. These transform Data objects into 3-D (or 2-D)
depictions in a Display window.<P>
DataRenderer is not Serializable and should not be copied
between JVMs.<P>
*/
public abstract class DataRenderer extends Object {
private DisplayImpl display;
/** used to insert output into scene graph */
private DisplayRenderer displayRenderer;
/** links to Data to be renderer by this */
private transient DataDisplayLink[] Links;
/** flag from DataDisplayLink.prepareData */
private boolean[] feasible; // it's a miracle if this is correct
private boolean[] is_null; // WLH 7 May 2001
/** flag to indicate that DataDisplayLink.prepareData was invoked */
private boolean[] changed;
private boolean any_changed;
private boolean all_feasible;
private boolean any_transform_control;
/** a Vector of BadMappingException and UnimplementedException
Strings generated during the last invocation of doAction */
private Vector exceptionVector = new Vector();
private boolean suppress_exceptions = false;
private boolean enabled = true;
public DataRenderer() {
Links = null;
display = null;
}
public void clearExceptions() {
exceptionVector.removeAllElements();
}
public void suppressExceptions(boolean suppress) {
suppress_exceptions = suppress;
}
/** add message from BadMappingException or
UnimplementedException to exceptionVector */
public void addException(Exception error) {
exceptionVector.addElement(error);
// System.out.println(error.getMessage());
}
/** this returns a Vector of Strings from the BadMappingExceptions
and UnimplementedExceptions generated during the last invocation
of this DataRenderer's doAction method;
there is no need to over-ride this method, but it may be invoked
by DisplayRenderer; gets a clone of exceptionVector to avoid
concurrent access by Display thread */
public Vector getExceptionVector() {
return (suppress_exceptions ? new Vector() : (Vector) exceptionVector.clone());
}
public boolean get_all_feasible() {
return all_feasible;
}
public boolean get_any_changed() {
return any_changed;
}
public boolean get_any_transform_control() {
return any_transform_control;
}
public void set_all_feasible(boolean b) {
all_feasible = b;
}
public abstract void setLinks(DataDisplayLink[] links, DisplayImpl d)
throws VisADException;
public void toggle(boolean on) {
enabled = on;
}
public boolean getEnabled() {
return enabled;
}
public synchronized void setLinks(DataDisplayLink[] links) {
if (links == null || links.length == 0) return;
Links = links;
feasible = new boolean[Links.length];
is_null = new boolean[Links.length];
changed = new boolean[Links.length];
for (int i=0; i<Links.length; i++) {
feasible[i] = false;
is_null[i] = true;
}
}
/** return an array of links to Data objects to be rendered;
Data objects are accessed by DataDisplayLink.getData() */
public DataDisplayLink[] getLinks() {
return Links;
}
public DisplayImpl getDisplay() {
return display;
}
public void setDisplay(DisplayImpl d) {
display = d;
}
public DisplayRenderer getDisplayRenderer() {
return displayRenderer;
}
public void setDisplayRenderer(DisplayRenderer r) {
displayRenderer = r;
}
public boolean checkAction() {
for (int i=0; i<Links.length; i++) {
if (Links[i].checkTicks() || !feasible[i]) {
return true;
}
// check if this Data includes any changed Controls
Enumeration maps = Links[i].getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.checkTicks(this, Links[i])) {
return true;
}
}
}
return false;
}
/** check if re-transform is needed; if initialize is true then
compute ranges for RealType-s and Animation sampling */
public DataShadow prepareAction(boolean go, boolean initialize,
DataShadow shadow)
throws VisADException, RemoteException {
any_changed = false;
all_feasible = true;
any_transform_control = false;
for (int i=0; i<Links.length; i++) {
changed[i] = false;
DataReference ref = Links[i].getDataReference();
// test for changed Controls that require doTransform
/*
System.out.println(display.getName() +
" Links[" + i + "].checkTicks() = " + Links[i].checkTicks() +
" feasible[" + i + "] = " + feasible[i] + " go = " + go);
MathType junk = Links[i].getType();
if (junk != null) System.out.println(junk.prettyString());
*/
if (Links[i].checkTicks() || !feasible[i] || go) {
/*
boolean check = Links[i].checkTicks();
System.out.println("DataRenderer.prepareAction: check = " + check + " feasible = " +
feasible[i] + " go = " + go + " " +
Links[i].getThingReference().getName());
// DisplayImpl.printStack("prepareAction");
*/
// data has changed - need to re-display
changed[i] = true;
any_changed = true;
// create ShadowType for data, classify data for display
try {
feasible[i] = Links[i].prepareData();
is_null[i] = (Links[i].getData() == null); // WLH 7 May 2001
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, Links[i]);
removeLink(Links[i]);
i--;
continue;
}
throw re;
}
if (!feasible[i]) {
all_feasible = false;
// WLH 31 March 99
clearBranch();
}
if (initialize && feasible[i]) {
// compute ranges of RealTypes and Animation sampling
ShadowType type = Links[i].getShadow().getAdaptedShadowType();
Data data;
try {
data = Links[i].getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, Links[i]);
removeLink(Links[i]);
i--;
continue;
}
throw re;
}
shadow = computeRanges(data, type, shadow);
/* WLH 8 Dec 2000
if (shadow == null) {
shadow =
data.computeRanges(type, display.getScalarCount());
}
else {
shadow = data.computeRanges(type, shadow);
}
*/
}
} // end if (Links[i].checkTicks() || !feasible[i] || go)
if (feasible[i]) {
// check if this Data includes any changed Controls
Enumeration maps = Links[i].getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.checkTicks(this, Links[i])) {
any_transform_control = true;
}
}
} // end if (feasible[i])
} // end for (int i=0; i<Links.length; i++)
return shadow;
}
public DataShadow computeRanges(Data data, ShadowType type, DataShadow shadow)
throws VisADException, RemoteException {
if (shadow == null) {
shadow =
data.computeRanges(type, display.getScalarCount());
}
else {
shadow = data.computeRanges(type, shadow);
}
return shadow;
}
/** clear scene graph component */
public abstract void clearBranch();
/** re-transform if needed;
return false if not done */
/** transform linked Data objects into a display list, if
any Data object values have changed or relevant Controls
have changed; DataRenderers that assume the default
implementation of DisplayImpl.doAction can determine
whether re-transform is needed by:
(get_all_feasible() && (get_any_changed() || get_any_transform_control()));
these flags are computed by the default DataRenderer
implementation of prepareAction;
the return boolean is true if the transform was done
successfully */
public abstract boolean doAction() throws VisADException, RemoteException;
public boolean getBadScale(boolean anyBadMap) {
boolean badScale = false;
for (int i=0; i<Links.length; i++) {
if (!feasible[i] && (anyBadMap || !is_null[i])) {
/*
try {
System.out.println("getBadScale not feasible " +
Links[i].getThingReference().getName());
}
catch (VisADException e) {}
catch (RemoteException e) {}
*/
return true;
}
Enumeration maps = Links[i].getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
badScale |= map.badRange();
/*
if (map.badRange()) {
System.out.println("getBadScale: " + map.getScalar().getName() + " -> " +
map.getDisplayScalar().getName());
}
*/
}
}
// System.out.println("getBadScale return " + badScale);
return badScale;
}
/** clear any display list created by the most recent doAction
invocation */
public abstract void clearScene();
public void clearAVControls() {
Enumeration controls = display.getControls(AVControl.class).elements();
while (controls.hasMoreElements()) {
((AVControl )controls.nextElement()).clearSwitches(this);
}
// a convenient place to throw this in
ProjectionControl control = display.getProjectionControl();
control.clearSwitches(this);
// a convenient place to throw this in
lat_index = -1;
lon_index = -1;
}
/** factory for constructing a subclass of ShadowType appropriate
for the graphics API, that also adapts ShadowFunctionType;
these factories are invoked by the buildShadowType methods of
the MathType subclasses, which are invoked by
DataDisplayLink.prepareData, which is invoked by
DataRenderer.prepareAction */
public abstract ShadowType makeShadowFunctionType(
FunctionType type, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException;
/** factory for constructing a subclass of ShadowType appropriate
for the graphics API, that also adapts ShadowRealTupleType */
public abstract ShadowType makeShadowRealTupleType(
RealTupleType type, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException;
/** factory for constructing a subclass of ShadowType appropriate
for the graphics API, that also adapts ShadowRealType */
public abstract ShadowType makeShadowRealType(
RealType type, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException;
/** factory for constructing a subclass of ShadowType appropriate
for the graphics API, that also adapts ShadowSetType */
public abstract ShadowType makeShadowSetType(
SetType type, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException;
/** factory for constructing a subclass of ShadowType appropriate
for the graphics API, that also adapts ShadowTextType */
public abstract ShadowType makeShadowTextType(
TextType type, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException;
/** factory for constructing a subclass of ShadowType appropriate
for the graphics API, that also adapts ShadowTupleType */
public abstract ShadowType makeShadowTupleType(
TupleType type, DataDisplayLink link, ShadowType parent)
throws VisADException, RemoteException;
/** DataRenderer-specific decision about which Controls require re-transform;
may be over-ridden by DataRenderer sub-classes; this decision may use
some values computed by link.prepareData */
public boolean isTransformControl(Control control, DataDisplayLink link) {
if (control instanceof ProjectionControl ||
control instanceof ToggleControl) {
return false;
}
/* WLH 1 Nov 97 - temporary hack -
RangeControl changes always require Transform
ValueControl and AnimationControl never do
if (control instanceof AnimationControl ||
control instanceof ValueControl ||
control instanceof RangeControl) {
return link.isTransform[control.getIndex()];
*/
if (control instanceof AnimationControl ||
control instanceof ValueControl) {
return false;
}
return true;
}
/** used for transform time-out hack */
public DataDisplayLink getLink() {
return null;
}
public boolean isLegalTextureMap() {
return true;
}
/* ********************** */
/* flow rendering stuff */
/* ********************** */
// value array (display_values) indices
// ((ScalarMap) MapVector.elementAt(valueToMap[index]))
// can get these indices through shadow_data_out or shadow_data_in
// true if lat and lon in data_in & shadow_data_in is allSpatial
// or if lat and lon in data_in & lat_lon_in_by_coord
boolean lat_lon_in = false;
// true if lat_lon_in and shadow_data_out is allSpatial
// i.e., map from lat, lon to display is through data CoordinateSystem
boolean lat_lon_in_by_coord = false;
// true if lat and lon in data_out & shadow_data_out is allSpatial
boolean lat_lon_out = false;
// true if lat_lon_out and shadow_data_in is allSpatial
// i.e., map from lat, lon to display is inverse via data CoordinateSystem
boolean lat_lon_out_by_coord = false;
int lat_lon_dimension = -1;
ShadowRealTupleType shadow_data_out = null;
RealTupleType data_out = null;
Unit[] data_units_out = null;
// CoordinateSystem data_coord_out is always null
ShadowRealTupleType shadow_data_in = null;
RealTupleType data_in = null;
Unit[] data_units_in = null;
CoordinateSystem[] data_coord_in = null; // may be one per point
// spatial ScalarMaps for allSpatial shadow_data_out
ScalarMap[] sdo_maps = null;
// spatial ScalarMaps for allSpatial shadow_data_in
ScalarMap[] sdi_maps = null;
int[] sdo_spatial_index = null;
int[] sdi_spatial_index = null;
// indices of RealType.Latitude and RealType.Longitude
// if lat_lon_in then indices in data_in
// if lat_lon_out then indices in data_out
// if lat_lon_spatial then values indices
int lat_index = -1;
int lon_index = -1;
// non-negative if lat & lon in a RealTupleType of length 3
int other_index = -1;
// true if other_index Units convertable to meter
boolean other_meters = false;
// from doTransform
RealVectorType[] rvts = {null, null};
public RealVectorType getRealVectorTypes(int index) {
if (index == 0 || index == 1) return rvts[index];
else return null;
}
public int[] getLatLonIndices() {
return new int[] {lat_index, lon_index};
}
public void setLatLonIndices(int[] indices) {
lat_index = indices[0];
lon_index = indices[1];
}
public int getEarthDimension() {
return lat_lon_dimension;
}
public Unit[] getEarthUnits() {
Unit[] units = null;
if (lat_lon_in) {
units = data_units_in;
}
else if (lat_lon_out) {
units = data_units_out;
}
else if (lat_lon_spatial) {
units = new Unit[] {RealType.Latitude.getDefaultUnit(),
RealType.Longitude.getDefaultUnit()};
}
else {
units = null;
}
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (units == null) {
return null;
}
else if (units.length == 2) {
return new Unit[] {lat >= 0 ? units[lat] : null,
lon >= 0 ? units[lon] : null};
}
else if (units.length == 3) {
return new Unit[] {lat >= 0 ? units[lat] : null,
lon >= 0 ? units[lon] : null,
other >= 0 ? units[other] : null};
}
else {
return null;
}
}
public float getLatLonRange() {
double[] rlat = null;
double[] rlon = null;
int lat = lat_index;
int lon = lon_index;
if ((lat_lon_out && !lat_lon_out_by_coord) ||
(lat_lon_in && lat_lon_in_by_coord)) {
rlat = lat >= 0 ? sdo_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN};
rlon = lon >= 0 ? sdo_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN};
}
else if ((lat_lon_in && !lat_lon_in_by_coord) ||
(lat_lon_out && lat_lon_out_by_coord)) {
rlat = lat >= 0 ? sdi_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN};
rlon = lon >= 0 ? sdi_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN};
}
else if (lat_lon_spatial) {
rlat = lat_map.getRange();
rlon = lon_map.getRange();
}
else {
return 1.0f;
}
double dlat = Math.abs(rlat[1] - rlat[0]);
double dlon = Math.abs(rlon[1] - rlon[0]);
if (dlat != dlat) dlat = 1.0f;
if (dlon != dlon) dlon = 1.0f;
return (dlat > dlon) ? (float) dlat : (float) dlon;
}
/** convert (lat, lon) or (lat, lon, other) values to
display (x, y, z) */
public float[][] earthToSpatial(float[][] locs, float[] vert)
throws VisADException {
return earthToSpatial(locs, vert, null);
}
public float[][] earthToSpatial(float[][] locs, float[] vert,
float[][] base_spatial_locs)
throws VisADException {
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (lat_index < 0 || lon_index < 0) return null;
int size = locs[0].length;
if (locs.length < lat_lon_dimension) {
// extend locs to lat_lon_dimension with zero fill
float[][] temp = locs;
locs = new float[lat_lon_dimension][];
for (int i=0; i<locs.length; i++) {
locs[i] = temp[i];
}
float[] zero = new float[size];
for (int j=0; j<size; j++) zero[j] = 0.0f;
for (int i=locs.length; i<lat_lon_dimension; i++) {
locs[i] = zero;
}
}
else if (locs.length > lat_lon_dimension) {
// truncate locs to lat_lon_dimension
float[][] temp = locs;
locs = new float[lat_lon_dimension][];
for (int i=0; i<lat_lon_dimension; i++) {
locs[i] = temp[i];
}
}
// permute (lat, lon, other) to data RealTupleType
float[][] tuple_locs = new float[lat_lon_dimension][];
float[][] spatial_locs = new float[3][];
tuple_locs[lat] = locs[0];
tuple_locs[lon] = locs[1];
if (lat_lon_dimension == 3) tuple_locs[other] = locs[2];
int vert_index = -1; // non-lat/lon index for lat_lon_dimension = 2
if (lat_lon_in) {
if (lat_lon_in_by_coord) {
// transform 'RealTupleType data_in' to 'RealTupleType data_out'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[0],
data_units_in, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[j],
data_units_in, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
// map data_out to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdo_spatial_index[i]] =
sdo_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]);
}
}
else {
// map data_in to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdi_spatial_index[i]] =
sdi_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]);
}
}
}
else if (lat_lon_out) {
if (lat_lon_out_by_coord) {
// transform 'RealTupleType data_out' to 'RealTupleType data_in'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[0], data_units_in, null, data_out,
null, data_units_out, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[j], data_units_in, null, data_out,
null, data_units_out, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
// map data_in to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdi_spatial_index[i]] =
sdi_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]);
}
}
else {
// map data_out to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdo_spatial_index[i]] =
sdo_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]);
}
}
}
else if (lat_lon_spatial) {
// map lat & lon, not in allSpatial RealTupleType, to
// spatial DisplayRealTypes
spatial_locs[lat_spatial_index] =
lat_map.scaleValues(tuple_locs[lat]);
spatial_locs[lon_spatial_index] =
lon_map.scaleValues(tuple_locs[lon]);
vert_index = 3 - (lat_spatial_index + lon_spatial_index);
}
else {
// should never happen
return null;
}
// WLH 9 Dec 99
// fill any empty spatial DisplayRealTypes with default values
for (int i=0; i<3; i++) {
if (spatial_locs[i] == null) {
if (base_spatial_locs != null && base_spatial_locs[i] != null) {
spatial_locs[i] = base_spatial_locs[i]; // copy not necessary
}
else {
spatial_locs[i] = new float[size];
float def = default_spatial_in[i]; // may be non-Cartesian
for (int j=0; j<size; j++) spatial_locs[i][j] = def;
}
}
}
// adjust non-lat/lon spatial_locs by vertical flow component
/* WLH 28 July 99
if (vert != null && vert_index > -1) {
for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j];
}
*/
if (vert != null && vert_index > -1 && spatial_locs[vert_index] != null) {
for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j];
}
if (display_coordinate_system != null) {
// transform non-Cartesian spatial DisplayRealTypes to Cartesian
if (spatial_locs != null && spatial_locs.length > 0 &&
spatial_locs[0] != null && spatial_locs[0].length > 0) {
spatial_locs = display_coordinate_system.toReference(spatial_locs);
}
}
return spatial_locs;
}
/** convert display (x, y, z) to (lat, lon) or (lat, lon, other)
values */
public float[][] spatialToEarth(float[][] spatial_locs)
throws VisADException {
float[][] base_spatial_locs = new float[3][];
return spatialToEarth(spatial_locs, base_spatial_locs);
}
public float[][] spatialToEarth(float[][] spatial_locs,
float[][] base_spatial_locs)
throws VisADException {
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (lat_index < 0 || lon_index < 0) return null;
if (spatial_locs.length != 3) return null;
int size = 0;
for (int i=0; i<3; i++) {
if (spatial_locs[i] != null && spatial_locs[i].length > size) {
size = spatial_locs[i].length;
}
}
if (size == 0) return null;
// fill any empty spatial DisplayRealTypes with default values
for (int i=0; i<3; i++) {
if (spatial_locs[i] == null) {
spatial_locs[i] = new float[size];
// defaults for Cartesian spatial DisplayRealTypes = 0.0f
for (int j=0; j<size; j++) spatial_locs[i][j] = 0.0f;
}
}
if (display_coordinate_system != null) {
// transform Cartesian spatial DisplayRealTypes to non-Cartesian
spatial_locs = display_coordinate_system.fromReference(spatial_locs);
}
base_spatial_locs[0] = spatial_locs[0];
base_spatial_locs[1] = spatial_locs[1];
base_spatial_locs[2] = spatial_locs[2];
float[][] tuple_locs = new float[lat_lon_dimension][];
if (lat_lon_in) {
if (lat_lon_in_by_coord) {
// map spatial DisplayRealTypes to data_out
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]);
}
// transform 'RealTupleType data_out' to 'RealTupleType data_in'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[0], data_units_in, null, data_out,
null, data_units_out, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[j], data_units_in, null, data_out,
null, data_units_out, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
}
else {
// map spatial DisplayRealTypes to data_in
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]);
}
}
}
else if (lat_lon_out) {
if (lat_lon_out_by_coord) {
// map spatial DisplayRealTypes to data_in
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]);
}
// transform 'RealTupleType data_in' to 'RealTupleType data_out'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[0],
data_units_in, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[j],
data_units_in, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
}
else {
// map spatial DisplayRealTypes to data_out
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]);
}
}
}
else if (lat_lon_spatial) {
// map spatial DisplayRealTypes to lat & lon, not in
// allSpatial RealTupleType
tuple_locs[lat] =
lat_map.inverseScaleValues(spatial_locs[lat_spatial_index]);
tuple_locs[lon] =
lon_map.inverseScaleValues(spatial_locs[lon_spatial_index]);
}
else {
// should never happen
return null;
}
// permute data RealTupleType to (lat, lon, other)
float[][] locs = new float[lat_lon_dimension][];
locs[0] = tuple_locs[lat];
locs[1] = tuple_locs[lon];
if (lat_lon_dimension == 3) locs[2] = tuple_locs[other];
return locs;
}
// information from doTransform
public void setEarthSpatialData(ShadowRealTupleType s_d_i,
ShadowRealTupleType s_d_o, RealTupleType d_o,
Unit[] d_u_o, RealTupleType d_i,
CoordinateSystem[] d_c_i, Unit[] d_u_i)
throws VisADException {
// first check for VectorRealType components mapped to flow
// TO_DO: check here for flow mapped via CoordinateSystem
if (d_o != null && d_o instanceof RealVectorType) {
ScalarMap[] maps = new ScalarMap[3];
int k = getFlowMaps(s_d_o, maps);
if (k > -1) rvts[k] = (RealVectorType) d_o;
}
if (d_i != null && d_i instanceof RealVectorType) {
ScalarMap[] maps = new ScalarMap[3];
int k = getFlowMaps(s_d_i, maps);
if (k > -1) rvts[k] = (RealVectorType) d_i;
}
int lat_index_local = -1;
int lon_index_local = -1;
- other_index = -1;
+ int other_index_local = -1;
int n = 0;
int m = 0;
if (d_i != null) {
n = d_i.getDimension();
for (int i=0; i<n; i++) {
RealType real = (RealType) d_i.getComponent(i);
if (RealType.Latitude.equals(real)) lat_index_local = i;
if (RealType.Longitude.equals(real)) lon_index_local = i;
}
}
if (lat_index_local > -1 && lon_index_local > -1 && (n == 2 || n == 3)) {
if (s_d_i != null && s_d_i.getAllSpatial() &&
!s_d_i.getSpatialReference()) {
lat_lon_in_by_coord = false;
sdi_spatial_index = new int[s_d_i.getDimension()];
sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index);
if (sdi_maps == null) {
throw new DisplayException("sdi_maps null A");
}
}
else if (s_d_o != null && s_d_o.getAllSpatial() &&
!s_d_o.getSpatialReference()) {
lat_lon_in_by_coord = true;
sdo_spatial_index = new int[s_d_o.getDimension()];
sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index);
if (sdo_maps == null) {
throw new DisplayException("sdo_maps null A");
}
}
else {
// do not update lat_index & lon_index
return;
}
lat_lon_in = true;
lat_lon_out = false;
lat_lon_out_by_coord = false;
lat_lon_spatial = false;
lat_lon_dimension = n;
if (n == 3) {
- other_index = 3 - (lat_index_local + lon_index_local);
- if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) {
+ other_index_local = 3 - (lat_index_local + lon_index_local);
+ if (Unit.canConvert(d_u_i[other_index_local], CommonUnit.meter)) {
other_meters = true;
}
}
}
else { // if( !(lat & lon in di, di dimension = 2 or 3) )
lat_index_local = -1;
lon_index_local = -1;
+ other_index_local = -1;
if (d_o != null) {
m = d_o.getDimension();
for (int i=0; i<m; i++) {
RealType real = (RealType) d_o.getComponent(i);
if (RealType.Latitude.equals(real)) lat_index_local = i;
if (RealType.Longitude.equals(real)) lon_index_local = i;
}
}
if (lat_index_local < 0 || lon_index_local < 0 || !(m == 2 || m == 3)) {
// do not update lat_index & lon_index
return;
}
if (s_d_o != null && s_d_o.getAllSpatial() &&
!s_d_o.getSpatialReference()) {
lat_lon_out_by_coord = false;
sdo_spatial_index = new int[s_d_o.getDimension()];
sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index);
if (sdo_maps == null) {
throw new DisplayException("sdo_maps null B");
}
}
else if (s_d_i != null && s_d_i.getAllSpatial() &&
!s_d_i.getSpatialReference()) {
lat_lon_out_by_coord = true;
sdi_spatial_index = new int[s_d_i.getDimension()];
sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index);
if (sdi_maps == null) {
throw new DisplayException("sdi_maps null B");
}
}
else {
// do not update lat_index & lon_index
return;
}
lat_lon_out = true;
lat_lon_in = false;
lat_lon_in_by_coord = false;
lat_lon_spatial = false;
lat_lon_dimension = m;
if (m == 3) {
- other_index = 3 - (lat_index_local + lon_index_local);
- if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) {
+ other_index_local = 3 - (lat_index_local + lon_index_local);
+ if (Unit.canConvert(d_u_i[other_index_local], CommonUnit.meter)) {
other_meters = true;
}
}
}
shadow_data_out = s_d_o;
data_out = d_o;
data_units_out = d_u_o;
shadow_data_in = s_d_i;
data_in = d_i;
data_units_in = d_u_i;
data_coord_in = d_c_i; // may be one per point
lat_index = lat_index_local;
lon_index = lon_index_local;
+ other_index = other_index_local;
return;
}
/** return array of spatial ScalarMap for srt, or null */
private ScalarMap[] getSpatialMaps(ShadowRealTupleType srt,
int[] spatial_index) {
int n = srt.getDimension();
ScalarMap[] maps = new ScalarMap[n];
for (int i=0; i<n; i++) {
ShadowRealType real = (ShadowRealType) srt.getComponent(i);
Enumeration ms = real.getSelectedMapVector().elements();
while (ms.hasMoreElements()) {
ScalarMap map = (ScalarMap) ms.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) {
maps[i] = map;
spatial_index[i] = dreal.getTupleIndex();
break;
}
}
if (maps[i] == null) {
return null;
}
}
return maps;
}
/** return array of flow ScalarMap for srt, or null */
private int getFlowMaps(ShadowRealTupleType srt, ScalarMap[] maps) {
int n = srt.getDimension();
maps[0] = null;
maps[1] = null;
maps[2] = null;
DisplayTupleType ftuple = null;
for (int i=0; i<n; i++) {
ShadowRealType real = (ShadowRealType) srt.getComponent(i);
Enumeration ms = real.getSelectedMapVector().elements();
while (ms.hasMoreElements()) {
ScalarMap map = (ScalarMap) ms.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (Display.DisplayFlow1Tuple.equals(tuple) ||
Display.DisplayFlow2Tuple.equals(tuple)) {
if (ftuple != null && !ftuple.equals(tuple)) return -1;
ftuple = tuple;
maps[i] = map;
break;
}
}
if (maps[i] == null) return -1;
}
return Display.DisplayFlow1Tuple.equals(ftuple) ? 0 : 1;
}
/* WLH 15 April 2000
// from assembleFlow
ScalarMap[][] flow_maps = null;
float[] flow_scale = null;
public void setFlowDisplay(ScalarMap[][] maps, float[] fs) {
flow_maps = maps;
flow_scale = fs;
}
*/
// if non-null, float[][] new_spatial_values =
// display_coordinate_system.toReference(spatial_values);
CoordinateSystem display_coordinate_system = null;
// spatial_tuple and spatial_value_indices are set whether
// display_coordinate_system is null or not
DisplayTupleType spatial_tuple = null;
// map from spatial_tuple tuple_index to value array indices
int[] spatial_value_indices = {-1, -1, -1};
float[] default_spatial_in = {0.0f, 0.0f, 0.0f};
// true if lat and lon mapped directly to spatial
boolean lat_lon_spatial = false;
ScalarMap lat_map = null;
ScalarMap lon_map = null;
int lat_spatial_index = -1;
int lon_spatial_index = -1;
// spatial map getRange() results for flow adjustment
double[] ranges = null;
public double[] getRanges() {
return ranges;
}
// WLH 4 March 2000
public CoordinateSystem getDisplayCoordinateSystem() {
return display_coordinate_system ;
}
// information from assembleSpatial
public void setEarthSpatialDisplay(CoordinateSystem coord,
DisplayTupleType t, DisplayImpl display, int[] indices,
float[] default_values, double[] r)
throws VisADException {
display_coordinate_system = coord;
spatial_tuple = t;
System.arraycopy(indices, 0, spatial_value_indices, 0, 3);
/* WLH 5 Dec 99
spatial_value_indices = indices;
*/
ranges = r;
for (int i=0; i<3; i++) {
int default_index = display.getDisplayScalarIndex(
((DisplayRealType) t.getComponent(i)) );
default_spatial_in[i] = default_values[default_index];
}
if (lat_index > -1 && lon_index > -1) return;
lat_index = -1;
lon_index = -1;
other_index = -1;
int valueArrayLength = display.getValueArrayLength();
int[] valueToScalar = display.getValueToScalar();
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) {
if (RealType.Latitude.equals(real)) {
lat_index = 0;
lat_map = map;
lat_spatial_index = dreal.getTupleIndex();
}
if (RealType.Longitude.equals(real)) {
lon_index = 1;
lon_map = map;
lon_spatial_index = dreal.getTupleIndex();
}
}
}
if (lat_index > -1 && lon_index > -1) {
lat_lon_spatial = true;
lat_lon_dimension = 2;
lat_lon_out = false;
lat_lon_in_by_coord = false;
lat_lon_in = false;
}
else {
lat_lon_spatial = false;
lat_index = -1;
lon_index = -1;
}
}
/* *************************** */
/* direct manipulation stuff */
/* *************************** */
private float[][] spatialValues = null;
/** if Function, last domain index and range values */
private int lastIndex = -1;
double[] lastD = null;
float[] lastX = new float[6];
/** index into spatialValues found by checkClose */
private int closeIndex = -1;
/** pick error offset, communicated from checkClose() to drag_direct() */
private float offsetx = 0.0f, offsety = 0.0f, offsetz = 0.0f;
/** count down to decay offset to 0.0 */
private int offset_count = 0;
/** initial offset_count */
private static final int OFFSET_COUNT_INIT = 30;
/** for use in drag_direct */
private transient DataDisplayLink link = null;
// private transient ShadowTypeJ3D type = null;
private transient DataReference ref = null;
private transient MathType type = null;
private transient ShadowType shadow = null;
/** point on direct manifold line or plane */
private float point_x, point_y, point_z;
/** normalized direction of line or perpendicular to plane */
private float line_x, line_y, line_z;
/** arrays of length one for inverseScaleValues */
private float[] f = new float[1];
private float[] d = new float[1];
private float[][] value = new float[1][1];
/** information calculated by checkDirect */
/** explanation for invalid use of DirectManipulationRenderer */
private String whyNotDirect = null;
/** mapping from spatial axes to tuple component */
private int[] axisToComponent = {-1, -1, -1};
/** mapping from spatial axes to ScalarMaps */
private ScalarMap[] directMap = {null, null, null};
/** spatial axis for Function domain */
private int domainAxis = -1;
/** dimension of direct manipulation
(including any Function domain) */
private int directManifoldDimension = 0;
/** spatial DisplayTupleType other than
DisplaySpatialCartesianTuple */
DisplayTupleType tuple;
/** possible values for whyNotDirect */
private final static String notRealFunction =
"FunctionType must be Real";
private final static String notSimpleField =
"not simple field";
private final static String notSimpleTuple =
"not simple tuple";
private final static String multipleMapping =
"RealType with multiple mappings";
private final static String multipleSpatialMapping =
"RealType with multiple spatial mappings";
private final static String nonSpatial =
"no spatial mapping";
private final static String viaReference =
"spatial mapping through Reference";
private final static String domainDimension =
"domain dimension must be 1";
private final static String domainNotSpatial =
"domain must be mapped to spatial";
private final static String rangeType =
"range must be RealType or RealTupleType";
private final static String rangeNotSpatial =
"range must be mapped to spatial";
private final static String domainSet =
"domain Set must be Gridded1DSet";
private final static String tooFewSpatial =
"Function without spatial domain";
private final static String functionTooFew =
"Function directManifoldDimension < 2";
private final static String badCoordSysManifoldDim =
"bad directManifoldDimension with spatial CoordinateSystem";
private final static String lostConnection =
"lost connection to Data server";
private boolean stop = false;
private int LastMouseModifiers = 0;
public synchronized void realCheckDirect()
throws VisADException, RemoteException {
setIsDirectManipulation(false);
DataDisplayLink[] Links = getLinks();
if (Links == null || Links.length == 0) {
link = null;
return;
}
link = Links[0];
ref = link.getDataReference();
shadow = link.getShadow().getAdaptedShadowType();
type = link.getType();
tuple = null;
if (type instanceof FunctionType) {
ShadowRealTupleType domain =
((ShadowFunctionType) shadow).getDomain();
ShadowType range =
((ShadowFunctionType) shadow).getRange();
tuple = domain.getDisplaySpatialTuple();
// there is some redundancy among these conditions
if (!((FunctionType) type).getReal()) {
whyNotDirect = notRealFunction;
return;
}
else if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_FIELD) {
whyNotDirect = notSimpleField;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if (domain.getDimension() != 1) {
whyNotDirect = domainDimension;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
whyNotDirect = domainNotSpatial;
return;
}
else if (domain.getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
DisplayTupleType rtuple = null;
if (range instanceof ShadowRealTupleType) {
rtuple = ((ShadowRealTupleType) range).getDisplaySpatialTuple();
}
else if (range instanceof ShadowRealType) {
rtuple = ((ShadowRealType) range).getDisplaySpatialTuple();
}
else {
whyNotDirect = rangeType;
return;
}
if (!tuple.equals(rtuple)) {
/* WLH 3 Aug 98
if (!Display.DisplaySpatialCartesianTuple.equals(rtuple)) {
*/
whyNotDirect = rangeNotSpatial;
return;
}
else if (range instanceof ShadowRealTupleType &&
((ShadowRealTupleType) range).getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
else {
Data data;
try {
data = link.getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, link);
removeLink(link);
link = null;
whyNotDirect = lostConnection;
return;
}
throw re;
}
if (!(data instanceof Field) ||
!(((Field) data).getDomainSet() instanceof Gridded1DSet))
{
whyNotDirect = domainSet;
return;
}
}
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension =
setDirectMap((ShadowRealType) domain.getComponent(0), -1, true);
if (range instanceof ShadowRealType) {
directManifoldDimension +=
setDirectMap((ShadowRealType) range, 0, false);
}
else if (range instanceof ShadowRealTupleType) {
ShadowRealTupleType r = (ShadowRealTupleType) range;
for (int i=0; i<r.getDimension(); i++) {
directManifoldDimension +=
setDirectMap((ShadowRealType) r.getComponent(i), i, false);
}
}
if (domainAxis == -1) {
whyNotDirect = tooFewSpatial;
return;
}
if (directManifoldDimension < 2) {
whyNotDirect = functionTooFew;
return;
}
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
/* WLH 3 Aug 98
if (domainAxis == -1) {
throw new DisplayException("DataRenderer.realCheckDirect:" +
"too few spatial domain");
}
if (directManifoldDimension < 2) {
throw new DisplayException("DataRenderer.realCheckDirect:" +
"directManifoldDimension < 2");
}
*/
}
else if (type instanceof RealTupleType) {
//
// TO_DO
// allow for any Flat ShadowTupleType
//
tuple = ((ShadowRealTupleType) shadow).getDisplaySpatialTuple();
if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) {
whyNotDirect = notSimpleTuple;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
/* WLH 3 Aug 98
else if (!Display.DisplaySpatialCartesianTuple.equals(
((ShadowRealTupleType) shadow).getDisplaySpatialTuple())) {
*/
whyNotDirect = nonSpatial;
return;
}
else if (((ShadowRealTupleType) shadow).getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
/* WLH 3 Aug 98
setIsDirectManipulation(true);
*/
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension = 0;
for (int i=0; i<((ShadowRealTupleType) shadow).getDimension(); i++) {
directManifoldDimension += setDirectMap((ShadowRealType)
((ShadowRealTupleType) shadow).getComponent(i), i, false);
}
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
}
else if (type instanceof RealType) {
tuple = ((ShadowRealType) shadow).getDisplaySpatialTuple();
if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) {
whyNotDirect = notSimpleTuple;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
/* WLH 3 Aug 98
else if(!Display.DisplaySpatialCartesianTuple.equals(
((ShadowRealType) shadow).getDisplaySpatialTuple())) {
*/
whyNotDirect = nonSpatial;
return;
}
/* WLH 3 Aug 98
setIsDirectManipulation(true);
*/
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension = setDirectMap((ShadowRealType) shadow, 0, false);
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
} // end else if (type instanceof RealType)
}
/** set directMap and axisToComponent (domain = false) or
domainAxis (domain = true) from real; called by realCheckDirect */
synchronized int setDirectMap(ShadowRealType real, int component, boolean domain) {
Enumeration maps = real.getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) ) {
int index = dreal.getTupleIndex();
if (domain) {
domainAxis = index;
}
else {
axisToComponent[index] = component;
}
directMap[index] = map;
return 1;
}
}
return 0;
}
private int getDirectManifoldDimension() {
return directManifoldDimension;
}
public String getWhyNotDirect() {
return whyNotDirect;
}
private int getAxisToComponent(int i) {
return axisToComponent[i];
}
private ScalarMap getDirectMap(int i) {
return directMap[i];
}
private int getDomainAxis() {
return domainAxis;
}
/** set spatialValues from ShadowType.doTransform */
public synchronized void setSpatialValues(float[][] spatial_values) {
// these are X, Y, Z values
spatialValues = spatial_values;
}
/** find minimum distance from ray to spatialValues */
public synchronized float checkClose(double[] origin, double[] direction) {
float distance = Float.MAX_VALUE;
lastIndex = -1;
if (spatialValues == null) return distance;
float o_x = (float) origin[0];
float o_y = (float) origin[1];
float o_z = (float) origin[2];
float d_x = (float) direction[0];
float d_y = (float) direction[1];
float d_z = (float) direction[2];
/*
System.out.println("origin = " + o_x + " " + o_y + " " + o_z);
System.out.println("direction = " + d_x + " " + d_y + " " + d_z);
*/
for (int i=0; i<spatialValues[0].length; i++) {
float x = spatialValues[0][i] - o_x;
float y = spatialValues[1][i] - o_y;
float z = spatialValues[2][i] - o_z;
float dot = x * d_x + y * d_y + z * d_z;
x = x - dot * d_x;
y = y - dot * d_y;
z = z - dot * d_z;
float d = (float) Math.sqrt(x * x + y * y + z * z);
if (d < distance) {
distance = d;
closeIndex = i;
offsetx = x;
offsety = y;
offsetz = z;
}
/*
System.out.println("spatialValues["+i+"] = " + spatialValues[0][i] + " " +
spatialValues[1][i] + " " + spatialValues[2][i] + " d = " + d);
*/
}
/*
System.out.println("checkClose: distance = " + distance);
*/
return distance;
}
/** mouse button released, ending direct manipulation */
public synchronized void release_direct() {
}
/** discontinue dragging this DataRenderer;
this method is not a general disable */
public void stop_direct() {
stop = true;
}
public int getLastMouseModifiers() {
return LastMouseModifiers;
}
public void setLastMouseModifiers(int mouseModifiers) {
LastMouseModifiers = mouseModifiers;
}
public synchronized void drag_direct(VisADRay ray, boolean first,
int mouseModifiers) {
// System.out.println("drag_direct " + first + " " + type);
if (spatialValues == null || ref == null || shadow == null ||
link == null) return;
if (first) {
stop = false;
}
else {
if (stop) return;
}
float o_x = (float) ray.position[0];
float o_y = (float) ray.position[1];
float o_z = (float) ray.position[2];
float d_x = (float) ray.vector[0];
float d_y = (float) ray.vector[1];
float d_z = (float) ray.vector[2];
if (first) {
offset_count = OFFSET_COUNT_INIT;
}
else {
if (offset_count > 0) offset_count--;
}
if (offset_count > 0) {
float mult = ((float) offset_count) / ((float) OFFSET_COUNT_INIT);
o_x += mult * offsetx;
o_y += mult * offsety;
o_z += mult * offsetz;
}
if (first) {
point_x = spatialValues[0][closeIndex];
point_y = spatialValues[1][closeIndex];
point_z = spatialValues[2][closeIndex];
int lineAxis = -1;
if (getDirectManifoldDimension() == 3) {
// coord sys ok
line_x = d_x;
line_y = d_y;
line_z = d_z;
}
else {
if (getDirectManifoldDimension() == 2) {
if (displayRenderer.getMode2D()) {
// coord sys ok
lineAxis = 2;
}
else {
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) < 0 && getDomainAxis() != i) {
lineAxis = i;
}
}
}
}
else if (getDirectManifoldDimension() == 1) {
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) >= 0) {
lineAxis = i;
}
}
}
line_x = (lineAxis == 0) ? 1.0f : 0.0f;
line_y = (lineAxis == 1) ? 1.0f : 0.0f;
line_z = (lineAxis == 2) ? 1.0f : 0.0f;
}
} // end if (first)
float[] x = new float[3]; // x marks the spot
if (getDirectManifoldDimension() == 1) {
// find closest point on line to ray
// logic from vis5d/cursor.c
// line o_, d_ to line point_, line_
float ld = d_x * line_x + d_y * line_y + d_z * line_z;
float od = o_x * d_x + o_y * d_y + o_z * d_z;
float pd = point_x * d_x + point_y * d_y + point_z * d_z;
float ol = o_x * line_x + o_y * line_y + o_z * line_z;
float pl = point_x * line_x + point_y * line_y + point_z * line_z;
if (ld * ld == 1.0f) return;
float t = ((pl - ol) - (ld * (pd - od))) / (ld * ld - 1.0f);
// x is closest point
x[0] = point_x + t * line_x;
x[1] = point_y + t * line_y;
x[2] = point_z + t * line_z;
}
else { // getDirectManifoldDimension() = 2 or 3
// intersect ray with plane
float dot = (point_x - o_x) * line_x +
(point_y - o_y) * line_y +
(point_z - o_z) * line_z;
float dot2 = d_x * line_x + d_y * line_y + d_z * line_z;
if (dot2 == 0.0) return;
dot = dot / dot2;
// x is intersection
x[0] = o_x + dot * d_x;
x[1] = o_y + dot * d_y;
x[2] = o_z + dot * d_z;
}
//
// TO_DO
// might estimate errors from pixel resolution on screen
//
try {
float[] xx = {x[0], x[1], x[2]};
if (tuple != null) {
float[][] cursor = {{x[0]}, {x[1]}, {x[2]}};
float[][] new_cursor =
tuple.getCoordinateSystem().fromReference(cursor);
x[0] = new_cursor[0][0];
x[1] = new_cursor[1][0];
x[2] = new_cursor[2][0];
}
Data newData = null;
Data data;
try {
data = link.getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, link);
removeLink(link);
link = null;
return;
}
throw re;
}
if (type instanceof RealType) {
addPoint(xx);
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
// RealType rtype = (RealType) data.getType();
RealType rtype = (RealType) type;
newData = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null);
// create location string
Vector vect = new Vector();
/* WLH 26 July 99
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
Real r = new Real(rtype, d[0]);
Unit overrideUnit = getDirectMap(i).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
getDisplayRenderer().setCursorStringVector(vect);
break;
}
}
ref.setData(newData);
link.clearData(); // WLH 27 July 99
}
else if (type instanceof RealTupleType) {
addPoint(xx);
int n = ((RealTuple) data).getDimension();
Real[] reals = new Real[n];
Vector vect = new Vector();
for (int i=0; i<3; i++) {
int j = getAxisToComponent(i);
if (j >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
Real c = (Real) ((RealTuple) data).getComponent(j);
RealType rtype = (RealType) c.getType();
reals[j] = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null);
// create location string
/* WLH 26 July 99
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
Real r = new Real(rtype, d[0]);
Unit overrideUnit = getDirectMap(i).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
}
}
getDisplayRenderer().setCursorStringVector(vect);
for (int j=0; j<n; j++) {
if (reals[j] == null) {
reals[j] = (Real) ((RealTuple) data).getComponent(j);
}
}
newData = new RealTuple((RealTupleType) type, reals,
((RealTuple) data).getCoordinateSystem());
ref.setData(newData);
link.clearData(); // WLH 27 July 99
}
else if (type instanceof FunctionType) {
Vector vect = new Vector();
if (first) lastIndex = -1;
int k = getDomainAxis();
f[0] = x[k];
d = getDirectMap(k).inverseScaleValues(f);
RealType rtype = (RealType) getDirectMap(k).getScalar();
// WLH 31 Aug 2000
// first, save value in default Unit
double dsave = d[0];
// WLH 4 Jan 99
// convert d from default Unit to actual domain Unit of data
Unit[] us = ((Field) data).getDomainUnits();
if (us != null && us[0] != null) {
d[0] = (float) us[0].toThis((double) d[0], rtype.getDefaultUnit());
}
// WLH 31 Aug 2000
Real r = new Real(rtype, dsave);
Unit overrideUnit = getDirectMap(k).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
dsave = overrideUnit.toThis(dsave, rtunit);
r = new Real(rtype, dsave, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
/*
// create location string
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// convert domain value to domain index
Gridded1DSet set = (Gridded1DSet) ((Field) data).getDomainSet();
value[0][0] = (float) d[0];
int[] indices = set.valueToIndex(value);
int thisIndex = indices[0];
if (thisIndex < 0) {
lastIndex = -1;
return;
}
if (lastIndex < 0) {
addPoint(xx);
}
else {
lastX[3] = xx[0];
lastX[4] = xx[1];
lastX[5] = xx[2];
addPoint(lastX);
}
lastX[0] = xx[0];
lastX[1] = xx[1];
lastX[2] = xx[2];
int n;
MathType range = ((FunctionType) type).getRange();
if (range instanceof RealType) {
n = 1;
}
else {
n = ((RealTupleType) range).getDimension();
}
double[] thisD = new double[n];
boolean[] directComponent = new boolean[n];
for (int j=0; j<n; j++) {
thisD[j] = Double.NaN;
directComponent[j] = false;
}
for (int i=0; i<3; i++) {
int j = getAxisToComponent(i);
if (j >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
// create location string
rtype = (RealType) getDirectMap(i).getScalar();
/* WLH 26 July 99
g = (float) d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
r = new Real(rtype, d[0]);
overrideUnit = getDirectMap(i).getOverrideUnit();
rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
thisD[j] = d[0];
directComponent[j] = true;
}
}
getDisplayRenderer().setCursorStringVector(vect);
if (lastIndex < 0) {
lastIndex = thisIndex;
lastD = new double[n];
for (int j=0; j<n; j++) {
lastD[j] = thisD[j];
}
}
Real[] reals = new Real[n];
int m = Math.abs(lastIndex - thisIndex) + 1;
indices = new int[m];
int index = thisIndex;
int inc = (lastIndex >= thisIndex) ? 1 : -1;
for (int i=0; i<m; i++) {
indices[i] = index;
index += inc;
}
float[][] values = set.indexToValue(indices);
double coefDiv = values[0][m-1] - values[0][0];
for (int i=0; i<m; i++) {
index = indices[i];
double coef = (i == 0 || coefDiv == 0.0) ? 0.0 :
(values[0][i] - values[0][0]) / coefDiv;
Data tuple = ((Field) data).getSample(index);
if (tuple instanceof Real) {
if (directComponent[0]) {
rtype = (RealType) tuple.getType();
tuple = new Real(rtype, thisD[0] + coef * (lastD[0] - thisD[0]),
rtype.getDefaultUnit(), null);
}
}
else {
for (int j=0; j<n; j++) {
Real c = (Real) ((RealTuple) tuple).getComponent(j);
if (directComponent[j]) {
rtype = (RealType) c.getType();
reals[j] = new Real(rtype, thisD[j] + coef * (lastD[j] - thisD[j]),
rtype.getDefaultUnit(), null);
}
else {
reals[j] = c;
}
}
tuple = new RealTuple(reals);
}
((Field) data).setSample(index, tuple);
} // end for (int i=0; i<m; i++)
if (ref instanceof RemoteDataReference &&
!(data instanceof RemoteData)) {
// ref is Remote and data is local, so we have only modified
// a local copy and must send it back to ref
ref.setData(data);
link.clearData(); // WLH 27 July 99
}
// set last index to this, and component values
lastIndex = thisIndex;
for (int j=0; j<n; j++) {
lastD[j] = thisD[j];
}
} // end else if (type instanceof FunctionType)
} // end try
catch (VisADException e) {
// do nothing
System.out.println("drag_direct " + e);
e.printStackTrace();
}
catch (RemoteException e) {
// do nothing
System.out.println("drag_direct " + e);
e.printStackTrace();
}
}
public void addPoint(float[] x) throws VisADException {
}
/** flag indicating whether DirectManipulationRenderer is valid
for this ShadowType */
private boolean isDirectManipulation;
/** set isDirectManipulation = true if this DataRenderer
supports direct manipulation for its linked Data */
public void checkDirect() throws VisADException, RemoteException {
isDirectManipulation = false;
}
public void setIsDirectManipulation(boolean b) {
isDirectManipulation = b;
}
public boolean getIsDirectManipulation() {
return isDirectManipulation;
}
private float ray_pos; // save last ray_pos as first guess for next
private static final int HALF_GUESSES = 200;
private static final int GUESSES = 2 * HALF_GUESSES + 1;
private static final float RAY_POS_INC = 0.1f;
private static final int TRYS = 10;
private static final double EPS = 0.001f;
public float findRayManifoldIntersection(boolean first, double[] origin,
double[] direction, DisplayTupleType tuple,
int otherindex, float othervalue)
throws VisADException {
ray_pos = Float.NaN;
if (otherindex < 0) return ray_pos;
CoordinateSystem tuplecs = null;
if (tuple != null) tuplecs = tuple.getCoordinateSystem();
if (tuple == null || tuplecs == null) {
ray_pos = (float)
((othervalue - origin[otherindex]) / direction[otherindex]);
}
else { // tuple != null
double adjust = Double.NaN;
if (Display.DisplaySpatialSphericalTuple.equals(tuple)) {
if (otherindex == 1) adjust = 360.0;
}
if (first) {
// generate a first guess ray_pos by brute force
ray_pos = Float.NaN;
float[][] guesses = new float[3][GUESSES];
for (int i=0; i<GUESSES; i++) {
float rp = (i - HALF_GUESSES) * RAY_POS_INC;
guesses[0][i] = (float) (origin[0] + rp * direction[0]);
guesses[1][i] = (float) (origin[1] + rp * direction[1]);
guesses[2][i] = (float) (origin[2] + rp * direction[2]);
if (adjust == adjust) {
guesses[otherindex][i] = (float)
(((othervalue + 0.5 * adjust + guesses[otherindex][i]) % adjust) -
(othervalue + 0.5 * adjust));
}
}
guesses = tuplecs.fromReference(guesses);
double distance = Double.MAX_VALUE;
float lastg = 0.0f;
for (int i=0; i<GUESSES; i++) {
float g = othervalue - guesses[otherindex][i];
// first, look for nearest zero crossing and interpolate
if (i > 0 && ((g < 0.0f && lastg >= 0.0f) || (g >= 0.0f && lastg < 0.0f))) {
float r = (float)
(i - (Math.abs(g) / (Math.abs(lastg) + Math.abs(g))));
ray_pos = (r - HALF_GUESSES) * RAY_POS_INC;
break;
}
lastg = g;
// otherwise look for closest to zero
double d = Math.abs(othervalue - guesses[otherindex][i]);
if (d < distance) {
distance = d;
ray_pos = (i - HALF_GUESSES) * RAY_POS_INC;
}
} // end for (int i=0; i<GUESSES; i++)
}
if (ray_pos == ray_pos) {
// use Newton's method to refine first guess
// double error_limit = 10.0 * EPS;
double error_limit = EPS;
double r = ray_pos;
double error = 1.0f;
double[][] guesses = new double[3][3];
int itry;
// System.out.println("\nothervalue = " + (float) othervalue + " r = " + (float) r);
for (itry=0; (itry<TRYS && r == r); itry++) {
double rp = r + EPS;
double rm = r - EPS;
guesses[0][0] = origin[0] + rp * direction[0];
guesses[1][0] = origin[1] + rp * direction[1];
guesses[2][0] = origin[2] + rp * direction[2];
guesses[0][1] = origin[0] + r * direction[0];
guesses[1][1] = origin[1] + r * direction[1];
guesses[2][1] = origin[2] + r * direction[2];
guesses[0][2] = origin[0] + rm * direction[0];
guesses[1][2] = origin[1] + rm * direction[1];
guesses[2][2] = origin[2] + rm * direction[2];
// System.out.println(" guesses = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
guesses = tuplecs.fromReference(guesses);
// System.out.println(" transformed = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
if (adjust == adjust) {
guesses[otherindex][0] =
((othervalue + 0.5 * adjust + guesses[otherindex][0]) % adjust) -
(othervalue + 0.5 * adjust);
guesses[otherindex][1] =
((othervalue + 0.5 * adjust + guesses[otherindex][1]) % adjust) -
(othervalue + 0.5 * adjust);
guesses[otherindex][2] =
((othervalue + 0.5 * adjust + guesses[otherindex][2]) % adjust) -
(othervalue + 0.5 * adjust);
}
// System.out.println(" adjusted = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
double g = othervalue - guesses[otherindex][1];
error = Math.abs(g);
if (error <= EPS) break;
double gp = othervalue - guesses[otherindex][0];
double gm = othervalue - guesses[otherindex][2];
double dg = (gp - gm) / (EPS + EPS);
// System.out.println("r = " + (float) r + " g = " + (float) g + " gm = " +
// (float) gm + " gp = " + (float) gp + " dg = " + (float) dg);
r = r - g / dg;
}
if (error < error_limit) {
ray_pos = (float) r;
}
else {
// System.out.println("error = " + error + " itry = " + itry);
ray_pos = Float.NaN;
}
}
} // end (tuple != null)
return ray_pos;
}
/**
* <b>WARNING!</b>
* Do <b>NOT</b> use this routine unless you know what you are doing!
*/
public void removeLink(DataDisplayLink link)
{
final int newLen = Links.length - 1;
if (newLen < 0) {
// give up if the Links array is already empty
return;
}
DataDisplayLink[] newLinks = new DataDisplayLink[newLen];
int n = 0;
for (int i = 0; i <= newLen; i++) {
if (Links[i] == link) {
// skip the specified link
} else {
if (n == newLen) {
// yikes! Obviously didn't find this link in the list!
return;
}
newLinks[n++] = Links[i];
}
}
if (n < newLen) {
// Hmmm ... seem to have removed multiple instances of 'link'!
DataDisplayLink[] newest = new DataDisplayLink[n];
System.arraycopy(newLinks, 0, newest, 0, n);
newLinks = newest;
}
Links = newLinks;
}
}
| false | true | public boolean isTransformControl(Control control, DataDisplayLink link) {
if (control instanceof ProjectionControl ||
control instanceof ToggleControl) {
return false;
}
/* WLH 1 Nov 97 - temporary hack -
RangeControl changes always require Transform
ValueControl and AnimationControl never do
if (control instanceof AnimationControl ||
control instanceof ValueControl ||
control instanceof RangeControl) {
return link.isTransform[control.getIndex()];
*/
if (control instanceof AnimationControl ||
control instanceof ValueControl) {
return false;
}
return true;
}
/** used for transform time-out hack */
public DataDisplayLink getLink() {
return null;
}
public boolean isLegalTextureMap() {
return true;
}
/* ********************** */
/* flow rendering stuff */
/* ********************** */
// value array (display_values) indices
// ((ScalarMap) MapVector.elementAt(valueToMap[index]))
// can get these indices through shadow_data_out or shadow_data_in
// true if lat and lon in data_in & shadow_data_in is allSpatial
// or if lat and lon in data_in & lat_lon_in_by_coord
boolean lat_lon_in = false;
// true if lat_lon_in and shadow_data_out is allSpatial
// i.e., map from lat, lon to display is through data CoordinateSystem
boolean lat_lon_in_by_coord = false;
// true if lat and lon in data_out & shadow_data_out is allSpatial
boolean lat_lon_out = false;
// true if lat_lon_out and shadow_data_in is allSpatial
// i.e., map from lat, lon to display is inverse via data CoordinateSystem
boolean lat_lon_out_by_coord = false;
int lat_lon_dimension = -1;
ShadowRealTupleType shadow_data_out = null;
RealTupleType data_out = null;
Unit[] data_units_out = null;
// CoordinateSystem data_coord_out is always null
ShadowRealTupleType shadow_data_in = null;
RealTupleType data_in = null;
Unit[] data_units_in = null;
CoordinateSystem[] data_coord_in = null; // may be one per point
// spatial ScalarMaps for allSpatial shadow_data_out
ScalarMap[] sdo_maps = null;
// spatial ScalarMaps for allSpatial shadow_data_in
ScalarMap[] sdi_maps = null;
int[] sdo_spatial_index = null;
int[] sdi_spatial_index = null;
// indices of RealType.Latitude and RealType.Longitude
// if lat_lon_in then indices in data_in
// if lat_lon_out then indices in data_out
// if lat_lon_spatial then values indices
int lat_index = -1;
int lon_index = -1;
// non-negative if lat & lon in a RealTupleType of length 3
int other_index = -1;
// true if other_index Units convertable to meter
boolean other_meters = false;
// from doTransform
RealVectorType[] rvts = {null, null};
public RealVectorType getRealVectorTypes(int index) {
if (index == 0 || index == 1) return rvts[index];
else return null;
}
public int[] getLatLonIndices() {
return new int[] {lat_index, lon_index};
}
public void setLatLonIndices(int[] indices) {
lat_index = indices[0];
lon_index = indices[1];
}
public int getEarthDimension() {
return lat_lon_dimension;
}
public Unit[] getEarthUnits() {
Unit[] units = null;
if (lat_lon_in) {
units = data_units_in;
}
else if (lat_lon_out) {
units = data_units_out;
}
else if (lat_lon_spatial) {
units = new Unit[] {RealType.Latitude.getDefaultUnit(),
RealType.Longitude.getDefaultUnit()};
}
else {
units = null;
}
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (units == null) {
return null;
}
else if (units.length == 2) {
return new Unit[] {lat >= 0 ? units[lat] : null,
lon >= 0 ? units[lon] : null};
}
else if (units.length == 3) {
return new Unit[] {lat >= 0 ? units[lat] : null,
lon >= 0 ? units[lon] : null,
other >= 0 ? units[other] : null};
}
else {
return null;
}
}
public float getLatLonRange() {
double[] rlat = null;
double[] rlon = null;
int lat = lat_index;
int lon = lon_index;
if ((lat_lon_out && !lat_lon_out_by_coord) ||
(lat_lon_in && lat_lon_in_by_coord)) {
rlat = lat >= 0 ? sdo_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN};
rlon = lon >= 0 ? sdo_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN};
}
else if ((lat_lon_in && !lat_lon_in_by_coord) ||
(lat_lon_out && lat_lon_out_by_coord)) {
rlat = lat >= 0 ? sdi_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN};
rlon = lon >= 0 ? sdi_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN};
}
else if (lat_lon_spatial) {
rlat = lat_map.getRange();
rlon = lon_map.getRange();
}
else {
return 1.0f;
}
double dlat = Math.abs(rlat[1] - rlat[0]);
double dlon = Math.abs(rlon[1] - rlon[0]);
if (dlat != dlat) dlat = 1.0f;
if (dlon != dlon) dlon = 1.0f;
return (dlat > dlon) ? (float) dlat : (float) dlon;
}
/** convert (lat, lon) or (lat, lon, other) values to
display (x, y, z) */
public float[][] earthToSpatial(float[][] locs, float[] vert)
throws VisADException {
return earthToSpatial(locs, vert, null);
}
public float[][] earthToSpatial(float[][] locs, float[] vert,
float[][] base_spatial_locs)
throws VisADException {
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (lat_index < 0 || lon_index < 0) return null;
int size = locs[0].length;
if (locs.length < lat_lon_dimension) {
// extend locs to lat_lon_dimension with zero fill
float[][] temp = locs;
locs = new float[lat_lon_dimension][];
for (int i=0; i<locs.length; i++) {
locs[i] = temp[i];
}
float[] zero = new float[size];
for (int j=0; j<size; j++) zero[j] = 0.0f;
for (int i=locs.length; i<lat_lon_dimension; i++) {
locs[i] = zero;
}
}
else if (locs.length > lat_lon_dimension) {
// truncate locs to lat_lon_dimension
float[][] temp = locs;
locs = new float[lat_lon_dimension][];
for (int i=0; i<lat_lon_dimension; i++) {
locs[i] = temp[i];
}
}
// permute (lat, lon, other) to data RealTupleType
float[][] tuple_locs = new float[lat_lon_dimension][];
float[][] spatial_locs = new float[3][];
tuple_locs[lat] = locs[0];
tuple_locs[lon] = locs[1];
if (lat_lon_dimension == 3) tuple_locs[other] = locs[2];
int vert_index = -1; // non-lat/lon index for lat_lon_dimension = 2
if (lat_lon_in) {
if (lat_lon_in_by_coord) {
// transform 'RealTupleType data_in' to 'RealTupleType data_out'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[0],
data_units_in, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[j],
data_units_in, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
// map data_out to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdo_spatial_index[i]] =
sdo_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]);
}
}
else {
// map data_in to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdi_spatial_index[i]] =
sdi_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]);
}
}
}
else if (lat_lon_out) {
if (lat_lon_out_by_coord) {
// transform 'RealTupleType data_out' to 'RealTupleType data_in'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[0], data_units_in, null, data_out,
null, data_units_out, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[j], data_units_in, null, data_out,
null, data_units_out, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
// map data_in to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdi_spatial_index[i]] =
sdi_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]);
}
}
else {
// map data_out to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdo_spatial_index[i]] =
sdo_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]);
}
}
}
else if (lat_lon_spatial) {
// map lat & lon, not in allSpatial RealTupleType, to
// spatial DisplayRealTypes
spatial_locs[lat_spatial_index] =
lat_map.scaleValues(tuple_locs[lat]);
spatial_locs[lon_spatial_index] =
lon_map.scaleValues(tuple_locs[lon]);
vert_index = 3 - (lat_spatial_index + lon_spatial_index);
}
else {
// should never happen
return null;
}
// WLH 9 Dec 99
// fill any empty spatial DisplayRealTypes with default values
for (int i=0; i<3; i++) {
if (spatial_locs[i] == null) {
if (base_spatial_locs != null && base_spatial_locs[i] != null) {
spatial_locs[i] = base_spatial_locs[i]; // copy not necessary
}
else {
spatial_locs[i] = new float[size];
float def = default_spatial_in[i]; // may be non-Cartesian
for (int j=0; j<size; j++) spatial_locs[i][j] = def;
}
}
}
// adjust non-lat/lon spatial_locs by vertical flow component
/* WLH 28 July 99
if (vert != null && vert_index > -1) {
for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j];
}
*/
if (vert != null && vert_index > -1 && spatial_locs[vert_index] != null) {
for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j];
}
if (display_coordinate_system != null) {
// transform non-Cartesian spatial DisplayRealTypes to Cartesian
if (spatial_locs != null && spatial_locs.length > 0 &&
spatial_locs[0] != null && spatial_locs[0].length > 0) {
spatial_locs = display_coordinate_system.toReference(spatial_locs);
}
}
return spatial_locs;
}
/** convert display (x, y, z) to (lat, lon) or (lat, lon, other)
values */
public float[][] spatialToEarth(float[][] spatial_locs)
throws VisADException {
float[][] base_spatial_locs = new float[3][];
return spatialToEarth(spatial_locs, base_spatial_locs);
}
public float[][] spatialToEarth(float[][] spatial_locs,
float[][] base_spatial_locs)
throws VisADException {
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (lat_index < 0 || lon_index < 0) return null;
if (spatial_locs.length != 3) return null;
int size = 0;
for (int i=0; i<3; i++) {
if (spatial_locs[i] != null && spatial_locs[i].length > size) {
size = spatial_locs[i].length;
}
}
if (size == 0) return null;
// fill any empty spatial DisplayRealTypes with default values
for (int i=0; i<3; i++) {
if (spatial_locs[i] == null) {
spatial_locs[i] = new float[size];
// defaults for Cartesian spatial DisplayRealTypes = 0.0f
for (int j=0; j<size; j++) spatial_locs[i][j] = 0.0f;
}
}
if (display_coordinate_system != null) {
// transform Cartesian spatial DisplayRealTypes to non-Cartesian
spatial_locs = display_coordinate_system.fromReference(spatial_locs);
}
base_spatial_locs[0] = spatial_locs[0];
base_spatial_locs[1] = spatial_locs[1];
base_spatial_locs[2] = spatial_locs[2];
float[][] tuple_locs = new float[lat_lon_dimension][];
if (lat_lon_in) {
if (lat_lon_in_by_coord) {
// map spatial DisplayRealTypes to data_out
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]);
}
// transform 'RealTupleType data_out' to 'RealTupleType data_in'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[0], data_units_in, null, data_out,
null, data_units_out, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[j], data_units_in, null, data_out,
null, data_units_out, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
}
else {
// map spatial DisplayRealTypes to data_in
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]);
}
}
}
else if (lat_lon_out) {
if (lat_lon_out_by_coord) {
// map spatial DisplayRealTypes to data_in
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]);
}
// transform 'RealTupleType data_in' to 'RealTupleType data_out'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[0],
data_units_in, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[j],
data_units_in, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
}
else {
// map spatial DisplayRealTypes to data_out
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]);
}
}
}
else if (lat_lon_spatial) {
// map spatial DisplayRealTypes to lat & lon, not in
// allSpatial RealTupleType
tuple_locs[lat] =
lat_map.inverseScaleValues(spatial_locs[lat_spatial_index]);
tuple_locs[lon] =
lon_map.inverseScaleValues(spatial_locs[lon_spatial_index]);
}
else {
// should never happen
return null;
}
// permute data RealTupleType to (lat, lon, other)
float[][] locs = new float[lat_lon_dimension][];
locs[0] = tuple_locs[lat];
locs[1] = tuple_locs[lon];
if (lat_lon_dimension == 3) locs[2] = tuple_locs[other];
return locs;
}
// information from doTransform
public void setEarthSpatialData(ShadowRealTupleType s_d_i,
ShadowRealTupleType s_d_o, RealTupleType d_o,
Unit[] d_u_o, RealTupleType d_i,
CoordinateSystem[] d_c_i, Unit[] d_u_i)
throws VisADException {
// first check for VectorRealType components mapped to flow
// TO_DO: check here for flow mapped via CoordinateSystem
if (d_o != null && d_o instanceof RealVectorType) {
ScalarMap[] maps = new ScalarMap[3];
int k = getFlowMaps(s_d_o, maps);
if (k > -1) rvts[k] = (RealVectorType) d_o;
}
if (d_i != null && d_i instanceof RealVectorType) {
ScalarMap[] maps = new ScalarMap[3];
int k = getFlowMaps(s_d_i, maps);
if (k > -1) rvts[k] = (RealVectorType) d_i;
}
int lat_index_local = -1;
int lon_index_local = -1;
other_index = -1;
int n = 0;
int m = 0;
if (d_i != null) {
n = d_i.getDimension();
for (int i=0; i<n; i++) {
RealType real = (RealType) d_i.getComponent(i);
if (RealType.Latitude.equals(real)) lat_index_local = i;
if (RealType.Longitude.equals(real)) lon_index_local = i;
}
}
if (lat_index_local > -1 && lon_index_local > -1 && (n == 2 || n == 3)) {
if (s_d_i != null && s_d_i.getAllSpatial() &&
!s_d_i.getSpatialReference()) {
lat_lon_in_by_coord = false;
sdi_spatial_index = new int[s_d_i.getDimension()];
sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index);
if (sdi_maps == null) {
throw new DisplayException("sdi_maps null A");
}
}
else if (s_d_o != null && s_d_o.getAllSpatial() &&
!s_d_o.getSpatialReference()) {
lat_lon_in_by_coord = true;
sdo_spatial_index = new int[s_d_o.getDimension()];
sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index);
if (sdo_maps == null) {
throw new DisplayException("sdo_maps null A");
}
}
else {
// do not update lat_index & lon_index
return;
}
lat_lon_in = true;
lat_lon_out = false;
lat_lon_out_by_coord = false;
lat_lon_spatial = false;
lat_lon_dimension = n;
if (n == 3) {
other_index = 3 - (lat_index_local + lon_index_local);
if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) {
other_meters = true;
}
}
}
else { // if( !(lat & lon in di, di dimension = 2 or 3) )
lat_index_local = -1;
lon_index_local = -1;
if (d_o != null) {
m = d_o.getDimension();
for (int i=0; i<m; i++) {
RealType real = (RealType) d_o.getComponent(i);
if (RealType.Latitude.equals(real)) lat_index_local = i;
if (RealType.Longitude.equals(real)) lon_index_local = i;
}
}
if (lat_index_local < 0 || lon_index_local < 0 || !(m == 2 || m == 3)) {
// do not update lat_index & lon_index
return;
}
if (s_d_o != null && s_d_o.getAllSpatial() &&
!s_d_o.getSpatialReference()) {
lat_lon_out_by_coord = false;
sdo_spatial_index = new int[s_d_o.getDimension()];
sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index);
if (sdo_maps == null) {
throw new DisplayException("sdo_maps null B");
}
}
else if (s_d_i != null && s_d_i.getAllSpatial() &&
!s_d_i.getSpatialReference()) {
lat_lon_out_by_coord = true;
sdi_spatial_index = new int[s_d_i.getDimension()];
sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index);
if (sdi_maps == null) {
throw new DisplayException("sdi_maps null B");
}
}
else {
// do not update lat_index & lon_index
return;
}
lat_lon_out = true;
lat_lon_in = false;
lat_lon_in_by_coord = false;
lat_lon_spatial = false;
lat_lon_dimension = m;
if (m == 3) {
other_index = 3 - (lat_index_local + lon_index_local);
if (Unit.canConvert(d_u_i[other_index], CommonUnit.meter)) {
other_meters = true;
}
}
}
shadow_data_out = s_d_o;
data_out = d_o;
data_units_out = d_u_o;
shadow_data_in = s_d_i;
data_in = d_i;
data_units_in = d_u_i;
data_coord_in = d_c_i; // may be one per point
lat_index = lat_index_local;
lon_index = lon_index_local;
return;
}
/** return array of spatial ScalarMap for srt, or null */
private ScalarMap[] getSpatialMaps(ShadowRealTupleType srt,
int[] spatial_index) {
int n = srt.getDimension();
ScalarMap[] maps = new ScalarMap[n];
for (int i=0; i<n; i++) {
ShadowRealType real = (ShadowRealType) srt.getComponent(i);
Enumeration ms = real.getSelectedMapVector().elements();
while (ms.hasMoreElements()) {
ScalarMap map = (ScalarMap) ms.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) {
maps[i] = map;
spatial_index[i] = dreal.getTupleIndex();
break;
}
}
if (maps[i] == null) {
return null;
}
}
return maps;
}
/** return array of flow ScalarMap for srt, or null */
private int getFlowMaps(ShadowRealTupleType srt, ScalarMap[] maps) {
int n = srt.getDimension();
maps[0] = null;
maps[1] = null;
maps[2] = null;
DisplayTupleType ftuple = null;
for (int i=0; i<n; i++) {
ShadowRealType real = (ShadowRealType) srt.getComponent(i);
Enumeration ms = real.getSelectedMapVector().elements();
while (ms.hasMoreElements()) {
ScalarMap map = (ScalarMap) ms.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (Display.DisplayFlow1Tuple.equals(tuple) ||
Display.DisplayFlow2Tuple.equals(tuple)) {
if (ftuple != null && !ftuple.equals(tuple)) return -1;
ftuple = tuple;
maps[i] = map;
break;
}
}
if (maps[i] == null) return -1;
}
return Display.DisplayFlow1Tuple.equals(ftuple) ? 0 : 1;
}
/* WLH 15 April 2000
// from assembleFlow
ScalarMap[][] flow_maps = null;
float[] flow_scale = null;
public void setFlowDisplay(ScalarMap[][] maps, float[] fs) {
flow_maps = maps;
flow_scale = fs;
}
*/
// if non-null, float[][] new_spatial_values =
// display_coordinate_system.toReference(spatial_values);
CoordinateSystem display_coordinate_system = null;
// spatial_tuple and spatial_value_indices are set whether
// display_coordinate_system is null or not
DisplayTupleType spatial_tuple = null;
// map from spatial_tuple tuple_index to value array indices
int[] spatial_value_indices = {-1, -1, -1};
float[] default_spatial_in = {0.0f, 0.0f, 0.0f};
// true if lat and lon mapped directly to spatial
boolean lat_lon_spatial = false;
ScalarMap lat_map = null;
ScalarMap lon_map = null;
int lat_spatial_index = -1;
int lon_spatial_index = -1;
// spatial map getRange() results for flow adjustment
double[] ranges = null;
public double[] getRanges() {
return ranges;
}
// WLH 4 March 2000
public CoordinateSystem getDisplayCoordinateSystem() {
return display_coordinate_system ;
}
// information from assembleSpatial
public void setEarthSpatialDisplay(CoordinateSystem coord,
DisplayTupleType t, DisplayImpl display, int[] indices,
float[] default_values, double[] r)
throws VisADException {
display_coordinate_system = coord;
spatial_tuple = t;
System.arraycopy(indices, 0, spatial_value_indices, 0, 3);
/* WLH 5 Dec 99
spatial_value_indices = indices;
*/
ranges = r;
for (int i=0; i<3; i++) {
int default_index = display.getDisplayScalarIndex(
((DisplayRealType) t.getComponent(i)) );
default_spatial_in[i] = default_values[default_index];
}
if (lat_index > -1 && lon_index > -1) return;
lat_index = -1;
lon_index = -1;
other_index = -1;
int valueArrayLength = display.getValueArrayLength();
int[] valueToScalar = display.getValueToScalar();
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) {
if (RealType.Latitude.equals(real)) {
lat_index = 0;
lat_map = map;
lat_spatial_index = dreal.getTupleIndex();
}
if (RealType.Longitude.equals(real)) {
lon_index = 1;
lon_map = map;
lon_spatial_index = dreal.getTupleIndex();
}
}
}
if (lat_index > -1 && lon_index > -1) {
lat_lon_spatial = true;
lat_lon_dimension = 2;
lat_lon_out = false;
lat_lon_in_by_coord = false;
lat_lon_in = false;
}
else {
lat_lon_spatial = false;
lat_index = -1;
lon_index = -1;
}
}
/* *************************** */
/* direct manipulation stuff */
/* *************************** */
private float[][] spatialValues = null;
/** if Function, last domain index and range values */
private int lastIndex = -1;
double[] lastD = null;
float[] lastX = new float[6];
/** index into spatialValues found by checkClose */
private int closeIndex = -1;
/** pick error offset, communicated from checkClose() to drag_direct() */
private float offsetx = 0.0f, offsety = 0.0f, offsetz = 0.0f;
/** count down to decay offset to 0.0 */
private int offset_count = 0;
/** initial offset_count */
private static final int OFFSET_COUNT_INIT = 30;
/** for use in drag_direct */
private transient DataDisplayLink link = null;
// private transient ShadowTypeJ3D type = null;
private transient DataReference ref = null;
private transient MathType type = null;
private transient ShadowType shadow = null;
/** point on direct manifold line or plane */
private float point_x, point_y, point_z;
/** normalized direction of line or perpendicular to plane */
private float line_x, line_y, line_z;
/** arrays of length one for inverseScaleValues */
private float[] f = new float[1];
private float[] d = new float[1];
private float[][] value = new float[1][1];
/** information calculated by checkDirect */
/** explanation for invalid use of DirectManipulationRenderer */
private String whyNotDirect = null;
/** mapping from spatial axes to tuple component */
private int[] axisToComponent = {-1, -1, -1};
/** mapping from spatial axes to ScalarMaps */
private ScalarMap[] directMap = {null, null, null};
/** spatial axis for Function domain */
private int domainAxis = -1;
/** dimension of direct manipulation
(including any Function domain) */
private int directManifoldDimension = 0;
/** spatial DisplayTupleType other than
DisplaySpatialCartesianTuple */
DisplayTupleType tuple;
/** possible values for whyNotDirect */
private final static String notRealFunction =
"FunctionType must be Real";
private final static String notSimpleField =
"not simple field";
private final static String notSimpleTuple =
"not simple tuple";
private final static String multipleMapping =
"RealType with multiple mappings";
private final static String multipleSpatialMapping =
"RealType with multiple spatial mappings";
private final static String nonSpatial =
"no spatial mapping";
private final static String viaReference =
"spatial mapping through Reference";
private final static String domainDimension =
"domain dimension must be 1";
private final static String domainNotSpatial =
"domain must be mapped to spatial";
private final static String rangeType =
"range must be RealType or RealTupleType";
private final static String rangeNotSpatial =
"range must be mapped to spatial";
private final static String domainSet =
"domain Set must be Gridded1DSet";
private final static String tooFewSpatial =
"Function without spatial domain";
private final static String functionTooFew =
"Function directManifoldDimension < 2";
private final static String badCoordSysManifoldDim =
"bad directManifoldDimension with spatial CoordinateSystem";
private final static String lostConnection =
"lost connection to Data server";
private boolean stop = false;
private int LastMouseModifiers = 0;
public synchronized void realCheckDirect()
throws VisADException, RemoteException {
setIsDirectManipulation(false);
DataDisplayLink[] Links = getLinks();
if (Links == null || Links.length == 0) {
link = null;
return;
}
link = Links[0];
ref = link.getDataReference();
shadow = link.getShadow().getAdaptedShadowType();
type = link.getType();
tuple = null;
if (type instanceof FunctionType) {
ShadowRealTupleType domain =
((ShadowFunctionType) shadow).getDomain();
ShadowType range =
((ShadowFunctionType) shadow).getRange();
tuple = domain.getDisplaySpatialTuple();
// there is some redundancy among these conditions
if (!((FunctionType) type).getReal()) {
whyNotDirect = notRealFunction;
return;
}
else if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_FIELD) {
whyNotDirect = notSimpleField;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if (domain.getDimension() != 1) {
whyNotDirect = domainDimension;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
whyNotDirect = domainNotSpatial;
return;
}
else if (domain.getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
DisplayTupleType rtuple = null;
if (range instanceof ShadowRealTupleType) {
rtuple = ((ShadowRealTupleType) range).getDisplaySpatialTuple();
}
else if (range instanceof ShadowRealType) {
rtuple = ((ShadowRealType) range).getDisplaySpatialTuple();
}
else {
whyNotDirect = rangeType;
return;
}
if (!tuple.equals(rtuple)) {
/* WLH 3 Aug 98
if (!Display.DisplaySpatialCartesianTuple.equals(rtuple)) {
*/
whyNotDirect = rangeNotSpatial;
return;
}
else if (range instanceof ShadowRealTupleType &&
((ShadowRealTupleType) range).getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
else {
Data data;
try {
data = link.getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, link);
removeLink(link);
link = null;
whyNotDirect = lostConnection;
return;
}
throw re;
}
if (!(data instanceof Field) ||
!(((Field) data).getDomainSet() instanceof Gridded1DSet))
{
whyNotDirect = domainSet;
return;
}
}
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension =
setDirectMap((ShadowRealType) domain.getComponent(0), -1, true);
if (range instanceof ShadowRealType) {
directManifoldDimension +=
setDirectMap((ShadowRealType) range, 0, false);
}
else if (range instanceof ShadowRealTupleType) {
ShadowRealTupleType r = (ShadowRealTupleType) range;
for (int i=0; i<r.getDimension(); i++) {
directManifoldDimension +=
setDirectMap((ShadowRealType) r.getComponent(i), i, false);
}
}
if (domainAxis == -1) {
whyNotDirect = tooFewSpatial;
return;
}
if (directManifoldDimension < 2) {
whyNotDirect = functionTooFew;
return;
}
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
/* WLH 3 Aug 98
if (domainAxis == -1) {
throw new DisplayException("DataRenderer.realCheckDirect:" +
"too few spatial domain");
}
if (directManifoldDimension < 2) {
throw new DisplayException("DataRenderer.realCheckDirect:" +
"directManifoldDimension < 2");
}
*/
}
else if (type instanceof RealTupleType) {
//
// TO_DO
// allow for any Flat ShadowTupleType
//
tuple = ((ShadowRealTupleType) shadow).getDisplaySpatialTuple();
if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) {
whyNotDirect = notSimpleTuple;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
/* WLH 3 Aug 98
else if (!Display.DisplaySpatialCartesianTuple.equals(
((ShadowRealTupleType) shadow).getDisplaySpatialTuple())) {
*/
whyNotDirect = nonSpatial;
return;
}
else if (((ShadowRealTupleType) shadow).getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
/* WLH 3 Aug 98
setIsDirectManipulation(true);
*/
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension = 0;
for (int i=0; i<((ShadowRealTupleType) shadow).getDimension(); i++) {
directManifoldDimension += setDirectMap((ShadowRealType)
((ShadowRealTupleType) shadow).getComponent(i), i, false);
}
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
}
else if (type instanceof RealType) {
tuple = ((ShadowRealType) shadow).getDisplaySpatialTuple();
if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) {
whyNotDirect = notSimpleTuple;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
/* WLH 3 Aug 98
else if(!Display.DisplaySpatialCartesianTuple.equals(
((ShadowRealType) shadow).getDisplaySpatialTuple())) {
*/
whyNotDirect = nonSpatial;
return;
}
/* WLH 3 Aug 98
setIsDirectManipulation(true);
*/
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension = setDirectMap((ShadowRealType) shadow, 0, false);
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
} // end else if (type instanceof RealType)
}
/** set directMap and axisToComponent (domain = false) or
domainAxis (domain = true) from real; called by realCheckDirect */
synchronized int setDirectMap(ShadowRealType real, int component, boolean domain) {
Enumeration maps = real.getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) ) {
int index = dreal.getTupleIndex();
if (domain) {
domainAxis = index;
}
else {
axisToComponent[index] = component;
}
directMap[index] = map;
return 1;
}
}
return 0;
}
private int getDirectManifoldDimension() {
return directManifoldDimension;
}
public String getWhyNotDirect() {
return whyNotDirect;
}
private int getAxisToComponent(int i) {
return axisToComponent[i];
}
private ScalarMap getDirectMap(int i) {
return directMap[i];
}
private int getDomainAxis() {
return domainAxis;
}
/** set spatialValues from ShadowType.doTransform */
public synchronized void setSpatialValues(float[][] spatial_values) {
// these are X, Y, Z values
spatialValues = spatial_values;
}
/** find minimum distance from ray to spatialValues */
public synchronized float checkClose(double[] origin, double[] direction) {
float distance = Float.MAX_VALUE;
lastIndex = -1;
if (spatialValues == null) return distance;
float o_x = (float) origin[0];
float o_y = (float) origin[1];
float o_z = (float) origin[2];
float d_x = (float) direction[0];
float d_y = (float) direction[1];
float d_z = (float) direction[2];
/*
System.out.println("origin = " + o_x + " " + o_y + " " + o_z);
System.out.println("direction = " + d_x + " " + d_y + " " + d_z);
*/
for (int i=0; i<spatialValues[0].length; i++) {
float x = spatialValues[0][i] - o_x;
float y = spatialValues[1][i] - o_y;
float z = spatialValues[2][i] - o_z;
float dot = x * d_x + y * d_y + z * d_z;
x = x - dot * d_x;
y = y - dot * d_y;
z = z - dot * d_z;
float d = (float) Math.sqrt(x * x + y * y + z * z);
if (d < distance) {
distance = d;
closeIndex = i;
offsetx = x;
offsety = y;
offsetz = z;
}
/*
System.out.println("spatialValues["+i+"] = " + spatialValues[0][i] + " " +
spatialValues[1][i] + " " + spatialValues[2][i] + " d = " + d);
*/
}
/*
System.out.println("checkClose: distance = " + distance);
*/
return distance;
}
/** mouse button released, ending direct manipulation */
public synchronized void release_direct() {
}
/** discontinue dragging this DataRenderer;
this method is not a general disable */
public void stop_direct() {
stop = true;
}
public int getLastMouseModifiers() {
return LastMouseModifiers;
}
public void setLastMouseModifiers(int mouseModifiers) {
LastMouseModifiers = mouseModifiers;
}
public synchronized void drag_direct(VisADRay ray, boolean first,
int mouseModifiers) {
// System.out.println("drag_direct " + first + " " + type);
if (spatialValues == null || ref == null || shadow == null ||
link == null) return;
if (first) {
stop = false;
}
else {
if (stop) return;
}
float o_x = (float) ray.position[0];
float o_y = (float) ray.position[1];
float o_z = (float) ray.position[2];
float d_x = (float) ray.vector[0];
float d_y = (float) ray.vector[1];
float d_z = (float) ray.vector[2];
if (first) {
offset_count = OFFSET_COUNT_INIT;
}
else {
if (offset_count > 0) offset_count--;
}
if (offset_count > 0) {
float mult = ((float) offset_count) / ((float) OFFSET_COUNT_INIT);
o_x += mult * offsetx;
o_y += mult * offsety;
o_z += mult * offsetz;
}
if (first) {
point_x = spatialValues[0][closeIndex];
point_y = spatialValues[1][closeIndex];
point_z = spatialValues[2][closeIndex];
int lineAxis = -1;
if (getDirectManifoldDimension() == 3) {
// coord sys ok
line_x = d_x;
line_y = d_y;
line_z = d_z;
}
else {
if (getDirectManifoldDimension() == 2) {
if (displayRenderer.getMode2D()) {
// coord sys ok
lineAxis = 2;
}
else {
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) < 0 && getDomainAxis() != i) {
lineAxis = i;
}
}
}
}
else if (getDirectManifoldDimension() == 1) {
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) >= 0) {
lineAxis = i;
}
}
}
line_x = (lineAxis == 0) ? 1.0f : 0.0f;
line_y = (lineAxis == 1) ? 1.0f : 0.0f;
line_z = (lineAxis == 2) ? 1.0f : 0.0f;
}
} // end if (first)
float[] x = new float[3]; // x marks the spot
if (getDirectManifoldDimension() == 1) {
// find closest point on line to ray
// logic from vis5d/cursor.c
// line o_, d_ to line point_, line_
float ld = d_x * line_x + d_y * line_y + d_z * line_z;
float od = o_x * d_x + o_y * d_y + o_z * d_z;
float pd = point_x * d_x + point_y * d_y + point_z * d_z;
float ol = o_x * line_x + o_y * line_y + o_z * line_z;
float pl = point_x * line_x + point_y * line_y + point_z * line_z;
if (ld * ld == 1.0f) return;
float t = ((pl - ol) - (ld * (pd - od))) / (ld * ld - 1.0f);
// x is closest point
x[0] = point_x + t * line_x;
x[1] = point_y + t * line_y;
x[2] = point_z + t * line_z;
}
else { // getDirectManifoldDimension() = 2 or 3
// intersect ray with plane
float dot = (point_x - o_x) * line_x +
(point_y - o_y) * line_y +
(point_z - o_z) * line_z;
float dot2 = d_x * line_x + d_y * line_y + d_z * line_z;
if (dot2 == 0.0) return;
dot = dot / dot2;
// x is intersection
x[0] = o_x + dot * d_x;
x[1] = o_y + dot * d_y;
x[2] = o_z + dot * d_z;
}
//
// TO_DO
// might estimate errors from pixel resolution on screen
//
try {
float[] xx = {x[0], x[1], x[2]};
if (tuple != null) {
float[][] cursor = {{x[0]}, {x[1]}, {x[2]}};
float[][] new_cursor =
tuple.getCoordinateSystem().fromReference(cursor);
x[0] = new_cursor[0][0];
x[1] = new_cursor[1][0];
x[2] = new_cursor[2][0];
}
Data newData = null;
Data data;
try {
data = link.getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, link);
removeLink(link);
link = null;
return;
}
throw re;
}
if (type instanceof RealType) {
addPoint(xx);
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
// RealType rtype = (RealType) data.getType();
RealType rtype = (RealType) type;
newData = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null);
// create location string
Vector vect = new Vector();
/* WLH 26 July 99
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
Real r = new Real(rtype, d[0]);
Unit overrideUnit = getDirectMap(i).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
getDisplayRenderer().setCursorStringVector(vect);
break;
}
}
ref.setData(newData);
link.clearData(); // WLH 27 July 99
}
else if (type instanceof RealTupleType) {
addPoint(xx);
int n = ((RealTuple) data).getDimension();
Real[] reals = new Real[n];
Vector vect = new Vector();
for (int i=0; i<3; i++) {
int j = getAxisToComponent(i);
if (j >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
Real c = (Real) ((RealTuple) data).getComponent(j);
RealType rtype = (RealType) c.getType();
reals[j] = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null);
// create location string
/* WLH 26 July 99
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
Real r = new Real(rtype, d[0]);
Unit overrideUnit = getDirectMap(i).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
}
}
getDisplayRenderer().setCursorStringVector(vect);
for (int j=0; j<n; j++) {
if (reals[j] == null) {
reals[j] = (Real) ((RealTuple) data).getComponent(j);
}
}
newData = new RealTuple((RealTupleType) type, reals,
((RealTuple) data).getCoordinateSystem());
ref.setData(newData);
link.clearData(); // WLH 27 July 99
}
else if (type instanceof FunctionType) {
Vector vect = new Vector();
if (first) lastIndex = -1;
int k = getDomainAxis();
f[0] = x[k];
d = getDirectMap(k).inverseScaleValues(f);
RealType rtype = (RealType) getDirectMap(k).getScalar();
// WLH 31 Aug 2000
// first, save value in default Unit
double dsave = d[0];
// WLH 4 Jan 99
// convert d from default Unit to actual domain Unit of data
Unit[] us = ((Field) data).getDomainUnits();
if (us != null && us[0] != null) {
d[0] = (float) us[0].toThis((double) d[0], rtype.getDefaultUnit());
}
// WLH 31 Aug 2000
Real r = new Real(rtype, dsave);
Unit overrideUnit = getDirectMap(k).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
dsave = overrideUnit.toThis(dsave, rtunit);
r = new Real(rtype, dsave, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
/*
// create location string
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// convert domain value to domain index
Gridded1DSet set = (Gridded1DSet) ((Field) data).getDomainSet();
value[0][0] = (float) d[0];
int[] indices = set.valueToIndex(value);
int thisIndex = indices[0];
if (thisIndex < 0) {
lastIndex = -1;
return;
}
if (lastIndex < 0) {
addPoint(xx);
}
else {
lastX[3] = xx[0];
lastX[4] = xx[1];
lastX[5] = xx[2];
addPoint(lastX);
}
lastX[0] = xx[0];
lastX[1] = xx[1];
lastX[2] = xx[2];
int n;
MathType range = ((FunctionType) type).getRange();
if (range instanceof RealType) {
n = 1;
}
else {
n = ((RealTupleType) range).getDimension();
}
double[] thisD = new double[n];
boolean[] directComponent = new boolean[n];
for (int j=0; j<n; j++) {
thisD[j] = Double.NaN;
directComponent[j] = false;
}
for (int i=0; i<3; i++) {
int j = getAxisToComponent(i);
if (j >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
// create location string
rtype = (RealType) getDirectMap(i).getScalar();
/* WLH 26 July 99
g = (float) d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
r = new Real(rtype, d[0]);
overrideUnit = getDirectMap(i).getOverrideUnit();
rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
thisD[j] = d[0];
directComponent[j] = true;
}
}
getDisplayRenderer().setCursorStringVector(vect);
if (lastIndex < 0) {
lastIndex = thisIndex;
lastD = new double[n];
for (int j=0; j<n; j++) {
lastD[j] = thisD[j];
}
}
Real[] reals = new Real[n];
int m = Math.abs(lastIndex - thisIndex) + 1;
indices = new int[m];
int index = thisIndex;
int inc = (lastIndex >= thisIndex) ? 1 : -1;
for (int i=0; i<m; i++) {
indices[i] = index;
index += inc;
}
float[][] values = set.indexToValue(indices);
double coefDiv = values[0][m-1] - values[0][0];
for (int i=0; i<m; i++) {
index = indices[i];
double coef = (i == 0 || coefDiv == 0.0) ? 0.0 :
(values[0][i] - values[0][0]) / coefDiv;
Data tuple = ((Field) data).getSample(index);
if (tuple instanceof Real) {
if (directComponent[0]) {
rtype = (RealType) tuple.getType();
tuple = new Real(rtype, thisD[0] + coef * (lastD[0] - thisD[0]),
rtype.getDefaultUnit(), null);
}
}
else {
for (int j=0; j<n; j++) {
Real c = (Real) ((RealTuple) tuple).getComponent(j);
if (directComponent[j]) {
rtype = (RealType) c.getType();
reals[j] = new Real(rtype, thisD[j] + coef * (lastD[j] - thisD[j]),
rtype.getDefaultUnit(), null);
}
else {
reals[j] = c;
}
}
tuple = new RealTuple(reals);
}
((Field) data).setSample(index, tuple);
} // end for (int i=0; i<m; i++)
if (ref instanceof RemoteDataReference &&
!(data instanceof RemoteData)) {
// ref is Remote and data is local, so we have only modified
// a local copy and must send it back to ref
ref.setData(data);
link.clearData(); // WLH 27 July 99
}
// set last index to this, and component values
lastIndex = thisIndex;
for (int j=0; j<n; j++) {
lastD[j] = thisD[j];
}
} // end else if (type instanceof FunctionType)
} // end try
catch (VisADException e) {
// do nothing
System.out.println("drag_direct " + e);
e.printStackTrace();
}
catch (RemoteException e) {
// do nothing
System.out.println("drag_direct " + e);
e.printStackTrace();
}
}
public void addPoint(float[] x) throws VisADException {
}
/** flag indicating whether DirectManipulationRenderer is valid
for this ShadowType */
private boolean isDirectManipulation;
/** set isDirectManipulation = true if this DataRenderer
supports direct manipulation for its linked Data */
public void checkDirect() throws VisADException, RemoteException {
isDirectManipulation = false;
}
public void setIsDirectManipulation(boolean b) {
isDirectManipulation = b;
}
public boolean getIsDirectManipulation() {
return isDirectManipulation;
}
private float ray_pos; // save last ray_pos as first guess for next
private static final int HALF_GUESSES = 200;
private static final int GUESSES = 2 * HALF_GUESSES + 1;
private static final float RAY_POS_INC = 0.1f;
private static final int TRYS = 10;
private static final double EPS = 0.001f;
public float findRayManifoldIntersection(boolean first, double[] origin,
double[] direction, DisplayTupleType tuple,
int otherindex, float othervalue)
throws VisADException {
ray_pos = Float.NaN;
if (otherindex < 0) return ray_pos;
CoordinateSystem tuplecs = null;
if (tuple != null) tuplecs = tuple.getCoordinateSystem();
if (tuple == null || tuplecs == null) {
ray_pos = (float)
((othervalue - origin[otherindex]) / direction[otherindex]);
}
else { // tuple != null
double adjust = Double.NaN;
if (Display.DisplaySpatialSphericalTuple.equals(tuple)) {
if (otherindex == 1) adjust = 360.0;
}
if (first) {
// generate a first guess ray_pos by brute force
ray_pos = Float.NaN;
float[][] guesses = new float[3][GUESSES];
for (int i=0; i<GUESSES; i++) {
float rp = (i - HALF_GUESSES) * RAY_POS_INC;
guesses[0][i] = (float) (origin[0] + rp * direction[0]);
guesses[1][i] = (float) (origin[1] + rp * direction[1]);
guesses[2][i] = (float) (origin[2] + rp * direction[2]);
if (adjust == adjust) {
guesses[otherindex][i] = (float)
(((othervalue + 0.5 * adjust + guesses[otherindex][i]) % adjust) -
(othervalue + 0.5 * adjust));
}
}
guesses = tuplecs.fromReference(guesses);
double distance = Double.MAX_VALUE;
float lastg = 0.0f;
for (int i=0; i<GUESSES; i++) {
float g = othervalue - guesses[otherindex][i];
// first, look for nearest zero crossing and interpolate
if (i > 0 && ((g < 0.0f && lastg >= 0.0f) || (g >= 0.0f && lastg < 0.0f))) {
float r = (float)
(i - (Math.abs(g) / (Math.abs(lastg) + Math.abs(g))));
ray_pos = (r - HALF_GUESSES) * RAY_POS_INC;
break;
}
lastg = g;
// otherwise look for closest to zero
double d = Math.abs(othervalue - guesses[otherindex][i]);
if (d < distance) {
distance = d;
ray_pos = (i - HALF_GUESSES) * RAY_POS_INC;
}
} // end for (int i=0; i<GUESSES; i++)
}
if (ray_pos == ray_pos) {
// use Newton's method to refine first guess
// double error_limit = 10.0 * EPS;
double error_limit = EPS;
double r = ray_pos;
double error = 1.0f;
double[][] guesses = new double[3][3];
int itry;
// System.out.println("\nothervalue = " + (float) othervalue + " r = " + (float) r);
for (itry=0; (itry<TRYS && r == r); itry++) {
double rp = r + EPS;
double rm = r - EPS;
guesses[0][0] = origin[0] + rp * direction[0];
guesses[1][0] = origin[1] + rp * direction[1];
guesses[2][0] = origin[2] + rp * direction[2];
guesses[0][1] = origin[0] + r * direction[0];
guesses[1][1] = origin[1] + r * direction[1];
guesses[2][1] = origin[2] + r * direction[2];
guesses[0][2] = origin[0] + rm * direction[0];
guesses[1][2] = origin[1] + rm * direction[1];
guesses[2][2] = origin[2] + rm * direction[2];
// System.out.println(" guesses = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
guesses = tuplecs.fromReference(guesses);
// System.out.println(" transformed = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
if (adjust == adjust) {
guesses[otherindex][0] =
((othervalue + 0.5 * adjust + guesses[otherindex][0]) % adjust) -
(othervalue + 0.5 * adjust);
guesses[otherindex][1] =
((othervalue + 0.5 * adjust + guesses[otherindex][1]) % adjust) -
(othervalue + 0.5 * adjust);
guesses[otherindex][2] =
((othervalue + 0.5 * adjust + guesses[otherindex][2]) % adjust) -
(othervalue + 0.5 * adjust);
}
// System.out.println(" adjusted = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
double g = othervalue - guesses[otherindex][1];
error = Math.abs(g);
if (error <= EPS) break;
double gp = othervalue - guesses[otherindex][0];
double gm = othervalue - guesses[otherindex][2];
double dg = (gp - gm) / (EPS + EPS);
// System.out.println("r = " + (float) r + " g = " + (float) g + " gm = " +
// (float) gm + " gp = " + (float) gp + " dg = " + (float) dg);
r = r - g / dg;
}
if (error < error_limit) {
ray_pos = (float) r;
}
else {
// System.out.println("error = " + error + " itry = " + itry);
ray_pos = Float.NaN;
}
}
} // end (tuple != null)
return ray_pos;
}
/**
* <b>WARNING!</b>
* Do <b>NOT</b> use this routine unless you know what you are doing!
*/
public void removeLink(DataDisplayLink link)
{
final int newLen = Links.length - 1;
if (newLen < 0) {
// give up if the Links array is already empty
return;
}
DataDisplayLink[] newLinks = new DataDisplayLink[newLen];
int n = 0;
for (int i = 0; i <= newLen; i++) {
if (Links[i] == link) {
// skip the specified link
} else {
if (n == newLen) {
// yikes! Obviously didn't find this link in the list!
return;
}
newLinks[n++] = Links[i];
}
}
if (n < newLen) {
// Hmmm ... seem to have removed multiple instances of 'link'!
DataDisplayLink[] newest = new DataDisplayLink[n];
System.arraycopy(newLinks, 0, newest, 0, n);
newLinks = newest;
}
Links = newLinks;
}
}
| public boolean isTransformControl(Control control, DataDisplayLink link) {
if (control instanceof ProjectionControl ||
control instanceof ToggleControl) {
return false;
}
/* WLH 1 Nov 97 - temporary hack -
RangeControl changes always require Transform
ValueControl and AnimationControl never do
if (control instanceof AnimationControl ||
control instanceof ValueControl ||
control instanceof RangeControl) {
return link.isTransform[control.getIndex()];
*/
if (control instanceof AnimationControl ||
control instanceof ValueControl) {
return false;
}
return true;
}
/** used for transform time-out hack */
public DataDisplayLink getLink() {
return null;
}
public boolean isLegalTextureMap() {
return true;
}
/* ********************** */
/* flow rendering stuff */
/* ********************** */
// value array (display_values) indices
// ((ScalarMap) MapVector.elementAt(valueToMap[index]))
// can get these indices through shadow_data_out or shadow_data_in
// true if lat and lon in data_in & shadow_data_in is allSpatial
// or if lat and lon in data_in & lat_lon_in_by_coord
boolean lat_lon_in = false;
// true if lat_lon_in and shadow_data_out is allSpatial
// i.e., map from lat, lon to display is through data CoordinateSystem
boolean lat_lon_in_by_coord = false;
// true if lat and lon in data_out & shadow_data_out is allSpatial
boolean lat_lon_out = false;
// true if lat_lon_out and shadow_data_in is allSpatial
// i.e., map from lat, lon to display is inverse via data CoordinateSystem
boolean lat_lon_out_by_coord = false;
int lat_lon_dimension = -1;
ShadowRealTupleType shadow_data_out = null;
RealTupleType data_out = null;
Unit[] data_units_out = null;
// CoordinateSystem data_coord_out is always null
ShadowRealTupleType shadow_data_in = null;
RealTupleType data_in = null;
Unit[] data_units_in = null;
CoordinateSystem[] data_coord_in = null; // may be one per point
// spatial ScalarMaps for allSpatial shadow_data_out
ScalarMap[] sdo_maps = null;
// spatial ScalarMaps for allSpatial shadow_data_in
ScalarMap[] sdi_maps = null;
int[] sdo_spatial_index = null;
int[] sdi_spatial_index = null;
// indices of RealType.Latitude and RealType.Longitude
// if lat_lon_in then indices in data_in
// if lat_lon_out then indices in data_out
// if lat_lon_spatial then values indices
int lat_index = -1;
int lon_index = -1;
// non-negative if lat & lon in a RealTupleType of length 3
int other_index = -1;
// true if other_index Units convertable to meter
boolean other_meters = false;
// from doTransform
RealVectorType[] rvts = {null, null};
public RealVectorType getRealVectorTypes(int index) {
if (index == 0 || index == 1) return rvts[index];
else return null;
}
public int[] getLatLonIndices() {
return new int[] {lat_index, lon_index};
}
public void setLatLonIndices(int[] indices) {
lat_index = indices[0];
lon_index = indices[1];
}
public int getEarthDimension() {
return lat_lon_dimension;
}
public Unit[] getEarthUnits() {
Unit[] units = null;
if (lat_lon_in) {
units = data_units_in;
}
else if (lat_lon_out) {
units = data_units_out;
}
else if (lat_lon_spatial) {
units = new Unit[] {RealType.Latitude.getDefaultUnit(),
RealType.Longitude.getDefaultUnit()};
}
else {
units = null;
}
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (units == null) {
return null;
}
else if (units.length == 2) {
return new Unit[] {lat >= 0 ? units[lat] : null,
lon >= 0 ? units[lon] : null};
}
else if (units.length == 3) {
return new Unit[] {lat >= 0 ? units[lat] : null,
lon >= 0 ? units[lon] : null,
other >= 0 ? units[other] : null};
}
else {
return null;
}
}
public float getLatLonRange() {
double[] rlat = null;
double[] rlon = null;
int lat = lat_index;
int lon = lon_index;
if ((lat_lon_out && !lat_lon_out_by_coord) ||
(lat_lon_in && lat_lon_in_by_coord)) {
rlat = lat >= 0 ? sdo_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN};
rlon = lon >= 0 ? sdo_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN};
}
else if ((lat_lon_in && !lat_lon_in_by_coord) ||
(lat_lon_out && lat_lon_out_by_coord)) {
rlat = lat >= 0 ? sdi_maps[lat].getRange() : new double[] {Double.NaN, Double.NaN};
rlon = lon >= 0 ? sdi_maps[lon].getRange() : new double[] {Double.NaN, Double.NaN};
}
else if (lat_lon_spatial) {
rlat = lat_map.getRange();
rlon = lon_map.getRange();
}
else {
return 1.0f;
}
double dlat = Math.abs(rlat[1] - rlat[0]);
double dlon = Math.abs(rlon[1] - rlon[0]);
if (dlat != dlat) dlat = 1.0f;
if (dlon != dlon) dlon = 1.0f;
return (dlat > dlon) ? (float) dlat : (float) dlon;
}
/** convert (lat, lon) or (lat, lon, other) values to
display (x, y, z) */
public float[][] earthToSpatial(float[][] locs, float[] vert)
throws VisADException {
return earthToSpatial(locs, vert, null);
}
public float[][] earthToSpatial(float[][] locs, float[] vert,
float[][] base_spatial_locs)
throws VisADException {
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (lat_index < 0 || lon_index < 0) return null;
int size = locs[0].length;
if (locs.length < lat_lon_dimension) {
// extend locs to lat_lon_dimension with zero fill
float[][] temp = locs;
locs = new float[lat_lon_dimension][];
for (int i=0; i<locs.length; i++) {
locs[i] = temp[i];
}
float[] zero = new float[size];
for (int j=0; j<size; j++) zero[j] = 0.0f;
for (int i=locs.length; i<lat_lon_dimension; i++) {
locs[i] = zero;
}
}
else if (locs.length > lat_lon_dimension) {
// truncate locs to lat_lon_dimension
float[][] temp = locs;
locs = new float[lat_lon_dimension][];
for (int i=0; i<lat_lon_dimension; i++) {
locs[i] = temp[i];
}
}
// permute (lat, lon, other) to data RealTupleType
float[][] tuple_locs = new float[lat_lon_dimension][];
float[][] spatial_locs = new float[3][];
tuple_locs[lat] = locs[0];
tuple_locs[lon] = locs[1];
if (lat_lon_dimension == 3) tuple_locs[other] = locs[2];
int vert_index = -1; // non-lat/lon index for lat_lon_dimension = 2
if (lat_lon_in) {
if (lat_lon_in_by_coord) {
// transform 'RealTupleType data_in' to 'RealTupleType data_out'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[0],
data_units_in, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[j],
data_units_in, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
// map data_out to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdo_spatial_index[i]] =
sdo_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]);
}
}
else {
// map data_in to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdi_spatial_index[i]] =
sdi_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]);
}
}
}
else if (lat_lon_out) {
if (lat_lon_out_by_coord) {
// transform 'RealTupleType data_out' to 'RealTupleType data_in'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[0], data_units_in, null, data_out,
null, data_units_out, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[j], data_units_in, null, data_out,
null, data_units_out, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
// map data_in to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdi_spatial_index[i]] =
sdi_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdi_spatial_index[0] + sdi_spatial_index[1]);
}
}
else {
// map data_out to spatial DisplayRealTypes
for (int i=0; i<lat_lon_dimension; i++) {
spatial_locs[sdo_spatial_index[i]] =
sdo_maps[i].scaleValues(tuple_locs[i]);
}
if (lat_lon_dimension == 2) {
vert_index = 3 - (sdo_spatial_index[0] + sdo_spatial_index[1]);
}
}
}
else if (lat_lon_spatial) {
// map lat & lon, not in allSpatial RealTupleType, to
// spatial DisplayRealTypes
spatial_locs[lat_spatial_index] =
lat_map.scaleValues(tuple_locs[lat]);
spatial_locs[lon_spatial_index] =
lon_map.scaleValues(tuple_locs[lon]);
vert_index = 3 - (lat_spatial_index + lon_spatial_index);
}
else {
// should never happen
return null;
}
// WLH 9 Dec 99
// fill any empty spatial DisplayRealTypes with default values
for (int i=0; i<3; i++) {
if (spatial_locs[i] == null) {
if (base_spatial_locs != null && base_spatial_locs[i] != null) {
spatial_locs[i] = base_spatial_locs[i]; // copy not necessary
}
else {
spatial_locs[i] = new float[size];
float def = default_spatial_in[i]; // may be non-Cartesian
for (int j=0; j<size; j++) spatial_locs[i][j] = def;
}
}
}
// adjust non-lat/lon spatial_locs by vertical flow component
/* WLH 28 July 99
if (vert != null && vert_index > -1) {
for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j];
}
*/
if (vert != null && vert_index > -1 && spatial_locs[vert_index] != null) {
for (int j=0; j<size; j++) spatial_locs[vert_index][j] += vert[j];
}
if (display_coordinate_system != null) {
// transform non-Cartesian spatial DisplayRealTypes to Cartesian
if (spatial_locs != null && spatial_locs.length > 0 &&
spatial_locs[0] != null && spatial_locs[0].length > 0) {
spatial_locs = display_coordinate_system.toReference(spatial_locs);
}
}
return spatial_locs;
}
/** convert display (x, y, z) to (lat, lon) or (lat, lon, other)
values */
public float[][] spatialToEarth(float[][] spatial_locs)
throws VisADException {
float[][] base_spatial_locs = new float[3][];
return spatialToEarth(spatial_locs, base_spatial_locs);
}
public float[][] spatialToEarth(float[][] spatial_locs,
float[][] base_spatial_locs)
throws VisADException {
int lat = lat_index;
int lon = lon_index;
int other = other_index;
if (lat_index < 0 || lon_index < 0) return null;
if (spatial_locs.length != 3) return null;
int size = 0;
for (int i=0; i<3; i++) {
if (spatial_locs[i] != null && spatial_locs[i].length > size) {
size = spatial_locs[i].length;
}
}
if (size == 0) return null;
// fill any empty spatial DisplayRealTypes with default values
for (int i=0; i<3; i++) {
if (spatial_locs[i] == null) {
spatial_locs[i] = new float[size];
// defaults for Cartesian spatial DisplayRealTypes = 0.0f
for (int j=0; j<size; j++) spatial_locs[i][j] = 0.0f;
}
}
if (display_coordinate_system != null) {
// transform Cartesian spatial DisplayRealTypes to non-Cartesian
spatial_locs = display_coordinate_system.fromReference(spatial_locs);
}
base_spatial_locs[0] = spatial_locs[0];
base_spatial_locs[1] = spatial_locs[1];
base_spatial_locs[2] = spatial_locs[2];
float[][] tuple_locs = new float[lat_lon_dimension][];
if (lat_lon_in) {
if (lat_lon_in_by_coord) {
// map spatial DisplayRealTypes to data_out
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]);
}
// transform 'RealTupleType data_out' to 'RealTupleType data_in'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[0], data_units_in, null, data_out,
null, data_units_out, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_in,
data_coord_in[j], data_units_in, null, data_out,
null, data_units_out, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
}
else {
// map spatial DisplayRealTypes to data_in
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]);
}
}
}
else if (lat_lon_out) {
if (lat_lon_out_by_coord) {
// map spatial DisplayRealTypes to data_in
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdi_maps[i].inverseScaleValues(spatial_locs[sdi_spatial_index[i]]);
}
// transform 'RealTupleType data_in' to 'RealTupleType data_out'
if (data_coord_in.length == 1) {
// one data_coord_in applies to all data points
tuple_locs = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[0],
data_units_in, null, tuple_locs);
}
else {
// one data_coord_in per data point
float[][] temp = new float[lat_lon_dimension][1];
for (int j=0; j<size; j++) {
for (int k=0; k<lat_lon_dimension; k++) temp[k][0] = tuple_locs[k][j];
temp = CoordinateSystem.transformCoordinates(data_out, null,
data_units_out, null, data_in, data_coord_in[j],
data_units_in, null, temp);
for (int k=0; k<lat_lon_dimension; k++) tuple_locs[k][j] = temp[k][0];
}
}
}
else {
// map spatial DisplayRealTypes to data_out
for (int i=0; i<lat_lon_dimension; i++) {
tuple_locs[i] =
sdo_maps[i].inverseScaleValues(spatial_locs[sdo_spatial_index[i]]);
}
}
}
else if (lat_lon_spatial) {
// map spatial DisplayRealTypes to lat & lon, not in
// allSpatial RealTupleType
tuple_locs[lat] =
lat_map.inverseScaleValues(spatial_locs[lat_spatial_index]);
tuple_locs[lon] =
lon_map.inverseScaleValues(spatial_locs[lon_spatial_index]);
}
else {
// should never happen
return null;
}
// permute data RealTupleType to (lat, lon, other)
float[][] locs = new float[lat_lon_dimension][];
locs[0] = tuple_locs[lat];
locs[1] = tuple_locs[lon];
if (lat_lon_dimension == 3) locs[2] = tuple_locs[other];
return locs;
}
// information from doTransform
public void setEarthSpatialData(ShadowRealTupleType s_d_i,
ShadowRealTupleType s_d_o, RealTupleType d_o,
Unit[] d_u_o, RealTupleType d_i,
CoordinateSystem[] d_c_i, Unit[] d_u_i)
throws VisADException {
// first check for VectorRealType components mapped to flow
// TO_DO: check here for flow mapped via CoordinateSystem
if (d_o != null && d_o instanceof RealVectorType) {
ScalarMap[] maps = new ScalarMap[3];
int k = getFlowMaps(s_d_o, maps);
if (k > -1) rvts[k] = (RealVectorType) d_o;
}
if (d_i != null && d_i instanceof RealVectorType) {
ScalarMap[] maps = new ScalarMap[3];
int k = getFlowMaps(s_d_i, maps);
if (k > -1) rvts[k] = (RealVectorType) d_i;
}
int lat_index_local = -1;
int lon_index_local = -1;
int other_index_local = -1;
int n = 0;
int m = 0;
if (d_i != null) {
n = d_i.getDimension();
for (int i=0; i<n; i++) {
RealType real = (RealType) d_i.getComponent(i);
if (RealType.Latitude.equals(real)) lat_index_local = i;
if (RealType.Longitude.equals(real)) lon_index_local = i;
}
}
if (lat_index_local > -1 && lon_index_local > -1 && (n == 2 || n == 3)) {
if (s_d_i != null && s_d_i.getAllSpatial() &&
!s_d_i.getSpatialReference()) {
lat_lon_in_by_coord = false;
sdi_spatial_index = new int[s_d_i.getDimension()];
sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index);
if (sdi_maps == null) {
throw new DisplayException("sdi_maps null A");
}
}
else if (s_d_o != null && s_d_o.getAllSpatial() &&
!s_d_o.getSpatialReference()) {
lat_lon_in_by_coord = true;
sdo_spatial_index = new int[s_d_o.getDimension()];
sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index);
if (sdo_maps == null) {
throw new DisplayException("sdo_maps null A");
}
}
else {
// do not update lat_index & lon_index
return;
}
lat_lon_in = true;
lat_lon_out = false;
lat_lon_out_by_coord = false;
lat_lon_spatial = false;
lat_lon_dimension = n;
if (n == 3) {
other_index_local = 3 - (lat_index_local + lon_index_local);
if (Unit.canConvert(d_u_i[other_index_local], CommonUnit.meter)) {
other_meters = true;
}
}
}
else { // if( !(lat & lon in di, di dimension = 2 or 3) )
lat_index_local = -1;
lon_index_local = -1;
other_index_local = -1;
if (d_o != null) {
m = d_o.getDimension();
for (int i=0; i<m; i++) {
RealType real = (RealType) d_o.getComponent(i);
if (RealType.Latitude.equals(real)) lat_index_local = i;
if (RealType.Longitude.equals(real)) lon_index_local = i;
}
}
if (lat_index_local < 0 || lon_index_local < 0 || !(m == 2 || m == 3)) {
// do not update lat_index & lon_index
return;
}
if (s_d_o != null && s_d_o.getAllSpatial() &&
!s_d_o.getSpatialReference()) {
lat_lon_out_by_coord = false;
sdo_spatial_index = new int[s_d_o.getDimension()];
sdo_maps = getSpatialMaps(s_d_o, sdo_spatial_index);
if (sdo_maps == null) {
throw new DisplayException("sdo_maps null B");
}
}
else if (s_d_i != null && s_d_i.getAllSpatial() &&
!s_d_i.getSpatialReference()) {
lat_lon_out_by_coord = true;
sdi_spatial_index = new int[s_d_i.getDimension()];
sdi_maps = getSpatialMaps(s_d_i, sdi_spatial_index);
if (sdi_maps == null) {
throw new DisplayException("sdi_maps null B");
}
}
else {
// do not update lat_index & lon_index
return;
}
lat_lon_out = true;
lat_lon_in = false;
lat_lon_in_by_coord = false;
lat_lon_spatial = false;
lat_lon_dimension = m;
if (m == 3) {
other_index_local = 3 - (lat_index_local + lon_index_local);
if (Unit.canConvert(d_u_i[other_index_local], CommonUnit.meter)) {
other_meters = true;
}
}
}
shadow_data_out = s_d_o;
data_out = d_o;
data_units_out = d_u_o;
shadow_data_in = s_d_i;
data_in = d_i;
data_units_in = d_u_i;
data_coord_in = d_c_i; // may be one per point
lat_index = lat_index_local;
lon_index = lon_index_local;
other_index = other_index_local;
return;
}
/** return array of spatial ScalarMap for srt, or null */
private ScalarMap[] getSpatialMaps(ShadowRealTupleType srt,
int[] spatial_index) {
int n = srt.getDimension();
ScalarMap[] maps = new ScalarMap[n];
for (int i=0; i<n; i++) {
ShadowRealType real = (ShadowRealType) srt.getComponent(i);
Enumeration ms = real.getSelectedMapVector().elements();
while (ms.hasMoreElements()) {
ScalarMap map = (ScalarMap) ms.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) {
maps[i] = map;
spatial_index[i] = dreal.getTupleIndex();
break;
}
}
if (maps[i] == null) {
return null;
}
}
return maps;
}
/** return array of flow ScalarMap for srt, or null */
private int getFlowMaps(ShadowRealTupleType srt, ScalarMap[] maps) {
int n = srt.getDimension();
maps[0] = null;
maps[1] = null;
maps[2] = null;
DisplayTupleType ftuple = null;
for (int i=0; i<n; i++) {
ShadowRealType real = (ShadowRealType) srt.getComponent(i);
Enumeration ms = real.getSelectedMapVector().elements();
while (ms.hasMoreElements()) {
ScalarMap map = (ScalarMap) ms.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (Display.DisplayFlow1Tuple.equals(tuple) ||
Display.DisplayFlow2Tuple.equals(tuple)) {
if (ftuple != null && !ftuple.equals(tuple)) return -1;
ftuple = tuple;
maps[i] = map;
break;
}
}
if (maps[i] == null) return -1;
}
return Display.DisplayFlow1Tuple.equals(ftuple) ? 0 : 1;
}
/* WLH 15 April 2000
// from assembleFlow
ScalarMap[][] flow_maps = null;
float[] flow_scale = null;
public void setFlowDisplay(ScalarMap[][] maps, float[] fs) {
flow_maps = maps;
flow_scale = fs;
}
*/
// if non-null, float[][] new_spatial_values =
// display_coordinate_system.toReference(spatial_values);
CoordinateSystem display_coordinate_system = null;
// spatial_tuple and spatial_value_indices are set whether
// display_coordinate_system is null or not
DisplayTupleType spatial_tuple = null;
// map from spatial_tuple tuple_index to value array indices
int[] spatial_value_indices = {-1, -1, -1};
float[] default_spatial_in = {0.0f, 0.0f, 0.0f};
// true if lat and lon mapped directly to spatial
boolean lat_lon_spatial = false;
ScalarMap lat_map = null;
ScalarMap lon_map = null;
int lat_spatial_index = -1;
int lon_spatial_index = -1;
// spatial map getRange() results for flow adjustment
double[] ranges = null;
public double[] getRanges() {
return ranges;
}
// WLH 4 March 2000
public CoordinateSystem getDisplayCoordinateSystem() {
return display_coordinate_system ;
}
// information from assembleSpatial
public void setEarthSpatialDisplay(CoordinateSystem coord,
DisplayTupleType t, DisplayImpl display, int[] indices,
float[] default_values, double[] r)
throws VisADException {
display_coordinate_system = coord;
spatial_tuple = t;
System.arraycopy(indices, 0, spatial_value_indices, 0, 3);
/* WLH 5 Dec 99
spatial_value_indices = indices;
*/
ranges = r;
for (int i=0; i<3; i++) {
int default_index = display.getDisplayScalarIndex(
((DisplayRealType) t.getComponent(i)) );
default_spatial_in[i] = default_values[default_index];
}
if (lat_index > -1 && lon_index > -1) return;
lat_index = -1;
lon_index = -1;
other_index = -1;
int valueArrayLength = display.getValueArrayLength();
int[] valueToScalar = display.getValueToScalar();
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (tuple != null &&
(tuple.equals(Display.DisplaySpatialCartesianTuple) ||
(tuple.getCoordinateSystem() != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)))) {
if (RealType.Latitude.equals(real)) {
lat_index = 0;
lat_map = map;
lat_spatial_index = dreal.getTupleIndex();
}
if (RealType.Longitude.equals(real)) {
lon_index = 1;
lon_map = map;
lon_spatial_index = dreal.getTupleIndex();
}
}
}
if (lat_index > -1 && lon_index > -1) {
lat_lon_spatial = true;
lat_lon_dimension = 2;
lat_lon_out = false;
lat_lon_in_by_coord = false;
lat_lon_in = false;
}
else {
lat_lon_spatial = false;
lat_index = -1;
lon_index = -1;
}
}
/* *************************** */
/* direct manipulation stuff */
/* *************************** */
private float[][] spatialValues = null;
/** if Function, last domain index and range values */
private int lastIndex = -1;
double[] lastD = null;
float[] lastX = new float[6];
/** index into spatialValues found by checkClose */
private int closeIndex = -1;
/** pick error offset, communicated from checkClose() to drag_direct() */
private float offsetx = 0.0f, offsety = 0.0f, offsetz = 0.0f;
/** count down to decay offset to 0.0 */
private int offset_count = 0;
/** initial offset_count */
private static final int OFFSET_COUNT_INIT = 30;
/** for use in drag_direct */
private transient DataDisplayLink link = null;
// private transient ShadowTypeJ3D type = null;
private transient DataReference ref = null;
private transient MathType type = null;
private transient ShadowType shadow = null;
/** point on direct manifold line or plane */
private float point_x, point_y, point_z;
/** normalized direction of line or perpendicular to plane */
private float line_x, line_y, line_z;
/** arrays of length one for inverseScaleValues */
private float[] f = new float[1];
private float[] d = new float[1];
private float[][] value = new float[1][1];
/** information calculated by checkDirect */
/** explanation for invalid use of DirectManipulationRenderer */
private String whyNotDirect = null;
/** mapping from spatial axes to tuple component */
private int[] axisToComponent = {-1, -1, -1};
/** mapping from spatial axes to ScalarMaps */
private ScalarMap[] directMap = {null, null, null};
/** spatial axis for Function domain */
private int domainAxis = -1;
/** dimension of direct manipulation
(including any Function domain) */
private int directManifoldDimension = 0;
/** spatial DisplayTupleType other than
DisplaySpatialCartesianTuple */
DisplayTupleType tuple;
/** possible values for whyNotDirect */
private final static String notRealFunction =
"FunctionType must be Real";
private final static String notSimpleField =
"not simple field";
private final static String notSimpleTuple =
"not simple tuple";
private final static String multipleMapping =
"RealType with multiple mappings";
private final static String multipleSpatialMapping =
"RealType with multiple spatial mappings";
private final static String nonSpatial =
"no spatial mapping";
private final static String viaReference =
"spatial mapping through Reference";
private final static String domainDimension =
"domain dimension must be 1";
private final static String domainNotSpatial =
"domain must be mapped to spatial";
private final static String rangeType =
"range must be RealType or RealTupleType";
private final static String rangeNotSpatial =
"range must be mapped to spatial";
private final static String domainSet =
"domain Set must be Gridded1DSet";
private final static String tooFewSpatial =
"Function without spatial domain";
private final static String functionTooFew =
"Function directManifoldDimension < 2";
private final static String badCoordSysManifoldDim =
"bad directManifoldDimension with spatial CoordinateSystem";
private final static String lostConnection =
"lost connection to Data server";
private boolean stop = false;
private int LastMouseModifiers = 0;
public synchronized void realCheckDirect()
throws VisADException, RemoteException {
setIsDirectManipulation(false);
DataDisplayLink[] Links = getLinks();
if (Links == null || Links.length == 0) {
link = null;
return;
}
link = Links[0];
ref = link.getDataReference();
shadow = link.getShadow().getAdaptedShadowType();
type = link.getType();
tuple = null;
if (type instanceof FunctionType) {
ShadowRealTupleType domain =
((ShadowFunctionType) shadow).getDomain();
ShadowType range =
((ShadowFunctionType) shadow).getRange();
tuple = domain.getDisplaySpatialTuple();
// there is some redundancy among these conditions
if (!((FunctionType) type).getReal()) {
whyNotDirect = notRealFunction;
return;
}
else if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_FIELD) {
whyNotDirect = notSimpleField;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if (domain.getDimension() != 1) {
whyNotDirect = domainDimension;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
whyNotDirect = domainNotSpatial;
return;
}
else if (domain.getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
DisplayTupleType rtuple = null;
if (range instanceof ShadowRealTupleType) {
rtuple = ((ShadowRealTupleType) range).getDisplaySpatialTuple();
}
else if (range instanceof ShadowRealType) {
rtuple = ((ShadowRealType) range).getDisplaySpatialTuple();
}
else {
whyNotDirect = rangeType;
return;
}
if (!tuple.equals(rtuple)) {
/* WLH 3 Aug 98
if (!Display.DisplaySpatialCartesianTuple.equals(rtuple)) {
*/
whyNotDirect = rangeNotSpatial;
return;
}
else if (range instanceof ShadowRealTupleType &&
((ShadowRealTupleType) range).getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
else {
Data data;
try {
data = link.getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, link);
removeLink(link);
link = null;
whyNotDirect = lostConnection;
return;
}
throw re;
}
if (!(data instanceof Field) ||
!(((Field) data).getDomainSet() instanceof Gridded1DSet))
{
whyNotDirect = domainSet;
return;
}
}
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension =
setDirectMap((ShadowRealType) domain.getComponent(0), -1, true);
if (range instanceof ShadowRealType) {
directManifoldDimension +=
setDirectMap((ShadowRealType) range, 0, false);
}
else if (range instanceof ShadowRealTupleType) {
ShadowRealTupleType r = (ShadowRealTupleType) range;
for (int i=0; i<r.getDimension(); i++) {
directManifoldDimension +=
setDirectMap((ShadowRealType) r.getComponent(i), i, false);
}
}
if (domainAxis == -1) {
whyNotDirect = tooFewSpatial;
return;
}
if (directManifoldDimension < 2) {
whyNotDirect = functionTooFew;
return;
}
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
/* WLH 3 Aug 98
if (domainAxis == -1) {
throw new DisplayException("DataRenderer.realCheckDirect:" +
"too few spatial domain");
}
if (directManifoldDimension < 2) {
throw new DisplayException("DataRenderer.realCheckDirect:" +
"directManifoldDimension < 2");
}
*/
}
else if (type instanceof RealTupleType) {
//
// TO_DO
// allow for any Flat ShadowTupleType
//
tuple = ((ShadowRealTupleType) shadow).getDisplaySpatialTuple();
if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) {
whyNotDirect = notSimpleTuple;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
/* WLH 3 Aug 98
else if (!Display.DisplaySpatialCartesianTuple.equals(
((ShadowRealTupleType) shadow).getDisplaySpatialTuple())) {
*/
whyNotDirect = nonSpatial;
return;
}
else if (((ShadowRealTupleType) shadow).getSpatialReference()) {
whyNotDirect = viaReference;
return;
}
/* WLH 3 Aug 98
setIsDirectManipulation(true);
*/
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension = 0;
for (int i=0; i<((ShadowRealTupleType) shadow).getDimension(); i++) {
directManifoldDimension += setDirectMap((ShadowRealType)
((ShadowRealTupleType) shadow).getComponent(i), i, false);
}
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
}
else if (type instanceof RealType) {
tuple = ((ShadowRealType) shadow).getDisplaySpatialTuple();
if (shadow.getLevelOfDifficulty() != ShadowType.SIMPLE_TUPLE) {
whyNotDirect = notSimpleTuple;
return;
}
else if (shadow.getMultipleSpatialDisplayScalar()) {
whyNotDirect = multipleSpatialMapping;
return;
}
else if(!(Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) )) {
/* WLH 3 Aug 98
else if(!Display.DisplaySpatialCartesianTuple.equals(
((ShadowRealType) shadow).getDisplaySpatialTuple())) {
*/
whyNotDirect = nonSpatial;
return;
}
/* WLH 3 Aug 98
setIsDirectManipulation(true);
*/
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
tuple = null;
}
domainAxis = -1;
for (int i=0; i<3; i++) {
axisToComponent[i] = -1;
directMap[i] = null;
}
directManifoldDimension = setDirectMap((ShadowRealType) shadow, 0, false);
boolean twod = displayRenderer.getMode2D();
if (tuple != null &&
(!twod && directManifoldDimension != 3 ||
twod && directManifoldDimension != 2) ) {
whyNotDirect = badCoordSysManifoldDim;
return;
}
setIsDirectManipulation(true);
} // end else if (type instanceof RealType)
}
/** set directMap and axisToComponent (domain = false) or
domainAxis (domain = true) from real; called by realCheckDirect */
synchronized int setDirectMap(ShadowRealType real, int component, boolean domain) {
Enumeration maps = real.getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType dreal = map.getDisplayScalar();
DisplayTupleType tuple = dreal.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple) ||
(tuple != null &&
tuple.getCoordinateSystem().getReference().equals(
Display.DisplaySpatialCartesianTuple)) ) {
int index = dreal.getTupleIndex();
if (domain) {
domainAxis = index;
}
else {
axisToComponent[index] = component;
}
directMap[index] = map;
return 1;
}
}
return 0;
}
private int getDirectManifoldDimension() {
return directManifoldDimension;
}
public String getWhyNotDirect() {
return whyNotDirect;
}
private int getAxisToComponent(int i) {
return axisToComponent[i];
}
private ScalarMap getDirectMap(int i) {
return directMap[i];
}
private int getDomainAxis() {
return domainAxis;
}
/** set spatialValues from ShadowType.doTransform */
public synchronized void setSpatialValues(float[][] spatial_values) {
// these are X, Y, Z values
spatialValues = spatial_values;
}
/** find minimum distance from ray to spatialValues */
public synchronized float checkClose(double[] origin, double[] direction) {
float distance = Float.MAX_VALUE;
lastIndex = -1;
if (spatialValues == null) return distance;
float o_x = (float) origin[0];
float o_y = (float) origin[1];
float o_z = (float) origin[2];
float d_x = (float) direction[0];
float d_y = (float) direction[1];
float d_z = (float) direction[2];
/*
System.out.println("origin = " + o_x + " " + o_y + " " + o_z);
System.out.println("direction = " + d_x + " " + d_y + " " + d_z);
*/
for (int i=0; i<spatialValues[0].length; i++) {
float x = spatialValues[0][i] - o_x;
float y = spatialValues[1][i] - o_y;
float z = spatialValues[2][i] - o_z;
float dot = x * d_x + y * d_y + z * d_z;
x = x - dot * d_x;
y = y - dot * d_y;
z = z - dot * d_z;
float d = (float) Math.sqrt(x * x + y * y + z * z);
if (d < distance) {
distance = d;
closeIndex = i;
offsetx = x;
offsety = y;
offsetz = z;
}
/*
System.out.println("spatialValues["+i+"] = " + spatialValues[0][i] + " " +
spatialValues[1][i] + " " + spatialValues[2][i] + " d = " + d);
*/
}
/*
System.out.println("checkClose: distance = " + distance);
*/
return distance;
}
/** mouse button released, ending direct manipulation */
public synchronized void release_direct() {
}
/** discontinue dragging this DataRenderer;
this method is not a general disable */
public void stop_direct() {
stop = true;
}
public int getLastMouseModifiers() {
return LastMouseModifiers;
}
public void setLastMouseModifiers(int mouseModifiers) {
LastMouseModifiers = mouseModifiers;
}
public synchronized void drag_direct(VisADRay ray, boolean first,
int mouseModifiers) {
// System.out.println("drag_direct " + first + " " + type);
if (spatialValues == null || ref == null || shadow == null ||
link == null) return;
if (first) {
stop = false;
}
else {
if (stop) return;
}
float o_x = (float) ray.position[0];
float o_y = (float) ray.position[1];
float o_z = (float) ray.position[2];
float d_x = (float) ray.vector[0];
float d_y = (float) ray.vector[1];
float d_z = (float) ray.vector[2];
if (first) {
offset_count = OFFSET_COUNT_INIT;
}
else {
if (offset_count > 0) offset_count--;
}
if (offset_count > 0) {
float mult = ((float) offset_count) / ((float) OFFSET_COUNT_INIT);
o_x += mult * offsetx;
o_y += mult * offsety;
o_z += mult * offsetz;
}
if (first) {
point_x = spatialValues[0][closeIndex];
point_y = spatialValues[1][closeIndex];
point_z = spatialValues[2][closeIndex];
int lineAxis = -1;
if (getDirectManifoldDimension() == 3) {
// coord sys ok
line_x = d_x;
line_y = d_y;
line_z = d_z;
}
else {
if (getDirectManifoldDimension() == 2) {
if (displayRenderer.getMode2D()) {
// coord sys ok
lineAxis = 2;
}
else {
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) < 0 && getDomainAxis() != i) {
lineAxis = i;
}
}
}
}
else if (getDirectManifoldDimension() == 1) {
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) >= 0) {
lineAxis = i;
}
}
}
line_x = (lineAxis == 0) ? 1.0f : 0.0f;
line_y = (lineAxis == 1) ? 1.0f : 0.0f;
line_z = (lineAxis == 2) ? 1.0f : 0.0f;
}
} // end if (first)
float[] x = new float[3]; // x marks the spot
if (getDirectManifoldDimension() == 1) {
// find closest point on line to ray
// logic from vis5d/cursor.c
// line o_, d_ to line point_, line_
float ld = d_x * line_x + d_y * line_y + d_z * line_z;
float od = o_x * d_x + o_y * d_y + o_z * d_z;
float pd = point_x * d_x + point_y * d_y + point_z * d_z;
float ol = o_x * line_x + o_y * line_y + o_z * line_z;
float pl = point_x * line_x + point_y * line_y + point_z * line_z;
if (ld * ld == 1.0f) return;
float t = ((pl - ol) - (ld * (pd - od))) / (ld * ld - 1.0f);
// x is closest point
x[0] = point_x + t * line_x;
x[1] = point_y + t * line_y;
x[2] = point_z + t * line_z;
}
else { // getDirectManifoldDimension() = 2 or 3
// intersect ray with plane
float dot = (point_x - o_x) * line_x +
(point_y - o_y) * line_y +
(point_z - o_z) * line_z;
float dot2 = d_x * line_x + d_y * line_y + d_z * line_z;
if (dot2 == 0.0) return;
dot = dot / dot2;
// x is intersection
x[0] = o_x + dot * d_x;
x[1] = o_y + dot * d_y;
x[2] = o_z + dot * d_z;
}
//
// TO_DO
// might estimate errors from pixel resolution on screen
//
try {
float[] xx = {x[0], x[1], x[2]};
if (tuple != null) {
float[][] cursor = {{x[0]}, {x[1]}, {x[2]}};
float[][] new_cursor =
tuple.getCoordinateSystem().fromReference(cursor);
x[0] = new_cursor[0][0];
x[1] = new_cursor[1][0];
x[2] = new_cursor[2][0];
}
Data newData = null;
Data data;
try {
data = link.getData();
} catch (RemoteException re) {
if (visad.collab.CollabUtil.isDisconnectException(re)) {
getDisplay().connectionFailed(this, link);
removeLink(link);
link = null;
return;
}
throw re;
}
if (type instanceof RealType) {
addPoint(xx);
for (int i=0; i<3; i++) {
if (getAxisToComponent(i) >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
// RealType rtype = (RealType) data.getType();
RealType rtype = (RealType) type;
newData = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null);
// create location string
Vector vect = new Vector();
/* WLH 26 July 99
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
Real r = new Real(rtype, d[0]);
Unit overrideUnit = getDirectMap(i).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
getDisplayRenderer().setCursorStringVector(vect);
break;
}
}
ref.setData(newData);
link.clearData(); // WLH 27 July 99
}
else if (type instanceof RealTupleType) {
addPoint(xx);
int n = ((RealTuple) data).getDimension();
Real[] reals = new Real[n];
Vector vect = new Vector();
for (int i=0; i<3; i++) {
int j = getAxisToComponent(i);
if (j >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
Real c = (Real) ((RealTuple) data).getComponent(j);
RealType rtype = (RealType) c.getType();
reals[j] = new Real(rtype, (double) d[0], rtype.getDefaultUnit(), null);
// create location string
/* WLH 26 July 99
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
Real r = new Real(rtype, d[0]);
Unit overrideUnit = getDirectMap(i).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
}
}
getDisplayRenderer().setCursorStringVector(vect);
for (int j=0; j<n; j++) {
if (reals[j] == null) {
reals[j] = (Real) ((RealTuple) data).getComponent(j);
}
}
newData = new RealTuple((RealTupleType) type, reals,
((RealTuple) data).getCoordinateSystem());
ref.setData(newData);
link.clearData(); // WLH 27 July 99
}
else if (type instanceof FunctionType) {
Vector vect = new Vector();
if (first) lastIndex = -1;
int k = getDomainAxis();
f[0] = x[k];
d = getDirectMap(k).inverseScaleValues(f);
RealType rtype = (RealType) getDirectMap(k).getScalar();
// WLH 31 Aug 2000
// first, save value in default Unit
double dsave = d[0];
// WLH 4 Jan 99
// convert d from default Unit to actual domain Unit of data
Unit[] us = ((Field) data).getDomainUnits();
if (us != null && us[0] != null) {
d[0] = (float) us[0].toThis((double) d[0], rtype.getDefaultUnit());
}
// WLH 31 Aug 2000
Real r = new Real(rtype, dsave);
Unit overrideUnit = getDirectMap(k).getOverrideUnit();
Unit rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
dsave = overrideUnit.toThis(dsave, rtunit);
r = new Real(rtype, dsave, overrideUnit);
}
String valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
/*
// create location string
float g = d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// convert domain value to domain index
Gridded1DSet set = (Gridded1DSet) ((Field) data).getDomainSet();
value[0][0] = (float) d[0];
int[] indices = set.valueToIndex(value);
int thisIndex = indices[0];
if (thisIndex < 0) {
lastIndex = -1;
return;
}
if (lastIndex < 0) {
addPoint(xx);
}
else {
lastX[3] = xx[0];
lastX[4] = xx[1];
lastX[5] = xx[2];
addPoint(lastX);
}
lastX[0] = xx[0];
lastX[1] = xx[1];
lastX[2] = xx[2];
int n;
MathType range = ((FunctionType) type).getRange();
if (range instanceof RealType) {
n = 1;
}
else {
n = ((RealTupleType) range).getDimension();
}
double[] thisD = new double[n];
boolean[] directComponent = new boolean[n];
for (int j=0; j<n; j++) {
thisD[j] = Double.NaN;
directComponent[j] = false;
}
for (int i=0; i<3; i++) {
int j = getAxisToComponent(i);
if (j >= 0) {
f[0] = x[i];
d = getDirectMap(i).inverseScaleValues(f);
// create location string
rtype = (RealType) getDirectMap(i).getScalar();
/* WLH 26 July 99
g = (float) d[0];
vect.addElement(rtype.getName() + " = " + g);
*/
// WLH 31 Aug 2000
r = new Real(rtype, d[0]);
overrideUnit = getDirectMap(i).getOverrideUnit();
rtunit = rtype.getDefaultUnit();
// units not part of Time string
if (overrideUnit != null && !overrideUnit.equals(rtunit) &&
(!Unit.canConvert(rtunit, CommonUnit.secondsSinceTheEpoch) ||
rtunit.getAbsoluteUnit().equals(rtunit))) {
double dval = overrideUnit.toThis((double) d[0], rtunit);
r = new Real(rtype, dval, overrideUnit);
}
valueString = r.toValueString();
vect.addElement(rtype.getName() + " = " + valueString);
thisD[j] = d[0];
directComponent[j] = true;
}
}
getDisplayRenderer().setCursorStringVector(vect);
if (lastIndex < 0) {
lastIndex = thisIndex;
lastD = new double[n];
for (int j=0; j<n; j++) {
lastD[j] = thisD[j];
}
}
Real[] reals = new Real[n];
int m = Math.abs(lastIndex - thisIndex) + 1;
indices = new int[m];
int index = thisIndex;
int inc = (lastIndex >= thisIndex) ? 1 : -1;
for (int i=0; i<m; i++) {
indices[i] = index;
index += inc;
}
float[][] values = set.indexToValue(indices);
double coefDiv = values[0][m-1] - values[0][0];
for (int i=0; i<m; i++) {
index = indices[i];
double coef = (i == 0 || coefDiv == 0.0) ? 0.0 :
(values[0][i] - values[0][0]) / coefDiv;
Data tuple = ((Field) data).getSample(index);
if (tuple instanceof Real) {
if (directComponent[0]) {
rtype = (RealType) tuple.getType();
tuple = new Real(rtype, thisD[0] + coef * (lastD[0] - thisD[0]),
rtype.getDefaultUnit(), null);
}
}
else {
for (int j=0; j<n; j++) {
Real c = (Real) ((RealTuple) tuple).getComponent(j);
if (directComponent[j]) {
rtype = (RealType) c.getType();
reals[j] = new Real(rtype, thisD[j] + coef * (lastD[j] - thisD[j]),
rtype.getDefaultUnit(), null);
}
else {
reals[j] = c;
}
}
tuple = new RealTuple(reals);
}
((Field) data).setSample(index, tuple);
} // end for (int i=0; i<m; i++)
if (ref instanceof RemoteDataReference &&
!(data instanceof RemoteData)) {
// ref is Remote and data is local, so we have only modified
// a local copy and must send it back to ref
ref.setData(data);
link.clearData(); // WLH 27 July 99
}
// set last index to this, and component values
lastIndex = thisIndex;
for (int j=0; j<n; j++) {
lastD[j] = thisD[j];
}
} // end else if (type instanceof FunctionType)
} // end try
catch (VisADException e) {
// do nothing
System.out.println("drag_direct " + e);
e.printStackTrace();
}
catch (RemoteException e) {
// do nothing
System.out.println("drag_direct " + e);
e.printStackTrace();
}
}
public void addPoint(float[] x) throws VisADException {
}
/** flag indicating whether DirectManipulationRenderer is valid
for this ShadowType */
private boolean isDirectManipulation;
/** set isDirectManipulation = true if this DataRenderer
supports direct manipulation for its linked Data */
public void checkDirect() throws VisADException, RemoteException {
isDirectManipulation = false;
}
public void setIsDirectManipulation(boolean b) {
isDirectManipulation = b;
}
public boolean getIsDirectManipulation() {
return isDirectManipulation;
}
private float ray_pos; // save last ray_pos as first guess for next
private static final int HALF_GUESSES = 200;
private static final int GUESSES = 2 * HALF_GUESSES + 1;
private static final float RAY_POS_INC = 0.1f;
private static final int TRYS = 10;
private static final double EPS = 0.001f;
public float findRayManifoldIntersection(boolean first, double[] origin,
double[] direction, DisplayTupleType tuple,
int otherindex, float othervalue)
throws VisADException {
ray_pos = Float.NaN;
if (otherindex < 0) return ray_pos;
CoordinateSystem tuplecs = null;
if (tuple != null) tuplecs = tuple.getCoordinateSystem();
if (tuple == null || tuplecs == null) {
ray_pos = (float)
((othervalue - origin[otherindex]) / direction[otherindex]);
}
else { // tuple != null
double adjust = Double.NaN;
if (Display.DisplaySpatialSphericalTuple.equals(tuple)) {
if (otherindex == 1) adjust = 360.0;
}
if (first) {
// generate a first guess ray_pos by brute force
ray_pos = Float.NaN;
float[][] guesses = new float[3][GUESSES];
for (int i=0; i<GUESSES; i++) {
float rp = (i - HALF_GUESSES) * RAY_POS_INC;
guesses[0][i] = (float) (origin[0] + rp * direction[0]);
guesses[1][i] = (float) (origin[1] + rp * direction[1]);
guesses[2][i] = (float) (origin[2] + rp * direction[2]);
if (adjust == adjust) {
guesses[otherindex][i] = (float)
(((othervalue + 0.5 * adjust + guesses[otherindex][i]) % adjust) -
(othervalue + 0.5 * adjust));
}
}
guesses = tuplecs.fromReference(guesses);
double distance = Double.MAX_VALUE;
float lastg = 0.0f;
for (int i=0; i<GUESSES; i++) {
float g = othervalue - guesses[otherindex][i];
// first, look for nearest zero crossing and interpolate
if (i > 0 && ((g < 0.0f && lastg >= 0.0f) || (g >= 0.0f && lastg < 0.0f))) {
float r = (float)
(i - (Math.abs(g) / (Math.abs(lastg) + Math.abs(g))));
ray_pos = (r - HALF_GUESSES) * RAY_POS_INC;
break;
}
lastg = g;
// otherwise look for closest to zero
double d = Math.abs(othervalue - guesses[otherindex][i]);
if (d < distance) {
distance = d;
ray_pos = (i - HALF_GUESSES) * RAY_POS_INC;
}
} // end for (int i=0; i<GUESSES; i++)
}
if (ray_pos == ray_pos) {
// use Newton's method to refine first guess
// double error_limit = 10.0 * EPS;
double error_limit = EPS;
double r = ray_pos;
double error = 1.0f;
double[][] guesses = new double[3][3];
int itry;
// System.out.println("\nothervalue = " + (float) othervalue + " r = " + (float) r);
for (itry=0; (itry<TRYS && r == r); itry++) {
double rp = r + EPS;
double rm = r - EPS;
guesses[0][0] = origin[0] + rp * direction[0];
guesses[1][0] = origin[1] + rp * direction[1];
guesses[2][0] = origin[2] + rp * direction[2];
guesses[0][1] = origin[0] + r * direction[0];
guesses[1][1] = origin[1] + r * direction[1];
guesses[2][1] = origin[2] + r * direction[2];
guesses[0][2] = origin[0] + rm * direction[0];
guesses[1][2] = origin[1] + rm * direction[1];
guesses[2][2] = origin[2] + rm * direction[2];
// System.out.println(" guesses = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
guesses = tuplecs.fromReference(guesses);
// System.out.println(" transformed = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
if (adjust == adjust) {
guesses[otherindex][0] =
((othervalue + 0.5 * adjust + guesses[otherindex][0]) % adjust) -
(othervalue + 0.5 * adjust);
guesses[otherindex][1] =
((othervalue + 0.5 * adjust + guesses[otherindex][1]) % adjust) -
(othervalue + 0.5 * adjust);
guesses[otherindex][2] =
((othervalue + 0.5 * adjust + guesses[otherindex][2]) % adjust) -
(othervalue + 0.5 * adjust);
}
// System.out.println(" adjusted = " + (float) guesses[0][1] + " " +
// (float) guesses[1][1] + " " + (float) guesses[2][1]);
double g = othervalue - guesses[otherindex][1];
error = Math.abs(g);
if (error <= EPS) break;
double gp = othervalue - guesses[otherindex][0];
double gm = othervalue - guesses[otherindex][2];
double dg = (gp - gm) / (EPS + EPS);
// System.out.println("r = " + (float) r + " g = " + (float) g + " gm = " +
// (float) gm + " gp = " + (float) gp + " dg = " + (float) dg);
r = r - g / dg;
}
if (error < error_limit) {
ray_pos = (float) r;
}
else {
// System.out.println("error = " + error + " itry = " + itry);
ray_pos = Float.NaN;
}
}
} // end (tuple != null)
return ray_pos;
}
/**
* <b>WARNING!</b>
* Do <b>NOT</b> use this routine unless you know what you are doing!
*/
public void removeLink(DataDisplayLink link)
{
final int newLen = Links.length - 1;
if (newLen < 0) {
// give up if the Links array is already empty
return;
}
DataDisplayLink[] newLinks = new DataDisplayLink[newLen];
int n = 0;
for (int i = 0; i <= newLen; i++) {
if (Links[i] == link) {
// skip the specified link
} else {
if (n == newLen) {
// yikes! Obviously didn't find this link in the list!
return;
}
newLinks[n++] = Links[i];
}
}
if (n < newLen) {
// Hmmm ... seem to have removed multiple instances of 'link'!
DataDisplayLink[] newest = new DataDisplayLink[n];
System.arraycopy(newLinks, 0, newest, 0, n);
newLinks = newest;
}
Links = newLinks;
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java
index cf4b59af6..231898398 100644
--- a/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java
+++ b/gdx/src/com/badlogic/gdx/graphics/glutils/ETC1TextureData.java
@@ -1,129 +1,129 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.graphics.glutils;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.TextureData;
import com.badlogic.gdx.graphics.glutils.ETC1.ETC1Data;
import com.badlogic.gdx.utils.GdxRuntimeException;
public class ETC1TextureData implements TextureData {
FileHandle file;
ETC1Data data;
boolean useMipMaps;
int width = 0;
int height = 0;
boolean isPrepared = false;
public ETC1TextureData (FileHandle file) {
this(file, false);
}
public ETC1TextureData (FileHandle file, boolean useMipMaps) {
this.file = file;
this.useMipMaps = useMipMaps;
}
public ETC1TextureData (ETC1Data encodedImage, boolean useMipMaps) {
this.data = encodedImage;
this.useMipMaps = useMipMaps;
}
@Override
public TextureDataType getType () {
return TextureDataType.Compressed;
}
@Override
public boolean isPrepared () {
return isPrepared;
}
@Override
public void prepare () {
if (isPrepared) throw new GdxRuntimeException("Already prepared");
if (file == null && data == null) throw new GdxRuntimeException("Can only load once from ETC1Data");
if (file != null) {
data = new ETC1Data(file);
}
width = data.width;
height = data.height;
isPrepared = true;
}
@Override
public void consumeCompressedData () {
if (!isPrepared) throw new GdxRuntimeException("Call prepare() before calling consumeCompressedData()");
- if (Gdx.app.getType() == ApplicationType.Desktop || Gdx.graphics.isGL20Available() == false) {
+ if (!Gdx.graphics.supportsExtension("GL_OES_compressed_ETC1_RGB8_texture") || Gdx.graphics.isGL20Available() == false) {
Pixmap pixmap = ETC1.decodeImage(data, Format.RGB565);
Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0,
pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels());
if (useMipMaps) MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), false);
pixmap.dispose();
useMipMaps = false;
} else {
Gdx.gl.glCompressedTexImage2D(GL10.GL_TEXTURE_2D, 0, ETC1.ETC1_RGB8_OES, width, height, 0,
data.compressedData.capacity() - data.dataOffset, data.compressedData);
if (useMipMaps()) Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D);
}
data.dispose();
data = null;
isPrepared = false;
}
@Override
public Pixmap consumePixmap () {
throw new GdxRuntimeException("This TextureData implementation does not return a Pixmap");
}
@Override
public boolean disposePixmap () {
throw new GdxRuntimeException("This TextureData implementation does not return a Pixmap");
}
@Override
public int getWidth () {
return width;
}
@Override
public int getHeight () {
return height;
}
@Override
public Format getFormat () {
return Format.RGB565;
}
@Override
public boolean useMipMaps () {
return useMipMaps;
}
@Override
public boolean isManaged () {
return true;
}
}
| true | true | public void consumeCompressedData () {
if (!isPrepared) throw new GdxRuntimeException("Call prepare() before calling consumeCompressedData()");
if (Gdx.app.getType() == ApplicationType.Desktop || Gdx.graphics.isGL20Available() == false) {
Pixmap pixmap = ETC1.decodeImage(data, Format.RGB565);
Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0,
pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels());
if (useMipMaps) MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), false);
pixmap.dispose();
useMipMaps = false;
} else {
Gdx.gl.glCompressedTexImage2D(GL10.GL_TEXTURE_2D, 0, ETC1.ETC1_RGB8_OES, width, height, 0,
data.compressedData.capacity() - data.dataOffset, data.compressedData);
if (useMipMaps()) Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D);
}
data.dispose();
data = null;
isPrepared = false;
}
| public void consumeCompressedData () {
if (!isPrepared) throw new GdxRuntimeException("Call prepare() before calling consumeCompressedData()");
if (!Gdx.graphics.supportsExtension("GL_OES_compressed_ETC1_RGB8_texture") || Gdx.graphics.isGL20Available() == false) {
Pixmap pixmap = ETC1.decodeImage(data, Format.RGB565);
Gdx.gl.glTexImage2D(GL10.GL_TEXTURE_2D, 0, pixmap.getGLInternalFormat(), pixmap.getWidth(), pixmap.getHeight(), 0,
pixmap.getGLFormat(), pixmap.getGLType(), pixmap.getPixels());
if (useMipMaps) MipMapGenerator.generateMipMap(pixmap, pixmap.getWidth(), pixmap.getHeight(), false);
pixmap.dispose();
useMipMaps = false;
} else {
Gdx.gl.glCompressedTexImage2D(GL10.GL_TEXTURE_2D, 0, ETC1.ETC1_RGB8_OES, width, height, 0,
data.compressedData.capacity() - data.dataOffset, data.compressedData);
if (useMipMaps()) Gdx.gl20.glGenerateMipmap(GL20.GL_TEXTURE_2D);
}
data.dispose();
data = null;
isPrepared = false;
}
|
diff --git a/src/com/phodev/andtools/widget/ListViewFixIndicators.java b/src/com/phodev/andtools/widget/ListViewFixIndicators.java
index b0cf12c..e7aab55 100644
--- a/src/com/phodev/andtools/widget/ListViewFixIndicators.java
+++ b/src/com/phodev/andtools/widget/ListViewFixIndicators.java
@@ -1,142 +1,142 @@
package com.phodev.andtools.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* 修改原有setScrollIndicators(up,down)方法,添加精确的可滚动判断
*
* @author sky
*
*/
public class ListViewFixIndicators extends ListView {
public ListViewFixIndicators(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ListViewFixIndicators(Context context) {
super(context);
init();
}
private void init() {
super.setOnScrollListener(innerScrollListener);
}
private View upScrollHintView;
private View downScrollHintView;
private final int[] rootXY = new int[2];
private int rootWindowBottom;
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
post(sysnScrollableTagViewRunnable);
getLocationInWindow(rootXY);
rootWindowBottom = rootXY[1] + getHeight();
}
@Override
public void setScrollIndicators(View up, View down) {
upScrollHintView = up;
downScrollHintView = down;
}
private OnScrollListener mOnScrollListener;
@Override
public void setOnScrollListener(OnScrollListener l) {
mOnScrollListener = l;
}
private OnScrollListener innerScrollListener = new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(view, scrollState);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
syncScrollableTag(firstVisibleItem, visibleItemCount,
totalItemCount);
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(view, firstVisibleItem,
visibleItemCount, totalItemCount);
}
}
};
private int[] itemXY = new int[2];
private void syncScrollableTag(int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (upScrollHintView == null || upScrollHintView == null) {
return;
}
- if (totalItemCount <= visibleItemCount) {
+ if (totalItemCount <= visibleItemCount || totalItemCount <= 0) {
checkVisibility(upScrollHintView, View.INVISIBLE);
checkVisibility(downScrollHintView, View.INVISIBLE);
} else {
if (firstVisibleItem > 0) {
checkVisibility(upScrollHintView, View.VISIBLE);
} else {// check scroll y
getChildAt(0).getLocationOnScreen(itemXY);
if (itemXY[1] < rootXY[1] - getPaddingTop()) {
checkVisibility(upScrollHintView, View.VISIBLE);
} else {
checkVisibility(upScrollHintView, View.INVISIBLE);
}
}
if (firstVisibleItem + visibleItemCount < totalItemCount) {
checkVisibility(downScrollHintView, View.VISIBLE);
} else {// check scroll y
View child = getChildAt(getChildCount() - 1);
child.getLocationOnScreen(itemXY);
//
int childBottom = itemXY[1] + child.getHeight();
//
if (childBottom > rootWindowBottom - getPaddingBottom()) {
checkVisibility(downScrollHintView, View.VISIBLE);
} else {
checkVisibility(downScrollHintView, View.INVISIBLE);
}
}
}
}
private Runnable sysnScrollableTagViewRunnable = new Runnable() {
@Override
public void run() {
int firstVisibleItem;
int visibleItemCount;
int totalItemCount;
ListAdapter ad = getAdapter();
if (ad == null) {
firstVisibleItem = 0;
visibleItemCount = 0;
totalItemCount = 0;
} else {
firstVisibleItem = getFirstVisiblePosition();
visibleItemCount = getLastVisiblePosition() - firstVisibleItem;
totalItemCount = ad.getCount();
}
syncScrollableTag(firstVisibleItem, visibleItemCount,
totalItemCount);
}
};
private void checkVisibility(View v, int visibility) {
if (v != null && v.getVisibility() != visibility) {
v.setVisibility(visibility);
}
}
}
| true | true | private void syncScrollableTag(int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (upScrollHintView == null || upScrollHintView == null) {
return;
}
if (totalItemCount <= visibleItemCount) {
checkVisibility(upScrollHintView, View.INVISIBLE);
checkVisibility(downScrollHintView, View.INVISIBLE);
} else {
if (firstVisibleItem > 0) {
checkVisibility(upScrollHintView, View.VISIBLE);
} else {// check scroll y
getChildAt(0).getLocationOnScreen(itemXY);
if (itemXY[1] < rootXY[1] - getPaddingTop()) {
checkVisibility(upScrollHintView, View.VISIBLE);
} else {
checkVisibility(upScrollHintView, View.INVISIBLE);
}
}
if (firstVisibleItem + visibleItemCount < totalItemCount) {
checkVisibility(downScrollHintView, View.VISIBLE);
} else {// check scroll y
View child = getChildAt(getChildCount() - 1);
child.getLocationOnScreen(itemXY);
//
int childBottom = itemXY[1] + child.getHeight();
//
if (childBottom > rootWindowBottom - getPaddingBottom()) {
checkVisibility(downScrollHintView, View.VISIBLE);
} else {
checkVisibility(downScrollHintView, View.INVISIBLE);
}
}
}
}
| private void syncScrollableTag(int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (upScrollHintView == null || upScrollHintView == null) {
return;
}
if (totalItemCount <= visibleItemCount || totalItemCount <= 0) {
checkVisibility(upScrollHintView, View.INVISIBLE);
checkVisibility(downScrollHintView, View.INVISIBLE);
} else {
if (firstVisibleItem > 0) {
checkVisibility(upScrollHintView, View.VISIBLE);
} else {// check scroll y
getChildAt(0).getLocationOnScreen(itemXY);
if (itemXY[1] < rootXY[1] - getPaddingTop()) {
checkVisibility(upScrollHintView, View.VISIBLE);
} else {
checkVisibility(upScrollHintView, View.INVISIBLE);
}
}
if (firstVisibleItem + visibleItemCount < totalItemCount) {
checkVisibility(downScrollHintView, View.VISIBLE);
} else {// check scroll y
View child = getChildAt(getChildCount() - 1);
child.getLocationOnScreen(itemXY);
//
int childBottom = itemXY[1] + child.getHeight();
//
if (childBottom > rootWindowBottom - getPaddingBottom()) {
checkVisibility(downScrollHintView, View.VISIBLE);
} else {
checkVisibility(downScrollHintView, View.INVISIBLE);
}
}
}
}
|
diff --git a/src/com/jetbrains/crucible/actions/AddCommentAction.java b/src/com/jetbrains/crucible/actions/AddCommentAction.java
index 5e98b3d..4b2b820 100644
--- a/src/com/jetbrains/crucible/actions/AddCommentAction.java
+++ b/src/com/jetbrains/crucible/actions/AddCommentAction.java
@@ -1,154 +1,153 @@
package com.jetbrains.crucible.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupAdapter;
import com.intellij.openapi.ui.popup.LightweightWindowEvent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.ui.AnActionButton;
import com.intellij.ui.table.JBTable;
import com.intellij.util.PlatformIcons;
import com.jetbrains.crucible.model.Comment;
import com.jetbrains.crucible.model.Review;
import com.jetbrains.crucible.ui.toolWindow.details.*;
import com.jetbrains.crucible.ui.toolWindow.diff.ReviewGutterIconRenderer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.tree.*;
/**
* User: ktisha
* <p/>
* Reply to comment
*/
@SuppressWarnings("ComponentNotRegistered")
public class AddCommentAction extends AnActionButton implements DumbAware {
private final Editor myEditor;
private final VirtualFile myVirtualFile;
private final String myName;
private final Review myReview;
private final boolean myIsReply;
public AddCommentAction(@NotNull final Review review, @Nullable final Editor editor,
@Nullable final VirtualFile vFile, @NotNull final String description,
@NotNull final String name, boolean isReply) {
super(description, description, PlatformIcons.EDIT_IN_SECTION_ICON);
myIsReply = isReply;
myReview = review;
myEditor = editor;
myVirtualFile = vFile;
myName = name;
}
public void actionPerformed(AnActionEvent e) {
final Project project = e.getData(PlatformDataKeys.PROJECT);
if (project == null) return;
final ToolWindow toolWindow = e.getData(PlatformDataKeys.TOOL_WINDOW);
if (toolWindow != null) {
addGeneralComment(project, toolWindow);
}
else {
addVersionedComment(project);
}
}
private void addGeneralComment(@NotNull final Project project, @NotNull final ToolWindow toolWindow) {
final CommentBalloonBuilder builder = new CommentBalloonBuilder();
final CommentForm commentForm = new CommentForm(project, myName, true, myIsReply);
commentForm.setReview(myReview);
if (myIsReply) {
final JBTable contextComponent = (JBTable)getContextComponent();
final int selectedRow = contextComponent.getSelectedRow();
if (selectedRow >= 0) {
final Object parentComment = contextComponent.getValueAt(selectedRow, 0);
if (parentComment instanceof Comment) {
commentForm.setParentComment(((Comment)parentComment));
}
}
}
final Balloon balloon = builder.getNewCommentBalloon(commentForm);
balloon.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
final JComponent component = getContextComponent();
if (component instanceof CommentsTreeTable) {
((CommentsTreeTable)component).updateModel(commentForm.getReview());
}
}
});
commentForm.setBalloon(balloon);
balloon.showInCenterOf(toolWindow.getComponent());
commentForm.requestFocus();
}
private void addVersionedComment(@NotNull final Project project) {
if (myEditor == null || myVirtualFile == null) return;
final CommentBalloonBuilder builder = new CommentBalloonBuilder();
final CommentForm commentForm = new CommentForm(project, myName, false, myIsReply);
commentForm.setReview(myReview);
final JComponent contextComponent = getContextComponent();
if (myIsReply && contextComponent instanceof CommentsTree) {
final Object selected = ((CommentsTree)contextComponent).getLastSelectedPathComponent();
if (selected instanceof DefaultMutableTreeNode) {
Object userObject = ((DefaultMutableTreeNode)selected).getUserObject();
if (userObject instanceof CommentNode) {
final Comment comment = ((CommentNode)userObject).getComment();
commentForm.setParentComment(comment);
}
}
}
commentForm.setEditor(myEditor);
commentForm.setVirtualFile(myVirtualFile);
final Balloon balloon = builder.getNewCommentBalloon(commentForm);
balloon.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
+ final Comment comment = commentForm.getComment();
if (!myIsReply) {
final MarkupModel markup = myEditor.getMarkupModel();
- final Comment comment = commentForm.getComment();
if (comment != null) {
final RangeHighlighter highlighter = markup.addLineHighlighter(Integer.parseInt(comment.getLine()),
HighlighterLayer.ERROR + 1, null);
final ReviewGutterIconRenderer gutterIconRenderer =
new ReviewGutterIconRenderer(myReview, myVirtualFile, comment);
highlighter.setGutterIconRenderer(gutterIconRenderer);
}
}
else {
final JComponent contextComponent = getContextComponent();
if (contextComponent instanceof CommentsTree) {
final TreePath selectionPath = ((JTree)contextComponent).getSelectionPath();
final Object component = selectionPath.getLastPathComponent();
- if (component instanceof DefaultMutableTreeNode){
- ((DefaultMutableTreeNode)component).add(
- new DefaultMutableTreeNode(new CommentNode(commentForm.getComment())));
+ if (component instanceof DefaultMutableTreeNode && comment != null ){
+ ((DefaultMutableTreeNode)component).add( new DefaultMutableTreeNode(new CommentNode(comment)));
final TreeModel model = ((JTree)contextComponent).getModel();
if (model instanceof DefaultTreeModel) {
((DefaultTreeModel)model).reload();
}
}
}
}
}
});
commentForm.setBalloon(balloon);
balloon.showInCenterOf(contextComponent);
commentForm.requestFocus();
}
}
| false | true | private void addVersionedComment(@NotNull final Project project) {
if (myEditor == null || myVirtualFile == null) return;
final CommentBalloonBuilder builder = new CommentBalloonBuilder();
final CommentForm commentForm = new CommentForm(project, myName, false, myIsReply);
commentForm.setReview(myReview);
final JComponent contextComponent = getContextComponent();
if (myIsReply && contextComponent instanceof CommentsTree) {
final Object selected = ((CommentsTree)contextComponent).getLastSelectedPathComponent();
if (selected instanceof DefaultMutableTreeNode) {
Object userObject = ((DefaultMutableTreeNode)selected).getUserObject();
if (userObject instanceof CommentNode) {
final Comment comment = ((CommentNode)userObject).getComment();
commentForm.setParentComment(comment);
}
}
}
commentForm.setEditor(myEditor);
commentForm.setVirtualFile(myVirtualFile);
final Balloon balloon = builder.getNewCommentBalloon(commentForm);
balloon.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
if (!myIsReply) {
final MarkupModel markup = myEditor.getMarkupModel();
final Comment comment = commentForm.getComment();
if (comment != null) {
final RangeHighlighter highlighter = markup.addLineHighlighter(Integer.parseInt(comment.getLine()),
HighlighterLayer.ERROR + 1, null);
final ReviewGutterIconRenderer gutterIconRenderer =
new ReviewGutterIconRenderer(myReview, myVirtualFile, comment);
highlighter.setGutterIconRenderer(gutterIconRenderer);
}
}
else {
final JComponent contextComponent = getContextComponent();
if (contextComponent instanceof CommentsTree) {
final TreePath selectionPath = ((JTree)contextComponent).getSelectionPath();
final Object component = selectionPath.getLastPathComponent();
if (component instanceof DefaultMutableTreeNode){
((DefaultMutableTreeNode)component).add(
new DefaultMutableTreeNode(new CommentNode(commentForm.getComment())));
final TreeModel model = ((JTree)contextComponent).getModel();
if (model instanceof DefaultTreeModel) {
((DefaultTreeModel)model).reload();
}
}
}
}
}
});
commentForm.setBalloon(balloon);
balloon.showInCenterOf(contextComponent);
commentForm.requestFocus();
}
| private void addVersionedComment(@NotNull final Project project) {
if (myEditor == null || myVirtualFile == null) return;
final CommentBalloonBuilder builder = new CommentBalloonBuilder();
final CommentForm commentForm = new CommentForm(project, myName, false, myIsReply);
commentForm.setReview(myReview);
final JComponent contextComponent = getContextComponent();
if (myIsReply && contextComponent instanceof CommentsTree) {
final Object selected = ((CommentsTree)contextComponent).getLastSelectedPathComponent();
if (selected instanceof DefaultMutableTreeNode) {
Object userObject = ((DefaultMutableTreeNode)selected).getUserObject();
if (userObject instanceof CommentNode) {
final Comment comment = ((CommentNode)userObject).getComment();
commentForm.setParentComment(comment);
}
}
}
commentForm.setEditor(myEditor);
commentForm.setVirtualFile(myVirtualFile);
final Balloon balloon = builder.getNewCommentBalloon(commentForm);
balloon.addListener(new JBPopupAdapter() {
@Override
public void onClosed(LightweightWindowEvent event) {
final Comment comment = commentForm.getComment();
if (!myIsReply) {
final MarkupModel markup = myEditor.getMarkupModel();
if (comment != null) {
final RangeHighlighter highlighter = markup.addLineHighlighter(Integer.parseInt(comment.getLine()),
HighlighterLayer.ERROR + 1, null);
final ReviewGutterIconRenderer gutterIconRenderer =
new ReviewGutterIconRenderer(myReview, myVirtualFile, comment);
highlighter.setGutterIconRenderer(gutterIconRenderer);
}
}
else {
final JComponent contextComponent = getContextComponent();
if (contextComponent instanceof CommentsTree) {
final TreePath selectionPath = ((JTree)contextComponent).getSelectionPath();
final Object component = selectionPath.getLastPathComponent();
if (component instanceof DefaultMutableTreeNode && comment != null ){
((DefaultMutableTreeNode)component).add( new DefaultMutableTreeNode(new CommentNode(comment)));
final TreeModel model = ((JTree)contextComponent).getModel();
if (model instanceof DefaultTreeModel) {
((DefaultTreeModel)model).reload();
}
}
}
}
}
});
commentForm.setBalloon(balloon);
balloon.showInCenterOf(contextComponent);
commentForm.requestFocus();
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java
index 793b81bff..eec7b0b01 100644
--- a/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/transport/tcp/SslTransportFactoryTest.java
@@ -1,154 +1,154 @@
/**
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport.tcp;
import junit.framework.TestCase;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class SslTransportFactoryTest extends TestCase {
private static final transient Log log = LogFactory.getLog(SslTransportFactoryTest.class);
private SslTransportFactory factory;
private boolean verbose;
protected void setUp() throws Exception {
factory = new SslTransportFactory();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public void testBindServerOptions() throws IOException {
SslTransportServer sslTransportServer = null;
for (int i = 0; i < 4; ++i) {
final boolean wantClientAuth = ((i & 0x1) == 1);
final boolean needClientAuth = ((i & 0x2) == 1);
String options = "wantClientAuth=" + (wantClientAuth ? "true" : "false") +
"&needClientAuth=" + (needClientAuth ? "true" : "false");
try {
sslTransportServer = (SslTransportServer)
factory.doBind("brokerId", new URI("ssl://localhost:61616?" + options));
}
catch (Exception e) {
fail("Unable to bind to address: " + e.getMessage());
}
assertEquals("Created ServerSocket did not have correct wantClientAuth status.",
sslTransportServer.getWantClientAuth(), wantClientAuth);
assertEquals("Created ServerSocket did not have correct needClientAuth status.",
sslTransportServer.getNeedClientAuth(), needClientAuth);
try {
sslTransportServer.stop();
}
catch (Exception e) {
fail("Unable to stop TransportServer: " + e.getMessage());
}
}
}
private int getMthNaryDigit(int number, int digitIdx, int numBase) {
return (number / ((int) Math.pow(numBase, digitIdx))) % numBase;
}
public void testCompositeConfigure() throws IOException {
// The 5 options being tested.
int optionSettings[] = new int[5];
String optionNames[] = {
"wantClientAuth",
"needClientAuth",
"socket.wantClientAuth",
"socket.needClientAuth",
"socket.useClientMode"
};
// Using a trinary interpretation of i to set all possible values of stub options for socket and transport.
// 2 transport options, 3 socket options, 3 settings for each option => 3^5 = 243 combos.
for (int i = 0; i < 243; ++i) {
Map options = new HashMap();
for (int j = 0; j < 5; ++j) {
// -1 since the option range is [-1,1], not [0,2].
optionSettings[j] = getMthNaryDigit(i, j, 3) - 1;
if (optionSettings[j] != -1) {
options.put(optionNames[j], (optionSettings[j] == 1 ? "true" : "false"));
}
}
StubSSLSocket socketStub = new StubSSLSocket(null);
StubSslTransport transport = null;
try {
transport = new StubSslTransport(null, socketStub);
}
catch (Exception e) {
fail("Unable to create StubSslTransport: " + e.getMessage());
}
if (verbose) {
- log.info();
+ log.info("");
log.info("Iteration: " + i);
log.info("Map settings: " + options);
for (int x = 0; x < optionSettings.length; x++) {
log.info("optionSetting[" + x + "] = " + optionSettings[x]);
}
}
factory.compositeConfigure(transport, new OpenWireFormat(), options);
// lets start the transport to force the introspection
try {
transport.start();
}
catch (Exception e) {
// ignore bad connection
}
if (socketStub.getWantClientAuthStatus() != optionSettings[2]) {
log.info("sheiite");
}
assertEquals("wantClientAuth was not properly set for iteration: " + i,
optionSettings[0], transport.getWantClientAuthStatus());
assertEquals("needClientAuth was not properly set for iteration: " + i,
optionSettings[1], transport.getNeedClientAuthStatus());
assertEquals("socket.wantClientAuth was not properly set for iteration: " + i,
optionSettings[2], socketStub.getWantClientAuthStatus());
assertEquals("socket.needClientAuth was not properly set for iteration: " + i,
optionSettings[3], socketStub.getNeedClientAuthStatus());
assertEquals("socket.useClientMode was not properly set for iteration: " + i,
optionSettings[4], socketStub.getUseClientModeStatus());
}
}
}
| true | true | public void testCompositeConfigure() throws IOException {
// The 5 options being tested.
int optionSettings[] = new int[5];
String optionNames[] = {
"wantClientAuth",
"needClientAuth",
"socket.wantClientAuth",
"socket.needClientAuth",
"socket.useClientMode"
};
// Using a trinary interpretation of i to set all possible values of stub options for socket and transport.
// 2 transport options, 3 socket options, 3 settings for each option => 3^5 = 243 combos.
for (int i = 0; i < 243; ++i) {
Map options = new HashMap();
for (int j = 0; j < 5; ++j) {
// -1 since the option range is [-1,1], not [0,2].
optionSettings[j] = getMthNaryDigit(i, j, 3) - 1;
if (optionSettings[j] != -1) {
options.put(optionNames[j], (optionSettings[j] == 1 ? "true" : "false"));
}
}
StubSSLSocket socketStub = new StubSSLSocket(null);
StubSslTransport transport = null;
try {
transport = new StubSslTransport(null, socketStub);
}
catch (Exception e) {
fail("Unable to create StubSslTransport: " + e.getMessage());
}
if (verbose) {
log.info();
log.info("Iteration: " + i);
log.info("Map settings: " + options);
for (int x = 0; x < optionSettings.length; x++) {
log.info("optionSetting[" + x + "] = " + optionSettings[x]);
}
}
factory.compositeConfigure(transport, new OpenWireFormat(), options);
// lets start the transport to force the introspection
try {
transport.start();
}
catch (Exception e) {
// ignore bad connection
}
if (socketStub.getWantClientAuthStatus() != optionSettings[2]) {
log.info("sheiite");
}
assertEquals("wantClientAuth was not properly set for iteration: " + i,
optionSettings[0], transport.getWantClientAuthStatus());
assertEquals("needClientAuth was not properly set for iteration: " + i,
optionSettings[1], transport.getNeedClientAuthStatus());
assertEquals("socket.wantClientAuth was not properly set for iteration: " + i,
optionSettings[2], socketStub.getWantClientAuthStatus());
assertEquals("socket.needClientAuth was not properly set for iteration: " + i,
optionSettings[3], socketStub.getNeedClientAuthStatus());
assertEquals("socket.useClientMode was not properly set for iteration: " + i,
optionSettings[4], socketStub.getUseClientModeStatus());
}
}
| public void testCompositeConfigure() throws IOException {
// The 5 options being tested.
int optionSettings[] = new int[5];
String optionNames[] = {
"wantClientAuth",
"needClientAuth",
"socket.wantClientAuth",
"socket.needClientAuth",
"socket.useClientMode"
};
// Using a trinary interpretation of i to set all possible values of stub options for socket and transport.
// 2 transport options, 3 socket options, 3 settings for each option => 3^5 = 243 combos.
for (int i = 0; i < 243; ++i) {
Map options = new HashMap();
for (int j = 0; j < 5; ++j) {
// -1 since the option range is [-1,1], not [0,2].
optionSettings[j] = getMthNaryDigit(i, j, 3) - 1;
if (optionSettings[j] != -1) {
options.put(optionNames[j], (optionSettings[j] == 1 ? "true" : "false"));
}
}
StubSSLSocket socketStub = new StubSSLSocket(null);
StubSslTransport transport = null;
try {
transport = new StubSslTransport(null, socketStub);
}
catch (Exception e) {
fail("Unable to create StubSslTransport: " + e.getMessage());
}
if (verbose) {
log.info("");
log.info("Iteration: " + i);
log.info("Map settings: " + options);
for (int x = 0; x < optionSettings.length; x++) {
log.info("optionSetting[" + x + "] = " + optionSettings[x]);
}
}
factory.compositeConfigure(transport, new OpenWireFormat(), options);
// lets start the transport to force the introspection
try {
transport.start();
}
catch (Exception e) {
// ignore bad connection
}
if (socketStub.getWantClientAuthStatus() != optionSettings[2]) {
log.info("sheiite");
}
assertEquals("wantClientAuth was not properly set for iteration: " + i,
optionSettings[0], transport.getWantClientAuthStatus());
assertEquals("needClientAuth was not properly set for iteration: " + i,
optionSettings[1], transport.getNeedClientAuthStatus());
assertEquals("socket.wantClientAuth was not properly set for iteration: " + i,
optionSettings[2], socketStub.getWantClientAuthStatus());
assertEquals("socket.needClientAuth was not properly set for iteration: " + i,
optionSettings[3], socketStub.getNeedClientAuthStatus());
assertEquals("socket.useClientMode was not properly set for iteration: " + i,
optionSettings[4], socketStub.getUseClientModeStatus());
}
}
|
diff --git a/src/com/atlauncher/data/Downloadable.java b/src/com/atlauncher/data/Downloadable.java
index 09ff7e14..a9970f5c 100644
--- a/src/com/atlauncher/data/Downloadable.java
+++ b/src/com/atlauncher/data/Downloadable.java
@@ -1,449 +1,449 @@
/**
* Copyright 2013 by ATLauncher and Contributors
*
* This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/.
*/
package com.atlauncher.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import com.atlauncher.App;
import com.atlauncher.utils.Utils;
import com.atlauncher.workers.InstanceInstaller;
public class Downloadable {
private String beforeURL;
private String url;
private File file;
private File oldFile;
private String hash;
private int size;
private HttpURLConnection connection;
private InstanceInstaller instanceInstaller;
private boolean isATLauncherDownload;
private File copyTo;
private boolean actuallyCopy;
private int attempts = 0;
public Downloadable(String url, File file, String hash, int size,
InstanceInstaller instanceInstaller, boolean isATLauncherDownload, File copyTo,
boolean actuallyCopy) {
if (isATLauncherDownload) {
this.url = App.settings.getFileURL(url);
} else {
this.url = url;
}
this.beforeURL = url;
this.file = file;
this.hash = hash;
this.size = size;
this.instanceInstaller = instanceInstaller;
this.isATLauncherDownload = isATLauncherDownload;
this.copyTo = copyTo;
this.actuallyCopy = actuallyCopy;
}
public Downloadable(String url, File file, String hash, int size,
InstanceInstaller instanceInstaller, boolean isATLauncherDownload) {
this(url, file, hash, size, instanceInstaller, isATLauncherDownload, null, false);
}
public Downloadable(String url, File file, String hash, InstanceInstaller instanceInstaller,
boolean isATLauncherDownload) {
this(url, file, hash, -1, instanceInstaller, isATLauncherDownload, null, false);
}
public Downloadable(String url, boolean isATLauncherDownload) {
this(url, null, null, -1, null, isATLauncherDownload, null, false);
}
public String getFilename() {
if (this.copyTo == null) {
return this.file.getName();
}
return this.copyTo.getName();
}
public boolean isMD5() {
if (hash == null) {
return true;
}
if (hash.length() == 40) {
return false;
}
return true;
}
public String getHashFromURL() throws IOException {
String etag = null;
etag = getConnection().getHeaderField("ETag");
if (etag == null) {
etag = getConnection().getHeaderField("ATLauncher-MD5");
}
if (etag == null) {
return "-";
}
if ((etag.startsWith("\"")) && (etag.endsWith("\""))) {
etag = etag.substring(1, etag.length() - 1);
}
if (etag.matches("[A-Za-z0-9]{32}")) {
return etag;
} else {
return "-";
}
}
public int getFilesize() {
if (this.size == -1) {
int size = getConnection().getContentLength();
if (size == -1) {
this.size = 0;
} else {
this.size = size;
}
}
return this.size;
}
public boolean needToDownload() {
if (this.file == null) {
return true;
}
if (this.file.exists()) {
if (isMD5()) {
if (Utils.getMD5(this.file).equalsIgnoreCase(getHash())) {
return false;
}
} else {
if (Utils.getSHA1(this.file).equalsIgnoreCase(getHash())) {
return false;
}
}
}
return true;
}
public void copyFile() {
if (this.copyTo != null && this.actuallyCopy) {
if (this.copyTo.exists()) {
Utils.delete(this.copyTo);
}
new File(this.copyTo.getAbsolutePath().substring(0,
this.copyTo.getAbsolutePath().lastIndexOf(File.separatorChar))).mkdirs();
Utils.copyFile(this.file, this.copyTo, true);
}
}
public String getHash() {
if (this.hash == null || this.hash.isEmpty()) {
try {
this.hash = getHashFromURL();
} catch (IOException e) {
App.settings.logStackTrace(e);
this.hash = "-";
this.connection = null;
}
}
return this.hash;
}
public File getFile() {
return this.file;
}
public File getCopyToFile() {
return this.copyTo;
}
public boolean isGziped() {
if (getConnection().getContentEncoding() == null) {
return false;
} else if (getConnection().getContentEncoding().equalsIgnoreCase("gzip")) {
return true;
} else {
return false;
}
}
private HttpURLConnection getConnection() {
if (this.instanceInstaller != null) {
if (this.instanceInstaller.isCancelled()) {
return null;
}
}
if (this.connection == null) {
try {
this.connection = (HttpURLConnection) new URL(this.url).openConnection();
this.connection.setUseCaches(false);
this.connection.setDefaultUseCaches(false);
this.connection.setConnectTimeout(5000);
this.connection.setRequestProperty("Accept-Encoding", "gzip");
this.connection.setRequestProperty("User-Agent", App.settings.getUserAgent());
this.connection.setRequestProperty("Auth-Key", App.settings.getAuthKey());
this.connection.setRequestProperty("Cache-Control", "no-store,max-age=0,no-cache");
this.connection.setRequestProperty("Expires", "0");
this.connection.setRequestProperty("Pragma", "no-cache");
this.connection.connect();
if (this.connection.getResponseCode() / 100 != 2) {
if (this.connection.getResponseCode() == 401 && this.isATLauncherDownload) {
App.settings
.log(this.url
+ " returned response code "
+ this.connection.getResponseCode()
+ (this.connection.getResponseMessage() != null ? " with message of "
+ this.connection.getResponseMessage()
: "") + " and auth key error of "
+ this.connection.getHeaderField("Auth-Key-Error"),
LogMessageType.error, false);
if (App.settings.checkAuthKey()) {
this.connection = null; // Clear the connection
return this.getConnection(); // Try getting it again
} else {
if (this.instanceInstaller != null) {
this.instanceInstaller.cancel(true);
}
return null;
}
}
throw new IOException(this.url
+ " returned response code "
+ this.connection.getResponseCode()
+ (this.connection.getResponseMessage() != null ? " with message of "
+ this.connection.getResponseMessage() : ""));
}
} catch (IOException e) {
App.settings.logStackTrace(e);
if (this.isATLauncherDownload) {
if (App.settings.getNextServer()) {
this.url = App.settings.getFileURL(this.beforeURL);
this.connection = null;
return getConnection();
} else {
App.settings.log("Failed to download " + this.beforeURL
+ " from all ATLauncher servers. Cancelling install!",
LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
}
}
}
return this.connection;
}
private void downloadFile(boolean downloadAsLibrary) {
if (instanceInstaller != null) {
if (instanceInstaller.isCancelled()) {
return;
}
}
InputStream in = null;
FileOutputStream writer = null;
try {
if (isGziped()) {
in = new GZIPInputStream(getConnection().getInputStream());
} else {
in = getConnection().getInputStream();
}
writer = new FileOutputStream(this.file);
byte[] buffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = in.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
buffer = new byte[2048];
if (this.instanceInstaller != null && downloadAsLibrary && getFilesize() != 0) {
this.instanceInstaller.addDownloadedBytes(bytesRead);
}
}
} catch (SocketException e) {
// Connection reset. Close connection and try again
App.settings.logStackTrace(e);
this.connection.disconnect();
this.connection = null;
} catch (IOException e) {
App.settings.logStackTrace(e);
} finally {
try {
if (writer != null) {
writer.close();
}
if (in != null) {
in.close();
}
} catch (IOException e1) {
App.settings.logStackTrace(e1);
}
}
}
public String getContents() {
if (instanceInstaller != null) {
if (instanceInstaller.isCancelled()) {
return null;
}
}
StringBuilder response = null;
try {
InputStream in = null;
if (isGziped()) {
in = new GZIPInputStream(getConnection().getInputStream());
} else {
in = getConnection().getInputStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in));
response = new StringBuilder();
String inputLine;
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
App.settings.logStackTrace(e);
return null;
}
this.connection.disconnect();
return response.toString();
}
public void download(boolean downloadAsLibrary) {
download(downloadAsLibrary, false);
}
public void download(boolean downloadAsLibrary, boolean force) {
this.attempts = 0;
if (this.connection != null) {
this.connection.disconnect();
this.connection = null;
}
if (this.file == null) {
App.settings.log("Cannot download " + this.url + " to file as one wasn't specified!",
LogMessageType.error, false);
return;
}
if (this.file.exists()) {
this.oldFile = new File(this.file.getParent(), this.file.getName() + ".bak");
Utils.moveFile(this.file, this.oldFile, true);
}
if (instanceInstaller != null) {
if (instanceInstaller.isCancelled()) {
return;
}
}
if (!this.file.canWrite()) {
Utils.delete(this.file);
}
if (this.file.exists() && this.file.isFile()) {
Utils.delete(this.file);
}
// Create the directory structure
new File(this.file.getAbsolutePath().substring(0,
this.file.getAbsolutePath().lastIndexOf(File.separatorChar))).mkdirs();
if (getHash().equalsIgnoreCase("-")) {
downloadFile(downloadAsLibrary); // Only download the file once since we have no MD5 to
// check
} else {
String fileHash = "0";
boolean done = false;
while (attempts <= 3) {
attempts++;
if (this.file.exists()) {
if (isMD5()) {
fileHash = Utils.getMD5(this.file);
} else {
fileHash = Utils.getSHA1(this.file);
}
} else {
fileHash = "0";
}
if (fileHash.equalsIgnoreCase(getHash())) {
done = true;
break; // Hash matches, file is good
}
if (this.connection != null) {
this.connection.disconnect();
this.connection = null;
}
if (this.file.exists()) {
Utils.delete(this.file); // Delete file since it doesn't match MD5
}
downloadFile(downloadAsLibrary); // Keep downloading file until it matches MD5
}
if (done) {
- if (this.oldFile.exists()) {
+ if (this.oldFile!=null && this.oldFile.exists()) {
Utils.delete(this.oldFile);
}
}
if (!done) {
- if (this.oldFile.exists()) {
+ if (this.oldFile!=null && this.oldFile.exists()) {
Utils.moveFile(this.oldFile, this.file, true);
}
if (this.isATLauncherDownload) {
if (App.settings.getNextServer()) {
App.settings.log("Error downloading " + this.file.getName() + " from "
+ this.url + ". Expected hash of " + getHash() + " but got "
+ fileHash + " instead. Trying another server!",
LogMessageType.warning, false);
this.url = App.settings.getFileURL(this.beforeURL);
download(downloadAsLibrary); // Redownload the file
} else {
App.settings.log("Failed to download file " + this.file.getName()
+ " from all ATLauncher servers. Cancelling install!",
LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
} else {
App.settings.log("Error downloading " + this.file.getName() + " from "
+ this.url + ". Expected hash of " + getHash() + " but got " + fileHash
+ " instead. Cancelling install!", LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
} else if (this.copyTo != null && this.actuallyCopy) {
String fileHash2;
if (this.copyTo.exists()) {
if (isMD5()) {
fileHash2 = Utils.getMD5(this.file);
} else {
fileHash2 = Utils.getSHA1(this.file);
}
} else {
fileHash2 = "0";
}
if (!fileHash2.equalsIgnoreCase(getHash())) {
if (this.copyTo.exists()) {
Utils.delete(this.copyTo);
}
new File(this.copyTo.getAbsolutePath().substring(0,
this.copyTo.getAbsolutePath().lastIndexOf(File.separatorChar)))
.mkdirs();
Utils.copyFile(this.file, this.copyTo, true);
}
}
App.settings.clearTriedServers(); // Okay downloaded it so clear the servers used
}
if (this.connection != null) {
this.connection.disconnect();
}
}
}
| false | true | public void download(boolean downloadAsLibrary, boolean force) {
this.attempts = 0;
if (this.connection != null) {
this.connection.disconnect();
this.connection = null;
}
if (this.file == null) {
App.settings.log("Cannot download " + this.url + " to file as one wasn't specified!",
LogMessageType.error, false);
return;
}
if (this.file.exists()) {
this.oldFile = new File(this.file.getParent(), this.file.getName() + ".bak");
Utils.moveFile(this.file, this.oldFile, true);
}
if (instanceInstaller != null) {
if (instanceInstaller.isCancelled()) {
return;
}
}
if (!this.file.canWrite()) {
Utils.delete(this.file);
}
if (this.file.exists() && this.file.isFile()) {
Utils.delete(this.file);
}
// Create the directory structure
new File(this.file.getAbsolutePath().substring(0,
this.file.getAbsolutePath().lastIndexOf(File.separatorChar))).mkdirs();
if (getHash().equalsIgnoreCase("-")) {
downloadFile(downloadAsLibrary); // Only download the file once since we have no MD5 to
// check
} else {
String fileHash = "0";
boolean done = false;
while (attempts <= 3) {
attempts++;
if (this.file.exists()) {
if (isMD5()) {
fileHash = Utils.getMD5(this.file);
} else {
fileHash = Utils.getSHA1(this.file);
}
} else {
fileHash = "0";
}
if (fileHash.equalsIgnoreCase(getHash())) {
done = true;
break; // Hash matches, file is good
}
if (this.connection != null) {
this.connection.disconnect();
this.connection = null;
}
if (this.file.exists()) {
Utils.delete(this.file); // Delete file since it doesn't match MD5
}
downloadFile(downloadAsLibrary); // Keep downloading file until it matches MD5
}
if (done) {
if (this.oldFile.exists()) {
Utils.delete(this.oldFile);
}
}
if (!done) {
if (this.oldFile.exists()) {
Utils.moveFile(this.oldFile, this.file, true);
}
if (this.isATLauncherDownload) {
if (App.settings.getNextServer()) {
App.settings.log("Error downloading " + this.file.getName() + " from "
+ this.url + ". Expected hash of " + getHash() + " but got "
+ fileHash + " instead. Trying another server!",
LogMessageType.warning, false);
this.url = App.settings.getFileURL(this.beforeURL);
download(downloadAsLibrary); // Redownload the file
} else {
App.settings.log("Failed to download file " + this.file.getName()
+ " from all ATLauncher servers. Cancelling install!",
LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
} else {
App.settings.log("Error downloading " + this.file.getName() + " from "
+ this.url + ". Expected hash of " + getHash() + " but got " + fileHash
+ " instead. Cancelling install!", LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
} else if (this.copyTo != null && this.actuallyCopy) {
String fileHash2;
if (this.copyTo.exists()) {
if (isMD5()) {
fileHash2 = Utils.getMD5(this.file);
} else {
fileHash2 = Utils.getSHA1(this.file);
}
} else {
fileHash2 = "0";
}
if (!fileHash2.equalsIgnoreCase(getHash())) {
if (this.copyTo.exists()) {
Utils.delete(this.copyTo);
}
new File(this.copyTo.getAbsolutePath().substring(0,
this.copyTo.getAbsolutePath().lastIndexOf(File.separatorChar)))
.mkdirs();
Utils.copyFile(this.file, this.copyTo, true);
}
}
App.settings.clearTriedServers(); // Okay downloaded it so clear the servers used
}
if (this.connection != null) {
this.connection.disconnect();
}
}
| public void download(boolean downloadAsLibrary, boolean force) {
this.attempts = 0;
if (this.connection != null) {
this.connection.disconnect();
this.connection = null;
}
if (this.file == null) {
App.settings.log("Cannot download " + this.url + " to file as one wasn't specified!",
LogMessageType.error, false);
return;
}
if (this.file.exists()) {
this.oldFile = new File(this.file.getParent(), this.file.getName() + ".bak");
Utils.moveFile(this.file, this.oldFile, true);
}
if (instanceInstaller != null) {
if (instanceInstaller.isCancelled()) {
return;
}
}
if (!this.file.canWrite()) {
Utils.delete(this.file);
}
if (this.file.exists() && this.file.isFile()) {
Utils.delete(this.file);
}
// Create the directory structure
new File(this.file.getAbsolutePath().substring(0,
this.file.getAbsolutePath().lastIndexOf(File.separatorChar))).mkdirs();
if (getHash().equalsIgnoreCase("-")) {
downloadFile(downloadAsLibrary); // Only download the file once since we have no MD5 to
// check
} else {
String fileHash = "0";
boolean done = false;
while (attempts <= 3) {
attempts++;
if (this.file.exists()) {
if (isMD5()) {
fileHash = Utils.getMD5(this.file);
} else {
fileHash = Utils.getSHA1(this.file);
}
} else {
fileHash = "0";
}
if (fileHash.equalsIgnoreCase(getHash())) {
done = true;
break; // Hash matches, file is good
}
if (this.connection != null) {
this.connection.disconnect();
this.connection = null;
}
if (this.file.exists()) {
Utils.delete(this.file); // Delete file since it doesn't match MD5
}
downloadFile(downloadAsLibrary); // Keep downloading file until it matches MD5
}
if (done) {
if (this.oldFile!=null && this.oldFile.exists()) {
Utils.delete(this.oldFile);
}
}
if (!done) {
if (this.oldFile!=null && this.oldFile.exists()) {
Utils.moveFile(this.oldFile, this.file, true);
}
if (this.isATLauncherDownload) {
if (App.settings.getNextServer()) {
App.settings.log("Error downloading " + this.file.getName() + " from "
+ this.url + ". Expected hash of " + getHash() + " but got "
+ fileHash + " instead. Trying another server!",
LogMessageType.warning, false);
this.url = App.settings.getFileURL(this.beforeURL);
download(downloadAsLibrary); // Redownload the file
} else {
App.settings.log("Failed to download file " + this.file.getName()
+ " from all ATLauncher servers. Cancelling install!",
LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
} else {
App.settings.log("Error downloading " + this.file.getName() + " from "
+ this.url + ". Expected hash of " + getHash() + " but got " + fileHash
+ " instead. Cancelling install!", LogMessageType.error, false);
if (this.instanceInstaller != null) {
instanceInstaller.cancel(true);
}
}
} else if (this.copyTo != null && this.actuallyCopy) {
String fileHash2;
if (this.copyTo.exists()) {
if (isMD5()) {
fileHash2 = Utils.getMD5(this.file);
} else {
fileHash2 = Utils.getSHA1(this.file);
}
} else {
fileHash2 = "0";
}
if (!fileHash2.equalsIgnoreCase(getHash())) {
if (this.copyTo.exists()) {
Utils.delete(this.copyTo);
}
new File(this.copyTo.getAbsolutePath().substring(0,
this.copyTo.getAbsolutePath().lastIndexOf(File.separatorChar)))
.mkdirs();
Utils.copyFile(this.file, this.copyTo, true);
}
}
App.settings.clearTriedServers(); // Okay downloaded it so clear the servers used
}
if (this.connection != null) {
this.connection.disconnect();
}
}
|
diff --git a/ini/trakem2/imaging/StitchingTEM.java b/ini/trakem2/imaging/StitchingTEM.java
index 2c21f285..732d3a29 100644
--- a/ini/trakem2/imaging/StitchingTEM.java
+++ b/ini/trakem2/imaging/StitchingTEM.java
@@ -1,969 +1,976 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005-2009 Albert Cardona and Rodney Douglas.
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 (http://www.gnu.org/licenses/gpl.txt )
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.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.imaging;
import ij.gui.Roi;
import ij.process.ImageProcessor;
import ij.ImagePlus;
import ij.gui.GenericDialog;
import ini.trakem2.utils.IJError;
import ini.trakem2.utils.Utils;
import ini.trakem2.display.Patch;
import ini.trakem2.display.Display;
import ini.trakem2.display.Displayable;
import ini.trakem2.display.Layer;
import ini.trakem2.utils.Worker;
import ini.trakem2.utils.Bureaucrat;
import ini.trakem2.persistence.Loader;
import mpi.fruitfly.registration.CrossCorrelation2D;
import mpi.fruitfly.registration.ImageFilter;
import mpi.fruitfly.math.datastructures.FloatArray2D;
import mpicbg.imglib.algorithm.fft.PhaseCorrelationPeak;
import mpicbg.models.ErrorStatistic;
import mpicbg.models.Tile;
import mpicbg.models.TranslationModel2D;
import mpicbg.models.Point;
import mpicbg.models.PointMatch;
import mpicbg.trakem2.align.Align;
import mpicbg.trakem2.align.AbstractAffineTile2D;
import mpicbg.trakem2.align.TranslationTile2D;
import mpicbg.trakem2.align.AlignTask;
import java.awt.Rectangle;
import java.awt.Image;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.awt.geom.AffineTransform;
/** Given:
* - list of images
* - grid width
* - known percent overlap
*
* This class will attempt to find the optimal montage,
* by applying phase-correlation, and/or cross-correlation, and/or SIFT-based correlation) between neighboring images.
*
* The method is oriented to images acquired with Transmission Electron Microscopy,
* where the acquisition of each image elastically deforms the sample, and thus
* earlier images are regarded as better than later ones.
*
* It is assumed that images were acquired from 0 to n, as in the grid.
*
*/
public class StitchingTEM {
static public final int WORKING = -1;
static public final int DONE = 0;
static public final int ERROR = 1;
static public final int INTERRUPTED = 2;
static public final int SUCCESS = 3;
static public final int TOP_BOTTOM = 4;
static public final int LEFT_RIGHT = 5;
static public final int TOP_LEFT_RULE = 0;
static public final int FREE_RULE = 1;
static public final float DEFAULT_MIN_R = 0.4f;
/** available stitching rules */
public static final String[] rules = new String[]{"Top left", "Free"};
/** Returns the same Patch instances with their coordinates modified; the top-left image is assumed to be the first one, and thus serves as reference; so, after the first image, coordinates are ignored for each specific Patch.
*
* The cross-correlation is done always with the image to the left, and on its absence, with the image above.
* If the cross-correlation returns values that would mean a depart larger than the known percent overlap, the image will be cross-correlated with its second option (i.e. the one above in almost all cases). In the absence of a second option to compare with, the percent overlap is applied as the least damaging option in the montage.
*
* The Patch[] array is unidimensional to allow for missing images in the last row not to interfere.
*
* The stitching runs in a separate thread; interested parties can query the status of the processing by calling the method getStatus().
*
* The scale is used to make the images smaller when doing cross-correlation. If larger than 1, it gets put back to 1.
*
* Rotation of the images is NOT considered by the TOP_LEFT_RULE (phase- and cross-correlation),
* but it can be for the FREE_RULE (SIFT).
*
* @return A new Runnable task, or null if the initialization didn't pass the tests (all tiles have to have the same dimensions, for example).
*/
static public Runnable stitch(
final Patch[] patch,
final int grid_width,
final double default_bottom_top_overlap,
final double default_left_right_overlap,
final boolean optimize,
final int stitching_rule)
{
// check preconditions
if (null == patch || grid_width < 1) {
return null;
}
if (patch.length < 2) {
return null;
}
// compare Patch dimensions: later code needs all to be equal
Rectangle b0 = patch[0].getBoundingBox(null);
for (int i=1; i<patch.length; i++) {
Rectangle bi = patch[i].getBoundingBox(null);
if (bi.width != b0.width || bi.height != b0.height) {
Utils.log2("Stitching: dimensions' missmatch.\n\tAll images MUST have the same dimensions."); // i.e. all Patches, actually (meaning, all Patch objects must have the same width and the same height).
return null;
}
}
Utils.log2("patch layer: " + patch[0].getLayer());
patch[0].getLayerSet().addTransformStep(patch[0].getLayer());
switch (stitching_rule) {
case StitchingTEM.TOP_LEFT_RULE:
return StitchingTEM.stitchTopLeft(patch, grid_width, default_bottom_top_overlap, default_left_right_overlap, optimize);
case StitchingTEM.FREE_RULE:
final HashSet<Patch> hs = new HashSet<Patch>();
for (int i=0; i<patch.length; i++) hs.add(patch[i]);
final ArrayList<Patch> fixed = new ArrayList<Patch>();
fixed.add(patch[0]);
return new Runnable() { public void run() {
AlignTask.alignPatches( new ArrayList<Patch>(hs), fixed );
}};
}
return null;
}
/**
* Stitch array of patches with upper left rule
*
* @param patch
* @param grid_width
* @param default_bottom_top_overlap
* @param default_left_right_overlap
* @param optimize
* @return
*/
static private Runnable stitchTopLeft(
final Patch[] patch,
final int grid_width,
final double default_bottom_top_overlap,
final double default_left_right_overlap,
final boolean optimize)
{
return new Runnable()
{
public void run() {
// Launch phase correlation dialog
PhaseCorrelationParam param = new PhaseCorrelationParam();
param.setup(patch[0]);
try {
final int LEFT = 0, TOP = 1;
int prev_i = 0;
int prev = LEFT;
double[] R1=null,
R2=null;
// for minimization:
ArrayList<AbstractAffineTile2D<?>> al_tiles = new ArrayList<AbstractAffineTile2D<?>>();
// first patch-tile:
TranslationModel2D first_tile_model = new TranslationModel2D();
//first_tile_model.getAffine().setTransform( patch[ 0 ].getAffineTransform() );
first_tile_model.set( (float) patch[0].getAffineTransform().getTranslateX(),
(float) patch[0].getAffineTransform().getTranslateY());
al_tiles.add(new TranslationTile2D(first_tile_model, patch[0]));
for (int i=1; i<patch.length; i++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
// boundary checks: don't allow displacements beyond these values
final double default_dx = default_left_right_overlap;
final double default_dy = default_bottom_top_overlap;
// for minimization:
AbstractAffineTile2D<?> tile_left = null;
AbstractAffineTile2D<?> tile_top = null;
TranslationModel2D tile_model = new TranslationModel2D();
//tile_model.getAffine().setTransform( patch[ i ].getAffineTransform() );
tile_model.set( (float) patch[i].getAffineTransform().getTranslateX(),
(float) patch[i].getAffineTransform().getTranslateY());
AbstractAffineTile2D<?> tile = new TranslationTile2D(tile_model, patch[i]);
al_tiles.add(tile);
// stitch with the one above if starting row
if (0 == i % grid_width) {
prev_i = i - grid_width;
prev = TOP;
} else {
prev_i = i -1;
prev = LEFT;
}
if (TOP == prev) {
// compare with top only
R1 = correlate(patch[prev_i], patch[i], param.overlap, param.cc_scale, TOP_BOTTOM, default_dx, default_dy, param.min_R);
R2 = null;
tile_top = al_tiles.get(i - grid_width);
} else {
// the one on the left
R2 = correlate(patch[prev_i], patch[i], param.overlap, param.cc_scale, LEFT_RIGHT, default_dx, default_dy, param.min_R);
tile_left = al_tiles.get(i - 1);
// the one above
if (i - grid_width > -1) {
R1 = correlate(patch[i - grid_width], patch[i], param.overlap, param.cc_scale, TOP_BOTTOM, default_dx, default_dy, param.min_R);
tile_top = al_tiles.get(i - grid_width);
} else {
R1 = null;
}
}
// boundary limits: don't move by more than the small dimension of the stripe
int max_abs_delta; // TODO: only the dx for left (and the dy for top) should be compared and found to be smaller or equal; the other dimension should be unbounded -for example, for manually acquired, grossly out-of-grid tiles.
final Rectangle box = new Rectangle();
final Rectangle box2 = new Rectangle();
// check and apply: falls back to default overlaps when getting bad results
if (TOP == prev) {
if (SUCCESS == R1[2]) {
// trust top
if (optimize) addMatches(tile_top, tile, R1[0], R1[1]);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x + R1[0], box.y + R1[1]);
}
} else {
final Rectangle b2 = patch[i - grid_width].getBoundingBox(null);
// don't move: use default overlap
if (optimize) addMatches(tile_top, tile, 0, b2.height - default_bottom_top_overlap);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x, box.y + b2.height - default_bottom_top_overlap);
}
}
} else { // LEFT
// the one on top, if any
if (i - grid_width > -1) {
if (SUCCESS == R1[2]) {
// top is good
if (SUCCESS == R2[2]) {
// combine left and top
if (optimize) {
addMatches(tile_left, tile, R2[0], R2[1]);
addMatches(tile_top, tile, R1[0], R1[1]);
} else {
patch[i-1].getBoundingBox(box);
patch[i - grid_width].getBoundingBox(box2);
patch[i].setLocation((box.x + R1[0] + box2.x + R2[0]) / 2, (box.y + R1[1] + box2.y + R2[1]) / 2);
}
} else {
// use top alone
if (optimize) addMatches(tile_top, tile, R1[0], R1[1]);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x + R1[0], box.y + R1[1]);
}
}
} else {
// ignore top
if (SUCCESS == R2[2]) {
// use left alone
if (optimize) addMatches(tile_left, tile, R2[0], R2[1]);
else {
patch[i-1].getBoundingBox(box);
patch[i].setLocation(box.x + R2[0], box.y + R2[1]);
}
} else {
patch[prev_i].getBoundingBox(box);
patch[i - grid_width].getBoundingBox(box2);
// left not trusted, top not trusted: use a combination of defaults for both
if (optimize) {
addMatches(tile_left, tile, box.width - default_left_right_overlap, 0);
addMatches(tile_top, tile, 0, box2.height - default_bottom_top_overlap);
} else {
patch[i].setLocation(box.x + box.width - default_left_right_overlap, box2.y + box2.height - default_bottom_top_overlap);
}
}
}
} else if (SUCCESS == R2[2]) {
// use left alone (top not applicable in top row)
if (optimize) addMatches(tile_left, tile, R2[0], R2[1]);
else {
patch[i-1].getBoundingBox(box);
patch[i].setLocation(box.x + R2[0], box.y + R2[1]);
}
} else {
patch[prev_i].getBoundingBox(box);
// left not trusted, and top not applicable: use default overlap with left tile
if (optimize) addMatches(tile_left, tile, box.width - default_left_right_overlap, 0);
else {
patch[i].setLocation(box.x + box.width - default_left_right_overlap, box.y);
}
}
}
if (!optimize) Display.repaint(patch[i].getLayer(), patch[i], null, 0, false);
Utils.log2(i + ": Done patch " + patch[i]);
}
if (optimize) {
ArrayList<AbstractAffineTile2D<?>> al_fixed_tiles = new ArrayList<AbstractAffineTile2D<?>>();
- al_fixed_tiles.add(al_tiles.get(0));
+ // Add locked tiles as fixed tiles, if any:
+ for (int i=0; i<patch.length; i++) {
+ if (patch[i].isLocked2()) al_fixed_tiles.add(al_tiles.get(i));
+ }
+ if (al_fixed_tiles.isEmpty()) {
+ // When none, add the first one as fixed
+ al_fixed_tiles.add(al_tiles.get(0));
+ }
// Optimize iteratively tile configuration by removing bad matches
optimizeTileConfiguration(al_tiles, al_fixed_tiles, param);
for ( AbstractAffineTile2D< ? > t : al_tiles )
t.getPatch().setAffineTransform( t.getModel().createAffine() );
}
// Remove or hide disconnected tiles
if(param.hide_disconnected || param.remove_disconnected)
{
List< Set< Tile< ? > > > graphs = AbstractAffineTile2D.identifyConnectedGraphs( al_tiles );
final List< AbstractAffineTile2D< ? > > interestingTiles;
// find largest graph
Set< Tile< ? > > largestGraph = null;
for ( Set< Tile< ? > > graph : graphs )
if ( largestGraph == null || largestGraph.size() < graph.size() )
largestGraph = graph;
Utils.log("Size of largest stitching graph = " + largestGraph.size());
interestingTiles = new ArrayList< AbstractAffineTile2D< ? > >();
for ( Tile< ? > t : largestGraph )
interestingTiles.add( ( AbstractAffineTile2D< ? > )t );
if ( param.hide_disconnected )
for ( AbstractAffineTile2D< ? > t : al_tiles )
if ( !interestingTiles.contains( t ) )
t.getPatch().setVisible( false );
if ( param.remove_disconnected )
for ( AbstractAffineTile2D< ? > t : al_tiles )
if ( !interestingTiles.contains( t ) )
t.getPatch().remove( false );
}
Display.repaint(patch[0].getLayer(), null, 0, true); // all
//
} catch (Exception e) {
IJError.print(e);
}
}
};
}
/** dx, dy is the position of t2 relative to the 0,0 of t1. */
static private final void addMatches(AbstractAffineTile2D<?> t1, AbstractAffineTile2D<?> t2, double dx, double dy) {
Point p1 = new Point(new float[]{0f, 0f});
Point p2 = new Point(new float[]{(float)dx, (float)dy});
t1.addMatch(new PointMatch(p2, p1, 1.0f));
t2.addMatch(new PointMatch(p1, p2, 1.0f));
t1.addConnectedTile(t2);
t2.addConnectedTile(t1);
}
static public ImageProcessor makeStripe(final Patch p, final Roi roi, final float scale) {
return makeStripe(p, roi, scale, false);
}
// static public ImageProcessor makeStripe(final Patch p, final float scale, final boolean ignore_patch_transform) {
// return makeStripe(p, null, scale, ignore_patch_transform);
// }
/** @return FloatProcessor.
* @param ignore_patch_transform will prevent resizing of the ImageProcessor in the event of the Patch having a transform different than identity. */
// TODO 2: there is a combination of options that ends up resulting in the actual ImageProcessor of the Patch being returned as is, which is DANGEROUS because it can potentially result in changes in the data.
static public ImageProcessor makeStripe(final Patch p, final Roi roi, final float scale, boolean ignore_patch_transform) {
ImagePlus imp = null;
ImageProcessor ip = null;
Loader loader = p.getProject().getLoader();
// check if using mipmaps and if there is a file for it. If there isn't, most likely this method is being called in an import sequence as grid procedure.
if (loader.isMipMapsEnabled() && loader.checkMipMapFileExists(p, scale))
{
// Read the transform image from the patch (this way we avoid the JPEG artifacts)
final Patch.PatchImage pai = p.createTransformedImage();
pai.target.setMinAndMax( p.getMin(), p.getMax() );
Image image = pai.target.createImage(); //p.getProject().getLoader().fetchImage(p, scale);
// check that dimensions are correct. If anything, they'll be larger
//Utils.log2("patch w,h " + p.getWidth() + ", " + p.getHeight() + " fetched image w,h: " + image.getWidth(null) + ", " + image.getHeight(null));
if (Math.abs(p.getWidth() * scale - image.getWidth(null)) > 0.001 || Math.abs(p.getHeight() * scale - image.getHeight(null)) > 0.001) {
image = image.getScaledInstance((int)(p.getWidth() * scale), (int)(p.getHeight() * scale), Image.SCALE_AREA_AVERAGING); // slow but good quality. Makes an RGB image, but it doesn't matter.
//Utils.log2(" resizing, now image w,h: " + image.getWidth(null) + ", " + image.getHeight(null));
}
try {
imp = new ImagePlus("s", image);
ip = imp.getProcessor();
//imp.show();
} catch (Exception e) {
IJError.print(e);
}
// cut
if (null != roi) {
// scale ROI!
Rectangle rb = roi.getBounds();
Roi roi2 = new Roi((int)(rb.x * scale), (int)(rb.y * scale), (int)(rb.width * scale), (int)(rb.height * scale));
rb = roi2.getBounds();
if (ip.getWidth() != rb.width || ip.getHeight() != rb.height) {
ip.setRoi(roi2);
ip = ip.crop();
}
}
//Utils.log2("scale: " + scale + " ip w,h: " + ip.getWidth() + ", " + ip.getHeight());
} else {
final Patch.PatchImage pai = p.createTransformedImage();
pai.target.setMinAndMax( p.getMin(), p.getMax() );
ip = pai.target;
imp = new ImagePlus("", ip);
// compare and adjust
if (!ignore_patch_transform && p.getAffineTransform().getType() != AffineTransform.TYPE_TRANSLATION) { // if it's not only a translation:
final Rectangle b = p.getBoundingBox();
ip = ip.resize(b.width, b.height);
//Utils.log2("resizing stripe for patch: " + p);
// the above is only meant to correct for improperly acquired images at the microscope, the scale only.
}
// cut
if (null != roi) {
final Rectangle rb = roi.getBounds();
if (ip.getWidth() != rb.width || ip.getHeight() != rb.height) {
ip.setRoi(roi);
ip = ip.crop();
}
}
// scale
if (scale < 1) {
p.getProject().getLoader().releaseToFit((long)(ip.getWidth() * ip.getHeight() * 4 * 1.2)); // floats have 4 bytes, plus some java peripherals correction factor
ip = ip.convertToFloat();
ip.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.getPixels(), ip.getWidth(), ip.getHeight()), (float)Math.sqrt(0.25 / scale / scale - 0.25)).data); // scaling with area averaging is the same as a gaussian of sigma 0.5/scale and then resize with nearest neightbor So this line does the gaussian, and line below does the neares-neighbor scaling
ip = ip.resize((int)(ip.getWidth() * scale)); // scale maintaining aspect ratio
}
}
//Utils.log2("makeStripe: w,h " + ip.getWidth() + ", " + ip.getHeight());
// return a FloatProcessor
if (imp.getType() != ImagePlus.GRAY32) return ip.convertToFloat();
return ip;
}
/** @param scale For optimizing the speed of phase- and cross-correlation.<br />
* @param percent_overlap The minimum chunk of adjacent images to compare with, will automatically and gradually increase to 100% if no good matches are found.<br />
* @return a double[4] array containing:<br />
* - x2: relative X position of the second Patch<br />
* - y2: relative Y position of the second Patch<br />
* - flag: ERROR or SUCCESS<br />
* - R: cross-correlation coefficient<br />
*/
static public double[] correlate(final Patch base, final Patch moving, final float percent_overlap, final float scale, final int direction, final double default_dx, final double default_dy, final float min_R) {
//PhaseCorrelation2D pc = null;
double R = -2;
//final int limit = 5; // number of peaks to check in the PhaseCorrelation results
//final float min_R = 0.40f; // minimum R for phase-correlation to be considered good
// half this min_R will be considered good for cross-correlation
// Iterate until PhaseCorrelation correlation coefficient R is over 0.5, or there's no more
// image overlap to feed
//Utils.log2("min_R: " + min_R);
ImageProcessor ip1, ip2;
final Rectangle b1 = base.getBoundingBox(null);
final Rectangle b2 = moving.getBoundingBox(null);
final int w1 = b1.width,
h1 = b1.height,
w2 = b2.width,
h2 = b2.height;
Roi roi1=null,
roi2=null;
float overlap = percent_overlap;
double dx = default_dx,
dy = default_dy;
do {
// create rois for the stripes
switch(direction) {
case TOP_BOTTOM:
roi1 = new Roi(0, h1 - (int)(h1 * overlap), w1, (int)(h1 * overlap)); // bottom
roi2 = new Roi(0, 0, w2, (int)(h2 * overlap)); // top
break;
case LEFT_RIGHT:
roi1 = new Roi(w1 - (int)(w1 * overlap), 0, (int)(w1 * overlap), h1); // right
roi2 = new Roi(0, 0, (int)(w2 * overlap), h2); // left
break;
}
//Utils.log2("roi1: " + roi1);
//Utils.log2("roi2: " + roi2);
ip1 = makeStripe(base, roi1, scale); // will apply the transform if necessary
ip2 = makeStripe(moving, roi2, scale);
//new ImagePlus("roi1", ip1).show();
//new ImagePlus("roi2", ip2).show();
ip1.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip1.getPixels(), ip1.getWidth(), ip1.getHeight()), 1f).data);
ip2.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip2.getPixels(), ip2.getWidth(), ip2.getHeight()), 1f).data);
//
final ImagePlus imp1 = new ImagePlus( "", ip1 );
final ImagePlus imp2 = new ImagePlus( "", ip2 );
PhaseCorrelationCalculator t = new PhaseCorrelationCalculator(imp1, imp2);
PhaseCorrelationPeak peak = t.getPeak();
final double resultR = peak.getCrossCorrelationPeak();
final int[] peackPostion = peak.getPosition();
final java.awt.Point shift = new java.awt.Point(peackPostion[0], peackPostion[1]);
//pc = new PhaseCorrelation2D(ip1, ip2, limit, true, false, false); // with windowing
//final java.awt.Point shift = pc.computePhaseCorrelation();
//final PhaseCorrelation2D.CrossCorrelationResult result = pc.getResult();
//Utils.log2("overlap: " + overlap + " R: " + resultR + " shift: " + shift + " dx,dy: " + dx + ", " + dy);
if (resultR >= min_R) {
// success
int success = SUCCESS;
switch(direction) {
case TOP_BOTTOM:
// boundary checks:
//if (shift.y/scale > default_dy) success = ERROR;
dx = shift.x/scale;
dy = roi1.getBounds().y + shift.y/scale;
break;
case LEFT_RIGHT:
// boundary checks:
//if (shift.x/scale > default_dx) success = ERROR;
dx = roi1.getBounds().x + shift.x/scale;
dy = shift.y/scale;
break;
}
//Utils.log2("R: " + resultR + " shift: " + shift + " dx,dy: " + dx + ", " + dy);
return new double[]{dx, dy, success, resultR};
}
//new ImagePlus("roi1", ip1.duplicate()).show();
//new ImagePlus("roi2", ip2.duplicate()).show();
//try { Thread.sleep(1000000000); } catch (Exception e) {}
// increase for next iteration
overlap += 0.10; // increments of 10%
} while (R < min_R && Math.abs(overlap - 1.0f) < 0.001f);
// Phase-correlation failed, fall back to cross-correlation with a safe overlap
overlap = percent_overlap * 2;
if (overlap > 1.0f) overlap = 1.0f;
switch(direction) {
case TOP_BOTTOM:
roi1 = new Roi(0, h1 - (int)(h1 * overlap), w1, (int)(h1 * overlap)); // bottom
roi2 = new Roi(0, 0, w2, (int)(h2 * overlap)); // top
break;
case LEFT_RIGHT:
roi1 = new Roi(w1 - (int)(w1 * overlap), 0, (int)(w1 * overlap), h1); // right
roi2 = new Roi(0, 0, (int)(w2 * overlap), h2); // left
break;
}
// use one third of the size used for phase-correlation though! Otherwise, it may take FOREVER
float scale_cc = (float)(scale / 3f);
ip1 = makeStripe(base, roi1, scale_cc);
ip2 = makeStripe(moving, roi2, scale_cc);
// gaussian blur them before cross-correlation
ip1.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip1.getPixels(), ip1.getWidth(), ip1.getHeight()), 1f).data);
ip2.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip2.getPixels(), ip2.getWidth(), ip2.getHeight()), 1f).data);
//new ImagePlus("CC roi1", ip1).show();
//new ImagePlus("CC roi2", ip2).show();
final CrossCorrelation2D cc = new CrossCorrelation2D(ip1, ip2, false);
double[] cc_result = null;
switch (direction) {
case TOP_BOTTOM:
cc_result = cc.computeCrossCorrelationMT(0.9, 0.3, false);
break;
case LEFT_RIGHT:
cc_result = cc.computeCrossCorrelationMT(0.3, 0.9, false);
break;
}
if (cc_result[2] > min_R/2) { //accepting if R is above half the R accepted for Phase Correlation
// success
int success = SUCCESS;
switch(direction) {
case TOP_BOTTOM:
// boundary checks:
//if (cc_result[1]/scale_cc > default_dy) success = ERROR;
dx = cc_result[0]/scale_cc;
dy = roi1.getBounds().y + cc_result[1]/scale_cc;
break;
case LEFT_RIGHT:
// boundary checks:
//if (cc_result[0]/scale_cc > default_dx) success = ERROR;
dx = roi1.getBounds().x + cc_result[0]/scale_cc;
dy = cc_result[1]/scale_cc;
break;
}
//Utils.log2("CC R: " + cc_result[2] + " dx, dy: " + cc_result[0] + ", " + cc_result[1]);
//Utils.log2("\trois: \t" + roi1 + "\n\t\t" + roi2);
return new double[]{dx, dy, success, cc_result[2]};
}
// else both failed: return default values
//Utils.log2("Using default");
return new double[]{default_dx, default_dy, ERROR, 0};
/// ABOVE: boundary checks don't work if default_dx,dy are zero! And may actually be harmful in anycase
}
/** Figure out from which direction is the dragged object approaching the object being overlapped. 0=left, 1=top, 2=right, 3=bottom. This method by Stephan Nufer. */
static private int getClosestOverlapLocation(Patch dragging_ob, Patch overlapping_ob) {
Rectangle x_rect = dragging_ob.getBoundingBox();
Rectangle y_rect = overlapping_ob.getBoundingBox();
Rectangle overlap = x_rect.intersection(y_rect);
if (overlap.width / (double)overlap.height > 1) {
// horizontal stitch
if (y_rect.y < x_rect.y) return 3;
else return 1;
} else {
// vertical stitch
if (y_rect.x < x_rect.x) return 2;
else return 0;
}
}
/**
* For each Patch, find who overlaps with it and perform a phase correlation or cross-correlation with it;
* then consider all successful correlations as links and run the optimizer on it all.
* ASSUMES the patches have only TRANSLATION in their affine transforms--will warn you about it.*/
static public Bureaucrat montageWithPhaseCorrelation(final Collection<Patch> col) {
if (null == col || col.size() < 1) return null;
return Bureaucrat.createAndStart(new Worker.Task("Montage with phase-correlation") {
public void exec() {
final PhaseCorrelationParam param = new PhaseCorrelationParam();
if (!param.setup(col.iterator().next())) {
return;
}
AlignTask.transformPatchesAndVectorData(col, new Runnable() { public void run() {
montageWithPhaseCorrelation(col, param);
}});
}
}, col.iterator().next().getProject());
}
static public Bureaucrat montageWithPhaseCorrelation(final List<Layer> layers) {
if (null == layers || layers.size() < 1) return null;
return Bureaucrat.createAndStart(new Worker.Task("Montage layer 1/" + layers.size()) {
public void exec() {
final PhaseCorrelationParam param = new PhaseCorrelationParam();
final Collection<Displayable> col = layers.get(0).getDisplayables(Patch.class);
if (!param.setup(col.size() > 0 ? (Patch)col.iterator().next() : null)) {
return;
}
int i = 1;
for (Layer la : layers) {
if (Thread.currentThread().isInterrupted() || hasQuitted()) return;
setTaskName("Montage layer " + i + "/" + layers.size());
final Collection<Patch> patches = (Collection<Patch>) (Collection) la.getDisplayables(Patch.class);
AlignTask.transformPatchesAndVectorData(patches, new Runnable() { public void run() {
montageWithPhaseCorrelation(patches, param);
}});
}
}
}, layers.get(0).getProject());
}
/**
* Phase correlation parameters class
*
*/
static public class PhaseCorrelationParam
{
public float cc_scale = 0.25f;
public float overlap = 0.1f;
public boolean hide_disconnected = false;
public boolean remove_disconnected = false;
public float mean_factor = 2.5f;
public float min_R = 0.3f;
public PhaseCorrelationParam(
float cc_scale,
float overlap,
boolean hide_disconnected,
boolean remove_disconnected,
float mean_factor,
float min_R)
{
this.cc_scale = cc_scale;
this.overlap = overlap;
this.hide_disconnected = hide_disconnected;
this.remove_disconnected = remove_disconnected;
this.mean_factor = mean_factor;
this.min_R = min_R;
}
/**
* Empty constructor
*/
public PhaseCorrelationParam() {}
/**
* Returns false when canceled.
* @param ref is an optional Patch from which to estimate an appropriate image scale
* at which to perform the phase correlation, for performance reasons.
* */
public boolean setup(Patch ref)
{
GenericDialog gd = new GenericDialog("Montage with phase correlation");
if (overlap < 0) overlap = 0.1f;
else if (overlap > 1) overlap = 1;
gd.addSlider("tile_overlap (%): ", 1, 100, overlap * 100);
int sc = (int)cc_scale * 100;
if (null != ref) {
// Estimate scale from ref Patch dimensions
int w = ref.getOWidth();
int h = ref.getOHeight();
sc = (int)((512.0 / (w > h ? w : h)) * 100); // guess a scale so that image is 512x512 aprox
}
if (sc < 0) sc = 25;
else if (sc > 100) sc = 100;
gd.addSlider("scale (%):", 1, 100, sc);
gd.addNumericField( "max/avg displacement threshold: ", mean_factor, 2 );
gd.addNumericField("regression threshold (R):", min_R, 2);
gd.addCheckbox("hide disconnected", false);
gd.addCheckbox("remove disconnected", false);
gd.showDialog();
if (gd.wasCanceled()) return false;
overlap = (float)gd.getNextNumber() / 100f;
cc_scale = (float)gd.getNextNumber() / 100f;
mean_factor = ( float )gd.getNextNumber();
min_R = (float) gd.getNextNumber();
hide_disconnected = gd.getNextBoolean();
remove_disconnected = gd.getNextBoolean();
return true;
}
}
/**
* Perform montage based on phase correlation
* @param col collection of patches
* @param param phase correlation parameters
*/
static public void montageWithPhaseCorrelation(final Collection<Patch> col, final PhaseCorrelationParam param)
{
if (null == col || col.size() < 1) return;
final ArrayList<Patch> al = new ArrayList<Patch>(col);
final ArrayList<AbstractAffineTile2D<?>> tiles = new ArrayList<AbstractAffineTile2D<?>>();
final ArrayList<AbstractAffineTile2D<?>> fixed_tiles = new ArrayList<AbstractAffineTile2D<?>>();
for (final Patch p : al) {
// Pre-check: just a warning
final int aff_type = p.getAffineTransform().getType();
if (AffineTransform.TYPE_IDENTITY != aff_type
|| 0 != (AffineTransform.TYPE_TRANSLATION ^ aff_type)) {
Utils.log2("WARNING: patch with a non-translation transform: " + p);
}
// create tiles
TranslationTile2D tile = new TranslationTile2D(new TranslationModel2D(), p);
tiles.add(tile);
if (p.isLocked2()) {
Utils.log("Added fixed (locked) tile " + p);
fixed_tiles.add(tile);
}
}
// Get acceptable values
float cc_scale = param.cc_scale;
if (cc_scale < 0 || cc_scale > 1) {
Utils.log("Unacceptable cc_scale of " + param.cc_scale + ". Using 1 instead.");
cc_scale = 1;
}
float overlap = param.overlap;
if (overlap < 0 || overlap > 1) {
Utils.log("Unacceptable overlap of " + param.overlap + ". Using 1 instead.");
overlap = 1;
}
for (int i=0; i<al.size(); i++) {
final Patch p1 = al.get(i);
final Rectangle r1 = p1.getBoundingBox();
// find overlapping, add as connections
for (int j=i+1; j<al.size(); j++) {
if (Thread.currentThread().isInterrupted()) return;
final Patch p2 = al.get(j);
final Rectangle r2 = p2.getBoundingBox();
if (r1.intersects(r2)) {
// Skip if it's a diagonal overlap
final int dx = Math.abs(r1.x - r2.x);
final int dy = Math.abs(r1.y - r2.y);
if (dx > r1.width/2 && dy > r1.height/2) {
// skip diagonal match
Utils.log2("Skipping diagonal overlap between " + p1 + " and " + p2);
continue;
}
p1.getProject().getLoader().releaseToFit((long)(p1.getWidth() * p1.getHeight() * 25));
final double[] R;
if (1 == overlap) {
R = correlate(p1, p2, overlap, cc_scale, TOP_BOTTOM, 0, 0, param.min_R );
if (SUCCESS == R[2]) {
addMatches(tiles.get(i), tiles.get(j), R[0], R[1]);
}
} else {
switch (getClosestOverlapLocation(p1, p2)) {
case 0: // p1 overlaps p2 from the left
R = correlate(p1, p2, overlap, cc_scale, LEFT_RIGHT, 0, 0, param.min_R);
if (SUCCESS == R[2]) {
addMatches(tiles.get(i), tiles.get(j), R[0], R[1]);
}
break;
case 1: // p1 overlaps p2 from the top
R = correlate(p1, p2, overlap, cc_scale, TOP_BOTTOM, 0, 0, param.min_R);
if (SUCCESS == R[2]) {
addMatches(tiles.get(i), tiles.get(j), R[0], R[1]);
}
break;
case 2: // p1 overlaps p2 from the right
R = correlate(p2, p1, overlap, cc_scale, LEFT_RIGHT, 0, 0, param.min_R);
if (SUCCESS == R[2]) {
addMatches(tiles.get(j), tiles.get(i), R[0], R[1]);
}
break;
case 3: // p1 overlaps p2 from the bottom
R = correlate(p2, p1, overlap, cc_scale, TOP_BOTTOM, 0, 0, param.min_R);
if (SUCCESS == R[2]) {
addMatches(tiles.get(j), tiles.get(i), R[0], R[1]);
}
break;
default:
Utils.log("Unknown overlap direction!");
continue;
}
}
}
}
}
if (param.remove_disconnected || param.hide_disconnected) {
for (Iterator<AbstractAffineTile2D<?>> it = tiles.iterator(); it.hasNext(); ) {
AbstractAffineTile2D<?> t = it.next();
if (null != t.getMatches() && t.getMatches().isEmpty()) {
if (param.hide_disconnected) t.getPatch().setVisible(false);
else if (param.remove_disconnected) t.getPatch().remove(false);
it.remove();
}
}
}
// Optimize tile configuration by removing bad matches
optimizeTileConfiguration(tiles, fixed_tiles, param);
for ( AbstractAffineTile2D< ? > t : tiles )
t.getPatch().setAffineTransform( t.getModel().createAffine() );
try { Display.repaint(al.get(0).getLayer()); } catch (Exception e) {}
}
/**
* Optimize tile configuration by removing bad matches
*
* @param tiles complete list of tiles
* @param fixed_tiles list of fixed tiles
* @param param phase correlation parameters
*/
public static void optimizeTileConfiguration(
ArrayList<AbstractAffineTile2D<?>> tiles,
ArrayList<AbstractAffineTile2D<?>> fixed_tiles,
PhaseCorrelationParam param)
{
// Run optimization
if (fixed_tiles.isEmpty()) fixed_tiles.add(tiles.get(0));
// with default parameters
boolean proceed = true;
while ( proceed )
{
Align.optimizeTileConfiguration( new Align.ParamOptimize(), tiles, fixed_tiles );
/* get all transfer errors */
final ErrorStatistic e = new ErrorStatistic( tiles.size() + 1 );
for ( final AbstractAffineTile2D< ? > t : tiles )
t.update();
for ( final AbstractAffineTile2D< ? > t : tiles )
{
for ( final PointMatch p : t.getMatches() )
{
e.add( p.getDistance() );
}
}
/* remove the worst if there is one */
if ( e.max > param.mean_factor * e.mean )
{
A: for ( final AbstractAffineTile2D< ? > t : tiles )
{
for ( final PointMatch p : t.getMatches() )
{
if ( p.getDistance() >= e.max )
{
final AbstractAffineTile2D< ? > o = t.findConnectedTile( p );
t.removeConnectedTile( o );
o.removeConnectedTile( t );
//Utils.log2( "Removing bad match from configuration, error = " + e.max );
break A;
}
}
}
}
else
proceed = false;
}
}
}
| true | true | static private Runnable stitchTopLeft(
final Patch[] patch,
final int grid_width,
final double default_bottom_top_overlap,
final double default_left_right_overlap,
final boolean optimize)
{
return new Runnable()
{
public void run() {
// Launch phase correlation dialog
PhaseCorrelationParam param = new PhaseCorrelationParam();
param.setup(patch[0]);
try {
final int LEFT = 0, TOP = 1;
int prev_i = 0;
int prev = LEFT;
double[] R1=null,
R2=null;
// for minimization:
ArrayList<AbstractAffineTile2D<?>> al_tiles = new ArrayList<AbstractAffineTile2D<?>>();
// first patch-tile:
TranslationModel2D first_tile_model = new TranslationModel2D();
//first_tile_model.getAffine().setTransform( patch[ 0 ].getAffineTransform() );
first_tile_model.set( (float) patch[0].getAffineTransform().getTranslateX(),
(float) patch[0].getAffineTransform().getTranslateY());
al_tiles.add(new TranslationTile2D(first_tile_model, patch[0]));
for (int i=1; i<patch.length; i++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
// boundary checks: don't allow displacements beyond these values
final double default_dx = default_left_right_overlap;
final double default_dy = default_bottom_top_overlap;
// for minimization:
AbstractAffineTile2D<?> tile_left = null;
AbstractAffineTile2D<?> tile_top = null;
TranslationModel2D tile_model = new TranslationModel2D();
//tile_model.getAffine().setTransform( patch[ i ].getAffineTransform() );
tile_model.set( (float) patch[i].getAffineTransform().getTranslateX(),
(float) patch[i].getAffineTransform().getTranslateY());
AbstractAffineTile2D<?> tile = new TranslationTile2D(tile_model, patch[i]);
al_tiles.add(tile);
// stitch with the one above if starting row
if (0 == i % grid_width) {
prev_i = i - grid_width;
prev = TOP;
} else {
prev_i = i -1;
prev = LEFT;
}
if (TOP == prev) {
// compare with top only
R1 = correlate(patch[prev_i], patch[i], param.overlap, param.cc_scale, TOP_BOTTOM, default_dx, default_dy, param.min_R);
R2 = null;
tile_top = al_tiles.get(i - grid_width);
} else {
// the one on the left
R2 = correlate(patch[prev_i], patch[i], param.overlap, param.cc_scale, LEFT_RIGHT, default_dx, default_dy, param.min_R);
tile_left = al_tiles.get(i - 1);
// the one above
if (i - grid_width > -1) {
R1 = correlate(patch[i - grid_width], patch[i], param.overlap, param.cc_scale, TOP_BOTTOM, default_dx, default_dy, param.min_R);
tile_top = al_tiles.get(i - grid_width);
} else {
R1 = null;
}
}
// boundary limits: don't move by more than the small dimension of the stripe
int max_abs_delta; // TODO: only the dx for left (and the dy for top) should be compared and found to be smaller or equal; the other dimension should be unbounded -for example, for manually acquired, grossly out-of-grid tiles.
final Rectangle box = new Rectangle();
final Rectangle box2 = new Rectangle();
// check and apply: falls back to default overlaps when getting bad results
if (TOP == prev) {
if (SUCCESS == R1[2]) {
// trust top
if (optimize) addMatches(tile_top, tile, R1[0], R1[1]);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x + R1[0], box.y + R1[1]);
}
} else {
final Rectangle b2 = patch[i - grid_width].getBoundingBox(null);
// don't move: use default overlap
if (optimize) addMatches(tile_top, tile, 0, b2.height - default_bottom_top_overlap);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x, box.y + b2.height - default_bottom_top_overlap);
}
}
} else { // LEFT
// the one on top, if any
if (i - grid_width > -1) {
if (SUCCESS == R1[2]) {
// top is good
if (SUCCESS == R2[2]) {
// combine left and top
if (optimize) {
addMatches(tile_left, tile, R2[0], R2[1]);
addMatches(tile_top, tile, R1[0], R1[1]);
} else {
patch[i-1].getBoundingBox(box);
patch[i - grid_width].getBoundingBox(box2);
patch[i].setLocation((box.x + R1[0] + box2.x + R2[0]) / 2, (box.y + R1[1] + box2.y + R2[1]) / 2);
}
} else {
// use top alone
if (optimize) addMatches(tile_top, tile, R1[0], R1[1]);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x + R1[0], box.y + R1[1]);
}
}
} else {
// ignore top
if (SUCCESS == R2[2]) {
// use left alone
if (optimize) addMatches(tile_left, tile, R2[0], R2[1]);
else {
patch[i-1].getBoundingBox(box);
patch[i].setLocation(box.x + R2[0], box.y + R2[1]);
}
} else {
patch[prev_i].getBoundingBox(box);
patch[i - grid_width].getBoundingBox(box2);
// left not trusted, top not trusted: use a combination of defaults for both
if (optimize) {
addMatches(tile_left, tile, box.width - default_left_right_overlap, 0);
addMatches(tile_top, tile, 0, box2.height - default_bottom_top_overlap);
} else {
patch[i].setLocation(box.x + box.width - default_left_right_overlap, box2.y + box2.height - default_bottom_top_overlap);
}
}
}
} else if (SUCCESS == R2[2]) {
// use left alone (top not applicable in top row)
if (optimize) addMatches(tile_left, tile, R2[0], R2[1]);
else {
patch[i-1].getBoundingBox(box);
patch[i].setLocation(box.x + R2[0], box.y + R2[1]);
}
} else {
patch[prev_i].getBoundingBox(box);
// left not trusted, and top not applicable: use default overlap with left tile
if (optimize) addMatches(tile_left, tile, box.width - default_left_right_overlap, 0);
else {
patch[i].setLocation(box.x + box.width - default_left_right_overlap, box.y);
}
}
}
if (!optimize) Display.repaint(patch[i].getLayer(), patch[i], null, 0, false);
Utils.log2(i + ": Done patch " + patch[i]);
}
if (optimize) {
ArrayList<AbstractAffineTile2D<?>> al_fixed_tiles = new ArrayList<AbstractAffineTile2D<?>>();
al_fixed_tiles.add(al_tiles.get(0));
// Optimize iteratively tile configuration by removing bad matches
optimizeTileConfiguration(al_tiles, al_fixed_tiles, param);
for ( AbstractAffineTile2D< ? > t : al_tiles )
t.getPatch().setAffineTransform( t.getModel().createAffine() );
}
// Remove or hide disconnected tiles
if(param.hide_disconnected || param.remove_disconnected)
{
List< Set< Tile< ? > > > graphs = AbstractAffineTile2D.identifyConnectedGraphs( al_tiles );
final List< AbstractAffineTile2D< ? > > interestingTiles;
// find largest graph
Set< Tile< ? > > largestGraph = null;
for ( Set< Tile< ? > > graph : graphs )
if ( largestGraph == null || largestGraph.size() < graph.size() )
largestGraph = graph;
Utils.log("Size of largest stitching graph = " + largestGraph.size());
interestingTiles = new ArrayList< AbstractAffineTile2D< ? > >();
for ( Tile< ? > t : largestGraph )
interestingTiles.add( ( AbstractAffineTile2D< ? > )t );
if ( param.hide_disconnected )
for ( AbstractAffineTile2D< ? > t : al_tiles )
if ( !interestingTiles.contains( t ) )
t.getPatch().setVisible( false );
if ( param.remove_disconnected )
for ( AbstractAffineTile2D< ? > t : al_tiles )
if ( !interestingTiles.contains( t ) )
t.getPatch().remove( false );
}
Display.repaint(patch[0].getLayer(), null, 0, true); // all
//
} catch (Exception e) {
IJError.print(e);
}
}
};
}
| static private Runnable stitchTopLeft(
final Patch[] patch,
final int grid_width,
final double default_bottom_top_overlap,
final double default_left_right_overlap,
final boolean optimize)
{
return new Runnable()
{
public void run() {
// Launch phase correlation dialog
PhaseCorrelationParam param = new PhaseCorrelationParam();
param.setup(patch[0]);
try {
final int LEFT = 0, TOP = 1;
int prev_i = 0;
int prev = LEFT;
double[] R1=null,
R2=null;
// for minimization:
ArrayList<AbstractAffineTile2D<?>> al_tiles = new ArrayList<AbstractAffineTile2D<?>>();
// first patch-tile:
TranslationModel2D first_tile_model = new TranslationModel2D();
//first_tile_model.getAffine().setTransform( patch[ 0 ].getAffineTransform() );
first_tile_model.set( (float) patch[0].getAffineTransform().getTranslateX(),
(float) patch[0].getAffineTransform().getTranslateY());
al_tiles.add(new TranslationTile2D(first_tile_model, patch[0]));
for (int i=1; i<patch.length; i++) {
if (Thread.currentThread().isInterrupted()) {
return;
}
// boundary checks: don't allow displacements beyond these values
final double default_dx = default_left_right_overlap;
final double default_dy = default_bottom_top_overlap;
// for minimization:
AbstractAffineTile2D<?> tile_left = null;
AbstractAffineTile2D<?> tile_top = null;
TranslationModel2D tile_model = new TranslationModel2D();
//tile_model.getAffine().setTransform( patch[ i ].getAffineTransform() );
tile_model.set( (float) patch[i].getAffineTransform().getTranslateX(),
(float) patch[i].getAffineTransform().getTranslateY());
AbstractAffineTile2D<?> tile = new TranslationTile2D(tile_model, patch[i]);
al_tiles.add(tile);
// stitch with the one above if starting row
if (0 == i % grid_width) {
prev_i = i - grid_width;
prev = TOP;
} else {
prev_i = i -1;
prev = LEFT;
}
if (TOP == prev) {
// compare with top only
R1 = correlate(patch[prev_i], patch[i], param.overlap, param.cc_scale, TOP_BOTTOM, default_dx, default_dy, param.min_R);
R2 = null;
tile_top = al_tiles.get(i - grid_width);
} else {
// the one on the left
R2 = correlate(patch[prev_i], patch[i], param.overlap, param.cc_scale, LEFT_RIGHT, default_dx, default_dy, param.min_R);
tile_left = al_tiles.get(i - 1);
// the one above
if (i - grid_width > -1) {
R1 = correlate(patch[i - grid_width], patch[i], param.overlap, param.cc_scale, TOP_BOTTOM, default_dx, default_dy, param.min_R);
tile_top = al_tiles.get(i - grid_width);
} else {
R1 = null;
}
}
// boundary limits: don't move by more than the small dimension of the stripe
int max_abs_delta; // TODO: only the dx for left (and the dy for top) should be compared and found to be smaller or equal; the other dimension should be unbounded -for example, for manually acquired, grossly out-of-grid tiles.
final Rectangle box = new Rectangle();
final Rectangle box2 = new Rectangle();
// check and apply: falls back to default overlaps when getting bad results
if (TOP == prev) {
if (SUCCESS == R1[2]) {
// trust top
if (optimize) addMatches(tile_top, tile, R1[0], R1[1]);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x + R1[0], box.y + R1[1]);
}
} else {
final Rectangle b2 = patch[i - grid_width].getBoundingBox(null);
// don't move: use default overlap
if (optimize) addMatches(tile_top, tile, 0, b2.height - default_bottom_top_overlap);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x, box.y + b2.height - default_bottom_top_overlap);
}
}
} else { // LEFT
// the one on top, if any
if (i - grid_width > -1) {
if (SUCCESS == R1[2]) {
// top is good
if (SUCCESS == R2[2]) {
// combine left and top
if (optimize) {
addMatches(tile_left, tile, R2[0], R2[1]);
addMatches(tile_top, tile, R1[0], R1[1]);
} else {
patch[i-1].getBoundingBox(box);
patch[i - grid_width].getBoundingBox(box2);
patch[i].setLocation((box.x + R1[0] + box2.x + R2[0]) / 2, (box.y + R1[1] + box2.y + R2[1]) / 2);
}
} else {
// use top alone
if (optimize) addMatches(tile_top, tile, R1[0], R1[1]);
else {
patch[i - grid_width].getBoundingBox(box);
patch[i].setLocation(box.x + R1[0], box.y + R1[1]);
}
}
} else {
// ignore top
if (SUCCESS == R2[2]) {
// use left alone
if (optimize) addMatches(tile_left, tile, R2[0], R2[1]);
else {
patch[i-1].getBoundingBox(box);
patch[i].setLocation(box.x + R2[0], box.y + R2[1]);
}
} else {
patch[prev_i].getBoundingBox(box);
patch[i - grid_width].getBoundingBox(box2);
// left not trusted, top not trusted: use a combination of defaults for both
if (optimize) {
addMatches(tile_left, tile, box.width - default_left_right_overlap, 0);
addMatches(tile_top, tile, 0, box2.height - default_bottom_top_overlap);
} else {
patch[i].setLocation(box.x + box.width - default_left_right_overlap, box2.y + box2.height - default_bottom_top_overlap);
}
}
}
} else if (SUCCESS == R2[2]) {
// use left alone (top not applicable in top row)
if (optimize) addMatches(tile_left, tile, R2[0], R2[1]);
else {
patch[i-1].getBoundingBox(box);
patch[i].setLocation(box.x + R2[0], box.y + R2[1]);
}
} else {
patch[prev_i].getBoundingBox(box);
// left not trusted, and top not applicable: use default overlap with left tile
if (optimize) addMatches(tile_left, tile, box.width - default_left_right_overlap, 0);
else {
patch[i].setLocation(box.x + box.width - default_left_right_overlap, box.y);
}
}
}
if (!optimize) Display.repaint(patch[i].getLayer(), patch[i], null, 0, false);
Utils.log2(i + ": Done patch " + patch[i]);
}
if (optimize) {
ArrayList<AbstractAffineTile2D<?>> al_fixed_tiles = new ArrayList<AbstractAffineTile2D<?>>();
// Add locked tiles as fixed tiles, if any:
for (int i=0; i<patch.length; i++) {
if (patch[i].isLocked2()) al_fixed_tiles.add(al_tiles.get(i));
}
if (al_fixed_tiles.isEmpty()) {
// When none, add the first one as fixed
al_fixed_tiles.add(al_tiles.get(0));
}
// Optimize iteratively tile configuration by removing bad matches
optimizeTileConfiguration(al_tiles, al_fixed_tiles, param);
for ( AbstractAffineTile2D< ? > t : al_tiles )
t.getPatch().setAffineTransform( t.getModel().createAffine() );
}
// Remove or hide disconnected tiles
if(param.hide_disconnected || param.remove_disconnected)
{
List< Set< Tile< ? > > > graphs = AbstractAffineTile2D.identifyConnectedGraphs( al_tiles );
final List< AbstractAffineTile2D< ? > > interestingTiles;
// find largest graph
Set< Tile< ? > > largestGraph = null;
for ( Set< Tile< ? > > graph : graphs )
if ( largestGraph == null || largestGraph.size() < graph.size() )
largestGraph = graph;
Utils.log("Size of largest stitching graph = " + largestGraph.size());
interestingTiles = new ArrayList< AbstractAffineTile2D< ? > >();
for ( Tile< ? > t : largestGraph )
interestingTiles.add( ( AbstractAffineTile2D< ? > )t );
if ( param.hide_disconnected )
for ( AbstractAffineTile2D< ? > t : al_tiles )
if ( !interestingTiles.contains( t ) )
t.getPatch().setVisible( false );
if ( param.remove_disconnected )
for ( AbstractAffineTile2D< ? > t : al_tiles )
if ( !interestingTiles.contains( t ) )
t.getPatch().remove( false );
}
Display.repaint(patch[0].getLayer(), null, 0, true); // all
//
} catch (Exception e) {
IJError.print(e);
}
}
};
}
|
diff --git a/android/MapTime/src/com/maptime/maptime/Timelinechoice.java b/android/MapTime/src/com/maptime/maptime/Timelinechoice.java
index 4c9ebb6..0ff9cf2 100644
--- a/android/MapTime/src/com/maptime/maptime/Timelinechoice.java
+++ b/android/MapTime/src/com/maptime/maptime/Timelinechoice.java
@@ -1,215 +1,209 @@
package com.maptime.maptime;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class Timelinechoice extends Activity {
public final static String GEOPOINTS = "com.maptime.maptime.GEOPOINTS";
private final static String APIURL = "http://jakob-aungiers.com/misc/example.xml";
private ArrayList<Timeline> timelines = new ArrayList<Timeline>();
private int timelineChoice = -1;
@SuppressLint({ "NewApi", "NewApi" }) //so it doesn't error on getActionBar()
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timelinechoice);
if (android.os.Build.VERSION.SDK_INT >= 11) { //11 = API 11 i.e. honeycomb
getActionBar().setDisplayHomeAsUpEnabled(true);
}
//TODO: get timeline list, populate list with timelines
//somehow return a list of geopoints to the main activity when something is selected here
//TODO: the intent returning needs to be done somehow before onPause() so
//prob at after user selects a timeline from the list. Every time user selects timeline from list
//new Thread(new TimelineRetriever(this)).start();
new TimelineRetrieverTask(this).execute();
}
private void retrieveTimelines() {
try {
readXML();
} catch (Exception e) {}
}
/*
* Read the XML file in a nice way
*/
private void readXML() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
- System.out.println("Starting Read...");
DefaultHandler handler = new DefaultHandler() {
int noOfTimelines = 0;
boolean btime = false;
boolean bname = false;
boolean bdesc = false;
boolean bmonth = false;
boolean bday = false;
String name;
Double time;
String desc;
int month;
int day;
int timepointID;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
- System.out.println("Start Element: " + qName);
if (qName.equalsIgnoreCase("name")) { bname = true; }
if (qName.equalsIgnoreCase("description")) { bdesc = true; }
if (qName.equalsIgnoreCase("month")) { bmonth = true; }
if (qName.equalsIgnoreCase("day")) { bday = true; }
if (qName.equalsIgnoreCase("yearInBC")) { btime = true; }
for (int i = 0; i < attributes.getLength(); i++) {
if (attributes.getQName(i).equalsIgnoreCase("timelineName")) {
timelines.add(noOfTimelines, new Timeline(attributes.getValue(i), noOfTimelines));
noOfTimelines++;
}
if (attributes.getQName(i).equalsIgnoreCase("timepointID")) {
timepointID = Integer.parseInt(attributes.getValue(i));
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
- System.out.println("End Element: " + qName);
if(qName.equalsIgnoreCase("timepoint")) {
timelines.get(noOfTimelines - 1).addTimePoint(time, timepointID, name, desc, month, day);
- System.out.println("+ TP [" + timelines.get(noOfTimelines - 1).getLineName() + "]: " + time + "|" + timepointID + "|" + name + "|" + desc + "|" + month + "|" + day);
- //size++;
}
- //TODO: Add a timelineName option to get the different timeline names
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bname) {
name = new String(ch, start, length);
bname = false;
}
if (bdesc) {
desc = new String(ch, start, length);
bdesc = false;
}
if (bmonth) {
month = Integer.parseInt(new String(ch, start, length));
bmonth = false;
}
if (bday) {
day = Integer.parseInt(new String(ch, start, length));
bday = false;
}
if (btime) {
time = Double.parseDouble(new String(ch, start, length));
btime = false;
}
}
};
saxParser.parse(APIURL, handler);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_timelinechoice, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.menu_refresh:
new TimelineRetrieverTask(this).execute();
return true;
}
return super.onOptionsItemSelected(item);
}
private class TimelineRetrieverTask extends AsyncTask<Void, Void, Void> {
private Context context;
public TimelineRetrieverTask(Context ct) {
context = ct;
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
retrieveTimelines();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
String[] tlNames = new String[timelines.size()];
for (int i = 0; i < timelines.size(); i++) {
tlNames[i] = timelines.get(i).getLineName();
}
ArrayAdapter ad=new ArrayAdapter(context,android.R.layout.simple_list_item_1,tlNames);
final ListView list=(ListView)findViewById(R.id.tlcList);
list.setAdapter(ad);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
TextView txt=(TextView)findViewById(R.id.tlcTXT);
txt.setText(list.getItemAtPosition(arg2).toString());
timelineChoice = arg2;
//the following is quick/dirty purely for making-work purposes
Intent result = new Intent();
result.putExtra("selectedTimeline", timelines.get(arg2));
setResult(RESULT_OK, result);
finish();
}
});
}
}
}
| false | true | private void readXML() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
System.out.println("Starting Read...");
DefaultHandler handler = new DefaultHandler() {
int noOfTimelines = 0;
boolean btime = false;
boolean bname = false;
boolean bdesc = false;
boolean bmonth = false;
boolean bday = false;
String name;
Double time;
String desc;
int month;
int day;
int timepointID;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
System.out.println("Start Element: " + qName);
if (qName.equalsIgnoreCase("name")) { bname = true; }
if (qName.equalsIgnoreCase("description")) { bdesc = true; }
if (qName.equalsIgnoreCase("month")) { bmonth = true; }
if (qName.equalsIgnoreCase("day")) { bday = true; }
if (qName.equalsIgnoreCase("yearInBC")) { btime = true; }
for (int i = 0; i < attributes.getLength(); i++) {
if (attributes.getQName(i).equalsIgnoreCase("timelineName")) {
timelines.add(noOfTimelines, new Timeline(attributes.getValue(i), noOfTimelines));
noOfTimelines++;
}
if (attributes.getQName(i).equalsIgnoreCase("timepointID")) {
timepointID = Integer.parseInt(attributes.getValue(i));
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("End Element: " + qName);
if(qName.equalsIgnoreCase("timepoint")) {
timelines.get(noOfTimelines - 1).addTimePoint(time, timepointID, name, desc, month, day);
System.out.println("+ TP [" + timelines.get(noOfTimelines - 1).getLineName() + "]: " + time + "|" + timepointID + "|" + name + "|" + desc + "|" + month + "|" + day);
//size++;
}
//TODO: Add a timelineName option to get the different timeline names
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bname) {
name = new String(ch, start, length);
bname = false;
}
if (bdesc) {
desc = new String(ch, start, length);
bdesc = false;
}
if (bmonth) {
month = Integer.parseInt(new String(ch, start, length));
bmonth = false;
}
if (bday) {
day = Integer.parseInt(new String(ch, start, length));
bday = false;
}
if (btime) {
time = Double.parseDouble(new String(ch, start, length));
btime = false;
}
}
};
saxParser.parse(APIURL, handler);
}
| private void readXML() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
int noOfTimelines = 0;
boolean btime = false;
boolean bname = false;
boolean bdesc = false;
boolean bmonth = false;
boolean bday = false;
String name;
Double time;
String desc;
int month;
int day;
int timepointID;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("name")) { bname = true; }
if (qName.equalsIgnoreCase("description")) { bdesc = true; }
if (qName.equalsIgnoreCase("month")) { bmonth = true; }
if (qName.equalsIgnoreCase("day")) { bday = true; }
if (qName.equalsIgnoreCase("yearInBC")) { btime = true; }
for (int i = 0; i < attributes.getLength(); i++) {
if (attributes.getQName(i).equalsIgnoreCase("timelineName")) {
timelines.add(noOfTimelines, new Timeline(attributes.getValue(i), noOfTimelines));
noOfTimelines++;
}
if (attributes.getQName(i).equalsIgnoreCase("timepointID")) {
timepointID = Integer.parseInt(attributes.getValue(i));
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("timepoint")) {
timelines.get(noOfTimelines - 1).addTimePoint(time, timepointID, name, desc, month, day);
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bname) {
name = new String(ch, start, length);
bname = false;
}
if (bdesc) {
desc = new String(ch, start, length);
bdesc = false;
}
if (bmonth) {
month = Integer.parseInt(new String(ch, start, length));
bmonth = false;
}
if (bday) {
day = Integer.parseInt(new String(ch, start, length));
bday = false;
}
if (btime) {
time = Double.parseDouble(new String(ch, start, length));
btime = false;
}
}
};
saxParser.parse(APIURL, handler);
}
|
diff --git a/src/main/java/org/apache/log4j/helpers/QuietWriter.java b/src/main/java/org/apache/log4j/helpers/QuietWriter.java
index 68a96da8..c244f80f 100644
--- a/src/main/java/org/apache/log4j/helpers/QuietWriter.java
+++ b/src/main/java/org/apache/log4j/helpers/QuietWriter.java
@@ -1,75 +1,77 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.helpers;
import java.io.Writer;
import java.io.FilterWriter;
import java.io.IOException;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.ErrorCode;
/**
QuietWriter does not throw exceptions when things go
wrong. Instead, it delegates error handling to its {@link ErrorHandler}.
@author Ceki Gülcü
@since 0.7.3
*/
public class QuietWriter extends FilterWriter {
protected ErrorHandler errorHandler;
public
QuietWriter(Writer writer, ErrorHandler errorHandler) {
super(writer);
setErrorHandler(errorHandler);
}
public
void write(String string) {
- try {
- out.write(string);
- } catch(IOException e) {
- errorHandler.error("Failed to write ["+string+"].", e,
- ErrorCode.WRITE_FAILURE);
+ if (string != null) {
+ try {
+ out.write(string);
+ } catch(IOException e) {
+ errorHandler.error("Failed to write ["+string+"].", e,
+ ErrorCode.WRITE_FAILURE);
+ }
}
}
public
void flush() {
try {
out.flush();
} catch(IOException e) {
errorHandler.error("Failed to flush writer,", e,
ErrorCode.FLUSH_FAILURE);
}
}
public
void setErrorHandler(ErrorHandler eh) {
if(eh == null) {
// This is a programming error on the part of the enclosing appender.
throw new IllegalArgumentException("Attempted to set null ErrorHandler.");
} else {
this.errorHandler = eh;
}
}
}
| true | true | void write(String string) {
try {
out.write(string);
} catch(IOException e) {
errorHandler.error("Failed to write ["+string+"].", e,
ErrorCode.WRITE_FAILURE);
}
}
| void write(String string) {
if (string != null) {
try {
out.write(string);
} catch(IOException e) {
errorHandler.error("Failed to write ["+string+"].", e,
ErrorCode.WRITE_FAILURE);
}
}
}
|
diff --git a/common/net/minecraft/src/buildcraft/logisticspipes/items/CraftingSignCreator.java b/common/net/minecraft/src/buildcraft/logisticspipes/items/CraftingSignCreator.java
index 79975573..89397cbb 100644
--- a/common/net/minecraft/src/buildcraft/logisticspipes/items/CraftingSignCreator.java
+++ b/common/net/minecraft/src/buildcraft/logisticspipes/items/CraftingSignCreator.java
@@ -1,201 +1,201 @@
package net.minecraft.src.buildcraft.logisticspipes.items;
import net.minecraft.src.BuildCraftTransport;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.ItemStack;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
import net.minecraft.src.mod_BuildCraftTransport;
import net.minecraft.src.mod_LogisticsPipes;
import net.minecraft.src.buildcraft.krapht.LogisticsItem;
import net.minecraft.src.buildcraft.krapht.RoutedPipe;
import net.minecraft.src.buildcraft.krapht.logic.LogicCrafting;
import net.minecraft.src.buildcraft.krapht.pipes.PipeItemsCraftingLogistics;
import net.minecraft.src.buildcraft.logisticspipes.blocks.LogisticsBlock;
import net.minecraft.src.buildcraft.logisticspipes.blocks.LogisticsTileEntiy;
import net.minecraft.src.buildcraft.transport.Pipe;
import net.minecraft.src.buildcraft.transport.PipeLogic;
import net.minecraft.src.buildcraft.transport.TileGenericPipe;
public class CraftingSignCreator extends LogisticsItem {
public CraftingSignCreator(int i) {
super(i);
this.setMaxStackSize(1);
}
@Override
public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int sideinput)
{
- if(itemStack.getItemDamage() > this.getMaxDamage()) {
+ if(itemStack.getItemDamage() > this.getMaxDamage() || itemStack.stackSize == 0) {
return false;
}
int side = sideinput % 10;
boolean selfcalled = sideinput > 10;
TileEntity tile = world.getBlockTileEntity(x, y, z);
if(!(tile instanceof TileGenericPipe)) {
return false;
}
Pipe pipe = ((TileGenericPipe)tile).pipe;
if(pipe == null) {
return false;
}
if(!(pipe instanceof RoutedPipe)) {
itemStack.damageItem(10, player);
return true;
}
if(pipe.logic instanceof LogicCrafting) {
if(side > 1 && side < 6) {
int signX = x;
int signY = y;
int signZ = z;
int pipechecksignX = x;
int pipechecksignY = y;
int pipechecksignZ = z;
switch(side) {
case 2:
signZ--;
pipechecksignZ++;
break;
case 3:
signZ++;
pipechecksignZ--;
break;
case 4:
signX--;
pipechecksignX++;
break;
case 5:
signX++;
pipechecksignX--;
break;
}
if(!(world.getBlockTileEntity(pipechecksignX, pipechecksignY, pipechecksignZ) instanceof TileGenericPipe && ((TileGenericPipe)tile).pipe instanceof PipeItemsCraftingLogistics) && !selfcalled) {
if(world.getBlockId(signX, signY, signZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(signX, signY, signZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(signX, signY, signZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(signX, signY, signZ, 0, 0);
}
}
}
} else {
TileEntity secondTile = world.getBlockTileEntity(pipechecksignX, pipechecksignY, pipechecksignZ);
if(secondTile instanceof TileGenericPipe) {
Pipe secondpipe = ((TileGenericPipe)secondTile).pipe;
if(secondpipe != null) {
if(secondpipe instanceof PipeItemsCraftingLogistics) {
double disX = x - player.posX;
double disZ = z - player.posZ;
int secondSignX = x;
int secondSignY = y;
int secondSignZ = z;
switch(side) {
case 2:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 3:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 4:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
case 5:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
}
if(world.getBlockId(secondSignX, secondSignY, secondSignZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(secondSignX, secondSignY, secondSignZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, 0, 0);
}
}
}
this.onItemUse(itemStack, player ,world, pipechecksignX, pipechecksignY, pipechecksignZ, side + 10);
}
}
} else if(selfcalled) {
double disX = x - player.posX;
double disZ = z - player.posZ;
int secondSignX = x;
int secondSignY = y;
int secondSignZ = z;
switch(side) {
case 2:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 3:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 4:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
case 5:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
}
if(world.getBlockId(secondSignX, secondSignY, secondSignZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(secondSignX, secondSignY, secondSignZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, 0, 0);
}
}
}
}
}
}
}
return true;
}
@Override
public int getMaxDamage() {
return 100;
}
}
| true | true | public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int sideinput)
{
if(itemStack.getItemDamage() > this.getMaxDamage()) {
return false;
}
int side = sideinput % 10;
boolean selfcalled = sideinput > 10;
TileEntity tile = world.getBlockTileEntity(x, y, z);
if(!(tile instanceof TileGenericPipe)) {
return false;
}
Pipe pipe = ((TileGenericPipe)tile).pipe;
if(pipe == null) {
return false;
}
if(!(pipe instanceof RoutedPipe)) {
itemStack.damageItem(10, player);
return true;
}
if(pipe.logic instanceof LogicCrafting) {
if(side > 1 && side < 6) {
int signX = x;
int signY = y;
int signZ = z;
int pipechecksignX = x;
int pipechecksignY = y;
int pipechecksignZ = z;
switch(side) {
case 2:
signZ--;
pipechecksignZ++;
break;
case 3:
signZ++;
pipechecksignZ--;
break;
case 4:
signX--;
pipechecksignX++;
break;
case 5:
signX++;
pipechecksignX--;
break;
}
if(!(world.getBlockTileEntity(pipechecksignX, pipechecksignY, pipechecksignZ) instanceof TileGenericPipe && ((TileGenericPipe)tile).pipe instanceof PipeItemsCraftingLogistics) && !selfcalled) {
if(world.getBlockId(signX, signY, signZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(signX, signY, signZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(signX, signY, signZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(signX, signY, signZ, 0, 0);
}
}
}
} else {
TileEntity secondTile = world.getBlockTileEntity(pipechecksignX, pipechecksignY, pipechecksignZ);
if(secondTile instanceof TileGenericPipe) {
Pipe secondpipe = ((TileGenericPipe)secondTile).pipe;
if(secondpipe != null) {
if(secondpipe instanceof PipeItemsCraftingLogistics) {
double disX = x - player.posX;
double disZ = z - player.posZ;
int secondSignX = x;
int secondSignY = y;
int secondSignZ = z;
switch(side) {
case 2:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 3:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 4:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
case 5:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
}
if(world.getBlockId(secondSignX, secondSignY, secondSignZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(secondSignX, secondSignY, secondSignZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, 0, 0);
}
}
}
this.onItemUse(itemStack, player ,world, pipechecksignX, pipechecksignY, pipechecksignZ, side + 10);
}
}
} else if(selfcalled) {
double disX = x - player.posX;
double disZ = z - player.posZ;
int secondSignX = x;
int secondSignY = y;
int secondSignZ = z;
switch(side) {
case 2:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 3:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 4:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
case 5:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
}
if(world.getBlockId(secondSignX, secondSignY, secondSignZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(secondSignX, secondSignY, secondSignZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, 0, 0);
}
}
}
}
}
}
}
return true;
}
| public boolean onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int sideinput)
{
if(itemStack.getItemDamage() > this.getMaxDamage() || itemStack.stackSize == 0) {
return false;
}
int side = sideinput % 10;
boolean selfcalled = sideinput > 10;
TileEntity tile = world.getBlockTileEntity(x, y, z);
if(!(tile instanceof TileGenericPipe)) {
return false;
}
Pipe pipe = ((TileGenericPipe)tile).pipe;
if(pipe == null) {
return false;
}
if(!(pipe instanceof RoutedPipe)) {
itemStack.damageItem(10, player);
return true;
}
if(pipe.logic instanceof LogicCrafting) {
if(side > 1 && side < 6) {
int signX = x;
int signY = y;
int signZ = z;
int pipechecksignX = x;
int pipechecksignY = y;
int pipechecksignZ = z;
switch(side) {
case 2:
signZ--;
pipechecksignZ++;
break;
case 3:
signZ++;
pipechecksignZ--;
break;
case 4:
signX--;
pipechecksignX++;
break;
case 5:
signX++;
pipechecksignX--;
break;
}
if(!(world.getBlockTileEntity(pipechecksignX, pipechecksignY, pipechecksignZ) instanceof TileGenericPipe && ((TileGenericPipe)tile).pipe instanceof PipeItemsCraftingLogistics) && !selfcalled) {
if(world.getBlockId(signX, signY, signZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(signX, signY, signZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(signX, signY, signZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(signX, signY, signZ, 0, 0);
}
}
}
} else {
TileEntity secondTile = world.getBlockTileEntity(pipechecksignX, pipechecksignY, pipechecksignZ);
if(secondTile instanceof TileGenericPipe) {
Pipe secondpipe = ((TileGenericPipe)secondTile).pipe;
if(secondpipe != null) {
if(secondpipe instanceof PipeItemsCraftingLogistics) {
double disX = x - player.posX;
double disZ = z - player.posZ;
int secondSignX = x;
int secondSignY = y;
int secondSignZ = z;
switch(side) {
case 2:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 3:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 4:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
case 5:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
}
if(world.getBlockId(secondSignX, secondSignY, secondSignZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(secondSignX, secondSignY, secondSignZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, 0, 0);
}
}
}
this.onItemUse(itemStack, player ,world, pipechecksignX, pipechecksignY, pipechecksignZ, side + 10);
}
}
} else if(selfcalled) {
double disX = x - player.posX;
double disZ = z - player.posZ;
int secondSignX = x;
int secondSignY = y;
int secondSignZ = z;
switch(side) {
case 2:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 3:
if(disX > 0) {
secondSignX--;
} else {
secondSignX++;
}
break;
case 4:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
case 5:
if(disZ > 0) {
secondSignZ--;
} else {
secondSignZ++;
}
break;
}
if(world.getBlockId(secondSignX, secondSignY, secondSignZ) == 0) {
if(((PipeItemsCraftingLogistics)pipe).canRegisterSign()) {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, mod_LogisticsPipes.LOGISTICS_BLOCK_ID, LogisticsBlock.SignBlockID);
TileEntity tilesign = world.getBlockTileEntity(secondSignX, secondSignY, secondSignZ);
if(tilesign instanceof LogisticsTileEntiy) {
((PipeItemsCraftingLogistics)pipe).addSign((LogisticsTileEntiy)tilesign);
itemStack.damageItem(1, player);
} else {
world.setBlockAndMetadataWithNotify(secondSignX, secondSignY, secondSignZ, 0, 0);
}
}
}
}
}
}
}
return true;
}
|
diff --git a/src/java/com/google/caja/parser/html/HtmlDomParser.java b/src/java/com/google/caja/parser/html/HtmlDomParser.java
index 5488fe13..cc94d124 100644
--- a/src/java/com/google/caja/parser/html/HtmlDomParser.java
+++ b/src/java/com/google/caja/parser/html/HtmlDomParser.java
@@ -1,296 +1,298 @@
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.caja.parser.html;
import com.google.caja.lexer.HtmlTokenType;
import com.google.caja.lexer.TokenQueue;
import com.google.caja.lexer.ParseException;
import com.google.caja.lexer.Token;
import com.google.caja.lexer.FilePosition;
import com.google.caja.lexer.TokenType;
import com.google.caja.lexer.TokenQueue.Mark;
import com.google.caja.plugin.HtmlPluginCompiler;
import com.google.caja.plugin.GxpCompiler;
import com.google.caja.reporting.MessagePart;
import com.google.caja.reporting.Message;
import com.google.caja.reporting.MessageType;
import com.google.caja.parser.ParseTreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* parses a {@link DomTree} from a stream of xml tokens.
*
* @author [email protected]
*/
public final class HtmlDomParser {
public static DomTree parseDocument(
TokenQueue<HtmlTokenType> tokens, HtmlPluginCompiler c)
throws ParseException {
ignoreTopLevelIgnorables(tokens);
DomTree doc = parseDom(tokens, c);
ignoreTopLevelIgnorables(tokens);
tokens.expectEmpty();
return doc;
}
private static void ignoreTopLevelIgnorables(TokenQueue<HtmlTokenType> tokens)
throws ParseException {
while (!tokens.isEmpty()) {
Token<HtmlTokenType> t = tokens.peek();
if (HtmlTokenType.IGNORABLE != t.type && HtmlTokenType.COMMENT != t.type
&& (HtmlTokenType.TEXT != t.type || !"".equals(t.text.trim()))) {
break;
}
tokens.advance();
}
}
private static DomTree parseDom(TokenQueue<HtmlTokenType> tokens,
HtmlPluginCompiler c)
throws ParseException {
while (true) {
Token<HtmlTokenType> t = tokens.pop();
Token<HtmlTokenType> end = t;
switch (t.type) {
case TAGBEGIN:
if (isClose(t)) {
throw new ParseException(new Message(
MessageType.MALFORMED_XHTML, t.pos,
MessagePart.Factory.valueOf(t.text)));
}
List<DomTree> children = new ArrayList<DomTree>();
end = parseElement(t, tokens, children, c);
children = Collections.unmodifiableList(normalize(children));
return new DomTree.Tag(children, t, end);
case CDATA:
return new DomTree.CData(t);
case TEXT:
return new DomTree.Text(t);
case COMMENT:
//continue;
// There were nasty issues when the contents of a script tag were nested
// within html comments <!-- ... -->. Returning null here resolves them
// by counting the comment token as a complete tag rather than just an
// open tag.
// TODO(ihab): Modify the markup lexer to take a set of tag names
// whose content is CDATA, and for html, initialize it with
// (script|style|xmp|listing).
return null;
default:
throw new ParseException(new Message(
MessageType.MALFORMED_XHTML, t.pos,
MessagePart.Factory.valueOf(t.text)));
}
}
}
private static Token<HtmlTokenType> parseElement(
Token<HtmlTokenType> start, TokenQueue<HtmlTokenType> tokens,
List<DomTree> children, HtmlPluginCompiler c)
throws ParseException {
Token<HtmlTokenType> last;
tokloop:
while (true) {
last = tokens.peek();
switch (last.type) {
case TAGEND:
tokens.advance();
break tokloop;
case ATTRNAME:
children.add(parseAttrib(tokens));
break;
default:
throw new ParseException(new Message(
MessageType.MALFORMED_XHTML, last.pos,
MessagePart.Factory.valueOf(last.text)));
}
}
if (">".equals(last.text)) { // look for an end tag
String tagName = tagName(start);
if (tagName.equals("script") || tagName.equals("style")) {
return extractTagContents(tagName, last, tokens, c);
}
while (true) {
last = tokens.peek();
if (last.type == HtmlTokenType.TAGBEGIN && isClose(last)) {
if (!tagName.equals(tagName(last))) {
throw new ParseException(new Message(
MessageType.MISSING_ENDTAG, last.pos,
MessagePart.Factory.valueOf("<" + tagName + ">"),
MessagePart.Factory.valueOf(last.text + ">")));
}
tokens.advance();
// consume ignorable whitespace until we see a tagend
while (tokens.peek().type == HtmlTokenType.IGNORABLE) {
tokens.advance();
}
last = tokens.peek();
tokens.expectToken(">");
break;
} else {
DomTree dom = parseDom(tokens, c);
if (dom != null) {
children.add(dom);
}
}
}
}
return last;
}
/**
* When we see a <script> or <style> tag, we want to read its entire contents
* and then route them back through the compiler appropriately before resuming
* html parsing as normal.
*/
private static Token<HtmlTokenType> extractTagContents(
String tagName, Token<HtmlTokenType> last,
TokenQueue<HtmlTokenType> tokens, HtmlPluginCompiler c)
throws ParseException {
FilePosition posBegin = last.pos;
FilePosition posEnd = last.pos;
Mark start = tokens.mark();
+ Mark end = start;
while (true) {
last = tokens.peek();
if (last.type == HtmlTokenType.TAGBEGIN && isClose(last) &&
tagName.equalsIgnoreCase(tagName(last))) {
// consume ignorable whitespace until we see a tagend
while (true) {
posEnd = last.pos;
tokens.advance();
if (tokens.peek().type != HtmlTokenType.IGNORABLE) {
break;
}
}
last = tokens.peek();
tokens.expectToken(">");
break;
}
+ end = tokens.mark();
tokens.advance();
}
- Mark end = tokens.mark();
// the TokenQueue skips over some things (e.g. whitespace) so it's important
// that we go back and extract the tag's contents from the input
// source itself.
FilePosition pos = FilePosition.between(posBegin, posEnd);
String tagContent = contentBetween(start, end, tokens);
// Remove HTML comments in the SCRIPT tag that HTML authors use to cloak
// JavaScript from older browsers.
tagContent = tagContent
.replaceFirst("^(\\s*)<!--", "$1 ")
.replaceFirst("-->(\\s*)", " $1");
+ String canonicalTagName = tagName.toLowerCase();
try {
ParseTreeNode node = null;
- if (tagName.equals("script")) {
+ if (canonicalTagName.equals("script")) {
node = c.parseJsString(tagContent, pos);
- } else if (tagName.equals("style")) {
+ } else if (canonicalTagName.equals("style")) {
node = c.parseCssString(tagContent, pos);
}
c.addInput(node);
} catch (GxpCompiler.BadContentException ex) {
throw new ParseException(
new Message(
MessageType.PARSE_ERROR,
pos,
- MessagePart.Factory.valueOf(
- ("<" + tagName + "> tag."))));
+ MessagePart.Factory.valueOf(("<" + tagName + "> tag."))),
+ ex);
}
return last;
}
/**
* Reconstructs the input text between a range of marks from a token queue.
* @param start inclusive
* @param end exclusive
*/
private static <T extends TokenType>
String contentBetween(Mark start, Mark end, TokenQueue<T> q)
throws ParseException {
Mark orig = q.mark();
q.rewind(end);
int endChar = q.currentPosition().endCharInFile();
q.rewind(start);
int startChar = q.currentPosition().startCharInFile();
StringBuilder sb = new StringBuilder(endChar - startChar);
while (q.currentPosition().startCharInFile() < endChar) {
Token t = q.pop();
sb.append(t.text);
}
q.rewind(orig);
return sb.toString();
}
private static DomTree parseAttrib(TokenQueue<HtmlTokenType> tokens)
throws ParseException {
Token<HtmlTokenType> name = tokens.pop();
Token<HtmlTokenType> value = tokens.pop();
if (value.type != HtmlTokenType.ATTRVALUE) {
throw new ParseException(
new Message(MessageType.MALFORMED_XHTML,
value.pos, MessagePart.Factory.valueOf(value.text)));
}
return new DomTree.Attrib(new DomTree.Value(value), name, name);
}
private static boolean isClose(Token<HtmlTokenType> t) {
return t.text.startsWith("</");
}
private static String tagName(Token<HtmlTokenType> t) {
return t.text.substring(isClose(t) ? 2 : 1);
}
/** collapse adjacent text nodes. */
private static List<DomTree> normalize(List<DomTree> nodes) {
for (int i = 0; i < nodes.size(); ++i) {
DomTree node = nodes.get(i);
if (HtmlTokenType.TEXT == node.getType()) {
int j = i + 1;
for (int n = nodes.size(); j < n; ++j) {
if (HtmlTokenType.TEXT != nodes.get(j).getType()) { break; }
}
if (j - i > 1) {
Token<HtmlTokenType> firstToken = node.getToken(),
lastToken = nodes.get(j - 1).getToken();
StringBuilder newText = new StringBuilder(firstToken.text);
for (int k = i + 1; k < j; ++k) {
newText.append(nodes.get(k).getToken().text);
}
Token<HtmlTokenType> normalToken = Token.<HtmlTokenType>instance(
newText.toString(), HtmlTokenType.TEXT,
FilePosition.span(firstToken.pos, lastToken.pos));
nodes.set(i, new DomTree.Text(normalToken));
nodes.subList(i + 1, j).clear();
i = j - 1;
}
}
}
return nodes;
}
private HtmlDomParser() {
// uninstantiable
}
}
| false | true | private static Token<HtmlTokenType> extractTagContents(
String tagName, Token<HtmlTokenType> last,
TokenQueue<HtmlTokenType> tokens, HtmlPluginCompiler c)
throws ParseException {
FilePosition posBegin = last.pos;
FilePosition posEnd = last.pos;
Mark start = tokens.mark();
while (true) {
last = tokens.peek();
if (last.type == HtmlTokenType.TAGBEGIN && isClose(last) &&
tagName.equalsIgnoreCase(tagName(last))) {
// consume ignorable whitespace until we see a tagend
while (true) {
posEnd = last.pos;
tokens.advance();
if (tokens.peek().type != HtmlTokenType.IGNORABLE) {
break;
}
}
last = tokens.peek();
tokens.expectToken(">");
break;
}
tokens.advance();
}
Mark end = tokens.mark();
// the TokenQueue skips over some things (e.g. whitespace) so it's important
// that we go back and extract the tag's contents from the input
// source itself.
FilePosition pos = FilePosition.between(posBegin, posEnd);
String tagContent = contentBetween(start, end, tokens);
// Remove HTML comments in the SCRIPT tag that HTML authors use to cloak
// JavaScript from older browsers.
tagContent = tagContent
.replaceFirst("^(\\s*)<!--", "$1 ")
.replaceFirst("-->(\\s*)", " $1");
try {
ParseTreeNode node = null;
if (tagName.equals("script")) {
node = c.parseJsString(tagContent, pos);
} else if (tagName.equals("style")) {
node = c.parseCssString(tagContent, pos);
}
c.addInput(node);
} catch (GxpCompiler.BadContentException ex) {
throw new ParseException(
new Message(
MessageType.PARSE_ERROR,
pos,
MessagePart.Factory.valueOf(
("<" + tagName + "> tag."))));
}
return last;
}
| private static Token<HtmlTokenType> extractTagContents(
String tagName, Token<HtmlTokenType> last,
TokenQueue<HtmlTokenType> tokens, HtmlPluginCompiler c)
throws ParseException {
FilePosition posBegin = last.pos;
FilePosition posEnd = last.pos;
Mark start = tokens.mark();
Mark end = start;
while (true) {
last = tokens.peek();
if (last.type == HtmlTokenType.TAGBEGIN && isClose(last) &&
tagName.equalsIgnoreCase(tagName(last))) {
// consume ignorable whitespace until we see a tagend
while (true) {
posEnd = last.pos;
tokens.advance();
if (tokens.peek().type != HtmlTokenType.IGNORABLE) {
break;
}
}
last = tokens.peek();
tokens.expectToken(">");
break;
}
end = tokens.mark();
tokens.advance();
}
// the TokenQueue skips over some things (e.g. whitespace) so it's important
// that we go back and extract the tag's contents from the input
// source itself.
FilePosition pos = FilePosition.between(posBegin, posEnd);
String tagContent = contentBetween(start, end, tokens);
// Remove HTML comments in the SCRIPT tag that HTML authors use to cloak
// JavaScript from older browsers.
tagContent = tagContent
.replaceFirst("^(\\s*)<!--", "$1 ")
.replaceFirst("-->(\\s*)", " $1");
String canonicalTagName = tagName.toLowerCase();
try {
ParseTreeNode node = null;
if (canonicalTagName.equals("script")) {
node = c.parseJsString(tagContent, pos);
} else if (canonicalTagName.equals("style")) {
node = c.parseCssString(tagContent, pos);
}
c.addInput(node);
} catch (GxpCompiler.BadContentException ex) {
throw new ParseException(
new Message(
MessageType.PARSE_ERROR,
pos,
MessagePart.Factory.valueOf(("<" + tagName + "> tag."))),
ex);
}
return last;
}
|
diff --git a/src/vddlogger/VddSummaryReporter.java b/src/vddlogger/VddSummaryReporter.java
index 583ee7b..df748f5 100644
--- a/src/vddlogger/VddSummaryReporter.java
+++ b/src/vddlogger/VddSummaryReporter.java
@@ -1,827 +1,833 @@
/*
Copyright 2011 SugarCRM 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 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.
Please see the License for the specific language governing permissions and
limitations under the License.
*/
package vddlogger;
import java.io.*;
import java.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class VddSummaryReporter {
private String HTML_HEADER_RESOURCE = "summaryreporter-header.txt";
private String HTML_HEADER_ISSUES_RESOURCE = "issues-header.txt";
private int count;
private ArrayList<File> xmlFiles;
private int passedTests = 0;
private int failedTests = 0;
private int blockedTests = 0;
private int failedAsserts = 0;
private int passedAsserts = 0;
private int exceptions = 0;
private int errors = 0;
private int watchdog = 0;
private int hours = 0;
private int minutes = 0;
private int seconds = 0;
private FileOutputStream output;
private PrintStream repFile;
private Document dom;
private String basedir = "";
private VddLogIssues issues = null;
private String issuesHtmlFile = null;
public VddSummaryReporter(ArrayList<File> xmlFiles, String path) {
this.count = 0;
this.xmlFiles = xmlFiles;
passedTests = 0;
failedTests = 0;
blockedTests = 0;
failedAsserts = 0;
passedAsserts = 0;
exceptions = 0;
errors = 0;
watchdog = 0;
hours = 0;
minutes = 0;
seconds = 0;
String summaryFile = String.format("%s%s%s", path, File.separatorChar, "summary.html");
this.issuesHtmlFile = String.format("%s%s%s", path, File.separatorChar, "issues.html");
this.basedir = path;
this.issues = new VddLogIssues();
try {
output = new FileOutputStream(summaryFile);
System.out.printf("(*)SummaryFile: %s\n", summaryFile);
repFile = new PrintStream(output);
} catch (Exception e) {
System.out.printf("(!)Error: Failed trying to write file: '%s'!\n", summaryFile);
e.printStackTrace();
}
}
private void writeIssues() {
String[] errors_keys = null;
String[] warnings_keys = null;
String[] except_keys = null;
String line = "";
InputStream stream = null;
HashMap<String, Integer> tmpMap = null;
System.out.printf("(*)Writting issues file...\n");
errors_keys = sortIssue(this.issues.getData().get("errors"));
warnings_keys = sortIssue(this.issues.getData().get("warnings"));
except_keys = sortIssue(this.issues.getData().get("exceptions"));
try {
String className = this.getClass().getName().replace('.', '/');
String classJar = this.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:")) {
stream = getClass().getResourceAsStream(this.HTML_HEADER_ISSUES_RESOURCE);
} else {
File header_fd = new File(getClass().getResource(this.HTML_HEADER_ISSUES_RESOURCE).getFile());
stream = new FileInputStream(header_fd);
}
InputStreamReader in = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(in);
File fd = new File(this.issuesHtmlFile);
BufferedWriter out = new BufferedWriter(new FileWriter(fd));
while ((line = br.readLine()) != null) {
out.write(line + "\n");
}
br.close();
in.close();
tmpMap = this.issues.getData().get("errors");
out.write("<table>\n");
out.write("<tr>\n<td class=\"td_header_master\" colspan=\"2\">Errors:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = errors_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(errors_keys[i]);
+ errors_keys[i] = errors_keys[i].replaceAll("<", "<");
+ errors_keys[i] = errors_keys[i].replaceAll(">", ">");
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, errors_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("\n<hr></hr>\n");
tmpMap = this.issues.getData().get("exceptions");
out.write("<table>\n");
out.write("<tr>\n<td class=\"td_header_master\" colspan=\"2\">Exceptions:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = except_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(except_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
+ except_keys[i] = except_keys[i].replaceAll("<", "<");
+ except_keys[i] = except_keys[i].replaceAll(">", ">");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, except_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("\n<hr></hr>\n");
tmpMap = this.issues.getData().get("warnings");
out.write("<table>\n");
out.write("<tr>\n\t<td class=\"td_header_master\" colspan=\"2\">Warnings:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = warnings_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(warnings_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
+ warnings_keys[i] = warnings_keys[i].replaceAll("<", "<");
+ warnings_keys[i] = warnings_keys[i].replaceAll(">", ">");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, warnings_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("</body></html>\n");
out.close();
} catch (Exception exp ) {
exp.printStackTrace();
}
System.out.printf("(*)Finished writting issues file.\n");
}
private String[] sortIssue(HashMap<String, Integer> map) {
String[] keys = null;
keys = map.keySet().toArray(new String[0]);
for (int i = 0; i <= keys.length -1; i++) {
int count = map.get(keys[i]);
keys[i] = String.format("%d:%s", count, keys[i]);
}
Arrays.sort(keys);
for (int i = 0; i <= keys.length -1; i++) {
keys[i] = keys[i].replaceFirst("\\d+:", "");
}
return keys;
}
public void generateReport() {
HashMap<String, HashMap<String, Object>> list = new HashMap<String, HashMap<String,Object>>();
repFile.print(generateHTMLHeader());
String name = "";
String[] keys = null;
for (int i = 0; i < xmlFiles.size(); i ++) {
HashMap<String, Object> suiteData = null;
suiteData = parseXMLFile(xmlFiles.get(i));
name = suiteData.get("suitename").toString();
list.put(name, suiteData);
}
keys = list.keySet().toArray(new String[0]);
java.util.Arrays.sort(keys);
for (int i = 0; i <= keys.length -1; i++) {
String key = keys[i];
repFile.print(generateTableRow(key, list.get(key)));
}
repFile.print(generateHTMLFooter());
repFile.print("\n</body>\n</html>\n");
repFile.close();
this.writeIssues();
}
private boolean isRestart(Node node) {
boolean result = false;
NodeList parent = node.getParentNode().getChildNodes();
for (int i = 0; i <= parent.getLength() -1; i++) {
Node tmp = parent.item(i);
String name = tmp.getNodeName();
if (name.contains("isrestart")) {
result = Boolean.valueOf(tmp.getTextContent());
break;
}
}
return result;
}
private boolean isLibTest(Node node) {
boolean result = false;
NodeList parent = node.getParentNode().getChildNodes();
for (int i = 0; i <= parent.getLength() -1; i++) {
Node tmp = parent.item(i);
String name = tmp.getNodeName();
if (name.contains("testfile")) {
File fd = new File(tmp.getTextContent());
String path = fd.getParent();
path = path.toLowerCase();
if (path.contains("lib")) {
//System.out.printf("LIBFILE: %s\n", tmp.getTextContent());
result = true;
break;
}
}
}
return result;
}
private boolean isBlocked(Node node) {
boolean result = false;
NodeList parent = node.getParentNode().getChildNodes();
for (int i = 0; i <= parent.getLength() -1; i++) {
Node tmp = parent.item(i);
String name = tmp.getNodeName();
if (name.contains("blocked")) {
int blocked = Integer.valueOf(tmp.getTextContent());
if (blocked != 0) {
result = true;
} else {
result = false;
}
break;
}
}
return result;
}
private HashMap<String, Object> getSuiteData(Document doc) {
HashMap<String, Object> result = new HashMap<String, Object>();
int passed = 0, failed = 0, blocked = 0, asserts = 0, assertsF = 0, errors = 0, exceptions = 0, wd = 0, total = 0;
String runtime = "";
String suiteName = getSuiteName(doc);
passed = getAmtPassed(doc);
blocked = getAmtBlocked(doc);
failed = getAmtFailed(doc);
wd = getAmtwatchdog(doc);
asserts = getAmtAsserts(doc);
assertsF = getAmtAssertsF(doc);
exceptions = getAmtExceptions(doc);
errors = getAmtErrors(doc);
total = assertsF + exceptions + errors;
runtime = getRunTime(doc);
result.put("passed", passed);
result.put("blocked", blocked);
result.put("failed", failed);
result.put("wd", wd);
result.put("asserts", asserts);
result.put("assertsF", assertsF);
result.put("exceptions", exceptions);
result.put("errors", errors);
result.put("total", total);
result.put("runtime", runtime);
result.put("suitename", suiteName);
result.put("testlogs", this.getTestLogs(doc));
return result;
}
/**
* generates a table row for summary.html from a DOM
* @return - a nicely formatted html table row for summary.html
*/
@SuppressWarnings("unchecked")
private String generateTableRow(String suiteName, HashMap<String, Object> data) {
int passed, failed, blocked, asserts, assertsF, errors, exceptions, wd, total;
suiteName = data.get("suitename").toString();
String runtime = "";
String html = "<tr id=\""+count+"\" class=\"unhighlight\" onmouseover=\"this.className='highlight'\" onmouseout=\"this.className='unhighlight'\"> \n" +
"<td class=\"td_file_data\">\n" +
"<a href=\""+suiteName+"/"+suiteName+".html\">"+suiteName+".xml</a> \n" +
"</td>";
passed = (Integer)data.get("passed");
blocked = (Integer)data.get("blocked");
failed = (Integer)data.get("failed");
wd = (Integer)data.get("wd");
asserts = (Integer)data.get("asserts");
assertsF = (Integer)data.get("assertsF");
exceptions = (Integer)data.get("exceptions");
errors = (Integer)data.get("errors");
total = assertsF + exceptions + errors;
runtime = data.get("runtime").toString();
int d1 = (passed+failed);
int d2 = (passed+failed+blocked);
String runclass = "td_run_data_error";
if (d1 == d2) {
runclass = "td_run_data";
}
html += "\t <td class=\""+runclass+"\">"+(passed+failed)+"/"+(passed+failed+blocked)+"</td>\n";
html += "\t <td class=\"td_passed_data\">"+passed+"</td> \n";
html += "\t <td class=\"td_failed_data\">"+failed+"</td> \n";
html += "\t <td class=\"td_blocked_data\">"+blocked+"</td> \n";
//"Results" column
if (wd == 0) {
html += "\t <td class=\"td_watchdog_data\">0</td> \n";
} else {
html += "\t <td class=\"td_watchdog_error_data\">"+wd+"</td> \n";
}
html += "\t <td class=\"td_assert_data\">"+asserts+"</td> \n";
if (assertsF == 0) {
html += "\t <td class=\"td_assert_data\">0</td> \n";
} else {
html += "\t <td class=\"td_assert_error_data\">"+assertsF+"</td> \n";
}
if (exceptions == 0) {
html += "\t <td class=\"td_exceptions_data\">0</td> \n";
} else {
html += "\t <td class=\"td_exceptions_error_data\">"+exceptions+"</td> \n";
}
if (errors == 0) {
html += "\t <td class=\"td_exceptions_data\">0</td> \n";
} else {
html += "\t <td class=\"td_exceptions_error_data\">"+errors+"</td> \n";
}
if (total == 0) {
html += "\t <td class=\"td_total_data\">0</td> \n";
} else {
html += "\t <td class=\"td_total_error_data\">"+total+"</td> \n";
}
html += "\t <td class=\"td_time_data\">"+runtime+"</td> \n";
html += "</tr>";
ArrayList<HashMap<String, String>> logs = (ArrayList<HashMap<String, String>>)data.get("testlogs");
VddSuiteReporter reporter = new VddSuiteReporter(suiteName, this.basedir, logs);
reporter.generateReport();
this.issues.appendIssues(reporter.getIssues());
return html;
}
/**
* generates the HTML table header for summary report, then returns it
* @return - String of html table header
*/
private String generateHTMLHeader() {
String header = "";
String line = "";
InputStream stream = null;
try {
String className = this.getClass().getName().replace('.', '/');
String classJar = this.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:")) {
stream = getClass().getResourceAsStream(this.HTML_HEADER_RESOURCE);
} else {
File header_fd = new File(getClass().getResource(this.HTML_HEADER_RESOURCE).getFile());
stream = new FileInputStream(header_fd);
}
InputStreamReader in = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(in);
while ((line = br.readLine()) != null) {
header += line;
header += "\n";
}
br.close();
in.close();
} catch (Exception exp ) {
exp.printStackTrace();
}
return header;
}
/**
* generates the HTML table footer for summary report, then returns it
* @return - String of html table footer
*/
private String generateHTMLFooter(){
int n1 = 0;
int n2 = 0;
String footerrun = "td_footer_run";
String failedtd = "td_footer_failed";
String blockedtd = "td_footer_blocked";
n1 = passedTests + failedTests;
n2 = passedTests + failedTests + blockedTests;
if (n1 != n2) {
footerrun = "td_footer_run_err";
}
if (failedTests == 0) {
failedtd = "td_footer_failed_zero";
}
if (blockedTests == 0) {
blockedtd = "td_footer_blocked_zero";
}
String footer = "<tr id=\"totals\"> \n" +
"\t <td class=\"td_header_master\">Totals:</td>" +
String.format("\t <td class=\"%s\">"+(passedTests + failedTests)+"/"+(passedTests + failedTests + blockedTests)+"</td>", footerrun) +
"\t <td class=\"td_footer_passed\">"+passedTests+"</td>" +
String.format("\t <td class=\"%s\">"+failedTests+"</td>", failedtd) +
String.format("\t <td class=\"%s\">"+blockedTests+"</td>", blockedtd) +
"\t <td class=\"td_footer_watchdog\">"+watchdog+"</td>" +
"\t <td class=\"td_footer_passed\">"+passedAsserts+"</td>" +
"\t <td class=\"td_footer_assert\">"+failedAsserts+"</td>" +
"\t <td class=\"td_footer_exceptions\">"+exceptions+"</td>" +
"\t <td class=\"td_footer_watchdog\">"+errors+"</td>" +
"\t <td class=\"td_footer_total\">"+(failedAsserts + exceptions + errors)+"</td>" +
"\t <td class=\"td_footer_times\">"+printTotalTime(hours, minutes, seconds)+"</td>" +
"</tr>" +
"</tbody>" +
"</table>";
return footer;
}
private HashMap<String, Object> parseXMLFile(File xml){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
HashMap<String, Object> result = new HashMap<String, Object>();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(xml);
result = getSuiteData(dom);
} catch(Exception e){
e.printStackTrace();
result = null;
}
return result;
}
/**
* get the number of tests that passed within this suite document
* @ param d - the Document containing suite run data
* @ return the number of tests that passed
*
*/
private int getAmtPassed(Document d) {
int n = 0;
Element el;
NodeList nl = d.getElementsByTagName("result");
boolean isrestart = false;
boolean islibfile = false;
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (el.getFirstChild().getNodeValue().compareToIgnoreCase("Passed") == 0) {
islibfile = isLibTest(nl.item(i));
isrestart = isRestart(nl.item(i));
if (isrestart) {
continue;
}
if (islibfile) {
continue;
}
n ++;
}
}
//global passedTests variable
passedTests += n;
return n;
}
/**
* get the number of tests that failed within this suite document
* @ param d - the Document containing suite run data
* @ return the number of tests that failed
*
*/
private int getAmtFailed(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
boolean isblocked = false;
NodeList nl = d.getElementsByTagName("result");
boolean islibfile = false;
for (int i = 0; i < nl.getLength(); i ++){
el = (Element)nl.item(i);
if (el.getFirstChild().getNodeValue().compareToIgnoreCase("Failed") == 0) {
isrestart = isRestart(nl.item(i));
isblocked = isBlocked(nl.item(i));
islibfile = isLibTest(nl.item(i));
if (isrestart) {
continue;
}
if (isblocked) {
continue;
}
if (islibfile) {
continue;
}
n ++;
}
}
//global failedTests variable
failedTests += n;
return n;
}
/**
* get the number of tests that was blocked within this suite document
* @ param d - the Document containing suite run data
* @ return the number of tests that was blocked
*
*/
private int getAmtBlocked(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
boolean islibfile = false;
NodeList nl = d.getElementsByTagName("blocked");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (el.getFirstChild().getNodeValue().compareToIgnoreCase("1") == 0) {
isrestart = isRestart(nl.item(i));
islibfile = isLibTest(nl.item(i));
if (isrestart) {
continue;
}
if (islibfile) {
continue;
}
n ++;
}
}
//global blockedTests variable
blockedTests += n;
return n;
}
private ArrayList<HashMap<String, String>> getTestLogs(Document d) {
ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String,String>>();
NodeList nodes = d.getElementsByTagName("test");
for (int i = 0; i <= nodes.getLength() -1; i++) {
Node currNode = nodes.item(i);
HashMap<String, String> newHash = new HashMap<String, String>();
NodeList kids = currNode.getChildNodes();
for (int x = 0; x <= kids.getLength() -1; x++) {
Node kidNode = kids.item(x);
if (kidNode.getNodeName().contains("testlog")) {
newHash.put(kidNode.getNodeName(), kidNode.getTextContent());
} else if (kidNode.getNodeName().contains("isrestart")) {
newHash.put(kidNode.getNodeName(), kidNode.getTextContent().toLowerCase());
}
}
result.add(newHash);
}
return result;
}
/**
* get the number of assertions that passed within this suite document
* @ param d - the Document containing suite run data
* @ return the number of passed assertions
*
*/
private int getAmtAsserts(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
NodeList nl = d.getElementsByTagName("passedasserts");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (Integer.parseInt(el.getFirstChild().getNodeValue()) > 0){
isrestart = isRestart(nl.item(i));
if (isrestart) {
//continue;
}
n += Integer.parseInt(el.getFirstChild().getNodeValue());
}
}
//global passedAsserts
passedAsserts += n;
return n;
}
/**
* get the number of assertions that failed within this suite document
* @ param d - the Document containing suite run data
* @ return the number of failed assertions
*
*/
private int getAmtAssertsF(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
NodeList nl = d.getElementsByTagName("failedasserts");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (Integer.parseInt(el.getFirstChild().getNodeValue()) > 0) {
isrestart = isRestart(nl.item(i));
if (isrestart) {
// continue;
}
n += Integer.parseInt(el.getFirstChild().getNodeValue());
}
}
//global failedAsserts
failedAsserts += n;
return n;
}
/**
* get the number of watchdogs within this suite document
* @ param d - the Document containing suite run data
* @ return the number of watchdogs
*
*/
private int getAmtwatchdog(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
NodeList nl = d.getElementsByTagName("watchdog");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (Integer.parseInt(el.getFirstChild().getNodeValue()) > 0) {
isrestart = isRestart(nl.item(i));
if (isrestart) {
// continue;
}
n += Integer.parseInt(el.getFirstChild().getNodeValue());
}
}
watchdog += n;
return n;
}
/**
* get the number of exceptions within this suite document
* @ param d - the Document containing suite run data
* @ return the number of exceptions
*
*/
private int getAmtExceptions(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
NodeList nl = d.getElementsByTagName("exceptions");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (Integer.parseInt(el.getFirstChild().getNodeValue()) > 0) {
isrestart = isRestart(nl.item(i));
if (isrestart) {
// continue;
}
n += Integer.parseInt(el.getFirstChild().getNodeValue());
}
}
//global exceptions
exceptions += n;
return n;
}
private int getAmtErrors(Document d) {
int n = 0;
Element el;
boolean isrestart = false;
NodeList nl = d.getElementsByTagName("errors");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
if (Integer.parseInt(el.getFirstChild().getNodeValue()) > 0) {
isrestart = isRestart(nl.item(i));
if (isrestart) {
// continue;
}
n += Integer.parseInt(el.getFirstChild().getNodeValue());
}
}
//global errors
errors += n;
return n;
}
/**
* calculates the running time fromt a suite xml file, and return it in a html-friendly format
* @param d - document to get time data from
* @return - total run time for this suite test in String
*/
private String getRunTime(Document d) {
String temp;
int h = 0, m = 0, s = 0;
Element el;
NodeList nl = d.getElementsByTagName("totaltesttime");
for (int i = 0; i < nl.getLength(); i ++) {
el = (Element)nl.item(i);
temp = el.getFirstChild().getNodeValue();
h += Integer.parseInt(temp.substring(0, temp.indexOf(":")));
m += Integer.parseInt(temp.substring(2, temp.lastIndexOf(":")));
s += Integer.parseInt(temp.substring(temp.lastIndexOf(":")+1, temp.indexOf(".")));
}
this.hours += h;
this.minutes += m;
this.seconds += s;
return printTotalTime(h, m , s);
}
/**
* formats and returns a correct String representation from inputs of hours, minutes and seconds
* @param hours
* @param minutes
* @param seconds
* @return correctly formatted time in String
*/
private String printTotalTime(int h, int m, int s) {
String time = "";
//carry over seconds
while (s >= 60) {
m ++;
s -= 60;
}
//carry over minutes
while(m >= 60) {
h ++;
m -= 60;
}
String ms = ""+ m, ss = ""+ s;
if (m < 10) {
ms = "0"+m;
}
if (s < 10) {
ss = "0"+s;
}
time = "0"+h+":"+ms+":"+ss;
return time;
}
/**
* get the name of the suite, without extension
* @param d
* @return
*/
private String getSuiteName(Document d) {
String name = "";
NodeList nl = d.getElementsByTagName("suitefile");
if (nl != null && nl.getLength() > 0) {
Element el = (Element)nl.item(0);
name = el.getFirstChild().getNodeValue();
}
name = name.substring(0, name.indexOf("."));
return name;
}
}
| false | true | private void writeIssues() {
String[] errors_keys = null;
String[] warnings_keys = null;
String[] except_keys = null;
String line = "";
InputStream stream = null;
HashMap<String, Integer> tmpMap = null;
System.out.printf("(*)Writting issues file...\n");
errors_keys = sortIssue(this.issues.getData().get("errors"));
warnings_keys = sortIssue(this.issues.getData().get("warnings"));
except_keys = sortIssue(this.issues.getData().get("exceptions"));
try {
String className = this.getClass().getName().replace('.', '/');
String classJar = this.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:")) {
stream = getClass().getResourceAsStream(this.HTML_HEADER_ISSUES_RESOURCE);
} else {
File header_fd = new File(getClass().getResource(this.HTML_HEADER_ISSUES_RESOURCE).getFile());
stream = new FileInputStream(header_fd);
}
InputStreamReader in = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(in);
File fd = new File(this.issuesHtmlFile);
BufferedWriter out = new BufferedWriter(new FileWriter(fd));
while ((line = br.readLine()) != null) {
out.write(line + "\n");
}
br.close();
in.close();
tmpMap = this.issues.getData().get("errors");
out.write("<table>\n");
out.write("<tr>\n<td class=\"td_header_master\" colspan=\"2\">Errors:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = errors_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(errors_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, errors_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("\n<hr></hr>\n");
tmpMap = this.issues.getData().get("exceptions");
out.write("<table>\n");
out.write("<tr>\n<td class=\"td_header_master\" colspan=\"2\">Exceptions:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = except_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(except_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, except_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("\n<hr></hr>\n");
tmpMap = this.issues.getData().get("warnings");
out.write("<table>\n");
out.write("<tr>\n\t<td class=\"td_header_master\" colspan=\"2\">Warnings:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = warnings_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(warnings_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, warnings_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("</body></html>\n");
out.close();
} catch (Exception exp ) {
exp.printStackTrace();
}
System.out.printf("(*)Finished writting issues file.\n");
}
| private void writeIssues() {
String[] errors_keys = null;
String[] warnings_keys = null;
String[] except_keys = null;
String line = "";
InputStream stream = null;
HashMap<String, Integer> tmpMap = null;
System.out.printf("(*)Writting issues file...\n");
errors_keys = sortIssue(this.issues.getData().get("errors"));
warnings_keys = sortIssue(this.issues.getData().get("warnings"));
except_keys = sortIssue(this.issues.getData().get("exceptions"));
try {
String className = this.getClass().getName().replace('.', '/');
String classJar = this.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:")) {
stream = getClass().getResourceAsStream(this.HTML_HEADER_ISSUES_RESOURCE);
} else {
File header_fd = new File(getClass().getResource(this.HTML_HEADER_ISSUES_RESOURCE).getFile());
stream = new FileInputStream(header_fd);
}
InputStreamReader in = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(in);
File fd = new File(this.issuesHtmlFile);
BufferedWriter out = new BufferedWriter(new FileWriter(fd));
while ((line = br.readLine()) != null) {
out.write(line + "\n");
}
br.close();
in.close();
tmpMap = this.issues.getData().get("errors");
out.write("<table>\n");
out.write("<tr>\n<td class=\"td_header_master\" colspan=\"2\">Errors:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = errors_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(errors_keys[i]);
errors_keys[i] = errors_keys[i].replaceAll("<", "<");
errors_keys[i] = errors_keys[i].replaceAll(">", ">");
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, errors_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("\n<hr></hr>\n");
tmpMap = this.issues.getData().get("exceptions");
out.write("<table>\n");
out.write("<tr>\n<td class=\"td_header_master\" colspan=\"2\">Exceptions:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = except_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(except_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
except_keys[i] = except_keys[i].replaceAll("<", "<");
except_keys[i] = except_keys[i].replaceAll(">", ">");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, except_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("\n<hr></hr>\n");
tmpMap = this.issues.getData().get("warnings");
out.write("<table>\n");
out.write("<tr>\n\t<td class=\"td_header_master\" colspan=\"2\">Warnings:</td>\n</tr>\n");
out.write("<tr>\n\t<td class=\"td_header_count\">Count:</td>\n\t<td class=\"td_header_sub\">Issue:</td>\n</tr>\n");
for (int i = warnings_keys.length -1; i >= 0 ; i--) {
int count = tmpMap.get(warnings_keys[i]);
out.write("<tr class=\"unhighlight\" onmouseout=\"this.className='unhighlight'\" onmouseover=\"this.className='highlight'\">\n");
warnings_keys[i] = warnings_keys[i].replaceAll("<", "<");
warnings_keys[i] = warnings_keys[i].replaceAll(">", ">");
String n = String.format("\t<td class=\"td_count_data\">%d</td>\n\t<td class=\"td_file_data\">%s</td>\n", count, warnings_keys[i]);
out.write(n);
out.write("</tr>\n");
}
out.write("</table>\n");
out.write("</body></html>\n");
out.close();
} catch (Exception exp ) {
exp.printStackTrace();
}
System.out.printf("(*)Finished writting issues file.\n");
}
|
diff --git a/NacaTrans/generate/java/verbs/CJavaCallProgram.java b/NacaTrans/generate/java/verbs/CJavaCallProgram.java
index 1acf0d0..7e80572 100644
--- a/NacaTrans/generate/java/verbs/CJavaCallProgram.java
+++ b/NacaTrans/generate/java/verbs/CJavaCallProgram.java
@@ -1,101 +1,103 @@
/*
* NacaRTTests - Naca Tests for NacaRT support.
*
* Copyright (c) 2005, 2006, 2007, 2008 Publicitas SA.
* Licensed under GPL (GPL-LICENSE.txt) license.
*/
/*
* Created on 5 ao�t 2004
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package generate.java.verbs;
import generate.CBaseLanguageExporter;
import semantic.CDataEntity;
import semantic.Verbs.CEntityCallProgram;
import utils.CObjectCatalog;
/**
* @author sly
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class CJavaCallProgram extends CEntityCallProgram
{
/**
* @param cat
* @param out
*/
public CJavaCallProgram(int l, CObjectCatalog cat, CBaseLanguageExporter out, CDataEntity ref)
{
super(l, cat, out, ref);
}
/* (non-Javadoc)
* @see semantic.CBaseLanguageEntity#DoExport()
*/
protected void DoExport()
{
String name = m_Reference.ExportReference(getLine());
if (name.startsWith("\""))
{
- name = name.subSequence(1, name.length()-1) + ".class";
+ name = name.substring(1, name.length()-1);
+ if (m_bChecked)
+ name += ".class";
}
if (m_bChecked)
{
WriteWord("call(" + name + ")") ;
}
else
{
WriteWord("call(\"" + name + "\")") ;
}
if (m_arrParameters.size()>0)
{
for (int i=0; i<m_arrParameters.size(); i++)
{
CCallParameter p = m_arrParameters.get(i) ;
if (!p.m_Reference.ignore())
{
String cs = "" ;
if (p.m_Methode == CCallParameterMethode.BY_REFERENCE)
{
cs = ".using(";
}
else if (p.m_Methode == CCallParameterMethode.LENGTH_OF)
{
cs = ".usingLengthOf(";
}
else if (p.m_Methode == CCallParameterMethode.BY_VALUE)
{
cs = ".usingValue(";
}
else if (p.m_Methode == CCallParameterMethode.BY_CONTENT)
{
cs = ".usingContent(";
}
else
{
cs = ".using(";
}
if (p.m_Reference != null)
{
cs += p.m_Reference.ExportReference(getLine());
}
else
{
cs += "[UNDEFINED]";
}
WriteWord(cs + ")");
}
}
}
WriteWord(".executeCall() ;");
WriteEOL();
}
}
| true | true | protected void DoExport()
{
String name = m_Reference.ExportReference(getLine());
if (name.startsWith("\""))
{
name = name.subSequence(1, name.length()-1) + ".class";
}
if (m_bChecked)
{
WriteWord("call(" + name + ")") ;
}
else
{
WriteWord("call(\"" + name + "\")") ;
}
if (m_arrParameters.size()>0)
{
for (int i=0; i<m_arrParameters.size(); i++)
{
CCallParameter p = m_arrParameters.get(i) ;
if (!p.m_Reference.ignore())
{
String cs = "" ;
if (p.m_Methode == CCallParameterMethode.BY_REFERENCE)
{
cs = ".using(";
}
else if (p.m_Methode == CCallParameterMethode.LENGTH_OF)
{
cs = ".usingLengthOf(";
}
else if (p.m_Methode == CCallParameterMethode.BY_VALUE)
{
cs = ".usingValue(";
}
else if (p.m_Methode == CCallParameterMethode.BY_CONTENT)
{
cs = ".usingContent(";
}
else
{
cs = ".using(";
}
if (p.m_Reference != null)
{
cs += p.m_Reference.ExportReference(getLine());
}
else
{
cs += "[UNDEFINED]";
}
WriteWord(cs + ")");
}
}
}
WriteWord(".executeCall() ;");
WriteEOL();
}
| protected void DoExport()
{
String name = m_Reference.ExportReference(getLine());
if (name.startsWith("\""))
{
name = name.substring(1, name.length()-1);
if (m_bChecked)
name += ".class";
}
if (m_bChecked)
{
WriteWord("call(" + name + ")") ;
}
else
{
WriteWord("call(\"" + name + "\")") ;
}
if (m_arrParameters.size()>0)
{
for (int i=0; i<m_arrParameters.size(); i++)
{
CCallParameter p = m_arrParameters.get(i) ;
if (!p.m_Reference.ignore())
{
String cs = "" ;
if (p.m_Methode == CCallParameterMethode.BY_REFERENCE)
{
cs = ".using(";
}
else if (p.m_Methode == CCallParameterMethode.LENGTH_OF)
{
cs = ".usingLengthOf(";
}
else if (p.m_Methode == CCallParameterMethode.BY_VALUE)
{
cs = ".usingValue(";
}
else if (p.m_Methode == CCallParameterMethode.BY_CONTENT)
{
cs = ".usingContent(";
}
else
{
cs = ".using(";
}
if (p.m_Reference != null)
{
cs += p.m_Reference.ExportReference(getLine());
}
else
{
cs += "[UNDEFINED]";
}
WriteWord(cs + ")");
}
}
}
WriteWord(".executeCall() ;");
WriteEOL();
}
|
diff --git a/src/com/bretth/osmosis/core/xml/common/BaseXmlWriter.java b/src/com/bretth/osmosis/core/xml/common/BaseXmlWriter.java
index 73d326b9..beb9dea7 100644
--- a/src/com/bretth/osmosis/core/xml/common/BaseXmlWriter.java
+++ b/src/com/bretth/osmosis/core/xml/common/BaseXmlWriter.java
@@ -1,177 +1,177 @@
package com.bretth.osmosis.core.xml.common;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bretth.osmosis.core.OsmosisRuntimeException;
/**
* An OSM data sink for storing all data to an xml file.
*
* @author Brett Henderson
*/
public abstract class BaseXmlWriter {
private static Logger log = Logger.getLogger(BaseXmlWriter.class.getName());
private File file;
private boolean initialized;
private BufferedWriter writer;
private CompressionMethod compressionMethod;
/**
* Creates a new instance.
*
* @param file
* The file to write.
* @param compressionMethod
* Specifies the compression method to employ.
*/
public BaseXmlWriter(File file, CompressionMethod compressionMethod) {
this.file = file;
this.compressionMethod = compressionMethod;
}
/**
* Sets the writer on the element writer used for this implementation.
*
* @param writer
* The writer receiving xml data.
*/
protected abstract void setWriterOnElementWriter(BufferedWriter writer);
/**
* Calls the begin method of the element writer used for this implementation.
*/
protected abstract void beginElementWriter();
/**
* Calls the end method of the element writer used for this implementation.
*/
protected abstract void endElementWriter();
/**
* Writes data to the output file.
*
* @param data
* The data to be written.
*/
private void write(String data) {
try {
writer.write(data);
} catch (IOException e) {
throw new OsmosisRuntimeException("Unable to write data.", e);
}
}
/**
* Writes a new line in the output file.
*/
private void writeNewLine() {
try {
writer.newLine();
} catch (IOException e) {
throw new OsmosisRuntimeException("Unable to write data.", e);
}
}
/**
* Initialises the output file for writing. This must be called by
* sub-classes before any writing is performed. This method may be called
* multiple times without adverse affect allowing sub-classes to invoke it
* every time they perform processing.
*/
protected void initialize() {
if (!initialized) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
outStream =
new CompressionActivator(compressionMethod).createCompressionOutputStream(outStream);
- writer = new BufferedWriter(new OutputStreamWriter(outStream));
+ writer = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8"));
outStream = null;
} catch (IOException e) {
throw new OsmosisRuntimeException("Unable to open file for writing.", e);
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
log.log(Level.SEVERE, "Unable to close output stream.", e);
}
outStream = null;
}
}
setWriterOnElementWriter(writer);
initialized = true;
write("<?xml version='1.0' encoding='UTF-8'?>");
writeNewLine();
beginElementWriter();
}
}
/**
* Flushes all changes to file.
*/
public void complete() {
try {
if (writer != null) {
endElementWriter();
writer.close();
}
} catch (IOException e) {
throw new OsmosisRuntimeException("Unable to complete writing to the xml stream.", e);
} finally {
initialized = false;
writer = null;
}
}
/**
* Cleans up any open file handles.
*/
public void release() {
try {
try {
if (writer != null) {
writer.close();
}
} catch(Exception e) {
log.log(Level.SEVERE, "Unable to close writer.", e);
}
} finally {
initialized = false;
writer = null;
}
}
}
| true | true | protected void initialize() {
if (!initialized) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
outStream =
new CompressionActivator(compressionMethod).createCompressionOutputStream(outStream);
writer = new BufferedWriter(new OutputStreamWriter(outStream));
outStream = null;
} catch (IOException e) {
throw new OsmosisRuntimeException("Unable to open file for writing.", e);
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
log.log(Level.SEVERE, "Unable to close output stream.", e);
}
outStream = null;
}
}
setWriterOnElementWriter(writer);
initialized = true;
write("<?xml version='1.0' encoding='UTF-8'?>");
writeNewLine();
beginElementWriter();
}
}
| protected void initialize() {
if (!initialized) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
outStream =
new CompressionActivator(compressionMethod).createCompressionOutputStream(outStream);
writer = new BufferedWriter(new OutputStreamWriter(outStream, "UTF-8"));
outStream = null;
} catch (IOException e) {
throw new OsmosisRuntimeException("Unable to open file for writing.", e);
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (Exception e) {
log.log(Level.SEVERE, "Unable to close output stream.", e);
}
outStream = null;
}
}
setWriterOnElementWriter(writer);
initialized = true;
write("<?xml version='1.0' encoding='UTF-8'?>");
writeNewLine();
beginElementWriter();
}
}
|
diff --git a/src/gdi/CargoWindow.java b/src/gdi/CargoWindow.java
index 9c1b99c..720b596 100644
--- a/src/gdi/CargoWindow.java
+++ b/src/gdi/CargoWindow.java
@@ -1,370 +1,370 @@
/*
* 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/>.
*/
/*
* Allows the cargo bay of a ship to be viewed.
* Nathan Wiehoff
*/
package gdi;
import cargo.Equipment;
import cargo.Hardpoint;
import cargo.Item;
import cargo.Weapon;
import celestial.Ship.Ship;
import celestial.Ship.Station;
import gdi.component.AstralList;
import gdi.component.AstralWindow;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import lib.Parser;
import lib.Parser.Term;
public class CargoWindow extends AstralWindow {
public static final String CMD_TRASH = "Trash";
public static final String CMD_EJECT = "Eject";
public static final String CMD_UNMOUNT = "Unmount";
public static final String CMD_MOUNT = "Mount";
public static final String CMD_STACK = "Stack";
public static final String CMD_SPLIT = "Split";
public static final String CMD_SPLITALL = "Split All";
public static final String CMD_ASSEMBLE = "Assemble";
public static final String CMD_PACKAGE = "Package";
public static final String CMD_DEPLOY = "Deploy";
AstralList cargoList = new AstralList(this);
AstralList propertyList = new AstralList(this);
AstralList optionList = new AstralList(this);
protected Ship ship;
public CargoWindow() {
super();
generate();
}
private void generate() {
backColor = windowGrey;
//size this window
width = 500;
height = 400;
setVisible(true);
//setup the cargo list
cargoList.setX(0);
cargoList.setY(0);
cargoList.setWidth(width);
cargoList.setHeight((height / 2) - 1);
cargoList.setVisible(true);
//setup the property list
propertyList.setX(0);
propertyList.setY(height / 2);
propertyList.setWidth((int) (width / 1.5));
propertyList.setHeight((height / 2) - 1);
propertyList.setVisible(true);
//setup the fitting label
optionList.setX((int) (width / 1.5) + 1);
optionList.setY(height / 2);
optionList.setWidth((int) (width / 3));
optionList.setHeight((height / 2) - 1);
optionList.setVisible(true);
//pack
addComponent(cargoList);
addComponent(propertyList);
addComponent(optionList);
}
public void update(Ship ship) {
setShip(ship);
cargoList.clearList();
propertyList.clearList();
optionList.clearList();
ArrayList<Item> logicalCargoList = new ArrayList<>();
if (ship != null) {
//add equipment
for (int a = 0; a < ship.getHardpoints().size(); a++) {
logicalCargoList.add(ship.getHardpoints().get(a).getMounted());
}
//add cargo goods
ArrayList<Item> cargo = ship.getCargoBay();
for (int a = 0; a < cargo.size(); a++) {
logicalCargoList.add(cargo.get(a));
}
//add to display
for (int a = 0; a < logicalCargoList.size(); a++) {
cargoList.addToList(logicalCargoList.get(a));
}
//display detailed information about the selected item
int index = cargoList.getIndex();
if (index < logicalCargoList.size()) {
Item selected = (Item) cargoList.getItemAtIndex(index);
//fill
propertyList.addToList("--GLOBAL--");
propertyList.addToList(" ");
propertyList.addToList("Credits: " + ship.getCash());
propertyList.addToList("Bay Volume: " + ship.getCargo());
propertyList.addToList("Volume Used: " + ship.getBayUsed());
propertyList.addToList("Percent Used: " + ship.getBayUsed() / ship.getCargo() * 100.0 + "%");
propertyList.addToList(" ");
propertyList.addToList("--BASIC--");
propertyList.addToList(" ");
propertyList.addToList("Name: " + selected.getName());
propertyList.addToList("Type: " + selected.getType());
propertyList.addToList("Mass: " + selected.getMass());
propertyList.addToList("Volume: " + selected.getVolume());
propertyList.addToList(" ");
propertyList.addToList("--MARKET--");
propertyList.addToList(" ");
propertyList.addToList("Min Price: " + selected.getMinPrice());
propertyList.addToList("Max Price: " + selected.getMaxPrice());
propertyList.addToList(" ");
propertyList.addToList("--DETAIL--");
fillDescriptionLines(selected);
fillCommandLines(selected);
}
}
}
public Ship getShip() {
return ship;
}
public void setShip(Ship ship) {
this.ship = ship;
}
private void fillDescriptionLines(Item selected) {
/*
* Fills in the item's description being aware of things like line breaking on spaces.
*/
String description = selected.getDescription();
int lineWidth = (((propertyList.getWidth() - 10) / (propertyList.getFont().getSize())));
int cursor = 0;
String tmp = "";
String[] words = description.split(" ");
for (int a = 0; a < words.length; a++) {
if (a < 0) {
a = 0;
}
int len = words[a].length();
if (cursor < lineWidth && !words[a].matches("/br/")) {
if (cursor + len <= lineWidth) {
tmp += " " + words[a];
cursor += len;
} else {
if (lineWidth > len) {
propertyList.addToList(tmp);
tmp = "";
cursor = 0;
a--;
} else {
tmp += "[LEN!]";
}
}
} else {
propertyList.addToList(tmp);
tmp = "";
cursor = 0;
if (!words[a].matches("/br/")) {
a--;
}
}
}
propertyList.addToList(tmp.toString());
}
private void fillCommandLines(Item selected) {
if (selected instanceof Equipment) {
optionList.addToList("--Fitting--");
Equipment tmp = (Equipment) selected;
Hardpoint socket = tmp.getSocket();
if (socket != null) {
//it is mounted
optionList.addToList(CMD_UNMOUNT);
} else {
//it is not mounted
optionList.addToList(CMD_MOUNT);
optionList.addToList(CMD_PACKAGE);
}
optionList.addToList(" ");
} else {
/*
* Options for stations
*/
//determine if this is a station
if (selected.getGroup().matches("constructionkit")) {
if (!ship.isDocked()) {
optionList.addToList("--Setup--");
optionList.addToList(CMD_DEPLOY);
optionList.addToList(" ");
}
}
/*
* Options for cannons
*/
if (selected.getType().matches(Item.TYPE_CANNON)) {
optionList.addToList("--Setup--");
optionList.addToList(CMD_ASSEMBLE);
optionList.addToList(" ");
}
/*
* Options for missiles
*/
if (selected.getType().matches(Item.TYPE_MISSILE)) {
optionList.addToList("--Setup--");
optionList.addToList(CMD_ASSEMBLE);
optionList.addToList(" ");
}
}
//for packaging and repackaging
optionList.addToList("--Packaging--");
optionList.addToList(CMD_STACK);
optionList.addToList(CMD_SPLIT);
optionList.addToList(CMD_SPLITALL);
//doing these last for safety.
optionList.addToList(" ");
optionList.addToList("--Dangerous--");
optionList.addToList(CMD_TRASH);
if (!ship.isDocked()) {
optionList.addToList(CMD_EJECT);
}
}
@Override
public void handleMouseClickedEvent(MouseEvent me) {
super.handleMouseClickedEvent(me);
//get the module and toggle its enabled status
if (optionList.isFocused()) {
String command = (String) optionList.getItemAtIndex(optionList.getIndex());
parseCommand(command);
}
}
private void parseCommand(String command) {
if (command != null) {
if (command.matches(CMD_TRASH)) {
/*
* This command simply destroys an item.
*/
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ship.removeFromCargoBay(selected);
} else if (command.matches(CMD_EJECT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ship.ejectCargo(selected);
} else if (command.matches(CMD_UNMOUNT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
Equipment tmp = (Equipment) selected;
ship.unfit(tmp);
} else if (command.matches(CMD_MOUNT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
Equipment tmp = (Equipment) selected;
ship.fit(tmp);
} else if (command.matches(CMD_STACK)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ArrayList<Item> cargoBay = ship.getCargoBay();
if (cargoBay.contains(selected)) {
stackItem(cargoBay, selected);
}
} else if (command.matches(CMD_SPLIT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ArrayList<Item> cargoBay = ship.getCargoBay();
if (cargoBay.contains(selected)) {
if (selected.getQuantity() > 1) {
Item tmp = new Item(selected.getName());
cargoBay.add(tmp);
selected.setQuantity(selected.getQuantity() - 1);
}
}
} else if (command.matches(CMD_SPLITALL)) {
ArrayList<Item> cargoBay = ship.getCargoBay();
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (ship.hasInCargo(selected)) {
if (selected.getQuantity() > 1) {
for (int a = 0; a < cargoBay.size(); a++) {
Item tmp = cargoBay.get(a);
if (tmp.getName().matches(selected.getName())) {
if (tmp.getType().matches(selected.getType())) {
if (tmp.getGroup().matches(selected.getGroup())) {
cargoBay.remove(tmp);
}
}
}
}
for (int a = 0; a < selected.getQuantity(); a++) {
Item tmp = new Item(selected.getName());
ship.addToCargoBay(tmp);
}
}
}
} else if (command.matches(CMD_ASSEMBLE)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
Weapon tmp = new Weapon(selected.getName());
ship.removeFromCargoBay(selected);
ship.addToCargoBay(tmp);
}
} else if (command.matches(CMD_PACKAGE)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
- Weapon tmp = (Weapon) selected;
+ Equipment tmp = (Equipment) selected;
ship.removeFromCargoBay(selected);
Item nTmp = new Item(tmp.getName());
ship.addToCargoBay(nTmp);
}
} else if (command.matches(CMD_DEPLOY)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
//deploy the station
Station ret = new Station(name, selected.getName());
ret.setName("Your "+selected.getName());
ret.setFaction(ship.getFaction());
ret.init(false);
//configure coordinates
double dx = ship.getWidth();
double dy = ship.getHeight();
double sx = (ship.getX() + ship.getWidth() / 2) + dx;
double sy = (ship.getY() + ship.getHeight() / 2) + dy;
ret.setX(sx);
ret.setY(sy);
//finalize
ret.setCurrentSystem(ship.getCurrentSystem());
ship.getCurrentSystem().putEntityInSystem(ret);
//remove item from cargo
selected.setQuantity(0);
ship.removeFromCargoBay(selected);
//since it's not NPC make sure it has no start cash
ret.clearWares();
}
}
}
}
private void stackItem(ArrayList<Item> cargoBay, Item selected) {
if (cargoBay.contains(selected)) {
for (int a = 0; a < cargoBay.size(); a++) {
Item tmp = cargoBay.get(a);
if (tmp != selected) {
if (selected.getName().matches(tmp.getName())) {
if (selected.getGroup().matches(tmp.getGroup())) {
if (selected.getType().matches(tmp.getType())) {
tmp.setQuantity(selected.getQuantity() + tmp.getQuantity());
cargoBay.remove(selected);
break;
}
}
}
}
}
}
}
}
| true | true | private void parseCommand(String command) {
if (command != null) {
if (command.matches(CMD_TRASH)) {
/*
* This command simply destroys an item.
*/
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ship.removeFromCargoBay(selected);
} else if (command.matches(CMD_EJECT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ship.ejectCargo(selected);
} else if (command.matches(CMD_UNMOUNT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
Equipment tmp = (Equipment) selected;
ship.unfit(tmp);
} else if (command.matches(CMD_MOUNT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
Equipment tmp = (Equipment) selected;
ship.fit(tmp);
} else if (command.matches(CMD_STACK)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ArrayList<Item> cargoBay = ship.getCargoBay();
if (cargoBay.contains(selected)) {
stackItem(cargoBay, selected);
}
} else if (command.matches(CMD_SPLIT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ArrayList<Item> cargoBay = ship.getCargoBay();
if (cargoBay.contains(selected)) {
if (selected.getQuantity() > 1) {
Item tmp = new Item(selected.getName());
cargoBay.add(tmp);
selected.setQuantity(selected.getQuantity() - 1);
}
}
} else if (command.matches(CMD_SPLITALL)) {
ArrayList<Item> cargoBay = ship.getCargoBay();
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (ship.hasInCargo(selected)) {
if (selected.getQuantity() > 1) {
for (int a = 0; a < cargoBay.size(); a++) {
Item tmp = cargoBay.get(a);
if (tmp.getName().matches(selected.getName())) {
if (tmp.getType().matches(selected.getType())) {
if (tmp.getGroup().matches(selected.getGroup())) {
cargoBay.remove(tmp);
}
}
}
}
for (int a = 0; a < selected.getQuantity(); a++) {
Item tmp = new Item(selected.getName());
ship.addToCargoBay(tmp);
}
}
}
} else if (command.matches(CMD_ASSEMBLE)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
Weapon tmp = new Weapon(selected.getName());
ship.removeFromCargoBay(selected);
ship.addToCargoBay(tmp);
}
} else if (command.matches(CMD_PACKAGE)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
Weapon tmp = (Weapon) selected;
ship.removeFromCargoBay(selected);
Item nTmp = new Item(tmp.getName());
ship.addToCargoBay(nTmp);
}
} else if (command.matches(CMD_DEPLOY)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
//deploy the station
Station ret = new Station(name, selected.getName());
ret.setName("Your "+selected.getName());
ret.setFaction(ship.getFaction());
ret.init(false);
//configure coordinates
double dx = ship.getWidth();
double dy = ship.getHeight();
double sx = (ship.getX() + ship.getWidth() / 2) + dx;
double sy = (ship.getY() + ship.getHeight() / 2) + dy;
ret.setX(sx);
ret.setY(sy);
//finalize
ret.setCurrentSystem(ship.getCurrentSystem());
ship.getCurrentSystem().putEntityInSystem(ret);
//remove item from cargo
selected.setQuantity(0);
ship.removeFromCargoBay(selected);
//since it's not NPC make sure it has no start cash
ret.clearWares();
}
}
}
}
| private void parseCommand(String command) {
if (command != null) {
if (command.matches(CMD_TRASH)) {
/*
* This command simply destroys an item.
*/
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ship.removeFromCargoBay(selected);
} else if (command.matches(CMD_EJECT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ship.ejectCargo(selected);
} else if (command.matches(CMD_UNMOUNT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
Equipment tmp = (Equipment) selected;
ship.unfit(tmp);
} else if (command.matches(CMD_MOUNT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
Equipment tmp = (Equipment) selected;
ship.fit(tmp);
} else if (command.matches(CMD_STACK)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ArrayList<Item> cargoBay = ship.getCargoBay();
if (cargoBay.contains(selected)) {
stackItem(cargoBay, selected);
}
} else if (command.matches(CMD_SPLIT)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
ArrayList<Item> cargoBay = ship.getCargoBay();
if (cargoBay.contains(selected)) {
if (selected.getQuantity() > 1) {
Item tmp = new Item(selected.getName());
cargoBay.add(tmp);
selected.setQuantity(selected.getQuantity() - 1);
}
}
} else if (command.matches(CMD_SPLITALL)) {
ArrayList<Item> cargoBay = ship.getCargoBay();
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (ship.hasInCargo(selected)) {
if (selected.getQuantity() > 1) {
for (int a = 0; a < cargoBay.size(); a++) {
Item tmp = cargoBay.get(a);
if (tmp.getName().matches(selected.getName())) {
if (tmp.getType().matches(selected.getType())) {
if (tmp.getGroup().matches(selected.getGroup())) {
cargoBay.remove(tmp);
}
}
}
}
for (int a = 0; a < selected.getQuantity(); a++) {
Item tmp = new Item(selected.getName());
ship.addToCargoBay(tmp);
}
}
}
} else if (command.matches(CMD_ASSEMBLE)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
Weapon tmp = new Weapon(selected.getName());
ship.removeFromCargoBay(selected);
ship.addToCargoBay(tmp);
}
} else if (command.matches(CMD_PACKAGE)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
Equipment tmp = (Equipment) selected;
ship.removeFromCargoBay(selected);
Item nTmp = new Item(tmp.getName());
ship.addToCargoBay(nTmp);
}
} else if (command.matches(CMD_DEPLOY)) {
Item selected = (Item) cargoList.getItemAtIndex(cargoList.getIndex());
if (selected.getQuantity() == 1) {
//deploy the station
Station ret = new Station(name, selected.getName());
ret.setName("Your "+selected.getName());
ret.setFaction(ship.getFaction());
ret.init(false);
//configure coordinates
double dx = ship.getWidth();
double dy = ship.getHeight();
double sx = (ship.getX() + ship.getWidth() / 2) + dx;
double sy = (ship.getY() + ship.getHeight() / 2) + dy;
ret.setX(sx);
ret.setY(sy);
//finalize
ret.setCurrentSystem(ship.getCurrentSystem());
ship.getCurrentSystem().putEntityInSystem(ret);
//remove item from cargo
selected.setQuantity(0);
ship.removeFromCargoBay(selected);
//since it's not NPC make sure it has no start cash
ret.clearWares();
}
}
}
}
|
diff --git a/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java b/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java
index 8a7bd642..f6d8631b 100644
--- a/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java
+++ b/axis2/src/main/java/org/apache/ode/axis2/ExternalService.java
@@ -1,182 +1,185 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ode.axis2;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.util.OMUtils;
import org.apache.ode.axis2.util.SOAPUtils;
import org.apache.ode.bpel.epr.EndpointFactory;
import org.apache.ode.bpel.epr.MutableEndpoint;
import org.apache.ode.bpel.epr.WSAEndpoint;
import org.apache.ode.bpel.iapi.Message;
import org.apache.ode.bpel.iapi.MessageExchange;
import org.apache.ode.bpel.iapi.PartnerRoleChannel;
import org.apache.ode.bpel.iapi.PartnerRoleMessageExchange;
import org.apache.ode.utils.DOMUtils;
import org.w3c.dom.Element;
import javax.wsdl.Definition;
import javax.xml.namespace.QName;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
/**
* Acts as a service not provided by ODE. Used mainly for invocation as a way to
* maintain the WSDL decription of used services.
*/
public class ExternalService implements PartnerRoleChannel {
private static final Log __log = LogFactory.getLog(ExternalService.class);
private ExecutorService _executorService;
private Definition _definition;
private QName _serviceName;
private String _portName;
private AxisConfiguration _axisConfig;
public ExternalService(Definition definition, QName serviceName,
String portName, ExecutorService executorService, AxisConfiguration axisConfig) {
_definition = definition;
_serviceName = serviceName;
_portName = portName;
_executorService = executorService;
_axisConfig = axisConfig;
}
public void invoke(final PartnerRoleMessageExchange odeMex) {
boolean isTwoWay = odeMex.getMessageExchangePattern() ==
org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
try {
Element msgContent = SOAPUtils.wrap(odeMex.getRequest().getMessage(), _definition, _serviceName,
odeMex.getOperation(), odeMex.getOperation().getInput().getMessage());
final OMElement payload = OMUtils.toOM(msgContent);
Options options = new Options();
EndpointReference axisEPR = new EndpointReference(((MutableEndpoint)odeMex.getEndpointReference()).getUrl());
__log.debug("Axis2 sending message to " + axisEPR.getAddress() + " using MEX " + odeMex);
__log.debug("Message: " + payload);
options.setTo(axisEPR);
+ String soapAction = SOAPUtils.getSoapAction(_definition, _serviceName, _portName,
+ odeMex.getOperationName());
+ options.setAction(soapAction);
ConfigurationContext ctx = new ConfigurationContext(_axisConfig);
final ServiceClient serviceClient = new ServiceClient(ctx, null);
serviceClient.setOptions(options);
// Override options are passed to the axis MessageContext so we can
// retrieve them in our session out handler.
Options mexOptions = new Options();
writeHeader(mexOptions, odeMex);
serviceClient.setOverrideOptions(mexOptions);
if (isTwoWay) {
// Invoking in a separate thread even though we're supposed to wait for a synchronous reply
// to force clear transaction separation.
Future<OMElement> freply = _executorService.submit(new Callable<OMElement>() {
public OMElement call() throws Exception {
return serviceClient.sendReceive(payload);
}
});
OMElement reply;
try {
reply = freply.get();
if (reply == null) {
String errmsg = "Received empty (null) reply for ODE mex " + odeMex;
__log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
} else {
Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
Element responseElmt = OMUtils.toDOM(reply);
responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
odeMex.getOperation().getOutput().getMessage(), _serviceName);
__log.debug("Received synchronous response for MEX " + odeMex);
__log.debug("Message: " + DOMUtils.domToString(responseElmt));
response.setMessage(responseElmt);
odeMex.reply(response);
}
} catch (Exception e) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
} else /** one-way case **/ {
serviceClient.fireAndForget(payload);
}
} catch (AxisFault axisFault) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, axisFault);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
}
/**
* Extracts endpoint information from ODE message exchange to stuff them into
* Axis MessageContext.
*/
private void writeHeader(Options options, PartnerRoleMessageExchange odeMex) {
WSAEndpoint targetEPR = EndpointFactory.convertToWSA((MutableEndpoint) odeMex.getEndpointReference());
WSAEndpoint myRoleEPR = EndpointFactory.convertToWSA((MutableEndpoint) odeMex.getMyRoleEndpointReference());
String partnerSessionId = odeMex.getProperty(MessageExchange.PROPERTY_SEP_PARTNERROLE_SESSIONID);
String myRoleSessionId = odeMex.getProperty(MessageExchange.PROPERTY_SEP_MYROLE_SESSIONID);
if (partnerSessionId != null) {
__log.debug("Partner session identifier found for WSA endpoint: " + partnerSessionId);
targetEPR.setSessionId(partnerSessionId);
}
options.setProperty("targetSessionEndpoint", targetEPR);
String soapAction = SOAPUtils.getSoapAction(_definition, _serviceName, _portName,
odeMex.getOperationName());
options.setProperty("soapAction", soapAction);
if (myRoleEPR != null) {
if (myRoleSessionId != null) {
__log.debug("MyRole session identifier found for myrole (callback) WSA endpoint: " + myRoleSessionId);
myRoleEPR.setSessionId(myRoleSessionId);
}
options.setProperty("callbackSessionEndpoint", odeMex.getMyRoleEndpointReference());
} else {
__log.debug("My-Role EPR not specified, SEP will not be used.");
}
}
public org.apache.ode.bpel.iapi.EndpointReference getInitialEndpointReference() {
Element eprElmt = ODEService.genEPRfromWSDL(_definition, _serviceName, _portName);
if (eprElmt == null)
throw new IllegalArgumentException("Service " + _serviceName + " and port " + _portName +
"couldn't be found in provided WSDL document!");
return EndpointFactory.convertToWSA(ODEService.createServiceRef(eprElmt));
}
public void close() {
// TODO Auto-generated method stub
}
}
| true | true | public void invoke(final PartnerRoleMessageExchange odeMex) {
boolean isTwoWay = odeMex.getMessageExchangePattern() ==
org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
try {
Element msgContent = SOAPUtils.wrap(odeMex.getRequest().getMessage(), _definition, _serviceName,
odeMex.getOperation(), odeMex.getOperation().getInput().getMessage());
final OMElement payload = OMUtils.toOM(msgContent);
Options options = new Options();
EndpointReference axisEPR = new EndpointReference(((MutableEndpoint)odeMex.getEndpointReference()).getUrl());
__log.debug("Axis2 sending message to " + axisEPR.getAddress() + " using MEX " + odeMex);
__log.debug("Message: " + payload);
options.setTo(axisEPR);
ConfigurationContext ctx = new ConfigurationContext(_axisConfig);
final ServiceClient serviceClient = new ServiceClient(ctx, null);
serviceClient.setOptions(options);
// Override options are passed to the axis MessageContext so we can
// retrieve them in our session out handler.
Options mexOptions = new Options();
writeHeader(mexOptions, odeMex);
serviceClient.setOverrideOptions(mexOptions);
if (isTwoWay) {
// Invoking in a separate thread even though we're supposed to wait for a synchronous reply
// to force clear transaction separation.
Future<OMElement> freply = _executorService.submit(new Callable<OMElement>() {
public OMElement call() throws Exception {
return serviceClient.sendReceive(payload);
}
});
OMElement reply;
try {
reply = freply.get();
if (reply == null) {
String errmsg = "Received empty (null) reply for ODE mex " + odeMex;
__log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
} else {
Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
Element responseElmt = OMUtils.toDOM(reply);
responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
odeMex.getOperation().getOutput().getMessage(), _serviceName);
__log.debug("Received synchronous response for MEX " + odeMex);
__log.debug("Message: " + DOMUtils.domToString(responseElmt));
response.setMessage(responseElmt);
odeMex.reply(response);
}
} catch (Exception e) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
} else /** one-way case **/ {
serviceClient.fireAndForget(payload);
}
} catch (AxisFault axisFault) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, axisFault);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
}
| public void invoke(final PartnerRoleMessageExchange odeMex) {
boolean isTwoWay = odeMex.getMessageExchangePattern() ==
org.apache.ode.bpel.iapi.MessageExchange.MessageExchangePattern.REQUEST_RESPONSE;
try {
Element msgContent = SOAPUtils.wrap(odeMex.getRequest().getMessage(), _definition, _serviceName,
odeMex.getOperation(), odeMex.getOperation().getInput().getMessage());
final OMElement payload = OMUtils.toOM(msgContent);
Options options = new Options();
EndpointReference axisEPR = new EndpointReference(((MutableEndpoint)odeMex.getEndpointReference()).getUrl());
__log.debug("Axis2 sending message to " + axisEPR.getAddress() + " using MEX " + odeMex);
__log.debug("Message: " + payload);
options.setTo(axisEPR);
String soapAction = SOAPUtils.getSoapAction(_definition, _serviceName, _portName,
odeMex.getOperationName());
options.setAction(soapAction);
ConfigurationContext ctx = new ConfigurationContext(_axisConfig);
final ServiceClient serviceClient = new ServiceClient(ctx, null);
serviceClient.setOptions(options);
// Override options are passed to the axis MessageContext so we can
// retrieve them in our session out handler.
Options mexOptions = new Options();
writeHeader(mexOptions, odeMex);
serviceClient.setOverrideOptions(mexOptions);
if (isTwoWay) {
// Invoking in a separate thread even though we're supposed to wait for a synchronous reply
// to force clear transaction separation.
Future<OMElement> freply = _executorService.submit(new Callable<OMElement>() {
public OMElement call() throws Exception {
return serviceClient.sendReceive(payload);
}
});
OMElement reply;
try {
reply = freply.get();
if (reply == null) {
String errmsg = "Received empty (null) reply for ODE mex " + odeMex;
__log.error(errmsg);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
} else {
Message response = odeMex.createMessage(odeMex.getOperation().getOutput().getMessage().getQName());
Element responseElmt = OMUtils.toDOM(reply);
responseElmt = SOAPUtils.unwrap(responseElmt, _definition,
odeMex.getOperation().getOutput().getMessage(), _serviceName);
__log.debug("Received synchronous response for MEX " + odeMex);
__log.debug("Message: " + DOMUtils.domToString(responseElmt));
response.setMessage(responseElmt);
odeMex.reply(response);
}
} catch (Exception e) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, e);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
} else /** one-way case **/ {
serviceClient.fireAndForget(payload);
}
} catch (AxisFault axisFault) {
String errmsg = "Error sending message to Axis2 for ODE mex " + odeMex;
__log.error(errmsg, axisFault);
odeMex.replyWithFailure(MessageExchange.FailureType.COMMUNICATION_ERROR, errmsg, null);
}
}
|
diff --git a/util/src/main/java/com/psddev/dari/util/HtmlApiFilter.java b/util/src/main/java/com/psddev/dari/util/HtmlApiFilter.java
index 392b0b6e..e34d8d13 100644
--- a/util/src/main/java/com/psddev/dari/util/HtmlApiFilter.java
+++ b/util/src/main/java/com/psddev/dari/util/HtmlApiFilter.java
@@ -1,218 +1,218 @@
package com.psddev.dari.util;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Map;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* Filter that automatically captures the HTML output from the response
* and formats it so that it's suitable for use as an API.
*
* <p>You can use it on any paths with the following query parameters:</p>
*
* <ul>
* <li>{@code ?_format=js}</li>
* <li>{@code ?_format=json}</li>
* <li>{@code ?_format=json&_result=html}</li>
* <li>{@code ?_format=jsonp&_callback=}</li>
* <li>{@code ?_format=jsonp&_callback=&_result=html}</li>
* </ul>
*
* @see HtmlMicrodata
*/
public class HtmlApiFilter extends AbstractFilter {
@Override
protected void doRequest(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String format = request.getParameter("_format");
if (ObjectUtils.isBlank(format)) {
chain.doFilter(request, response);
return;
}
Writer writer = response.getWriter();
if ("js".equals(format)) {
response.setContentType("text/javascript");
writer.write("(function(window, undefined) {");
writer.write("var d = window.document,");
writer.write("ss = d.getElementsByTagName('SCRIPT'),");
writer.write("s = ss[ss.length - 1],");
writer.write("f = d.createElement('IFRAME'),");
writer.write("h;");
writer.write("f.scrolling = 'no';");
writer.write("f.style.border = 'none';");
writer.write("f.style.width = '100%';");
writer.write("f.src = '");
writer.write(StringUtils.escapeJavaScript(JspUtils.getAbsoluteUrl(request, "", "_format", "_frame")));
writer.write("';");
- writer.write("s.parentNode.insertBefore(f);");
+ writer.write("s.parentNode.insertBefore(f, s);");
writer.write("window.addEventListener('message', function(event) {");
writer.write("var nh = parseInt(event.data, 10);");
writer.write("if (h !== nh) {");
writer.write("f.style.height = nh + 'px';");
writer.write("h = nh;");
writer.write("}");
writer.write("}, false);");
writer.write("})(window);");
return;
} else if ("_frame".equals(format)) {
@SuppressWarnings("resource")
HtmlWriter html = new HtmlWriter(writer);
response.setContentType("text/html");
html.writeTag("!doctype html");
html.writeStart("html");
html.writeStart("head");
html.writeEnd();
html.writeStart("body", "style", html.cssString(
"margin", 0,
"padding", 0));
html.writeStart("iframe",
"scrolling", "no",
"src", JspUtils.getAbsoluteUrl(request, "", "_format", null),
"style", html.cssString(
"border", "none",
"width", "100%"));
html.writeEnd();
html.writeStart("script", "type", "text/javascript");
html.writeRaw("(function(window, undefined) {");
html.writeRaw("setInterval(function() {");
html.writeRaw("var f = document.getElementsByTagName('iframe')[0], h = f.contentDocument.body.scrollHeight;");
html.writeRaw("f.height = h + 'px';");
html.writeRaw("window.parent.postMessage('' + h, '*');");
html.writeRaw("}, 500);");
html.writeRaw("})(window);");
html.writeEnd();
html.writeEnd();
html.writeEnd();
return;
}
CapturingResponse capturing = new CapturingResponse(response);
Object output;
try {
chain.doFilter(request, capturing);
output = capturing.getOutput();
} catch (RuntimeException error) {
output = error;
}
if ("json".equals(format)) {
response.setContentType("application/json");
writeJson(request, writer, output);
} else if ("jsonp".equals(format)) {
String callback = request.getParameter("callback");
ErrorUtils.errorIfBlank(callback, "callback");
response.setContentType("application/javascript");
writer.write(callback);
writer.write("(");
writeJson(request, writer, output);
writer.write(");");
} else if ("oembed".equals(format)) {
response.setContentType("application/json+oembed");
Map<String, Object> json = new CompactMap<String, Object>();
StringWriter string = new StringWriter();
@SuppressWarnings("resource")
HtmlWriter html = new HtmlWriter(string);
html.writeStart("script",
"type", "text/javascript",
"src", JspUtils.getAbsoluteUrl(request, "", "_format", "js"));
html.writeEnd();
json.put("version", "1.0");
json.put("type", "rich");
json.put("html", string.toString());
writer.write(ObjectUtils.toJson(json));
} else {
throw new IllegalArgumentException(String.format(
"[%s] isn't a valid API response format!", format));
}
}
private static void writeJson(HttpServletRequest request, Writer writer, Object output) throws IOException {
Map<String, Object> json = new CompactMap<String, Object>();
if (output instanceof Throwable) {
Throwable error = (Throwable) output;
json.put("status", "error");
json.put("errorClass", error.getClass().getName());
json.put("errorMessage", error.getMessage());
} else {
if (!"html".equals(request.getParameter("_result"))) {
output = HtmlMicrodata.Static.parseString(
new URL(JspUtils.getAbsoluteUrl(request, "")),
(String) output);
}
json.put("status", "ok");
json.put("result", output);
}
writer.write(ObjectUtils.toJson(json));
}
private final static class CapturingResponse extends HttpServletResponseWrapper {
private final StringWriter output;
private final PrintWriter printWriter;
public CapturingResponse(HttpServletResponse response) {
super(response);
this.output = new StringWriter();
this.printWriter = new PrintWriter(output);
}
@Override
public ServletOutputStream getOutputStream() {
throw new IllegalStateException();
}
@Override
public PrintWriter getWriter() {
return printWriter;
}
public String getOutput() {
return output.toString();
}
}
}
| true | true | protected void doRequest(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String format = request.getParameter("_format");
if (ObjectUtils.isBlank(format)) {
chain.doFilter(request, response);
return;
}
Writer writer = response.getWriter();
if ("js".equals(format)) {
response.setContentType("text/javascript");
writer.write("(function(window, undefined) {");
writer.write("var d = window.document,");
writer.write("ss = d.getElementsByTagName('SCRIPT'),");
writer.write("s = ss[ss.length - 1],");
writer.write("f = d.createElement('IFRAME'),");
writer.write("h;");
writer.write("f.scrolling = 'no';");
writer.write("f.style.border = 'none';");
writer.write("f.style.width = '100%';");
writer.write("f.src = '");
writer.write(StringUtils.escapeJavaScript(JspUtils.getAbsoluteUrl(request, "", "_format", "_frame")));
writer.write("';");
writer.write("s.parentNode.insertBefore(f);");
writer.write("window.addEventListener('message', function(event) {");
writer.write("var nh = parseInt(event.data, 10);");
writer.write("if (h !== nh) {");
writer.write("f.style.height = nh + 'px';");
writer.write("h = nh;");
writer.write("}");
writer.write("}, false);");
writer.write("})(window);");
return;
} else if ("_frame".equals(format)) {
@SuppressWarnings("resource")
HtmlWriter html = new HtmlWriter(writer);
response.setContentType("text/html");
html.writeTag("!doctype html");
html.writeStart("html");
html.writeStart("head");
html.writeEnd();
html.writeStart("body", "style", html.cssString(
"margin", 0,
"padding", 0));
html.writeStart("iframe",
"scrolling", "no",
"src", JspUtils.getAbsoluteUrl(request, "", "_format", null),
"style", html.cssString(
"border", "none",
"width", "100%"));
html.writeEnd();
html.writeStart("script", "type", "text/javascript");
html.writeRaw("(function(window, undefined) {");
html.writeRaw("setInterval(function() {");
html.writeRaw("var f = document.getElementsByTagName('iframe')[0], h = f.contentDocument.body.scrollHeight;");
html.writeRaw("f.height = h + 'px';");
html.writeRaw("window.parent.postMessage('' + h, '*');");
html.writeRaw("}, 500);");
html.writeRaw("})(window);");
html.writeEnd();
html.writeEnd();
html.writeEnd();
return;
}
CapturingResponse capturing = new CapturingResponse(response);
Object output;
try {
chain.doFilter(request, capturing);
output = capturing.getOutput();
} catch (RuntimeException error) {
output = error;
}
if ("json".equals(format)) {
response.setContentType("application/json");
writeJson(request, writer, output);
} else if ("jsonp".equals(format)) {
String callback = request.getParameter("callback");
ErrorUtils.errorIfBlank(callback, "callback");
response.setContentType("application/javascript");
writer.write(callback);
writer.write("(");
writeJson(request, writer, output);
writer.write(");");
} else if ("oembed".equals(format)) {
response.setContentType("application/json+oembed");
Map<String, Object> json = new CompactMap<String, Object>();
StringWriter string = new StringWriter();
@SuppressWarnings("resource")
HtmlWriter html = new HtmlWriter(string);
html.writeStart("script",
"type", "text/javascript",
"src", JspUtils.getAbsoluteUrl(request, "", "_format", "js"));
html.writeEnd();
json.put("version", "1.0");
json.put("type", "rich");
json.put("html", string.toString());
writer.write(ObjectUtils.toJson(json));
} else {
throw new IllegalArgumentException(String.format(
"[%s] isn't a valid API response format!", format));
}
}
| protected void doRequest(
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String format = request.getParameter("_format");
if (ObjectUtils.isBlank(format)) {
chain.doFilter(request, response);
return;
}
Writer writer = response.getWriter();
if ("js".equals(format)) {
response.setContentType("text/javascript");
writer.write("(function(window, undefined) {");
writer.write("var d = window.document,");
writer.write("ss = d.getElementsByTagName('SCRIPT'),");
writer.write("s = ss[ss.length - 1],");
writer.write("f = d.createElement('IFRAME'),");
writer.write("h;");
writer.write("f.scrolling = 'no';");
writer.write("f.style.border = 'none';");
writer.write("f.style.width = '100%';");
writer.write("f.src = '");
writer.write(StringUtils.escapeJavaScript(JspUtils.getAbsoluteUrl(request, "", "_format", "_frame")));
writer.write("';");
writer.write("s.parentNode.insertBefore(f, s);");
writer.write("window.addEventListener('message', function(event) {");
writer.write("var nh = parseInt(event.data, 10);");
writer.write("if (h !== nh) {");
writer.write("f.style.height = nh + 'px';");
writer.write("h = nh;");
writer.write("}");
writer.write("}, false);");
writer.write("})(window);");
return;
} else if ("_frame".equals(format)) {
@SuppressWarnings("resource")
HtmlWriter html = new HtmlWriter(writer);
response.setContentType("text/html");
html.writeTag("!doctype html");
html.writeStart("html");
html.writeStart("head");
html.writeEnd();
html.writeStart("body", "style", html.cssString(
"margin", 0,
"padding", 0));
html.writeStart("iframe",
"scrolling", "no",
"src", JspUtils.getAbsoluteUrl(request, "", "_format", null),
"style", html.cssString(
"border", "none",
"width", "100%"));
html.writeEnd();
html.writeStart("script", "type", "text/javascript");
html.writeRaw("(function(window, undefined) {");
html.writeRaw("setInterval(function() {");
html.writeRaw("var f = document.getElementsByTagName('iframe')[0], h = f.contentDocument.body.scrollHeight;");
html.writeRaw("f.height = h + 'px';");
html.writeRaw("window.parent.postMessage('' + h, '*');");
html.writeRaw("}, 500);");
html.writeRaw("})(window);");
html.writeEnd();
html.writeEnd();
html.writeEnd();
return;
}
CapturingResponse capturing = new CapturingResponse(response);
Object output;
try {
chain.doFilter(request, capturing);
output = capturing.getOutput();
} catch (RuntimeException error) {
output = error;
}
if ("json".equals(format)) {
response.setContentType("application/json");
writeJson(request, writer, output);
} else if ("jsonp".equals(format)) {
String callback = request.getParameter("callback");
ErrorUtils.errorIfBlank(callback, "callback");
response.setContentType("application/javascript");
writer.write(callback);
writer.write("(");
writeJson(request, writer, output);
writer.write(");");
} else if ("oembed".equals(format)) {
response.setContentType("application/json+oembed");
Map<String, Object> json = new CompactMap<String, Object>();
StringWriter string = new StringWriter();
@SuppressWarnings("resource")
HtmlWriter html = new HtmlWriter(string);
html.writeStart("script",
"type", "text/javascript",
"src", JspUtils.getAbsoluteUrl(request, "", "_format", "js"));
html.writeEnd();
json.put("version", "1.0");
json.put("type", "rich");
json.put("html", string.toString());
writer.write(ObjectUtils.toJson(json));
} else {
throw new IllegalArgumentException(String.format(
"[%s] isn't a valid API response format!", format));
}
}
|
diff --git a/drools-planner-core/src/main/java/org/drools/planner/core/constructionheuristic/placer/value/ValuePlacer.java b/drools-planner-core/src/main/java/org/drools/planner/core/constructionheuristic/placer/value/ValuePlacer.java
index a6198172..364767ae 100644
--- a/drools-planner-core/src/main/java/org/drools/planner/core/constructionheuristic/placer/value/ValuePlacer.java
+++ b/drools-planner-core/src/main/java/org/drools/planner/core/constructionheuristic/placer/value/ValuePlacer.java
@@ -1,117 +1,116 @@
package org.drools.planner.core.constructionheuristic.placer.value;
import org.drools.planner.core.constructionheuristic.placer.AbstractPlacer;
import org.drools.planner.core.constructionheuristic.scope.ConstructionHeuristicMoveScope;
import org.drools.planner.core.constructionheuristic.scope.ConstructionHeuristicSolverPhaseScope;
import org.drools.planner.core.constructionheuristic.scope.ConstructionHeuristicStepScope;
import org.drools.planner.core.domain.variable.PlanningVariableDescriptor;
import org.drools.planner.core.heuristic.selector.move.generic.ChangeMove;
import org.drools.planner.core.heuristic.selector.value.ValueSelector;
import org.drools.planner.core.localsearch.scope.LocalSearchSolverPhaseScope;
import org.drools.planner.core.move.Move;
import org.drools.planner.core.score.Score;
import org.drools.planner.core.score.director.ScoreDirector;
import org.drools.planner.core.termination.Termination;
public class ValuePlacer extends AbstractPlacer {
protected final Termination termination;
protected final ValueSelector valueSelector;
protected final PlanningVariableDescriptor variableDescriptor;
protected final int selectedCountLimit;
protected boolean assertMoveScoreIsUncorrupted = false;
protected boolean assertUndoMoveIsUncorrupted = false;
public ValuePlacer(Termination termination, ValueSelector valueSelector, int selectedCountLimit) {
this.termination = termination;
this.valueSelector = valueSelector;
variableDescriptor = valueSelector.getVariableDescriptor();
this.selectedCountLimit = selectedCountLimit;
solverPhaseLifecycleSupport.addEventListener(valueSelector);
// TODO don't use Integer.MAX_VALUE as a magical value
if (valueSelector.isNeverEnding() && selectedCountLimit == Integer.MAX_VALUE) {
throw new IllegalStateException("The placer (" + this
+ ") with selectedCountLimit (" + selectedCountLimit + ") has valueSelector (" + valueSelector
+ ") with neverEnding (" + valueSelector.isNeverEnding() + ").");
}
}
public void setAssertMoveScoreIsUncorrupted(boolean assertMoveScoreIsUncorrupted) {
this.assertMoveScoreIsUncorrupted = assertMoveScoreIsUncorrupted;
}
public void setAssertUndoMoveIsUncorrupted(boolean assertUndoMoveIsUncorrupted) {
this.assertUndoMoveIsUncorrupted = assertUndoMoveIsUncorrupted;
}
public void doPlacement(ConstructionHeuristicStepScope stepScope) {
// TODO extract to PlacerForager
Score maxScore = stepScope.getPhaseScope().getScoreDefinition().getPerfectMinimumScore();
ConstructionHeuristicMoveScope maxMoveScope = null;
Object entity = stepScope.getEntity();
- int selectedCount = 0;
int moveIndex = 0;
for (Object value : valueSelector) {
ConstructionHeuristicMoveScope moveScope = new ConstructionHeuristicMoveScope(stepScope);
moveScope.setMoveIndex(moveIndex);
ChangeMove move = new ChangeMove(entity, variableDescriptor, value);
moveScope.setMove(move);
if (!move.isMoveDoable(stepScope.getScoreDirector())) {
logger.trace(" Ignoring not doable move ({}).", move);
} else {
doMove(moveScope);
// TODO extract to PlacerForager
if (moveScope.getScore().compareTo(maxScore) > 0) {
maxScore = moveScope.getScore();
// TODO for non explicit Best Fit *, default to random picking from a maxMoveScopeList
maxMoveScope = moveScope;
}
- if (selectedCount >= selectedCountLimit) {
+ if (moveIndex >= selectedCountLimit) {
break;
}
}
moveIndex++;
if (termination.isPhaseTerminated(stepScope.getPhaseScope())) {
break;
}
}
if (maxMoveScope != null) {
Move step = maxMoveScope.getMove();
stepScope.setStep(step);
if (logger.isDebugEnabled()) {
stepScope.setStepString(step.toString());
}
stepScope.setUndoStep(maxMoveScope.getUndoMove());
stepScope.setScore(maxMoveScope.getScore());
}
}
private void doMove(ConstructionHeuristicMoveScope moveScope) {
ScoreDirector scoreDirector = moveScope.getScoreDirector();
Move move = moveScope.getMove();
Move undoMove = move.createUndoMove(scoreDirector);
moveScope.setUndoMove(undoMove);
move.doMove(scoreDirector);
processMove(moveScope);
undoMove.doMove(scoreDirector);
if (assertUndoMoveIsUncorrupted) {
ConstructionHeuristicSolverPhaseScope phaseScope = moveScope.getStepScope().getPhaseScope();
phaseScope.assertUndoMoveIsUncorrupted(move, undoMove);
}
logger.trace(" Move index ({}), score ({}) for move ({}).",
new Object[]{moveScope.getMoveIndex(), moveScope.getScore(), moveScope.getMove()});
}
private void processMove(ConstructionHeuristicMoveScope moveScope) {
Score score = moveScope.getStepScope().getPhaseScope().calculateScore();
if (assertMoveScoreIsUncorrupted) {
moveScope.getStepScope().getPhaseScope().assertWorkingScore(score);
}
moveScope.setScore(score);
// TODO work with forager
// forager.addMove(moveScope);
}
}
| false | true | public void doPlacement(ConstructionHeuristicStepScope stepScope) {
// TODO extract to PlacerForager
Score maxScore = stepScope.getPhaseScope().getScoreDefinition().getPerfectMinimumScore();
ConstructionHeuristicMoveScope maxMoveScope = null;
Object entity = stepScope.getEntity();
int selectedCount = 0;
int moveIndex = 0;
for (Object value : valueSelector) {
ConstructionHeuristicMoveScope moveScope = new ConstructionHeuristicMoveScope(stepScope);
moveScope.setMoveIndex(moveIndex);
ChangeMove move = new ChangeMove(entity, variableDescriptor, value);
moveScope.setMove(move);
if (!move.isMoveDoable(stepScope.getScoreDirector())) {
logger.trace(" Ignoring not doable move ({}).", move);
} else {
doMove(moveScope);
// TODO extract to PlacerForager
if (moveScope.getScore().compareTo(maxScore) > 0) {
maxScore = moveScope.getScore();
// TODO for non explicit Best Fit *, default to random picking from a maxMoveScopeList
maxMoveScope = moveScope;
}
if (selectedCount >= selectedCountLimit) {
break;
}
}
moveIndex++;
if (termination.isPhaseTerminated(stepScope.getPhaseScope())) {
break;
}
}
if (maxMoveScope != null) {
Move step = maxMoveScope.getMove();
stepScope.setStep(step);
if (logger.isDebugEnabled()) {
stepScope.setStepString(step.toString());
}
stepScope.setUndoStep(maxMoveScope.getUndoMove());
stepScope.setScore(maxMoveScope.getScore());
}
}
| public void doPlacement(ConstructionHeuristicStepScope stepScope) {
// TODO extract to PlacerForager
Score maxScore = stepScope.getPhaseScope().getScoreDefinition().getPerfectMinimumScore();
ConstructionHeuristicMoveScope maxMoveScope = null;
Object entity = stepScope.getEntity();
int moveIndex = 0;
for (Object value : valueSelector) {
ConstructionHeuristicMoveScope moveScope = new ConstructionHeuristicMoveScope(stepScope);
moveScope.setMoveIndex(moveIndex);
ChangeMove move = new ChangeMove(entity, variableDescriptor, value);
moveScope.setMove(move);
if (!move.isMoveDoable(stepScope.getScoreDirector())) {
logger.trace(" Ignoring not doable move ({}).", move);
} else {
doMove(moveScope);
// TODO extract to PlacerForager
if (moveScope.getScore().compareTo(maxScore) > 0) {
maxScore = moveScope.getScore();
// TODO for non explicit Best Fit *, default to random picking from a maxMoveScopeList
maxMoveScope = moveScope;
}
if (moveIndex >= selectedCountLimit) {
break;
}
}
moveIndex++;
if (termination.isPhaseTerminated(stepScope.getPhaseScope())) {
break;
}
}
if (maxMoveScope != null) {
Move step = maxMoveScope.getMove();
stepScope.setStep(step);
if (logger.isDebugEnabled()) {
stepScope.setStepString(step.toString());
}
stepScope.setUndoStep(maxMoveScope.getUndoMove());
stepScope.setScore(maxMoveScope.getScore());
}
}
|
diff --git a/loci/formats/in/LIFReader.java b/loci/formats/in/LIFReader.java
index 71132dc7c..6468cee8f 100644
--- a/loci/formats/in/LIFReader.java
+++ b/loci/formats/in/LIFReader.java
@@ -1,478 +1,479 @@
//
// LIFReader.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan
and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
import java.util.Vector;
import loci.formats.*;
/**
* LIFReader is the file format reader for Leica LIF files.
*
* @author Melissa Linkert linkert at cs.wisc.edu
*/
public class LIFReader extends FormatReader {
// -- Fields --
/** Current file. */
protected RandomAccessFile in;
/** Flag indicating whether current file is little endian. */
protected boolean littleEndian;
/** Number of image planes in the file. */
protected int numImages = 0;
/** Offsets to memory blocks, paired with their corresponding description. */
protected Vector offsets;
/**
* Dimension information for each image.
* The first index specifies the image number, and the second specifies
* the dimension from the following list:
* 0) width
* 1) height
* 2) Z
* 3) T
* 4) channels (1 or 3)
* 5) bits per pixel
* 6) extra dimensions
*/
protected int[][] dims;
private int width;
private int height;
private int c;
private int bpp;
private Vector xcal;
private Vector ycal;
private Vector zcal;
private Vector seriesNames;
// -- Constructor --
/** Constructs a new Leica LIF reader. */
public LIFReader() { super("Leica Image File Format", "lif"); }
// -- FormatReader API methods --
/** Checks if the given block is a valid header for a LIF file. */
public boolean isThisType(byte[] block) {
return block[0] == 0x70;
}
/** Determines the number of images in the given LIF file. */
public int getImageCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
numImages = dims[series][2] * dims[series][3];
return numImages;
}
/** Checks if the images in the file are RGB. */
public boolean isRGB(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][4] > 1;
}
/** Get the size of the X dimension. */
public int getSizeX(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][0];
}
/** Get the size of the Y dimension. */
public int getSizeY(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][1];
}
/** Get the size of the Z dimension. */
public int getSizeZ(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][2];
}
/** Get the size of the C dimension. */
public int getSizeC(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
if (getImageCount(id) == 1 && dims[series][4] < 3) dims[series][4] = 1;
return dims[series][4];
}
/** Get the size of the T dimension. */
public int getSizeT(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims[series][3];
}
/** Return true if the data is in little-endian format. */
public boolean isLittleEndian(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return littleEndian;
}
/**
* Return a five-character string representing the dimension order
* within the file.
*/
public String getDimensionOrder(String id)
throws FormatException, IOException
{
int sizeZ = getSizeZ(id);
int sizeT = getSizeT(id);
if (sizeZ > sizeT) return "XYCZT";
else return "XYCTZ";
}
/** Returns whether or not the channels are interleaved. */
public boolean isInterleaved(String id) throws FormatException, IOException {
return false;
}
/** Return the number of series in this file. */
public int getSeriesCount(String id) throws FormatException, IOException {
if (!id.equals(currentId)) initFile(id);
return dims.length;
}
/** Obtains the specified image from the given LIF file as a byte array. */
public byte[] openBytes(String id, int no)
throws FormatException, IOException
{
if (!id.equals(currentId)) initFile(id);
if (no < 0 || no >= getImageCount(id)) {
throw new FormatException("Invalid image number: " + no);
}
// determine which dataset the plane is part of
int z = getSizeZ(id);
int t = getSizeT(id);
width = dims[series][0];
height = dims[series][1];
c = dims[series][4];
if (c == 2) c--;
bpp = dims[series][5];
while (bpp % 8 != 0) bpp++;
int bytesPerPixel = bpp / 8;
int offset = ((Long) offsets.get(series)).intValue();
// get the image number within this dataset
in.seek(offset + width * height * bytesPerPixel * no * c);
byte[] data = new byte[(int) (width * height * bytesPerPixel * c)];
in.read(data);
return data;
}
/** Obtains the specified image from the given LIF file. */
public BufferedImage openImage(String id, int no)
throws FormatException, IOException
{
return ImageTools.makeImage(openBytes(id, no), width, height,
!isRGB(id) ? 1 : c, false, bpp / 8, littleEndian);
}
/** Closes any open files. */
public void close() throws FormatException, IOException {
if (in != null) in.close();
in = null;
currentId = null;
}
/** Initializes the given LIF file. */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
in = new RandomAccessFile(id, "r");
offsets = new Vector();
littleEndian = true;
xcal = new Vector();
ycal = new Vector();
zcal = new Vector();
// read the header
byte checkOne = (byte) in.read();
in.skipBytes(2);
byte checkTwo = (byte) in.read();
if (checkOne != 0x70 && checkTwo != 0x70) {
throw new FormatException(id + " is not a valid Leica LIF file");
}
in.skipBytes(4);
// read and parse the XML description
if (in.read() != 0x2a) {
throw new FormatException("Invalid XML description");
}
// number of Unicode characters in the XML block
int nc = DataTools.read4SignedBytes(in, littleEndian);
byte[] s = new byte[nc * 2];
in.read(s);
String xml = DataTools.stripString(new String(s));
while (in.getFilePointer() < in.length()) {
if (DataTools.read4SignedBytes(in, littleEndian) != 0x70) {
throw new FormatException("Invalid Memory Block");
}
in.skipBytes(4);
if (in.read() != 0x2a) {
throw new FormatException("Invalid Memory Description");
}
int blockLength = DataTools.read4SignedBytes(in, littleEndian);
if (in.read() != 0x2a) {
throw new FormatException("Invalid Memory Description");
}
int descrLength = DataTools.read4SignedBytes(in, littleEndian);
byte[] memDescr = new byte[2*descrLength];
in.read(memDescr);
if (blockLength > 0) {
offsets.add(new Long(in.getFilePointer()));
}
in.skipBytes(blockLength);
}
numImages = offsets.size();
initMetadata(xml);
}
// -- Helper methods --
/** Parses a string of XML and puts the values in a Hashtable. */
private void initMetadata(String xml) {
Vector elements = new Vector();
seriesNames = new Vector();
// first parse each element in the XML string
while (xml.length() > 2) {
String el = xml.substring(1, xml.indexOf(">"));
xml = xml.substring(xml.indexOf(">") + 1);
elements.add(el);
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
metadata.put(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
numImages = 0;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
String tmpToken = token;
if (token.indexOf("=") != -1) {
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
metadata.put(key, value);
}
}
token = tmpToken;
if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
seriesNames.add(token.substring(token.indexOf("=") + 2,
token.length() - 1));
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
float cal = Float.parseFloat((String) tmp.get("Length"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1: widths.add(new Integer(w)); xcal.add(new Float(cal));
break;
case 2: heights.add(new Integer(w)); ycal.add(new Float(cal));
break;
case 3: zs.add(new Integer(w)); zcal.add(new Float(cal));
break;
case 4: ts.add(new Integer(w)); break;
default: extras *= w;
}
}
}
ndx++;
try {
token = (String) elements.get(ndx);
}
catch (Exception e) { break; }
}
extraDims.add(new Integer(extras));
+ if (numChannels == 2) numChannels--;
channels.add(new Integer(numChannels));
if (zs.size() < channels.size()) zs.add(new Integer(1));
if (ts.size() < channels.size()) ts.add(new Integer(1));
}
ndx++;
}
numDatasets = widths.size();
dims = new int[numDatasets][7];
for (int i=0; i<numDatasets; i++) {
dims[i][0] = ((Integer) widths.get(i)).intValue();
dims[i][1] = ((Integer) heights.get(i)).intValue();
dims[i][2] = ((Integer) zs.get(i)).intValue();
dims[i][3] = ((Integer) ts.get(i)).intValue();
dims[i][4] = ((Integer) channels.get(i)).intValue();
dims[i][5] = ((Integer) bps.get(i)).intValue();
dims[i][6] = ((Integer) extraDims.get(i)).intValue();
if (dims[i][6] > 1) {
if (dims[i][2] == 1) dims[i][2] = dims[i][6];
else dims[i][3] *= dims[i][6];
dims[i][6] = 1;
}
numImages += (dims[i][2] * dims[i][3] * dims[i][6]);
}
// Populate metadata store
// The metadata store we're working with.
try {
MetadataStore store = getMetadataStore(currentId);
String type = "int8";
switch (dims[0][5]) {
case 12: type = "int16"; break;
case 16: type = "int16"; break;
case 32: type = "float"; break;
}
for (int i=0; i<numDatasets; i++) {
Integer ii = new Integer(i);
store.setImage((String) seriesNames.get(i), null, null, ii);
store.setPixels(
new Integer(dims[i][0]), // SizeX
new Integer(dims[i][1]), // SizeY
new Integer(dims[i][2]), // SizeZ
new Integer(dims[i][4]), // SizeC
new Integer(dims[i][3]), // SizeT
type, // PixelType
new Boolean(!littleEndian), // BigEndian
getDimensionOrder(currentId), // DimensionOrder
ii); // Index
Float xf = i < xcal.size() ? (Float) xcal.get(i) : null;
Float yf = i < ycal.size() ? (Float) ycal.get(i) : null;
Float zf = i < zcal.size() ? (Float) zcal.get(i) : null;
store.setDimensions(xf, yf, zf, null, null, ii);
}
}
catch (Exception e) { e.printStackTrace(); }
}
// -- Main method --
public static void main(String[] args) throws FormatException, IOException {
new LIFReader().testRead(args);
}
}
| true | true | private void initMetadata(String xml) {
Vector elements = new Vector();
seriesNames = new Vector();
// first parse each element in the XML string
while (xml.length() > 2) {
String el = xml.substring(1, xml.indexOf(">"));
xml = xml.substring(xml.indexOf(">") + 1);
elements.add(el);
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
metadata.put(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
numImages = 0;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
String tmpToken = token;
if (token.indexOf("=") != -1) {
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
metadata.put(key, value);
}
}
token = tmpToken;
if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
seriesNames.add(token.substring(token.indexOf("=") + 2,
token.length() - 1));
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
float cal = Float.parseFloat((String) tmp.get("Length"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1: widths.add(new Integer(w)); xcal.add(new Float(cal));
break;
case 2: heights.add(new Integer(w)); ycal.add(new Float(cal));
break;
case 3: zs.add(new Integer(w)); zcal.add(new Float(cal));
break;
case 4: ts.add(new Integer(w)); break;
default: extras *= w;
}
}
}
ndx++;
try {
token = (String) elements.get(ndx);
}
catch (Exception e) { break; }
}
extraDims.add(new Integer(extras));
channels.add(new Integer(numChannels));
if (zs.size() < channels.size()) zs.add(new Integer(1));
if (ts.size() < channels.size()) ts.add(new Integer(1));
}
ndx++;
}
numDatasets = widths.size();
dims = new int[numDatasets][7];
for (int i=0; i<numDatasets; i++) {
dims[i][0] = ((Integer) widths.get(i)).intValue();
dims[i][1] = ((Integer) heights.get(i)).intValue();
dims[i][2] = ((Integer) zs.get(i)).intValue();
dims[i][3] = ((Integer) ts.get(i)).intValue();
dims[i][4] = ((Integer) channels.get(i)).intValue();
dims[i][5] = ((Integer) bps.get(i)).intValue();
dims[i][6] = ((Integer) extraDims.get(i)).intValue();
if (dims[i][6] > 1) {
if (dims[i][2] == 1) dims[i][2] = dims[i][6];
else dims[i][3] *= dims[i][6];
dims[i][6] = 1;
}
numImages += (dims[i][2] * dims[i][3] * dims[i][6]);
}
// Populate metadata store
// The metadata store we're working with.
try {
MetadataStore store = getMetadataStore(currentId);
String type = "int8";
switch (dims[0][5]) {
case 12: type = "int16"; break;
case 16: type = "int16"; break;
case 32: type = "float"; break;
}
for (int i=0; i<numDatasets; i++) {
Integer ii = new Integer(i);
store.setImage((String) seriesNames.get(i), null, null, ii);
store.setPixels(
new Integer(dims[i][0]), // SizeX
new Integer(dims[i][1]), // SizeY
new Integer(dims[i][2]), // SizeZ
new Integer(dims[i][4]), // SizeC
new Integer(dims[i][3]), // SizeT
type, // PixelType
new Boolean(!littleEndian), // BigEndian
getDimensionOrder(currentId), // DimensionOrder
ii); // Index
Float xf = i < xcal.size() ? (Float) xcal.get(i) : null;
Float yf = i < ycal.size() ? (Float) ycal.get(i) : null;
Float zf = i < zcal.size() ? (Float) zcal.get(i) : null;
store.setDimensions(xf, yf, zf, null, null, ii);
}
}
catch (Exception e) { e.printStackTrace(); }
}
| private void initMetadata(String xml) {
Vector elements = new Vector();
seriesNames = new Vector();
// first parse each element in the XML string
while (xml.length() > 2) {
String el = xml.substring(1, xml.indexOf(">"));
xml = xml.substring(xml.indexOf(">") + 1);
elements.add(el);
}
// the first element contains version information
String token = (String) elements.get(0);
String key = token.substring(0, token.indexOf("\""));
String value = token.substring(token.indexOf("\"") + 1, token.length()-1);
metadata.put(key, value);
// what we have right now is a vector of XML elements, which need to
// be parsed into the appropriate image dimensions
int ndx = 1;
numImages = 0;
// the image data we need starts with the token "ElementName='blah'" and
// ends with the token "/ImageDescription"
int numDatasets = 0;
Vector widths = new Vector();
Vector heights = new Vector();
Vector zs = new Vector();
Vector ts = new Vector();
Vector channels = new Vector();
Vector bps = new Vector();
Vector extraDims = new Vector();
while (ndx < elements.size()) {
token = (String) elements.get(ndx);
// if the element contains a key/value pair, parse it and put it in
// the metadata hashtable
String tmpToken = token;
if (token.indexOf("=") != -1) {
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
metadata.put(key, value);
}
}
token = tmpToken;
if (token.startsWith("Element Name")) {
// loop until we find "/ImageDescription"
seriesNames.add(token.substring(token.indexOf("=") + 2,
token.length() - 1));
numDatasets++;
int numChannels = 0;
int extras = 1;
while (token.indexOf("/ImageDescription") == -1) {
if (token.indexOf("=") != -1) {
// create a small hashtable to store just this element's data
Hashtable tmp = new Hashtable();
while (token.length() > 2) {
key = token.substring(0, token.indexOf("\"") - 1);
value = token.substring(token.indexOf("\"") + 1,
token.indexOf("\"", token.indexOf("\"") + 1));
token = token.substring(key.length() + value.length() + 3);
key = key.trim();
value = value.trim();
tmp.put(key, value);
}
if (tmp.get("ChannelDescription DataType") != null) {
// found channel description block
numChannels++;
if (numChannels == 1) {
bps.add(new Integer((String) tmp.get("Resolution")));
}
}
else if (tmp.get("DimensionDescription DimID") != null) {
// found dimension description block
int w = Integer.parseInt((String) tmp.get("NumberOfElements"));
float cal = Float.parseFloat((String) tmp.get("Length"));
int id = Integer.parseInt((String)
tmp.get("DimensionDescription DimID"));
switch (id) {
case 1: widths.add(new Integer(w)); xcal.add(new Float(cal));
break;
case 2: heights.add(new Integer(w)); ycal.add(new Float(cal));
break;
case 3: zs.add(new Integer(w)); zcal.add(new Float(cal));
break;
case 4: ts.add(new Integer(w)); break;
default: extras *= w;
}
}
}
ndx++;
try {
token = (String) elements.get(ndx);
}
catch (Exception e) { break; }
}
extraDims.add(new Integer(extras));
if (numChannels == 2) numChannels--;
channels.add(new Integer(numChannels));
if (zs.size() < channels.size()) zs.add(new Integer(1));
if (ts.size() < channels.size()) ts.add(new Integer(1));
}
ndx++;
}
numDatasets = widths.size();
dims = new int[numDatasets][7];
for (int i=0; i<numDatasets; i++) {
dims[i][0] = ((Integer) widths.get(i)).intValue();
dims[i][1] = ((Integer) heights.get(i)).intValue();
dims[i][2] = ((Integer) zs.get(i)).intValue();
dims[i][3] = ((Integer) ts.get(i)).intValue();
dims[i][4] = ((Integer) channels.get(i)).intValue();
dims[i][5] = ((Integer) bps.get(i)).intValue();
dims[i][6] = ((Integer) extraDims.get(i)).intValue();
if (dims[i][6] > 1) {
if (dims[i][2] == 1) dims[i][2] = dims[i][6];
else dims[i][3] *= dims[i][6];
dims[i][6] = 1;
}
numImages += (dims[i][2] * dims[i][3] * dims[i][6]);
}
// Populate metadata store
// The metadata store we're working with.
try {
MetadataStore store = getMetadataStore(currentId);
String type = "int8";
switch (dims[0][5]) {
case 12: type = "int16"; break;
case 16: type = "int16"; break;
case 32: type = "float"; break;
}
for (int i=0; i<numDatasets; i++) {
Integer ii = new Integer(i);
store.setImage((String) seriesNames.get(i), null, null, ii);
store.setPixels(
new Integer(dims[i][0]), // SizeX
new Integer(dims[i][1]), // SizeY
new Integer(dims[i][2]), // SizeZ
new Integer(dims[i][4]), // SizeC
new Integer(dims[i][3]), // SizeT
type, // PixelType
new Boolean(!littleEndian), // BigEndian
getDimensionOrder(currentId), // DimensionOrder
ii); // Index
Float xf = i < xcal.size() ? (Float) xcal.get(i) : null;
Float yf = i < ycal.size() ? (Float) ycal.get(i) : null;
Float zf = i < zcal.size() ? (Float) zcal.get(i) : null;
store.setDimensions(xf, yf, zf, null, null, ii);
}
}
catch (Exception e) { e.printStackTrace(); }
}
|
diff --git a/acteur-folder-auth/src/test/java/com/mastfrog/acteur/MD.java b/acteur-folder-auth/src/test/java/com/mastfrog/acteur/MD.java
index 4945d8f..b9c6dfb 100644
--- a/acteur-folder-auth/src/test/java/com/mastfrog/acteur/MD.java
+++ b/acteur-folder-auth/src/test/java/com/mastfrog/acteur/MD.java
@@ -1,472 +1,473 @@
package com.mastfrog.acteur;
import com.google.common.base.Optional;
import com.google.inject.AbstractModule;
import com.mastfrog.acteur.Event;
import com.mastfrog.acteur.util.HeaderValueType;
import com.mastfrog.acteur.util.Method;
import com.mastfrog.url.Path;
import com.mastfrog.util.Exceptions;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelConfig;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelMetadata;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelProgressivePromise;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.FileRegion;
import io.netty.handler.codec.http.DefaultHttpMessage;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
*
* @author Tim Boudreau
*/
class MD extends AbstractModule implements Event {
@Override
protected void configure() {
bind(MD.class).toInstance(this);
}
@Override
public Optional<Integer> getIntParameter(String name) {
String val = getParameter(name);
if (val != null) {
int ival = Integer.parseInt(val);
return Optional.of(ival);
}
return Optional.absent();
}
@Override
public Optional<Long> getLongParameter(String name) {
String val = getParameter(name);
if (val != null) {
long lval = Long.parseLong(val);
return Optional.of(lval);
}
return Optional.absent();
}
@Override
public Channel getChannel() {
return new Channel() {
public Integer id() {
return 1;
}
@Override
public EventLoop eventLoop() {
return null;
}
@Override
public Channel parent() {
return this;
}
@Override
public ChannelConfig config() {
return null;
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isRegistered() {
return true;
}
- public void deregister(ChannelPromise p) {
+ public ChannelFuture deregister(ChannelPromise p) {
// dealing with netty version skew
+ return null;
}
@Override
public boolean isActive() {
return true;
}
@Override
public ChannelMetadata metadata() {
return null;
}
private ByteBuf out = Unpooled.buffer();
public ByteBuf outboundByteBuffer() {
return out;
}
@Override
public SocketAddress localAddress() {
return new InetSocketAddress(1);
}
@Override
public SocketAddress remoteAddress() {
return new InetSocketAddress(2);
}
@Override
public ChannelFuture closeFuture() {
final Channel t = this;
return new ChannelFuture() {
@Override
public Channel channel() {
return t;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isSuccess() {
return true;
}
@Override
public Throwable cause() {
return null;
}
@Override
public ChannelFuture sync() throws InterruptedException {
return this;
}
@Override
public ChannelFuture syncUninterruptibly() {
return this;
}
@Override
public ChannelFuture await() throws InterruptedException {
return this;
}
@Override
public ChannelFuture awaitUninterruptibly() {
return this;
}
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public boolean await(long timeoutMillis) throws InterruptedException {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeoutMillis) {
return true;
}
@Override
public Void getNow() {
return null;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return true;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public Void get() throws InterruptedException, ExecutionException {
return null;
}
@Override
public Void get(long l, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
@Override
public ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
try {
GenericFutureListener f = listener;
f.operationComplete(this);
} catch (Exception ex) {
return Exceptions.chuck(ex);
}
return this;
}
@Override
public ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
for (GenericFutureListener<? extends Future<? super Void>> l : listeners) {
try {
GenericFutureListener f = l;
f.operationComplete(this);
} catch (Exception ex) {
return Exceptions.chuck(ex);
}
}
return this;
}
@Override
public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) {
return this;
}
@Override
public ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
return this;
}
@Override
public boolean isCancellable() {
return false;
}
};
}
@Override
public Channel.Unsafe unsafe() {
return null;
}
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
return null;
}
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
return closeFuture();
}
@Override
public ChannelFuture disconnect() {
return closeFuture();
}
@Override
public ChannelFuture close() {
return closeFuture();
}
public Channel flush() {
return this;
}
public ChannelFuture write(Object message) {
return closeFuture();
}
public ChannelFuture sendFile(FileRegion region) {
return closeFuture();
}
@Override
public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture disconnect(ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture close(ChannelPromise promise) {
return closeFuture();
}
public Channel read() {
return this;
}
public ChannelFuture flush(ChannelPromise promise) {
return closeFuture();
}
public ChannelFuture write(Object message, ChannelPromise promise) {
return closeFuture();
}
public ChannelFuture sendFile(FileRegion region, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelPipeline pipeline() {
return null;
}
@Override
public ByteBufAllocator alloc() {
return null;
}
@Override
public ChannelPromise newPromise() {
return null;
}
@Override
public ChannelFuture newSucceededFuture() {
return closeFuture();
}
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
return closeFuture();
}
@Override
public int compareTo(Channel t) {
return 0;
}
public boolean isWritable() {
return true;
}
public ChannelProgressivePromise newProgressivePromise() {
throw new UnsupportedOperationException();
}
public ChannelPromise voidPromise() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
return closeFuture();
}
};
}
@Override
public HttpMessage getRequest() {
return new DefaultHttpMessage(HttpVersion.HTTP_1_0) {
};
}
@Override
public Method getMethod() {
return Method.GET;
}
@Override
public SocketAddress getRemoteAddress() {
return new InetSocketAddress(2);
}
public void deregister(ChannelPromise p) {
}
@Override
public String getHeader(String nm) {
return null;
}
@Override
public String getParameter(String param) {
return null;
}
@Override
public Path getPath() {
return Path.parse("testTag");
}
@Override
public <T> T getHeader(HeaderValueType<T> value) {
return null;
}
@Override
public Map<String, String> getParametersAsMap() {
return Collections.emptyMap();
}
@Override
public <T> T getParametersAs(Class<T> type) {
return null;
}
@Override
public <T> T getContentAsJSON(Class<T> type) throws IOException {
return null;
}
@Override
public ByteBuf getContent() throws IOException {
return Unpooled.buffer();
}
@Override
public boolean isKeepAlive() {
return false;
}
@Override
public OutputStream getContentAsStream() throws IOException {
return new ByteArrayOutputStream(0);
}
}
| false | true | public Channel getChannel() {
return new Channel() {
public Integer id() {
return 1;
}
@Override
public EventLoop eventLoop() {
return null;
}
@Override
public Channel parent() {
return this;
}
@Override
public ChannelConfig config() {
return null;
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isRegistered() {
return true;
}
public void deregister(ChannelPromise p) {
// dealing with netty version skew
}
@Override
public boolean isActive() {
return true;
}
@Override
public ChannelMetadata metadata() {
return null;
}
private ByteBuf out = Unpooled.buffer();
public ByteBuf outboundByteBuffer() {
return out;
}
@Override
public SocketAddress localAddress() {
return new InetSocketAddress(1);
}
@Override
public SocketAddress remoteAddress() {
return new InetSocketAddress(2);
}
@Override
public ChannelFuture closeFuture() {
final Channel t = this;
return new ChannelFuture() {
@Override
public Channel channel() {
return t;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isSuccess() {
return true;
}
@Override
public Throwable cause() {
return null;
}
@Override
public ChannelFuture sync() throws InterruptedException {
return this;
}
@Override
public ChannelFuture syncUninterruptibly() {
return this;
}
@Override
public ChannelFuture await() throws InterruptedException {
return this;
}
@Override
public ChannelFuture awaitUninterruptibly() {
return this;
}
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public boolean await(long timeoutMillis) throws InterruptedException {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeoutMillis) {
return true;
}
@Override
public Void getNow() {
return null;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return true;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public Void get() throws InterruptedException, ExecutionException {
return null;
}
@Override
public Void get(long l, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
@Override
public ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
try {
GenericFutureListener f = listener;
f.operationComplete(this);
} catch (Exception ex) {
return Exceptions.chuck(ex);
}
return this;
}
@Override
public ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
for (GenericFutureListener<? extends Future<? super Void>> l : listeners) {
try {
GenericFutureListener f = l;
f.operationComplete(this);
} catch (Exception ex) {
return Exceptions.chuck(ex);
}
}
return this;
}
@Override
public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) {
return this;
}
@Override
public ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
return this;
}
@Override
public boolean isCancellable() {
return false;
}
};
}
@Override
public Channel.Unsafe unsafe() {
return null;
}
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
return null;
}
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
return closeFuture();
}
@Override
public ChannelFuture disconnect() {
return closeFuture();
}
@Override
public ChannelFuture close() {
return closeFuture();
}
public Channel flush() {
return this;
}
public ChannelFuture write(Object message) {
return closeFuture();
}
public ChannelFuture sendFile(FileRegion region) {
return closeFuture();
}
@Override
public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture disconnect(ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture close(ChannelPromise promise) {
return closeFuture();
}
public Channel read() {
return this;
}
public ChannelFuture flush(ChannelPromise promise) {
return closeFuture();
}
public ChannelFuture write(Object message, ChannelPromise promise) {
return closeFuture();
}
public ChannelFuture sendFile(FileRegion region, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelPipeline pipeline() {
return null;
}
@Override
public ByteBufAllocator alloc() {
return null;
}
@Override
public ChannelPromise newPromise() {
return null;
}
@Override
public ChannelFuture newSucceededFuture() {
return closeFuture();
}
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
return closeFuture();
}
@Override
public int compareTo(Channel t) {
return 0;
}
public boolean isWritable() {
return true;
}
public ChannelProgressivePromise newProgressivePromise() {
throw new UnsupportedOperationException();
}
public ChannelPromise voidPromise() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
return closeFuture();
}
};
}
| public Channel getChannel() {
return new Channel() {
public Integer id() {
return 1;
}
@Override
public EventLoop eventLoop() {
return null;
}
@Override
public Channel parent() {
return this;
}
@Override
public ChannelConfig config() {
return null;
}
@Override
public boolean isOpen() {
return true;
}
@Override
public boolean isRegistered() {
return true;
}
public ChannelFuture deregister(ChannelPromise p) {
// dealing with netty version skew
return null;
}
@Override
public boolean isActive() {
return true;
}
@Override
public ChannelMetadata metadata() {
return null;
}
private ByteBuf out = Unpooled.buffer();
public ByteBuf outboundByteBuffer() {
return out;
}
@Override
public SocketAddress localAddress() {
return new InetSocketAddress(1);
}
@Override
public SocketAddress remoteAddress() {
return new InetSocketAddress(2);
}
@Override
public ChannelFuture closeFuture() {
final Channel t = this;
return new ChannelFuture() {
@Override
public Channel channel() {
return t;
}
@Override
public boolean isDone() {
return true;
}
@Override
public boolean isSuccess() {
return true;
}
@Override
public Throwable cause() {
return null;
}
@Override
public ChannelFuture sync() throws InterruptedException {
return this;
}
@Override
public ChannelFuture syncUninterruptibly() {
return this;
}
@Override
public ChannelFuture await() throws InterruptedException {
return this;
}
@Override
public ChannelFuture awaitUninterruptibly() {
return this;
}
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
return true;
}
@Override
public boolean await(long timeoutMillis) throws InterruptedException {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeout, TimeUnit unit) {
return true;
}
@Override
public boolean awaitUninterruptibly(long timeoutMillis) {
return true;
}
@Override
public Void getNow() {
return null;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return true;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public Void get() throws InterruptedException, ExecutionException {
return null;
}
@Override
public Void get(long l, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException {
return null;
}
@Override
public ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
try {
GenericFutureListener f = listener;
f.operationComplete(this);
} catch (Exception ex) {
return Exceptions.chuck(ex);
}
return this;
}
@Override
public ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
for (GenericFutureListener<? extends Future<? super Void>> l : listeners) {
try {
GenericFutureListener f = l;
f.operationComplete(this);
} catch (Exception ex) {
return Exceptions.chuck(ex);
}
}
return this;
}
@Override
public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) {
return this;
}
@Override
public ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
return this;
}
@Override
public boolean isCancellable() {
return false;
}
};
}
@Override
public Channel.Unsafe unsafe() {
return null;
}
@Override
public <T> Attribute<T> attr(AttributeKey<T> key) {
return null;
}
@Override
public ChannelFuture bind(SocketAddress localAddress) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) {
return closeFuture();
}
@Override
public ChannelFuture disconnect() {
return closeFuture();
}
@Override
public ChannelFuture close() {
return closeFuture();
}
public Channel flush() {
return this;
}
public ChannelFuture write(Object message) {
return closeFuture();
}
public ChannelFuture sendFile(FileRegion region) {
return closeFuture();
}
@Override
public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture disconnect(ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture close(ChannelPromise promise) {
return closeFuture();
}
public Channel read() {
return this;
}
public ChannelFuture flush(ChannelPromise promise) {
return closeFuture();
}
public ChannelFuture write(Object message, ChannelPromise promise) {
return closeFuture();
}
public ChannelFuture sendFile(FileRegion region, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelPipeline pipeline() {
return null;
}
@Override
public ByteBufAllocator alloc() {
return null;
}
@Override
public ChannelPromise newPromise() {
return null;
}
@Override
public ChannelFuture newSucceededFuture() {
return closeFuture();
}
@Override
public ChannelFuture newFailedFuture(Throwable cause) {
return closeFuture();
}
@Override
public int compareTo(Channel t) {
return 0;
}
public boolean isWritable() {
return true;
}
public ChannelProgressivePromise newProgressivePromise() {
throw new UnsupportedOperationException();
}
public ChannelPromise voidPromise() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
return closeFuture();
}
@Override
public ChannelFuture writeAndFlush(Object msg) {
return closeFuture();
}
};
}
|
diff --git a/src/BookCopier/Commands.java b/src/BookCopier/Commands.java
index 4eb672c..ebbf597 100644
--- a/src/BookCopier/Commands.java
+++ b/src/BookCopier/Commands.java
@@ -1,196 +1,199 @@
package BookCopier;
import java.io.File;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
public class Commands
{
public static void setPlugin(BookCopier bc)
{
plugin = bc;
}
public static void commandCopy(Player commandSender, String args[])
{
if(plugin.config.getOPsOnly())
{
if(!commandSender.isOp())
return;
}
if(args.length == 0)
{
commandSender.sendMessage(ChatColor.RED + "Type: \"/bc help\" for more informations.");
+ return;
}
if(args[0].toLowerCase().matches("help"))
{
if(args.length == 1)
{
commandSender.sendMessage(ChatColor.AQUA + "BOOK COPIER COMMANDS AND INFO!");
commandSender.sendMessage("<> - required arguments");
commandSender.sendMessage("[] - optional arguments");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc copy [value] - Copies book in your hand.(No value means 1*)");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc give <player> [value] - Adds book in your hand to target player's inventory.");
+ commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc save <fileName> - Saves book in your hand to file.");
+ commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc load <fileName> - Loads book from file to your inventory.");
}
}
else if(args[0].toLowerCase().matches("give"))
{
if(args.length == 2)
{
Player p;
if((p = plugin.getServer().getPlayer(args[1])) != null)
{
try
{
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
p.getInventory().addItem(item);
p.sendMessage("You recieve some book...");
commandSender.sendMessage("Book has been added to target player's inventory!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage(ChatColor.RED + "Target player is offline");
}
}
else if(args.length == 3)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
Player p;
if((p = plugin.getServer().getPlayer(args[1])) != null)
{
try
{
int numberOfBooks = Integer.parseInt(args[2]);
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
item.setAmount(numberOfBooks);
p.getInventory().addItem(item);
p.sendMessage("You recieved some books...");
commandSender.sendMessage("Books has been added to target player's inventory!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage(ChatColor.RED + "Target player is offline");
}
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
else if(args[0].toLowerCase().matches("copy"))
{
if(args.length == 1)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
MyBook book = new MyBook(commandSender.getItemInHand());
commandSender.getInventory().addItem(book.createItem());
commandSender.sendMessage("Book has been copied!");
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
else if(args.length == 2)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
try
{
int numberOfBooks = Integer.parseInt(args[1]);
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
item.setAmount(numberOfBooks);
commandSender.getInventory().addItem(item);
commandSender.sendMessage("Books has been copied!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
else if(args[0].toLowerCase().matches("load"))
{
if(args.length == 2)
{
String fileName = args[1];
if(!fileName.endsWith(".book"))
{
fileName += ".book";
}
String completePath = "plugins/BookCopier/" + fileName;
File file = new File(completePath);
if(!file.exists())
{
commandSender.sendMessage(ChatColor.RED + "This file doesn't exist.");
return;
}
if(!BookCreator.checkFormat(completePath))
{
commandSender.sendMessage(ChatColor.RED + "Bad format of target file!");
return;
}
ItemStack item = BookCreator.loadBook(completePath);
commandSender.getInventory().addItem(item);
commandSender.sendMessage("Book has been loaded.");
}
}
else if(args[0].toLowerCase().matches("save"))
{
if(args.length == 2)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
String fileName = args[1];
if(!fileName.endsWith(".book"))
{
fileName += ".book";
}
String completePath = "plugins/BookCopier/" + fileName;
File file = new File(completePath);
if(file.exists())
{
commandSender.sendMessage(ChatColor.RED + "This file already exists.");
return;
}
MyBook book = new MyBook(commandSender.getItemInHand());
BookCreator.saveBook(book.getTitle(), book.getAuthor(), book.getPages(), completePath);
commandSender.sendMessage("Book has been saved.");
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
}
private static BookCopier plugin;
}
| false | true | public static void commandCopy(Player commandSender, String args[])
{
if(plugin.config.getOPsOnly())
{
if(!commandSender.isOp())
return;
}
if(args.length == 0)
{
commandSender.sendMessage(ChatColor.RED + "Type: \"/bc help\" for more informations.");
}
if(args[0].toLowerCase().matches("help"))
{
if(args.length == 1)
{
commandSender.sendMessage(ChatColor.AQUA + "BOOK COPIER COMMANDS AND INFO!");
commandSender.sendMessage("<> - required arguments");
commandSender.sendMessage("[] - optional arguments");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc copy [value] - Copies book in your hand.(No value means 1*)");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc give <player> [value] - Adds book in your hand to target player's inventory.");
}
}
else if(args[0].toLowerCase().matches("give"))
{
if(args.length == 2)
{
Player p;
if((p = plugin.getServer().getPlayer(args[1])) != null)
{
try
{
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
p.getInventory().addItem(item);
p.sendMessage("You recieve some book...");
commandSender.sendMessage("Book has been added to target player's inventory!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage(ChatColor.RED + "Target player is offline");
}
}
else if(args.length == 3)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
Player p;
if((p = plugin.getServer().getPlayer(args[1])) != null)
{
try
{
int numberOfBooks = Integer.parseInt(args[2]);
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
item.setAmount(numberOfBooks);
p.getInventory().addItem(item);
p.sendMessage("You recieved some books...");
commandSender.sendMessage("Books has been added to target player's inventory!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage(ChatColor.RED + "Target player is offline");
}
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
else if(args[0].toLowerCase().matches("copy"))
{
if(args.length == 1)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
MyBook book = new MyBook(commandSender.getItemInHand());
commandSender.getInventory().addItem(book.createItem());
commandSender.sendMessage("Book has been copied!");
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
else if(args.length == 2)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
try
{
int numberOfBooks = Integer.parseInt(args[1]);
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
item.setAmount(numberOfBooks);
commandSender.getInventory().addItem(item);
commandSender.sendMessage("Books has been copied!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
else if(args[0].toLowerCase().matches("load"))
{
if(args.length == 2)
{
String fileName = args[1];
if(!fileName.endsWith(".book"))
{
fileName += ".book";
}
String completePath = "plugins/BookCopier/" + fileName;
File file = new File(completePath);
if(!file.exists())
{
commandSender.sendMessage(ChatColor.RED + "This file doesn't exist.");
return;
}
if(!BookCreator.checkFormat(completePath))
{
commandSender.sendMessage(ChatColor.RED + "Bad format of target file!");
return;
}
ItemStack item = BookCreator.loadBook(completePath);
commandSender.getInventory().addItem(item);
commandSender.sendMessage("Book has been loaded.");
}
}
else if(args[0].toLowerCase().matches("save"))
{
if(args.length == 2)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
String fileName = args[1];
if(!fileName.endsWith(".book"))
{
fileName += ".book";
}
String completePath = "plugins/BookCopier/" + fileName;
File file = new File(completePath);
if(file.exists())
{
commandSender.sendMessage(ChatColor.RED + "This file already exists.");
return;
}
MyBook book = new MyBook(commandSender.getItemInHand());
BookCreator.saveBook(book.getTitle(), book.getAuthor(), book.getPages(), completePath);
commandSender.sendMessage("Book has been saved.");
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
}
| public static void commandCopy(Player commandSender, String args[])
{
if(plugin.config.getOPsOnly())
{
if(!commandSender.isOp())
return;
}
if(args.length == 0)
{
commandSender.sendMessage(ChatColor.RED + "Type: \"/bc help\" for more informations.");
return;
}
if(args[0].toLowerCase().matches("help"))
{
if(args.length == 1)
{
commandSender.sendMessage(ChatColor.AQUA + "BOOK COPIER COMMANDS AND INFO!");
commandSender.sendMessage("<> - required arguments");
commandSender.sendMessage("[] - optional arguments");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc copy [value] - Copies book in your hand.(No value means 1*)");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc give <player> [value] - Adds book in your hand to target player's inventory.");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc save <fileName> - Saves book in your hand to file.");
commandSender.sendMessage(ChatColor.YELLOW + "* " + ChatColor.WHITE + "/bc load <fileName> - Loads book from file to your inventory.");
}
}
else if(args[0].toLowerCase().matches("give"))
{
if(args.length == 2)
{
Player p;
if((p = plugin.getServer().getPlayer(args[1])) != null)
{
try
{
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
p.getInventory().addItem(item);
p.sendMessage("You recieve some book...");
commandSender.sendMessage("Book has been added to target player's inventory!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage(ChatColor.RED + "Target player is offline");
}
}
else if(args.length == 3)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
Player p;
if((p = plugin.getServer().getPlayer(args[1])) != null)
{
try
{
int numberOfBooks = Integer.parseInt(args[2]);
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
item.setAmount(numberOfBooks);
p.getInventory().addItem(item);
p.sendMessage("You recieved some books...");
commandSender.sendMessage("Books has been added to target player's inventory!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage(ChatColor.RED + "Target player is offline");
}
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
else if(args[0].toLowerCase().matches("copy"))
{
if(args.length == 1)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
MyBook book = new MyBook(commandSender.getItemInHand());
commandSender.getInventory().addItem(book.createItem());
commandSender.sendMessage("Book has been copied!");
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
else if(args.length == 2)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
try
{
int numberOfBooks = Integer.parseInt(args[1]);
ItemStack item = new MyBook(commandSender.getItemInHand()).createItem();
item.setAmount(numberOfBooks);
commandSender.getInventory().addItem(item);
commandSender.sendMessage("Books has been copied!");
}
catch(NumberFormatException e)
{
commandSender.sendMessage(ChatColor.RED + "Second argument must be number (Integer)");
e.printStackTrace();
}
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
else if(args[0].toLowerCase().matches("load"))
{
if(args.length == 2)
{
String fileName = args[1];
if(!fileName.endsWith(".book"))
{
fileName += ".book";
}
String completePath = "plugins/BookCopier/" + fileName;
File file = new File(completePath);
if(!file.exists())
{
commandSender.sendMessage(ChatColor.RED + "This file doesn't exist.");
return;
}
if(!BookCreator.checkFormat(completePath))
{
commandSender.sendMessage(ChatColor.RED + "Bad format of target file!");
return;
}
ItemStack item = BookCreator.loadBook(completePath);
commandSender.getInventory().addItem(item);
commandSender.sendMessage("Book has been loaded.");
}
}
else if(args[0].toLowerCase().matches("save"))
{
if(args.length == 2)
{
if(commandSender.getItemInHand().getTypeId() == 387)
{
String fileName = args[1];
if(!fileName.endsWith(".book"))
{
fileName += ".book";
}
String completePath = "plugins/BookCopier/" + fileName;
File file = new File(completePath);
if(file.exists())
{
commandSender.sendMessage(ChatColor.RED + "This file already exists.");
return;
}
MyBook book = new MyBook(commandSender.getItemInHand());
BookCreator.saveBook(book.getTitle(), book.getAuthor(), book.getPages(), completePath);
commandSender.sendMessage("Book has been saved.");
}
else
{
commandSender.sendMessage("This isn't book! You need ID: 387.");
}
}
}
}
|
diff --git a/src/Issue.java b/src/Issue.java
index 8166adb..508f905 100644
--- a/src/Issue.java
+++ b/src/Issue.java
@@ -1,184 +1,184 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com.google.gson.Gson;
import core.Channel;
import core.event.Join;
import core.event.Kick;
import core.event.Message;
import core.event.Quit;
import core.helpers.IRCException;
import core.plugin.Plugin;
import core.utils.Details;
import core.utils.IRC;
/**
* Allows admin users to create a new bug on github's issue tracker.
* @author Tom Leaman ([email protected])
*/
public class Issue implements Plugin {
private static final String AUTH_TOKEN_FILE = "auth_token";
private static final String GITHUB_URL = "https://api.github.com";
private static final String REPO_OWNER = "XeTK";
private static final String REPO_NAME = "JavaBot";
private Details details = Details.getInstance();
private IRC irc = IRC.getInstance();
private String authToken;
private boolean loaded = false;
public Issue() {
try {
authToken = loadAuthToken(AUTH_TOKEN_FILE);
} catch (FileNotFoundException e) {
System.err.println("No auth token file found in " + AUTH_TOKEN_FILE);
System.err.println("Issue plugin failed to load");
}
if (!authToken.equals(new String()))
loaded = true;
}
private String loadAuthToken(String filename) throws FileNotFoundException {
File f = new File(filename);
BufferedReader in = new BufferedReader(new FileReader(f));
String line = new String();
try {
line = in.readLine();
in.close();
} catch (IOException e) {
// tin foil hats a-plenty
loaded = false;
line = new String();
e.printStackTrace();
}
return line;
}
@Override
public void onMessage(Message message) throws Exception {
if (!loaded)
return;
if (message.getMessage().startsWith(".bug") && details.isAdmin(message.getUser()))
createIssue(message);
}
@Override
public String getHelpString() {
return "ISSUE: .bug <one_line_bug_report>";
}
private void createIssue(Message message) throws IssueException {
String issueTitle = message.getMessage().substring(5);
- String issueBody = "This message was generated automatically by " +
+ String issueBody = ":octocat: This message was generated automatically by " +
message.getUser() + " in " + message.getChannel() +
- ". Once confirmed, please remove `unconfirmed` tag. :octocat:";
+ ". Once confirmed, please remove `unconfirmed` tag.";
String jsonContent = "{\"title\":\"" + issueTitle + "\"" +
",\"body\":\"" + issueBody + "\"" +
",\"labels\":[\"bug\", \"unconfirmed\"]}";
try {
URL endpoint = new URL(
GITHUB_URL + "/repos/" + REPO_OWNER + "/" + REPO_NAME + "/issues");
HttpsURLConnection conn = (HttpsURLConnection) endpoint.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "token " + authToken);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.getOutputStream().write(jsonContent.getBytes("UTF-8"));
int responseCode = conn.getResponseCode();
if (responseCode >= 400) {
throw new IssueException(
"Failed to create issue (" + responseCode + ").");
}
StringBuffer response = new StringBuffer();
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
// send issue url to user
Gson parser = new Gson();
IssueResponse responseData =
(IssueResponse)parser.fromJson(response.toString(), IssueResponse.class);
irc.sendPrivmsg(message.getChannel(), message.getUser() + ": " +
"Issue #" + responseData.getNumber() +
" created: " + responseData.getHtmlUrl());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IRCException e) {
e.printStackTrace();
}
}
@Override
public void rawInput(String input) {
}
@Override
public void onCreate(Channel in_channel) {
}
@Override
public void onTime() throws Exception {
}
@Override
public void onJoin(Join join) throws Exception {
}
@Override
public void onQuit(Quit quit) throws Exception {
}
@Override
public void onKick(Kick kick) throws Exception {
}
@Override
public String name() {
return this.toString();
}
@Override
public String toString() {
return "Issue";
}
private class IssueException extends Exception {
public IssueException(String msg) {
super(msg);
}
}
}
| false | true | private void createIssue(Message message) throws IssueException {
String issueTitle = message.getMessage().substring(5);
String issueBody = "This message was generated automatically by " +
message.getUser() + " in " + message.getChannel() +
". Once confirmed, please remove `unconfirmed` tag. :octocat:";
String jsonContent = "{\"title\":\"" + issueTitle + "\"" +
",\"body\":\"" + issueBody + "\"" +
",\"labels\":[\"bug\", \"unconfirmed\"]}";
try {
URL endpoint = new URL(
GITHUB_URL + "/repos/" + REPO_OWNER + "/" + REPO_NAME + "/issues");
HttpsURLConnection conn = (HttpsURLConnection) endpoint.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "token " + authToken);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.getOutputStream().write(jsonContent.getBytes("UTF-8"));
int responseCode = conn.getResponseCode();
if (responseCode >= 400) {
throw new IssueException(
"Failed to create issue (" + responseCode + ").");
}
StringBuffer response = new StringBuffer();
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
// send issue url to user
Gson parser = new Gson();
IssueResponse responseData =
(IssueResponse)parser.fromJson(response.toString(), IssueResponse.class);
irc.sendPrivmsg(message.getChannel(), message.getUser() + ": " +
"Issue #" + responseData.getNumber() +
" created: " + responseData.getHtmlUrl());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IRCException e) {
e.printStackTrace();
}
}
| private void createIssue(Message message) throws IssueException {
String issueTitle = message.getMessage().substring(5);
String issueBody = ":octocat: This message was generated automatically by " +
message.getUser() + " in " + message.getChannel() +
". Once confirmed, please remove `unconfirmed` tag.";
String jsonContent = "{\"title\":\"" + issueTitle + "\"" +
",\"body\":\"" + issueBody + "\"" +
",\"labels\":[\"bug\", \"unconfirmed\"]}";
try {
URL endpoint = new URL(
GITHUB_URL + "/repos/" + REPO_OWNER + "/" + REPO_NAME + "/issues");
HttpsURLConnection conn = (HttpsURLConnection) endpoint.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "token " + authToken);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.getOutputStream().write(jsonContent.getBytes("UTF-8"));
int responseCode = conn.getResponseCode();
if (responseCode >= 400) {
throw new IssueException(
"Failed to create issue (" + responseCode + ").");
}
StringBuffer response = new StringBuffer();
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
// send issue url to user
Gson parser = new Gson();
IssueResponse responseData =
(IssueResponse)parser.fromJson(response.toString(), IssueResponse.class);
irc.sendPrivmsg(message.getChannel(), message.getUser() + ": " +
"Issue #" + responseData.getNumber() +
" created: " + responseData.getHtmlUrl());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IRCException e) {
e.printStackTrace();
}
}
|
diff --git a/src/com/dmdirc/ui/textpane/TextPaneCanvas.java b/src/com/dmdirc/ui/textpane/TextPaneCanvas.java
index 7bade8e5a..1e997133d 100644
--- a/src/com/dmdirc/ui/textpane/TextPaneCanvas.java
+++ b/src/com/dmdirc/ui/textpane/TextPaneCanvas.java
@@ -1,513 +1,513 @@
/*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.ui.textpane;
import com.dmdirc.ui.messages.Styliser;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.text.AttributedCharacterIterator;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.event.MouseInputListener;
import com.dmdirc.ui.messages.Styliser;
/** Canvas object to draw text. */
class TextPaneCanvas extends JPanel implements MouseInputListener {
/**
* A version number for this class. It should be changed whenever the
* class structure is changed (or anything else that would prevent
* serialized objects being unserialized with the new class).
*/
private static final long serialVersionUID = 4;
/** IRCDocument. */
private final IRCDocument document;
/** parent textpane. */
private final TextPane textPane;
/** Position -> TextLayout. */
private final Map<Rectangle, TextLayout> positions;
/** TextLayout -> Line numbers. */
private final Map<TextLayout, LineInfo> textLayouts;
/** Line number -> rectangle for lines containing hyperlinks. */
private final Map<TextLayout, Rectangle> hyperlinks;
/** position of the scrollbar. */
private int scrollBarPosition;
/** Start line of the selection. */
private int selStartLine;
/** Start character of the selection. */
private int selStartChar;
/** End line of the selection. */
private int selEndLine;
/** End character of the selection. */
private int selEndChar;
/**
* Creates a new text pane canvas.
*
* @param parent parent text pane for the canvas
* @param document IRCDocument to be displayed
*/
public TextPaneCanvas(final TextPane parent, final IRCDocument document) {
super();
this.document = document;
scrollBarPosition = 0;
textPane = parent;
this.setDoubleBuffered(true);
this.setOpaque(true);
textLayouts = new HashMap<TextLayout, LineInfo>();
positions = new HashMap<Rectangle, TextLayout>();
hyperlinks = new HashMap<TextLayout, Rectangle>();
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
/**
* Paints the text onto the canvas.
* @param g graphics object to draw onto
*/
public void paintComponent(final Graphics g) {
final Graphics2D graphics2D = (Graphics2D) g;
final float formatWidth = getWidth();
final float formatHeight = getHeight();
g.setColor(textPane.getBackground());
g.fillRect(0, 0, (int) formatWidth, (int) formatHeight);
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
boolean isHyperlink = false;
textLayouts.clear();
positions.clear();
hyperlinks.clear();
float drawPosY = formatHeight;
int startLine = scrollBarPosition;
// Check the start line is in range
if (startLine >= document.getNumLines()) {
startLine = document.getNumLines() - 1;
}
if (startLine <= 0) {
startLine = 0;
}
// We use these for drawing rather than the actual
// sel{Start,End}{Line,Char} vars defined in the highlightEvent
// This alllows for highlight in both directions.
int useStartLine;
int useStartChar;
int useEndLine;
int useEndChar;
if (selStartLine > selEndLine) {
// Swap both
useStartLine = selEndLine;
useStartChar = selEndChar;
useEndLine = selStartLine;
useEndChar = selStartChar;
} else if (selStartLine == selEndLine && selStartChar > selEndChar) {
// Just swap the chars
useStartLine = selStartLine;
useStartChar = selEndChar;
useEndLine = selEndLine;
useEndChar = selStartChar;
} else {
// Swap nothing
useStartLine = selStartLine;
useStartChar = selStartChar;
useEndLine = selEndLine;
useEndChar = selEndChar;
}
// Iterate through the lines
if (document.getNumLines() > 0) {
//int firstLineHeight = 0;
for (int i = startLine; i >= 0; i--) {
final AttributedCharacterIterator iterator = document.getLine(i).getIterator();
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(iterator, ((Graphics2D) g).getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
int wrappedLine = 0;
int height = 0;
//This needs to be moved to line 166, but that requires me changing the lines height.
int firstLineHeight = 0;
// Work out the number of lines this will take
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
if (firstLineHeight == 0) {
firstLineHeight = (int) (layout.getDescent() + layout.getLeading() + layout.getAscent());
}
height += firstLineHeight;
wrappedLine++;
}
// Get back to the start
lineMeasurer.setPosition(paragraphStart);
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
if (wrappedLine > 1) {
drawPosY -= height;
}
//Check if this line contains a hyperlink
for (Attribute attr : iterator.getAllAttributeKeys()) {
if (attr instanceof IRCTextAttribute) {
isHyperlink = true;
}
}
int j = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
// Calculate the Y offset
if (wrappedLine == 1) {
drawPosY -= firstLineHeight;
} else if (j != 0) {
drawPosY += firstLineHeight;
}
float drawPosX;
// Calculate the initial X position
if (layout.isLeftToRight()) {
drawPosX = 0;
} else {
drawPosX = formatWidth - layout.getAdvance();
}
// Check if the target is in range
if (drawPosY >= 0 || drawPosY <= formatHeight) {
// If the selection includes this line
if (useStartLine <= i && useEndLine >= i) {
int firstChar;
int lastChar;
// Determine the first char we care about
if (useStartLine < i || useStartChar < chars) {
firstChar = chars;
} else {
firstChar = useStartChar;
}
// ... And the last
if (useEndLine > i || useEndChar > chars + layout.getCharacterCount()) {
lastChar = chars + layout.getCharacterCount();
} else {
lastChar = useEndChar;
}
// If the selection includes the chars we're showing
if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) {
- final int trans = (int) (firstLineHeight - layout.getDescent() + drawPosY);
+ final int trans = (int) (firstLineHeight - layout.getDescent() + drawPosY - 5);
final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars);
graphics2D.setColor(UIManager.getColor("TextPane.selectionBackground"));
graphics2D.setBackground(UIManager.getColor("TextPane.selectionForeground"));
graphics2D.translate(0, trans);
graphics2D.fill(shape);
graphics2D.translate(0, -1 * trans);
}
}
graphics2D.setColor(textPane.getForeground());
- layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent());
+ layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent() - 5);
textLayouts.put(layout, new LineInfo(i, j));
positions.put(new Rectangle(
(int) drawPosX, (int) drawPosY,
(int) formatHeight, firstLineHeight), layout);
if (isHyperlink) {
hyperlinks.put(layout, new Rectangle((int) drawPosX,
(int) drawPosY, (int) formatWidth, firstLineHeight));
}
}
j++;
chars += layout.getCharacterCount();
}
if (j > 1) {
drawPosY -= height - firstLineHeight;
}
if (drawPosY <= 0) {
break;
}
}
}
}
/**
* sets the position of the scroll bar, and repaints if required.
* @param position scroll bar position
*/
protected void setScrollBarPosition(final int position) {
if (scrollBarPosition != position) {
scrollBarPosition = position;
if (textPane.isVisible()) {
repaint();
}
}
}
/** {@inheritDoc}. */
public void mouseClicked(final MouseEvent e) {
String clickedText = "";
int start = -1;
int end = -1;
final int[] info = getClickPosition(this.getMousePosition());
if (info[0] != -1) {
clickedText = textPane.getTextFromLine(info[0]);
start = info[2];
end = info[2];
if (start != -1 || end != -1) {
// Traverse backwards
while (start > 0 && start < clickedText.length() && clickedText.charAt(start) != ' ') {
start--;
}
if (start + 1 < clickedText.length() && clickedText.charAt(start) == ' ') {
start++;
}
// And forwards
while (end < clickedText.length() && end > 0 && clickedText.charAt(end) != ' ') {
end++;
}
if (e.getClickCount() == 2) {
selStartLine = info[0];
selEndLine = info[0];
selStartChar = start;
selEndChar = end;
} else if (e.getClickCount() == 3) {
selStartLine = info[0];
selEndLine = info[0];
selStartChar = 0;
selEndChar = clickedText.length();
} else {
checkClickedText(clickedText.substring(start, end));
}
}
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/** {@inheritDoc}. */
public void mousePressed(final MouseEvent e) {
if (e.getButton() == e.BUTTON1) {
highlightEvent(true, e);
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/** {@inheritDoc}. */
public void mouseReleased(final MouseEvent e) {
if (e.getButton() == e.BUTTON1) {
highlightEvent(false, e);
}
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/** {@inheritDoc}. */
public void mouseEntered(final MouseEvent e) {
//Ignore
}
/** {@inheritDoc}. */
public void mouseExited(final MouseEvent e) {
//Ignore
}
/** {@inheritDoc}. */
public void mouseDragged(final MouseEvent e) {
highlightEvent(false, e);
e.setSource(textPane);
textPane.dispatchEvent(e);
}
/** {@inheritDoc}. */
public void mouseMoved(final MouseEvent e) {
//Ignore
}
/**
* Sets the selection for the given event.
*
* @param start true = start
* @param e responsible mouse event
*/
private void highlightEvent(final boolean start, final MouseEvent e) {
final Point point = this.getMousePosition();
if (point == null) {
if (getLocationOnScreen().getY() > e.getYOnScreen()) {
textPane.setScrollBarPosition(scrollBarPosition - 1);
} else {
textPane.setScrollBarPosition(scrollBarPosition + 1);
}
} else {
final int[] info = getClickPosition(point);
if (info[0] != -1 && info[1] != -1) {
if (start) {
selStartLine = info[0];
selStartChar = info[2];
}
selEndLine = info[0];
selEndChar = info[2];
this.repaint();
}
}
}
/**
* Checks the clicked text and fires the appropriate events.
*
* @param clickedText Text clicked
*/
public void checkClickedText(final String clickedText) {
final Matcher matcher = Pattern.compile(Styliser.URL_REGEXP).matcher(clickedText);
if (matcher.find(0)) {
fireHyperlinkClicked(matcher.group());
} else if (textPane.isValidChannel(clickedText)) {
fireChannelClicked(clickedText);
}
}
/**
*
* Returns the line information from a mouse click inside the textpane.
*
* @param point mouse position
*
* @return line number, line part, position in whole line
*/
public int[] getClickPosition(final Point point) {
int lineNumber = -1;
int linePart = -1;
int pos = 0;
if (point != null) {
for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) {
if (entry.getKey().contains(point)) {
lineNumber = textLayouts.get(entry.getValue()).getLine();
linePart = textLayouts.get(entry.getValue()).getPart();
}
}
for (Map.Entry<Rectangle, TextLayout> entry : positions.entrySet()) {
if (textLayouts.get(entry.getValue()).getLine() == lineNumber) {
if (textLayouts.get(entry.getValue()).getPart() < linePart) {
pos += entry.getValue().getCharacterCount();
} else if (textLayouts.get(entry.getValue()).getPart() == linePart) {
pos += entry.getValue().hitTestChar((int) point.getX(),
(int) point.getY()).getInsertionIndex();
}
}
}
}
return new int[]{lineNumber, linePart, pos};
}
/**
* Informs listeners when a word has been clicked on.
* @param text word clicked on
*/
private void fireHyperlinkClicked(final String text) {
textPane.fireHyperlinkClicked(text);
}
/**
* Informs listeners when a word has been clicked on.
* @param text word clicked on
*/
private void fireChannelClicked(final String text) {
textPane.fireChannelClicked(text);
}
/**
* Returns the selected range info.
* <ul>
* <li>0 = start line</li>
* <li>1 = start char</li>
* <li>2 = end line</li>
* <li>3 = end char</li>
* </ul>
*
* @return Selected range info
*/
protected int[] getSelectedRange() {
if (selStartLine > selEndLine) {
// Swap both
return new int[]{selEndLine, selEndChar, selStartLine, selStartChar, };
} else if (selStartLine == selEndLine && selStartChar > selEndChar) {
// Just swap the chars
return new int[]{selStartLine, selEndChar, selEndLine, selStartChar, };
} else {
// Swap nothing
return new int[]{selStartLine, selStartChar, selEndLine, selEndChar, };
}
}
/** Clears the selection. */
protected void clearSelection() {
selEndLine = selStartLine;
selEndChar = selStartChar;
}
}
| false | true | public void paintComponent(final Graphics g) {
final Graphics2D graphics2D = (Graphics2D) g;
final float formatWidth = getWidth();
final float formatHeight = getHeight();
g.setColor(textPane.getBackground());
g.fillRect(0, 0, (int) formatWidth, (int) formatHeight);
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
boolean isHyperlink = false;
textLayouts.clear();
positions.clear();
hyperlinks.clear();
float drawPosY = formatHeight;
int startLine = scrollBarPosition;
// Check the start line is in range
if (startLine >= document.getNumLines()) {
startLine = document.getNumLines() - 1;
}
if (startLine <= 0) {
startLine = 0;
}
// We use these for drawing rather than the actual
// sel{Start,End}{Line,Char} vars defined in the highlightEvent
// This alllows for highlight in both directions.
int useStartLine;
int useStartChar;
int useEndLine;
int useEndChar;
if (selStartLine > selEndLine) {
// Swap both
useStartLine = selEndLine;
useStartChar = selEndChar;
useEndLine = selStartLine;
useEndChar = selStartChar;
} else if (selStartLine == selEndLine && selStartChar > selEndChar) {
// Just swap the chars
useStartLine = selStartLine;
useStartChar = selEndChar;
useEndLine = selEndLine;
useEndChar = selStartChar;
} else {
// Swap nothing
useStartLine = selStartLine;
useStartChar = selStartChar;
useEndLine = selEndLine;
useEndChar = selEndChar;
}
// Iterate through the lines
if (document.getNumLines() > 0) {
//int firstLineHeight = 0;
for (int i = startLine; i >= 0; i--) {
final AttributedCharacterIterator iterator = document.getLine(i).getIterator();
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(iterator, ((Graphics2D) g).getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
int wrappedLine = 0;
int height = 0;
//This needs to be moved to line 166, but that requires me changing the lines height.
int firstLineHeight = 0;
// Work out the number of lines this will take
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
if (firstLineHeight == 0) {
firstLineHeight = (int) (layout.getDescent() + layout.getLeading() + layout.getAscent());
}
height += firstLineHeight;
wrappedLine++;
}
// Get back to the start
lineMeasurer.setPosition(paragraphStart);
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
if (wrappedLine > 1) {
drawPosY -= height;
}
//Check if this line contains a hyperlink
for (Attribute attr : iterator.getAllAttributeKeys()) {
if (attr instanceof IRCTextAttribute) {
isHyperlink = true;
}
}
int j = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
// Calculate the Y offset
if (wrappedLine == 1) {
drawPosY -= firstLineHeight;
} else if (j != 0) {
drawPosY += firstLineHeight;
}
float drawPosX;
// Calculate the initial X position
if (layout.isLeftToRight()) {
drawPosX = 0;
} else {
drawPosX = formatWidth - layout.getAdvance();
}
// Check if the target is in range
if (drawPosY >= 0 || drawPosY <= formatHeight) {
// If the selection includes this line
if (useStartLine <= i && useEndLine >= i) {
int firstChar;
int lastChar;
// Determine the first char we care about
if (useStartLine < i || useStartChar < chars) {
firstChar = chars;
} else {
firstChar = useStartChar;
}
// ... And the last
if (useEndLine > i || useEndChar > chars + layout.getCharacterCount()) {
lastChar = chars + layout.getCharacterCount();
} else {
lastChar = useEndChar;
}
// If the selection includes the chars we're showing
if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) {
final int trans = (int) (firstLineHeight - layout.getDescent() + drawPosY);
final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars);
graphics2D.setColor(UIManager.getColor("TextPane.selectionBackground"));
graphics2D.setBackground(UIManager.getColor("TextPane.selectionForeground"));
graphics2D.translate(0, trans);
graphics2D.fill(shape);
graphics2D.translate(0, -1 * trans);
}
}
graphics2D.setColor(textPane.getForeground());
layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent());
textLayouts.put(layout, new LineInfo(i, j));
positions.put(new Rectangle(
(int) drawPosX, (int) drawPosY,
(int) formatHeight, firstLineHeight), layout);
if (isHyperlink) {
hyperlinks.put(layout, new Rectangle((int) drawPosX,
(int) drawPosY, (int) formatWidth, firstLineHeight));
}
}
j++;
chars += layout.getCharacterCount();
}
if (j > 1) {
drawPosY -= height - firstLineHeight;
}
if (drawPosY <= 0) {
break;
}
}
}
}
| public void paintComponent(final Graphics g) {
final Graphics2D graphics2D = (Graphics2D) g;
final float formatWidth = getWidth();
final float formatHeight = getHeight();
g.setColor(textPane.getBackground());
g.fillRect(0, 0, (int) formatWidth, (int) formatHeight);
int paragraphStart;
int paragraphEnd;
LineBreakMeasurer lineMeasurer;
boolean isHyperlink = false;
textLayouts.clear();
positions.clear();
hyperlinks.clear();
float drawPosY = formatHeight;
int startLine = scrollBarPosition;
// Check the start line is in range
if (startLine >= document.getNumLines()) {
startLine = document.getNumLines() - 1;
}
if (startLine <= 0) {
startLine = 0;
}
// We use these for drawing rather than the actual
// sel{Start,End}{Line,Char} vars defined in the highlightEvent
// This alllows for highlight in both directions.
int useStartLine;
int useStartChar;
int useEndLine;
int useEndChar;
if (selStartLine > selEndLine) {
// Swap both
useStartLine = selEndLine;
useStartChar = selEndChar;
useEndLine = selStartLine;
useEndChar = selStartChar;
} else if (selStartLine == selEndLine && selStartChar > selEndChar) {
// Just swap the chars
useStartLine = selStartLine;
useStartChar = selEndChar;
useEndLine = selEndLine;
useEndChar = selStartChar;
} else {
// Swap nothing
useStartLine = selStartLine;
useStartChar = selStartChar;
useEndLine = selEndLine;
useEndChar = selEndChar;
}
// Iterate through the lines
if (document.getNumLines() > 0) {
//int firstLineHeight = 0;
for (int i = startLine; i >= 0; i--) {
final AttributedCharacterIterator iterator = document.getLine(i).getIterator();
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
lineMeasurer = new LineBreakMeasurer(iterator, ((Graphics2D) g).getFontRenderContext());
lineMeasurer.setPosition(paragraphStart);
int wrappedLine = 0;
int height = 0;
//This needs to be moved to line 166, but that requires me changing the lines height.
int firstLineHeight = 0;
// Work out the number of lines this will take
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
if (firstLineHeight == 0) {
firstLineHeight = (int) (layout.getDescent() + layout.getLeading() + layout.getAscent());
}
height += firstLineHeight;
wrappedLine++;
}
// Get back to the start
lineMeasurer.setPosition(paragraphStart);
paragraphStart = iterator.getBeginIndex();
paragraphEnd = iterator.getEndIndex();
if (wrappedLine > 1) {
drawPosY -= height;
}
//Check if this line contains a hyperlink
for (Attribute attr : iterator.getAllAttributeKeys()) {
if (attr instanceof IRCTextAttribute) {
isHyperlink = true;
}
}
int j = 0;
int chars = 0;
// Loop through each wrapped line
while (lineMeasurer.getPosition() < paragraphEnd) {
final TextLayout layout = lineMeasurer.nextLayout(formatWidth);
// Calculate the Y offset
if (wrappedLine == 1) {
drawPosY -= firstLineHeight;
} else if (j != 0) {
drawPosY += firstLineHeight;
}
float drawPosX;
// Calculate the initial X position
if (layout.isLeftToRight()) {
drawPosX = 0;
} else {
drawPosX = formatWidth - layout.getAdvance();
}
// Check if the target is in range
if (drawPosY >= 0 || drawPosY <= formatHeight) {
// If the selection includes this line
if (useStartLine <= i && useEndLine >= i) {
int firstChar;
int lastChar;
// Determine the first char we care about
if (useStartLine < i || useStartChar < chars) {
firstChar = chars;
} else {
firstChar = useStartChar;
}
// ... And the last
if (useEndLine > i || useEndChar > chars + layout.getCharacterCount()) {
lastChar = chars + layout.getCharacterCount();
} else {
lastChar = useEndChar;
}
// If the selection includes the chars we're showing
if (lastChar > chars && firstChar < chars + layout.getCharacterCount()) {
final int trans = (int) (firstLineHeight - layout.getDescent() + drawPosY - 5);
final Shape shape = layout.getLogicalHighlightShape(firstChar - chars, lastChar - chars);
graphics2D.setColor(UIManager.getColor("TextPane.selectionBackground"));
graphics2D.setBackground(UIManager.getColor("TextPane.selectionForeground"));
graphics2D.translate(0, trans);
graphics2D.fill(shape);
graphics2D.translate(0, -1 * trans);
}
}
graphics2D.setColor(textPane.getForeground());
layout.draw(graphics2D, drawPosX, drawPosY + layout.getAscent() - 5);
textLayouts.put(layout, new LineInfo(i, j));
positions.put(new Rectangle(
(int) drawPosX, (int) drawPosY,
(int) formatHeight, firstLineHeight), layout);
if (isHyperlink) {
hyperlinks.put(layout, new Rectangle((int) drawPosX,
(int) drawPosY, (int) formatWidth, firstLineHeight));
}
}
j++;
chars += layout.getCharacterCount();
}
if (j > 1) {
drawPosY -= height - firstLineHeight;
}
if (drawPosY <= 0) {
break;
}
}
}
}
|
diff --git a/src/org/bh/validation/VRIsDouble.java b/src/org/bh/validation/VRIsDouble.java
index a647c496..521c7152 100644
--- a/src/org/bh/validation/VRIsDouble.java
+++ b/src/org/bh/validation/VRIsDouble.java
@@ -1,65 +1,65 @@
/*******************************************************************************
* Copyright 2011: Matthias Beste, Hannes Bischoff, Lisa Doerner, Victor Guettler, Markus Hattenbach, Tim Herzenstiel, Günter Hesse, Jochen Hülß, Daniel Krauth, Lukas Lochner, Mark Maltring, Sven Mayer, Benedikt Nees, Alexandre Pereira, Patrick Pfaff, Yannick Rödl, Denis Roster, Sebastian Schumacher, Norman Vogel, Simon Weber
*
* Copyright 2010: Anna Aichinger, Damian Berle, Patrick Dahl, Lisa Engelmann, Patrick Groß, Irene Ihl, Timo Klein, Alena Lang, Miriam Leuthold, Lukas Maciolek, Patrick Maisel, Vito Masiello, Moritz Olf, Ruben Reichle, Alexander Rupp, Daniel Schäfer, Simon Waldraff, Matthias Wurdig, Andreas Wußler
*
* Copyright 2009: Manuel Bross, Simon Drees, Marco Hammel, Patrick Heinz, Marcel Hockenberger, Marcus Katzor, Edgar Kauz, Anton Kharitonov, Sarah Kuhn, Michael Löckelt, Heiko Metzger, Jacqueline Missikewitz, Marcel Mrose, Steffen Nees, Alexander Roth, Sebastian Scharfenberger, Carsten Scheunemann, Dave Schikora, Alexander Schmalzhaf, Florian Schultze, Klaus Thiele, Patrick Tietze, Robert Vollmer, Norman Weisenburger, Lars Zuckschwerdt
*
* Copyright 2008: Camil Bartetzko, Tobias Bierer, Lukas Bretschneider, Johannes Gilbert, Daniel Huser, Christopher Kurschat, Dominik Pfauntsch, Sandra Rath, Daniel Weber
*
* This program is free software: you can redistribute it and/or modify it un-der 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 FIT-NESS 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.bh.validation;
import java.util.Locale;
import javax.swing.JTextField;
import org.bh.gui.IBHModelComponent;
import org.bh.gui.swing.comp.BHTextField;
import org.bh.platform.Services;
import org.bh.platform.i18n.BHTranslator;
import com.jgoodies.validation.ValidationResult;
/**
* This class contains validation rules to check a textfield's content to be doubles.
*
* @author Robert Vollmer, Patrick Heinz
* @version 1.0, 22.01.2010
*
*/
public class VRIsDouble extends ValidationRule {
public static final VRIsDouble INSTANCE = new VRIsDouble();
private VRIsDouble() {
}
@Override
public ValidationResult validate(IBHModelComponent comp) {
ValidationResult validationResult = new ValidationResult();
if (comp instanceof JTextField || comp instanceof BHTextField) {
BHTextField tf_toValidate = (BHTextField) comp;
double value = Services.stringToDouble(tf_toValidate.getText());
- if (tf_toValidate.getText().contains(".") && BHTranslator.getLoc() == Locale.GERMAN && ! tf_toValidate.getText().matches("(([1-9]\\d{0,2})(.\\d{3})*)")&& !tf_toValidate.getText().contains(","))
+ if (tf_toValidate.getText().contains(".") && BHTranslator.getLoc() == Locale.GERMAN && ! tf_toValidate.getText().matches("((-?)([1-9]\\d{0,2})(.\\d{3})*)")&& !tf_toValidate.getText().contains(","))
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
- else if (tf_toValidate.getText().contains(",") && BHTranslator.getLoc() == Locale.ENGLISH && ! tf_toValidate.getText().matches("(([1-9]\\d{0,2})(,\\d{3})*)")&& !tf_toValidate.getText().contains("."))
+ else if (tf_toValidate.getText().contains(",") && BHTranslator.getLoc() == Locale.ENGLISH && ! tf_toValidate.getText().matches("((-?)([1-9]\\d{0,2})(,\\d{3})*)")&& !tf_toValidate.getText().contains("."))
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
else if (Double.isNaN(value)) {
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
}
}
return validationResult;
}
}
| false | true | public ValidationResult validate(IBHModelComponent comp) {
ValidationResult validationResult = new ValidationResult();
if (comp instanceof JTextField || comp instanceof BHTextField) {
BHTextField tf_toValidate = (BHTextField) comp;
double value = Services.stringToDouble(tf_toValidate.getText());
if (tf_toValidate.getText().contains(".") && BHTranslator.getLoc() == Locale.GERMAN && ! tf_toValidate.getText().matches("(([1-9]\\d{0,2})(.\\d{3})*)")&& !tf_toValidate.getText().contains(","))
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
else if (tf_toValidate.getText().contains(",") && BHTranslator.getLoc() == Locale.ENGLISH && ! tf_toValidate.getText().matches("(([1-9]\\d{0,2})(,\\d{3})*)")&& !tf_toValidate.getText().contains("."))
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
else if (Double.isNaN(value)) {
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
}
}
return validationResult;
}
| public ValidationResult validate(IBHModelComponent comp) {
ValidationResult validationResult = new ValidationResult();
if (comp instanceof JTextField || comp instanceof BHTextField) {
BHTextField tf_toValidate = (BHTextField) comp;
double value = Services.stringToDouble(tf_toValidate.getText());
if (tf_toValidate.getText().contains(".") && BHTranslator.getLoc() == Locale.GERMAN && ! tf_toValidate.getText().matches("((-?)([1-9]\\d{0,2})(.\\d{3})*)")&& !tf_toValidate.getText().contains(","))
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
else if (tf_toValidate.getText().contains(",") && BHTranslator.getLoc() == Locale.ENGLISH && ! tf_toValidate.getText().matches("((-?)([1-9]\\d{0,2})(,\\d{3})*)")&& !tf_toValidate.getText().contains("."))
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
else if (Double.isNaN(value)) {
validationResult.addError(translator.translate("Efield") + " '"
+ translator.translate(tf_toValidate.getKey()) + "' "
+ translator.translate("EisDouble"));
}
}
return validationResult;
}
|
diff --git a/src/edu/fit/cs/sno/snes/Core.java b/src/edu/fit/cs/sno/snes/Core.java
index 6f9b3b1..57604b3 100644
--- a/src/edu/fit/cs/sno/snes/Core.java
+++ b/src/edu/fit/cs/sno/snes/Core.java
@@ -1,171 +1,173 @@
package edu.fit.cs.sno.snes;
import java.io.File;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import edu.fit.cs.sno.applet.SNOApplet;
import edu.fit.cs.sno.snes.apu.APUMemory;
import edu.fit.cs.sno.snes.apu.APURunnable;
import edu.fit.cs.sno.snes.cpu.CPU;
import edu.fit.cs.sno.snes.cpu.Timing;
import edu.fit.cs.sno.snes.mem.HiROMMemory;
import edu.fit.cs.sno.snes.mem.LoROMMemory;
import edu.fit.cs.sno.snes.mem.Memory;
import edu.fit.cs.sno.snes.mem.UnimplementedHardwareRegister;
import edu.fit.cs.sno.snes.ppu.PPU;
import edu.fit.cs.sno.snes.ppu.Sprites;
import edu.fit.cs.sno.snes.ppu.hwregs.CGRAM;
import edu.fit.cs.sno.snes.rom.RomLoader;
import edu.fit.cs.sno.util.Log;
import edu.fit.cs.sno.util.Settings;
import edu.fit.cs.sno.util.Util;
public class Core {
public static Memory mem;
public static long instCount;
public static long timeBegin;
public static long timeEnd;
public static boolean pause = false;
public static boolean advanceFrameOnce = false;
public static long maxInstructions;
public static boolean running = true;
public static Thread coreThread;
public static Thread apuThread;
public static void main(String args[]) {
System.out.println("Loading rom: " + args[0]);
try {
InputStream is = new FileInputStream(args[0]);
boolean isZip = args[0].endsWith(".zip");
Core.run(is, isZip);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void cycle(long count) throws Exception {
long instCount = 0;
// Do as many instructions as set in properties file
// Will execute indefinitely if instruction count is negative
try {
while ((instCount < count || count < 0) && running) {
if (pause && !advanceFrameOnce) continue;
CPU.cycle();
instCount++;
}
} catch (Exception err) {
// Finish timing and print stats before throwing error up
timeEnd = new Date().getTime();
System.out.println("Total time: " + ((timeEnd - timeBegin) / 1000) + " seconds");
System.out.println("Instructions performed: " + instCount);
System.out.println("Cycles performed: " + Timing.getCycles());
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f)) / (1024f * 1024f)) + " MHz");
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f))) + " Hz");
printMMaps();
throw err;
}
Core.instCount += instCount;
}
public static void init(InputStream is, boolean isZip) {
CPU.resetCPU();
PPU.init();
printStats();
Log.debug("====Starting SNO====");
RomLoader rl = new RomLoader(is, isZip);
if (rl.getRomInfo().isHiROM())
mem = new HiROMMemory();
else
mem = new LoROMMemory();
rl.loadMemory(mem);
instCount = 0;
// Initiate Reset Vector
CPU.resetVectorInit();
}
public static void run(InputStream is, boolean isZip) throws Exception {
init(is, isZip);
instCount = 0;
maxInstructions = Long.parseLong(Settings.get(Settings.CORE_MAX_INSTRUCTIONS));
// Load save file if found
if (Settings.isSet(Settings.SAVE_PATH)) {
InputStream saveStream = Util.getStreamFromUrl(Settings.get(Settings.SAVE_PATH));
if (saveStream != null) {
mem.loadSram(saveStream);
}
}
// Load save file if found
- File save = new File(Settings.get(Settings.SAVE_PATH));
- if (save != null) {
- mem.loadSram(new FileInputStream(save));
+ if (Settings.get(Settings.SAVE_PATH) != null) {
+ File save = new File(Settings.get(Settings.SAVE_PATH));
+ if (save != null) {
+ mem.loadSram(new FileInputStream(save));
+ }
}
// Execute and time game
if (Log.instruction.enabled() && Settings.get(Settings.CPU_ALT_DEBUG)=="false") {
Log.instruction("====CPU Execution====");
Log.instruction("romAdr pbr:pc op CPU Status args Instruction");
Log.instruction("------ ------- -- ------------------------------- --------------- -----------");
}
timeBegin = new Date().getTime();
cycle(maxInstructions);
timeEnd = new Date().getTime();
running = false;
// Print run stats
System.out.println("Total time: " + ((timeEnd - timeBegin) / 1000) + " seconds");
System.out.println("Instructions performed: " + instCount);
System.out.println("Cycles performed: " + Timing.getCycles());
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f)) / (1024f * 1024f)) + " MHz");
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f))) + " Hz");
printMMaps();
PPU.dumpVRAM();
mem.dumpWRAM();
APUMemory.dump();
renderScreen();
}
public static void printStats() {
Log.debug("====SNO Information====");
// Count number of implemented instructions
int instCount = 0;
for (int k = 0; k < CPU.jmp.length; k++) {
if (CPU.jmp[k] != null) instCount++;
}
Log.debug("Implemented Instructions: " + instCount + "/255");
}
public static void printMMaps() {
System.out.println("List of unimplemented but used hardware registers: ");
for (int i=0; i<0x4000; i++) {
if ((/*(LoROMMemory)*/mem).mmap[i] instanceof UnimplementedHardwareRegister) {
System.out.format(" 0x%04x\n", i+0x2000);
}
}
}
public static void renderScreen() {
CGRAM.readColors();
CGRAM.testColors();
Sprites.dumpOBJ();
}
}
| true | true | public static void run(InputStream is, boolean isZip) throws Exception {
init(is, isZip);
instCount = 0;
maxInstructions = Long.parseLong(Settings.get(Settings.CORE_MAX_INSTRUCTIONS));
// Load save file if found
if (Settings.isSet(Settings.SAVE_PATH)) {
InputStream saveStream = Util.getStreamFromUrl(Settings.get(Settings.SAVE_PATH));
if (saveStream != null) {
mem.loadSram(saveStream);
}
}
// Load save file if found
File save = new File(Settings.get(Settings.SAVE_PATH));
if (save != null) {
mem.loadSram(new FileInputStream(save));
}
// Execute and time game
if (Log.instruction.enabled() && Settings.get(Settings.CPU_ALT_DEBUG)=="false") {
Log.instruction("====CPU Execution====");
Log.instruction("romAdr pbr:pc op CPU Status args Instruction");
Log.instruction("------ ------- -- ------------------------------- --------------- -----------");
}
timeBegin = new Date().getTime();
cycle(maxInstructions);
timeEnd = new Date().getTime();
running = false;
// Print run stats
System.out.println("Total time: " + ((timeEnd - timeBegin) / 1000) + " seconds");
System.out.println("Instructions performed: " + instCount);
System.out.println("Cycles performed: " + Timing.getCycles());
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f)) / (1024f * 1024f)) + " MHz");
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f))) + " Hz");
printMMaps();
PPU.dumpVRAM();
mem.dumpWRAM();
APUMemory.dump();
renderScreen();
}
| public static void run(InputStream is, boolean isZip) throws Exception {
init(is, isZip);
instCount = 0;
maxInstructions = Long.parseLong(Settings.get(Settings.CORE_MAX_INSTRUCTIONS));
// Load save file if found
if (Settings.isSet(Settings.SAVE_PATH)) {
InputStream saveStream = Util.getStreamFromUrl(Settings.get(Settings.SAVE_PATH));
if (saveStream != null) {
mem.loadSram(saveStream);
}
}
// Load save file if found
if (Settings.get(Settings.SAVE_PATH) != null) {
File save = new File(Settings.get(Settings.SAVE_PATH));
if (save != null) {
mem.loadSram(new FileInputStream(save));
}
}
// Execute and time game
if (Log.instruction.enabled() && Settings.get(Settings.CPU_ALT_DEBUG)=="false") {
Log.instruction("====CPU Execution====");
Log.instruction("romAdr pbr:pc op CPU Status args Instruction");
Log.instruction("------ ------- -- ------------------------------- --------------- -----------");
}
timeBegin = new Date().getTime();
cycle(maxInstructions);
timeEnd = new Date().getTime();
running = false;
// Print run stats
System.out.println("Total time: " + ((timeEnd - timeBegin) / 1000) + " seconds");
System.out.println("Instructions performed: " + instCount);
System.out.println("Cycles performed: " + Timing.getCycles());
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f)) / (1024f * 1024f)) + " MHz");
System.out.println("Average speed: " + (((Timing.getCycles() + 0f) / ((timeEnd - timeBegin + 0f) / 1000f))) + " Hz");
printMMaps();
PPU.dumpVRAM();
mem.dumpWRAM();
APUMemory.dump();
renderScreen();
}
|
diff --git a/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java b/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java
index 71729016..be03bf6b 100644
--- a/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java
+++ b/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java
@@ -1,391 +1,392 @@
/*
* PatientView
*
* Copyright (c) Worth Solutions Limited 2004-2013
*
* This file is part of PatientView.
*
* PatientView 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.
* PatientView 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 PatientView in a file
* titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @package PatientView
* @link http://www.patientview.org
* @author PatientView <[email protected]>
* @copyright Copyright (c) 2004-2013, Worth Solutions Limited
* @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0
*/
package org.patientview.repository.impl;
import org.patientview.model.Patient;
import org.patientview.model.Patient_;
import org.patientview.model.Specialty;
import org.patientview.model.enums.SourceType;
import org.patientview.patientview.logon.PatientLogonWithTreatment;
import org.patientview.repository.AbstractHibernateDAO;
import org.patientview.repository.PatientDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Repository(value = "patientDao")
public class PatientDaoImpl extends AbstractHibernateDAO<Patient> implements PatientDao {
private JdbcTemplate jdbcTemplate;
@Inject
private DataSource dataSource;
@PostConstruct
public void init() {
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Patient get(Long id) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class);
Root<Patient> from = criteria.from(Patient.class);
List<Predicate> wherePredicates = new ArrayList<Predicate>();
wherePredicates.add(builder.equal(from.get(Patient_.id), id));
buildWhereClause(criteria, wherePredicates);
try {
return getEntityManager().createQuery(criteria).getSingleResult();
} catch (Exception e) {
return null;
}
}
@Override
public Patient get(String nhsno, String unitcode) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class);
Root<Patient> from = criteria.from(Patient.class);
List<Predicate> wherePredicates = new ArrayList<Predicate>();
wherePredicates.add(builder.equal(from.get(Patient_.nhsno), nhsno));
wherePredicates.add(builder.equal(from.get(Patient_.unitcode), unitcode));
wherePredicates.add(builder.equal(from.get(Patient_.sourceType), SourceType.PATIENT_VIEW.getName()));
buildWhereClause(criteria, wherePredicates);
try {
return getEntityManager().createQuery(criteria).getSingleResult();
} catch (Exception e) {
return null;
}
}
@Override
public List<Patient> getByNhsNo(String nhsNo) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class);
Root<Patient> from = criteria.from(Patient.class);
List<Predicate> wherePredicates = new ArrayList<Predicate>();
wherePredicates.add(builder.equal(from.get(Patient_.nhsno), nhsNo));
buildWhereClause(criteria, wherePredicates);
try {
return getEntityManager().createQuery(criteria).getResultList();
} catch (Exception e) {
return Collections.emptyList();
}
}
@Override
public void delete(String nhsno, String unitcode) {
// TODO Change this for 1.3
if (nhsno == null || nhsno.length() == 0 || unitcode == null || unitcode.length() == 0) {
throw new IllegalArgumentException("Required parameters nhsno and unitcode to delete patient");
}
Patient patient = get(nhsno, unitcode);
if (patient != null) {
delete(patient);
}
}
@Override
public List<Patient> get(String centreCode) {
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class);
Root<Patient> from = criteria.from(Patient.class);
List<Predicate> wherePredicates = new ArrayList<Predicate>();
wherePredicates.add(builder.equal(from.get(Patient_.unitcode), centreCode));
buildWhereClause(criteria, wherePredicates);
return getEntityManager().createQuery(criteria).getResultList();
}
//todo refactor into one query with the one below
//todo PERFORMANCE FIX: commented out the emailverification table to improve query speed.
// todo PERFORMANCE FIX & GENERAL BUG: removed the left join to the pv_user_log, need to reimplement
@Override
public List getUnitPatientsWithTreatmentDao(String unitcode, String nhsno, String name, boolean showgps,
Specialty specialty) {
StringBuilder query = new StringBuilder();
query.append("SELECT usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", usm.nhsno ");
query.append(", usm.unitcode ");
query.append(", null lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
+ query.append(", MAX(ptt.id) id ");
query.append(", MAX(ptt.treatment) treatment ");
query.append(", MAX(ptt.dateofbirth) dateofbirth ");
query.append(", MAX(ptt.rrtModality) rrtModality ");
query.append(", MAX(ptt.mostRecentTestResultDateRangeStopDate) mostRecentTestResultDateRangeStopDate ");
query.append("FROM USER usr ");
query.append("INNER JOIN usermapping usm ON usm.username = usr.username ");
query.append("LEFT JOIN patient ptt ON usm.nhsno = ptt.nhsno ");
query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id ");
// query.append("LEFT JOIN emailverification emv ON usr.username = emv.username ");
query.append("WHERE str.role = 'patient' ");
query.append("AND usr.username = usm.username ");
query.append("AND usr.id = str.user_id ");
query.append("AND usm.unitcode <> 'PATIENT' ");
query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL ");
query.append("AND usm.unitcode = ? ");
if (StringUtils.hasText(nhsno)) {
query.append("AND usm.nhsno LIKE ? ");
}
if (StringUtils.hasText(name)) {
query.append("AND usr.name LIKE ? ");
}
if (!showgps) {
query.append("AND usr.name NOT LIKE '%-GP' ");
}
query.append("AND str.specialty_id = ? ");
query.append("GROUP BY usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", usm.nhsno ");
query.append(", usm.unitcode ");
query.append(", lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
query.append(" ORDER BY usr.name ASC ");
List<Object> params = new ArrayList<Object>();
params.add(unitcode);
if (nhsno != null && nhsno.length() > 0) {
params.add('%' + nhsno + '%');
}
if (name != null && name.length() > 0) {
params.add('%' + name + '%');
}
params.add(specialty.getId());
return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper());
}
//todo refactor into one query with the one above
//todo PERFORMANCE FIX: commented out the emailverification table to improve query speed.
// todo PERFORMANCE FIX & GENERAL BUG: removed the left join to the pv_user_log, need to reimplement
@Override
public List getAllUnitPatientsWithTreatmentDao(String nhsno, String name, boolean showgps,
Specialty specialty) {
StringBuilder query = new StringBuilder();
query.append("SELECT DISTINCT ");
query.append(" usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", ptt.nhsno ");
query.append(", ptt.unitcode ");
query.append(", null lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
query.append(", ptt.id ");
query.append(", ptt.treatment ");
query.append(", ptt.dateofbirth ");
query.append(", ptt.rrtModality ");
query.append(", ptt.mostRecentTestResultDateRangeStopDate ");
query.append("FROM user usr ");
query.append("INNER JOIN usermapping usm ON usm.username = usr.username ");
query.append("LEFT JOIN patient ptt ON usm.nhsno = ptt.nhsno ");
query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id ");
query.append("WHERE str.role = 'patient' ");
query.append("AND usr.id = str.user_id ");
query.append("AND usm.unitcode <> 'PATIENT' ");
query.append("AND ptt.nhsno IS NOT NULL ");
query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL ");
if (nhsno != null && nhsno.length() > 0) {
query.append("AND usm.nhsno LIKE ? ");
}
if (name != null && name.length() > 0) {
query.append("AND usr.name LIKE ? ");
}
if (!showgps) {
query.append("AND usr.name NOT LIKE '%-GP' ");
}
query.append("AND str.specialty_id = ? ORDER BY usr.name ASC ");
List<Object> params = new ArrayList<Object>();
if (nhsno != null && nhsno.length() > 0) {
params.add('%' + nhsno + '%');
}
if (name != null && name.length() > 0) {
params.add('%' + name + '%');
}
params.add(specialty.getId());
return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper());
}
@Override
public List<PatientLogonWithTreatment> getUnitPatientsAllWithTreatmentDao(String unitcode, Specialty specialty) {
String sql = "SELECT "
+ " user.username, "
+ " user.password, "
+ " user.name, "
+ " user.email, "
+ " user.emailverified, "
+ " user.lastlogon, "
+ " usermapping.nhsno, "
+ " usermapping.unitcode, "
+ " user.firstlogon, "
+ " user.accountlocked, "
+ " patient.treatment, "
+ " patient.dateofbirth "
+ "FROM "
+ " user, "
+ " specialtyuserrole, "
+ " usermapping "
+ "LEFT JOIN "
+ " patient ON usermapping.nhsno = patient.nhsno "
+ "WHERE "
+ " usermapping.username = user.username "
+ "AND "
+ " user.id = specialtyuserrole.user_id "
+ "AND "
+ " usermapping.unitcode = ? "
+ "AND "
+ " specialtyuserrole.role = 'patient' "
+ "AND "
+ " user.name NOT LIKE '%-GP' "
+ "AND "
+ " specialtyuserrole.specialty_id = ? "
+ "ORDER BY "
+ " user.name ASC";
List<Object> params = new ArrayList<Object>();
params.add(unitcode);
params.add(specialty.getId());
return jdbcTemplate.query(sql, params.toArray(), new PatientLogonWithTreatmentMapper());
}
@Override
public List<Patient> getUktPatients() {
String sql = "SELECT DISTINCT patient.nhsno, patient.surname, patient.forename, "
+ " patient.dateofbirth, patient.postcode FROM patient, user, usermapping "
+ " WHERE patient.nhsno REGEXP '^[0-9]{10}$' AND patient.nhsno = usermapping.nhsno "
+ "AND user.username = usermapping.username "
+ " AND usermapping.username NOT LIKE '%-GP' AND user.dummypatient = 0";
return jdbcTemplate.query(sql, new PatientMapper());
}
private class PatientMapper implements RowMapper<Patient> {
@Override
public Patient mapRow(ResultSet resultSet, int i) throws SQLException {
Patient patient = new Patient();
patient.setNhsno(resultSet.getString("nhsno"));
patient.setSurname(resultSet.getString("surname"));
patient.setForename(resultSet.getString("forename"));
patient.setDateofbirth(resultSet.getDate("dateofbirth"));
patient.setPostcode(resultSet.getString("postcode"));
return patient;
}
}
private class PatientLogonWithTreatmentMapper implements RowMapper<PatientLogonWithTreatment> {
@Override
public PatientLogonWithTreatment mapRow(ResultSet resultSet, int i) throws SQLException {
PatientLogonWithTreatment patientLogonWithTreatment = new PatientLogonWithTreatment();
patientLogonWithTreatment.setUsername(resultSet.getString("username"));
patientLogonWithTreatment.setPassword(resultSet.getString("password"));
patientLogonWithTreatment.setName(resultSet.getString("name"));
patientLogonWithTreatment.setEmail(resultSet.getString("email"));
patientLogonWithTreatment.setEmailverified(resultSet.getBoolean("emailverified"));
patientLogonWithTreatment.setAccountlocked(resultSet.getBoolean("accountlocked"));
patientLogonWithTreatment.setNhsno(resultSet.getString("nhsno"));
patientLogonWithTreatment.setFirstlogon(resultSet.getBoolean("firstlogon"));
patientLogonWithTreatment.setLastlogon(resultSet.getDate("lastlogon"));
patientLogonWithTreatment.setUnitcode(resultSet.getString("unitcode"));
patientLogonWithTreatment.setTreatment(resultSet.getString("treatment"));
patientLogonWithTreatment.setDateofbirth(resultSet.getDate("dateofbirth"));
return patientLogonWithTreatment;
}
}
private class PatientLogonWithTreatmentExtendMapper extends PatientLogonWithTreatmentMapper {
@Override
public PatientLogonWithTreatment mapRow(ResultSet resultSet, int i) throws SQLException {
PatientLogonWithTreatment patientLogonWithTreatment = super.mapRow(resultSet, i);
patientLogonWithTreatment.setPatientId(resultSet.getLong("id"));
patientLogonWithTreatment.setLastverificationdate(resultSet.getDate("lastverificationdate"));
patientLogonWithTreatment.setRrtModality(resultSet.getInt("rrtModality"));
patientLogonWithTreatment.setLastdatadate(resultSet.getDate("mostRecentTestResultDateRangeStopDate"));
return patientLogonWithTreatment;
}
}
}
| true | true | public List getUnitPatientsWithTreatmentDao(String unitcode, String nhsno, String name, boolean showgps,
Specialty specialty) {
StringBuilder query = new StringBuilder();
query.append("SELECT usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", usm.nhsno ");
query.append(", usm.unitcode ");
query.append(", null lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
query.append(", MAX(ptt.treatment) treatment ");
query.append(", MAX(ptt.dateofbirth) dateofbirth ");
query.append(", MAX(ptt.rrtModality) rrtModality ");
query.append(", MAX(ptt.mostRecentTestResultDateRangeStopDate) mostRecentTestResultDateRangeStopDate ");
query.append("FROM USER usr ");
query.append("INNER JOIN usermapping usm ON usm.username = usr.username ");
query.append("LEFT JOIN patient ptt ON usm.nhsno = ptt.nhsno ");
query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id ");
// query.append("LEFT JOIN emailverification emv ON usr.username = emv.username ");
query.append("WHERE str.role = 'patient' ");
query.append("AND usr.username = usm.username ");
query.append("AND usr.id = str.user_id ");
query.append("AND usm.unitcode <> 'PATIENT' ");
query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL ");
query.append("AND usm.unitcode = ? ");
if (StringUtils.hasText(nhsno)) {
query.append("AND usm.nhsno LIKE ? ");
}
if (StringUtils.hasText(name)) {
query.append("AND usr.name LIKE ? ");
}
if (!showgps) {
query.append("AND usr.name NOT LIKE '%-GP' ");
}
query.append("AND str.specialty_id = ? ");
query.append("GROUP BY usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", usm.nhsno ");
query.append(", usm.unitcode ");
query.append(", lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
query.append(" ORDER BY usr.name ASC ");
List<Object> params = new ArrayList<Object>();
params.add(unitcode);
if (nhsno != null && nhsno.length() > 0) {
params.add('%' + nhsno + '%');
}
if (name != null && name.length() > 0) {
params.add('%' + name + '%');
}
params.add(specialty.getId());
return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper());
}
| public List getUnitPatientsWithTreatmentDao(String unitcode, String nhsno, String name, boolean showgps,
Specialty specialty) {
StringBuilder query = new StringBuilder();
query.append("SELECT usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", usm.nhsno ");
query.append(", usm.unitcode ");
query.append(", null lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
query.append(", MAX(ptt.id) id ");
query.append(", MAX(ptt.treatment) treatment ");
query.append(", MAX(ptt.dateofbirth) dateofbirth ");
query.append(", MAX(ptt.rrtModality) rrtModality ");
query.append(", MAX(ptt.mostRecentTestResultDateRangeStopDate) mostRecentTestResultDateRangeStopDate ");
query.append("FROM USER usr ");
query.append("INNER JOIN usermapping usm ON usm.username = usr.username ");
query.append("LEFT JOIN patient ptt ON usm.nhsno = ptt.nhsno ");
query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id ");
// query.append("LEFT JOIN emailverification emv ON usr.username = emv.username ");
query.append("WHERE str.role = 'patient' ");
query.append("AND usr.username = usm.username ");
query.append("AND usr.id = str.user_id ");
query.append("AND usm.unitcode <> 'PATIENT' ");
query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL ");
query.append("AND usm.unitcode = ? ");
if (StringUtils.hasText(nhsno)) {
query.append("AND usm.nhsno LIKE ? ");
}
if (StringUtils.hasText(name)) {
query.append("AND usr.name LIKE ? ");
}
if (!showgps) {
query.append("AND usr.name NOT LIKE '%-GP' ");
}
query.append("AND str.specialty_id = ? ");
query.append("GROUP BY usr.username ");
query.append(", usr.password ");
query.append(", usr.name ");
query.append(", usr.email ");
query.append(", usr.emailverified ");
query.append(", usr.accountlocked ");
query.append(", usm.nhsno ");
query.append(", usm.unitcode ");
query.append(", lastverificationdate ");
query.append(", usr.firstlogon ");
query.append(", usr.lastlogon ");
query.append(" ORDER BY usr.name ASC ");
List<Object> params = new ArrayList<Object>();
params.add(unitcode);
if (nhsno != null && nhsno.length() > 0) {
params.add('%' + nhsno + '%');
}
if (name != null && name.length() > 0) {
params.add('%' + name + '%');
}
params.add(specialty.getId());
return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper());
}
|
diff --git a/src/main/java/com/googlecode/mgwt/examples/showcase/client/activities/test/TestActivity.java b/src/main/java/com/googlecode/mgwt/examples/showcase/client/activities/test/TestActivity.java
index e6e474b..f88f285 100644
--- a/src/main/java/com/googlecode/mgwt/examples/showcase/client/activities/test/TestActivity.java
+++ b/src/main/java/com/googlecode/mgwt/examples/showcase/client/activities/test/TestActivity.java
@@ -1,58 +1,58 @@
package com.googlecode.mgwt.examples.showcase.client.activities.test;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.XMLParser;
import com.googlecode.mgwt.dom.client.event.tap.TapEvent;
import com.googlecode.mgwt.dom.client.event.tap.TapHandler;
import com.googlecode.mgwt.examples.showcase.client.ClientFactory;
import com.googlecode.mgwt.examples.showcase.client.DetailActivity;
import com.googlecode.mgwt.examples.showcase.client.activities.animation.AnimationSelectedEvent;
import com.googlecode.mgwt.examples.showcase.client.event.ActionEvent;
import com.googlecode.mgwt.examples.showcase.client.event.ActionNames;
import com.googlecode.mgwt.mvp.client.MGWTAbstractActivity;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedEvent;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedHandler;
public class TestActivity extends MGWTAbstractActivity {
private final ClientFactory clientFactory;
public TestActivity(ClientFactory clientFactory) {
this.clientFactory = clientFactory;
}
@Override
public void start(AcceptsOneWidget panel, final EventBus eventBus) {
super.start(panel, eventBus);
TestView view = clientFactory.getTestView();
view.setTitle("Test");
view.renderItems(clientFactory.getStationUtil().getAllStation());
addHandlerRegistration(view.getBackButton().addTapHandler(new TapHandler() {
@Override
public void onTap(TapEvent event) {
ActionEvent.fire(eventBus, ActionNames.BACK);
}
}));
addHandlerRegistration(view.getCellSelectedHandler().addCellSelectedHandler(
new CellSelectedHandler() {
@Override
public void onCellSelected(CellSelectedEvent event) {
int index = event.getIndex();
Document messageDom = XMLParser.parse(event.getTargetElement().toString());
- String stationName = messageDom.getElementsByTagName("div").item(index).getFirstChild().getNodeValue();
+ String stationName = messageDom.getElementsByTagName("div").item(0).getFirstChild().getNodeValue();
StationSelectedEvent.fire(eventBus, stationName);
}
}));
panel.setWidget(view);
}
}
| true | true | public void start(AcceptsOneWidget panel, final EventBus eventBus) {
super.start(panel, eventBus);
TestView view = clientFactory.getTestView();
view.setTitle("Test");
view.renderItems(clientFactory.getStationUtil().getAllStation());
addHandlerRegistration(view.getBackButton().addTapHandler(new TapHandler() {
@Override
public void onTap(TapEvent event) {
ActionEvent.fire(eventBus, ActionNames.BACK);
}
}));
addHandlerRegistration(view.getCellSelectedHandler().addCellSelectedHandler(
new CellSelectedHandler() {
@Override
public void onCellSelected(CellSelectedEvent event) {
int index = event.getIndex();
Document messageDom = XMLParser.parse(event.getTargetElement().toString());
String stationName = messageDom.getElementsByTagName("div").item(index).getFirstChild().getNodeValue();
StationSelectedEvent.fire(eventBus, stationName);
}
}));
panel.setWidget(view);
}
| public void start(AcceptsOneWidget panel, final EventBus eventBus) {
super.start(panel, eventBus);
TestView view = clientFactory.getTestView();
view.setTitle("Test");
view.renderItems(clientFactory.getStationUtil().getAllStation());
addHandlerRegistration(view.getBackButton().addTapHandler(new TapHandler() {
@Override
public void onTap(TapEvent event) {
ActionEvent.fire(eventBus, ActionNames.BACK);
}
}));
addHandlerRegistration(view.getCellSelectedHandler().addCellSelectedHandler(
new CellSelectedHandler() {
@Override
public void onCellSelected(CellSelectedEvent event) {
int index = event.getIndex();
Document messageDom = XMLParser.parse(event.getTargetElement().toString());
String stationName = messageDom.getElementsByTagName("div").item(0).getFirstChild().getNodeValue();
StationSelectedEvent.fire(eventBus, stationName);
}
}));
panel.setWidget(view);
}
|
diff --git a/TwirlTestTest/src/com/secondhand/model/EnemyTest.java b/TwirlTestTest/src/com/secondhand/model/EnemyTest.java
index 91cd1a1f..017b41ec 100644
--- a/TwirlTestTest/src/com/secondhand/model/EnemyTest.java
+++ b/TwirlTestTest/src/com/secondhand/model/EnemyTest.java
@@ -1,53 +1,54 @@
package com.secondhand.model;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import com.badlogic.gdx.math.Vector2;
import junit.framework.TestCase;
public class EnemyTest extends TestCase{
private final BufferObjectManager mBufferObjectManager = new BufferObjectManager();
public void setUp() {
// if we don't do this, an exception is thrown when calling the constructor of Circle.
BufferObjectManager.setActiveInstance(mBufferObjectManager);
}
public void testConstructor() {
final PhysicsWorld pw =new PhysicsWorld(new Vector2(), true);
Vector2 pos = new Vector2(2f, 4f);
float rad = 3.2f;
float maxSpeed = 10f;
Enemy enemy = new Enemy(pos, rad, pw, maxSpeed);
assertEquals(rad, enemy.getRadius());
assertEquals(pos.x, enemy.getX());
assertEquals(pos.y, enemy.getY());
assertEquals(maxSpeed, enemy.getMaxSpeed());
}
public void testIsBiggerThan() {
final PhysicsWorld pw =new PhysicsWorld(new Vector2(), true);
Vector2 pos = new Vector2(2f, 4f);
float rad = 3.2f;
+ float maxSpeed = 10f;
- Enemy enemy = new Enemy(pos, rad, pw);
+ Enemy enemy = new Enemy(pos, rad, pw, maxSpeed);
- Player other = new Player(pos, rad-1, pw);
+ Player other = new Player(pos, rad-1, pw, maxSpeed);
assertTrue(enemy.canEat(other));
- other = new Player(pos, rad, pw);
+ other = new Player(pos, rad, pw, maxSpeed);
assertFalse(enemy.canEat(other));
}
}
| false | true | public void testIsBiggerThan() {
final PhysicsWorld pw =new PhysicsWorld(new Vector2(), true);
Vector2 pos = new Vector2(2f, 4f);
float rad = 3.2f;
Enemy enemy = new Enemy(pos, rad, pw);
Player other = new Player(pos, rad-1, pw);
assertTrue(enemy.canEat(other));
other = new Player(pos, rad, pw);
assertFalse(enemy.canEat(other));
}
| public void testIsBiggerThan() {
final PhysicsWorld pw =new PhysicsWorld(new Vector2(), true);
Vector2 pos = new Vector2(2f, 4f);
float rad = 3.2f;
float maxSpeed = 10f;
Enemy enemy = new Enemy(pos, rad, pw, maxSpeed);
Player other = new Player(pos, rad-1, pw, maxSpeed);
assertTrue(enemy.canEat(other));
other = new Player(pos, rad, pw, maxSpeed);
assertFalse(enemy.canEat(other));
}
|
diff --git a/src/main/java/lcmc/data/CRMXML.java b/src/main/java/lcmc/data/CRMXML.java
index f5bc272e..1f30f377 100644
--- a/src/main/java/lcmc/data/CRMXML.java
+++ b/src/main/java/lcmc/data/CRMXML.java
@@ -1,4359 +1,4360 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
* Copyright (C) 2011-2012, Rastislav Levrinc.
*
* DRBD Management Console is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* DRBD Management Console is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package lcmc.data;
import lcmc.utilities.Tools;
import lcmc.utilities.ConvertCmdCallback;
import lcmc.utilities.SSH;
import lcmc.utilities.CRM;
import lcmc.robotest.RoboTest;
import lcmc.gui.resources.Info;
import lcmc.gui.resources.ServiceInfo;
import lcmc.gui.resources.ServicesInfo;
import lcmc.Exceptions;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Set;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Collections;
import java.util.Locale;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.Lock;
import org.apache.commons.collections15.map.MultiKeyMap;
import lcmc.utilities.Logger;
import lcmc.utilities.LoggerFactory;
/**
* This class parses ocf crm xml, stores information like
* short and long description, data types etc. for defined types
* of services in the hashes and provides methods to get this
* information.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
public final class CRMXML extends XML {
/** Logger. */
private static final Logger LOG = LoggerFactory.getLogger(CRMXML.class);
/** Host. */
private final Host host;
/** List of global parameters. */
private final List<String> globalParams = new ArrayList<String>();
/** List of not advanced global parameters. */
private final List<String> globalNotAdvancedParams =
new ArrayList<String>();
/** Map from global parameter to its access type. */
private final Map<String, ConfigData.AccessType> paramGlobalAccessTypes =
new HashMap<String, ConfigData.AccessType>();
/** List of required global parameters. */
private final List<String> globalRequiredParams = new ArrayList<String>();
/** Map from class to the list of all crm services. */
private final Map<String, List<ResourceAgent>> classToServicesMap =
new HashMap<String, List<ResourceAgent>>();
/** Map from global parameter to its short description. */
private final Map<String, String> paramGlobalShortDescMap =
new HashMap<String, String>();
/** Map from global parameter to its long description. */
private final Map<String, String> paramGlobalLongDescMap =
new HashMap<String, String>();
/** Map from global parameter to its default value. */
private final Map<String, String> paramGlobalDefaultMap =
new HashMap<String, String>();
/** Map from global parameter to its preferred value. */
private final Map<String, String> paramGlobalPreferredMap =
new HashMap<String, String>();
/** Map from global parameter to its type. */
private final Map<String, String> paramGlobalTypeMap =
new HashMap<String, String>();
/** Map from global parameter to the array of possible choices. */
private final Map<String, String[]> paramGlobalPossibleChoices =
new HashMap<String, String[]>();
/** List of parameters for colocations. */
private final List<String> colParams = new ArrayList<String>();
/** List of parameters for colocation in resource sets.
(rsc_colocation tag) */
private final List<String> rscSetColParams = new ArrayList<String>();
/** List of parameters for colocation in resource sets.
(resource_set tag) */
private final List<String> rscSetColConnectionParams =
new ArrayList<String>();
/** List of required parameters for colocations. */
private final List<String> colRequiredParams = new ArrayList<String>();
/** Map from colocation parameter to its short description. */
private final Map<String, String> paramColShortDescMap =
new HashMap<String, String>();
/** Map from colocation parameter to its long description. */
private final Map<String, String> paramColLongDescMap =
new HashMap<String, String>();
/** Map from colocation parameter to its default value. */
private final Map<String, String> paramColDefaultMap =
new HashMap<String, String>();
/** Map from colocation parameter to its preferred value. */
private final Map<String, String> paramColPreferredMap =
new HashMap<String, String>();
/** Map from colocation parameter to its type. */
private final Map<String, String> paramColTypeMap =
new HashMap<String, String>();
/** Map from colocation parameter to the array of possible choices. */
private final Map<String, String[]> paramColPossibleChoices =
new HashMap<String, String[]>();
/** Map from colocation parameter to the array of possible choices for
* master/slave resource. */
private final Map<String, String[]> paramColPossibleChoicesMS =
new HashMap<String, String[]>();
/** List of parameters for order. */
private final List<String> ordParams = new ArrayList<String>();
/** List of parameters for order in resource sets. (rsc_order tag) */
private final List<String> rscSetOrdParams = new ArrayList<String>();
/** List of parameters for order in resource sets. (resource_set tag) */
private final List<String> rscSetOrdConnectionParams =
new ArrayList<String>();
/** List of required parameters for orders. */
private final List<String> ordRequiredParams = new ArrayList<String>();
/** Map from order parameter to its short description. */
private final Map<String, String> paramOrdShortDescMap =
new HashMap<String, String>();
/** Map from order parameter to its long description. */
private final Map<String, String> paramOrdLongDescMap =
new HashMap<String, String>();
/** Map from order parameter to its default value. */
private final Map<String, String> paramOrdDefaultMap =
new HashMap<String, String>();
/** Map from order parameter to its preferred value. */
private final Map<String, String> paramOrdPreferredMap =
new HashMap<String, String>();
/** Map from order parameter to its type. */
private final Map<String, String> paramOrdTypeMap =
new HashMap<String, String>();
/** Map from order parameter to the array of possible choices. */
private final Map<String, String[]> paramOrdPossibleChoices =
new HashMap<String, String[]>();
/** Map from order parameter to the array of possible choices for
* master/slave resource. */
private final Map<String, String[]> paramOrdPossibleChoicesMS =
new HashMap<String, String[]>();
/** Predefined group as heartbeat service. */
private final ResourceAgent hbGroup =
new ResourceAgent(ConfigData.PM_GROUP_NAME,
"",
"group");
/** Predefined clone as pacemaker service. */
private final ResourceAgent pcmkClone;
/** Predefined drbddisk as heartbeat service. */
private final ResourceAgent hbDrbddisk =
new ResourceAgent("drbddisk",
ResourceAgent.HEARTBEAT_PROVIDER,
ResourceAgent.HEARTBEAT_CLASS);
/** Predefined linbit::drbd as pacemaker service. */
private final ResourceAgent hbLinbitDrbd =
new ResourceAgent("drbd", "linbit", ResourceAgent.OCF_CLASS);
/** Mapfrom heartbeat service defined by name and class to the heartbeat
* service object.
*/
private final MultiKeyMap<String, ResourceAgent> serviceToResourceAgentMap =
new MultiKeyMap<String, ResourceAgent>();
/** Whether drbddisk ra is present. */
private boolean drbddiskPresent;
/** Whether linbit::drbd ra is present. */
private boolean linbitDrbdPresent;
/** Choices for combo box in stonith hostlists. */
private final List<String> hostlistChoices = new ArrayList<String>();
/** Parameters of some RAs that are not advanced. */
private static final MultiKeyMap<String, String> RA_PARAM_SECTION =
new MultiKeyMap<String, String>();
/** Pacemaker "true" string. */
static final String PCMK_TRUE = "true";
/** Pacemaker "false" string. */
static final String PCMK_FALSE = "false";
/** Disabled string. */
public static final String DISABLED_STRING = "disabled";
/** Boolean parameter type. */
private static final String PARAM_TYPE_BOOLEAN = "boolean";
/** Integer parameter type. */
private static final String PARAM_TYPE_INTEGER = "integer";
/** Label parameter type. */
private static final String PARAM_TYPE_LABEL = "label";
/** String parameter type. */
private static final String PARAM_TYPE_STRING = "string";
/** Time parameter type. */
private static final String PARAM_TYPE_TIME = "time";
/** Fail count prefix. */
private static final String FAIL_COUNT_PREFIX = "fail-count-";
/** Attribute roles. */
private static final String[] ATTRIBUTE_ROLES = {null,
"Stopped",
"Started"};
/** Atribute roles for master/slave resource. */
private static final String[] ATTRIBUTE_ROLES_MS = {null,
"Stopped",
"Started",
"Master",
"Slave"};
/** Attribute actions. */
private static final String[] ATTRIBUTE_ACTIONS = {null,
"start",
"stop"};
/** Attribute actions for master/slave. */
private static final String[] ATTRIBUTE_ACTIONS_MS = {null,
"start",
"promote",
"demote",
"stop"};
/** Target role stopped. */
public static final String TARGET_ROLE_STOPPED = "stopped";
/** Target role started. */
private static final String TARGET_ROLE_STARTED = "started";
/** Target role master. */
private static final String TARGET_ROLE_MASTER = "master";
/** Target role slave. */
public static final String TARGET_ROLE_SLAVE = "slave";
/** INFINITY keyword. */
public static final String INFINITY_STRING = "INFINITY";
/** Alternative INFINITY keyword. */
public static final String PLUS_INFINITY_STRING = "+INFINITY";
/** -INFINITY keyword. */
public static final String MINUS_INFINITY_STRING = "-INFINITY";
/** Choices for integer fields. */
private static final String[] INTEGER_VALUES = {null,
"0",
"2",
"100",
INFINITY_STRING,
MINUS_INFINITY_STRING,
PLUS_INFINITY_STRING};
/** Name of the stonith timeout instance attribute. */
private static final String STONITH_TIMEOUT_INSTANCE_ATTR =
"stonith-timeout";
/** Name of the stonith priority instance attribute.
It is actually only "priority" but it clashes with priority meta
attribute. It is converted, wenn it is parsed and when it is stored to
cib. */
public static final String STONITH_PRIORITY_INSTANCE_ATTR =
"stonith-priority";
/** Constraint score keyword. */
public static final String SCORE_STRING = "score";
/** Meta attributes for primitives. Cannot be static because it changes
* with versions. */
private Map<String, String> metaAttrParams = null;
/** Meta attributes for rsc defaults meta attributes. */
private Map<String, String> rscDefaultsMetaAttrs = null;
/** Name of the priority meta attribute. */
private static final String PRIORITY_META_ATTR = "priority";
/** Name of the resource-stickiness meta attribute. */
private static final String RESOURCE_STICKINESS_META_ATTR =
"resource-stickiness";
/** Name of the migration-threshold meta attribute. */
private static final String MIGRATION_THRESHOLD_META_ATTR =
"migration-threshold";
/** Name of the failure-timeout meta attribute. */
private static final String FAILURE_TIMEOUT_META_ATTR = "failure-timeout";
/** Name of the multiple-timeout meta attribute. */
private static final String MULTIPLE_ACTIVE_META_ATTR = "multiple-active";
/** Name of the target-role meta attribute. */
private static final String TARGET_ROLE_META_ATTR = "target-role";
/** Name of the is-managed meta attribute. */
private static final String IS_MANAGED_META_ATTR = "is-managed";
/** Name of the allow-migrate meta attribute. */
private static final String ALLOW_MIGRATE_META_ATTR = "allow-migrate";
/** Name of the master-max clone meta attribute. */
private static final String MASTER_MAX_META_ATTR = "master-max";
/** Name of the master-node-max clone meta attribute. */
private static final String MASTER_NODE_MAX_META_ATTR = "master-node-max";
/** Name of the clone-max clone meta attribute. */
private static final String CLONE_MAX_META_ATTR = "clone-max";
/** Name of the clone-node-max clone meta attribute. */
private static final String CLONE_NODE_MAX_META_ATTR = "clone-node-max";
/** Name of the notify clone meta attribute. */
private static final String NOTIFY_META_ATTR = "notify";
/** Name of the globally-unique clone meta attribute. */
private static final String GLOBALLY_UNIQUE_META_ATTR = "globally-unique";
/** Name of the ordered clone meta attribute. */
private static final String ORDERED_META_ATTR = "ordered";
/** Name of the interleave clone meta attribute. */
private static final String INTERLEAVE_META_ATTR = "interleave";
/** Name of the ordered group meta attribute. It has different default than
* clone "ordered". */
public static final String GROUP_ORDERED_META_ATTR = "group-ordered";
/** Name of the collocated group meta attribute. */
private static final String GROUP_COLLOCATED_META_ATTR = "collocated";
/** Require all "true" value. */
public static final String REQUIRE_ALL_TRUE = PCMK_TRUE;
/** Require all "false" value. */
public static final String REQUIRE_ALL_FALSE = PCMK_FALSE;
/** Name of the require-all resource set attribute. */
public static final String REQUIRE_ALL_ATTR = "require-all";
/** Section for meta attributes in rsc_defaults. */
private static final Map<String, String> M_A_SECTION =
new HashMap<String, String>();
/** List of meta attributes that are not advanced. */
private static final List<String> M_A_NOT_ADVANCED =
new ArrayList<String>();
/** List of group meta attributes that are not advanced. */
private static final List<String> GROUP_M_A_NOT_ADVANCED =
new ArrayList<String>();
/** Access type of meta attributes. */
private static final Map<String, ConfigData.AccessType> M_A_ACCESS_TYPE =
new HashMap<String, ConfigData.AccessType>();
/** Access type of meta attributes in rsc defaults. */
private static final Map<String, ConfigData.AccessType>
M_A_RSC_DEFAULTS_ACCESS_TYPE =
new HashMap<String, ConfigData.AccessType>();
/** Possible choices for meta attributes. */
private static final Map<String, String[]> M_A_POSSIBLE_CHOICES =
new HashMap<String, String[]>();
/** Possible choices for m/s meta attributes. */
private static final Map<String, String[]> M_A_POSSIBLE_CHOICES_MS =
new HashMap<String, String[]>();
/** Short descriptions for meta attributes. */
private static final Map<String, String> M_A_SHORT_DESC =
new HashMap<String, String>();
/** Long descriptions for meta attributes. */
private static final Map<String, String> M_A_LONG_DESC =
new HashMap<String, String>();
/** Defaults for meta attributes. */
private static final Map<String, String> M_A_DEFAULT =
new HashMap<String, String>();
/** Types for meta attributes. */
private static final Map<String, String> M_A_TYPE =
new HashMap<String, String>();
/** Preferred values for meta attributes. */
private static final Map<String, String> M_A_PREFERRED =
new HashMap<String, String>();
/** Array of boolean values names in the cluster manager. */
private static final String[] PCMK_BOOLEAN_VALUES = {PCMK_TRUE, PCMK_FALSE};
private static final List<String> IGNORE_DEFAULTS_FOR =
new ArrayList<String>();
/** Stonith parameters that are not in meta-data. */
private static final String PCMK_HOST_CHECK_PARAM = "pcmk_host_check";
private static final String PCMK_HOST_LIST_PARAM = "pcmk_host_list";
private static final String PCMK_HOST_MAP_PARAM = "pcmk_host_map";
private static final String FENCING_ACTION_PARAM = "action";
/** TODO: If this is set PCMK_HOST_LIST must be set. */
private static final String PCMK_HOST_CHECK_STATIC = "static-list";
/** TODO: If this is set PCMK_HOST_LIST must not be set. */
private static final String PCMK_HOST_CHECK_DYNAMIC = "dynamic-list";
/** OCF check level. */
public static final String PAR_CHECK_LEVEL = "OCF_CHECK_LEVEL";
static {
/* target-role */
M_A_POSSIBLE_CHOICES.put(
TARGET_ROLE_META_ATTR,
new String[]{null, TARGET_ROLE_STARTED, TARGET_ROLE_STOPPED});
M_A_POSSIBLE_CHOICES_MS.put(
TARGET_ROLE_META_ATTR,
new String[]{null,
TARGET_ROLE_MASTER,
TARGET_ROLE_STARTED,
TARGET_ROLE_SLAVE,
TARGET_ROLE_STOPPED});
M_A_SHORT_DESC.put(TARGET_ROLE_META_ATTR,
Tools.getString("CRMXML.TargetRole.ShortDesc"));
M_A_LONG_DESC.put(TARGET_ROLE_META_ATTR,
Tools.getString("CRMXML.TargetRole.LongDesc"));
M_A_DEFAULT.put(TARGET_ROLE_META_ATTR, null);
M_A_NOT_ADVANCED.add(TARGET_ROLE_META_ATTR);
GROUP_M_A_NOT_ADVANCED.add(TARGET_ROLE_META_ATTR);
/* is-managed */
M_A_POSSIBLE_CHOICES.put(IS_MANAGED_META_ATTR, PCMK_BOOLEAN_VALUES);
M_A_SHORT_DESC.put(IS_MANAGED_META_ATTR,
Tools.getString("CRMXML.IsManaged.ShortDesc"));
M_A_LONG_DESC.put(IS_MANAGED_META_ATTR,
Tools.getString("CRMXML.IsManaged.LongDesc"));
M_A_DEFAULT.put(IS_MANAGED_META_ATTR, PCMK_TRUE);
M_A_TYPE.put(IS_MANAGED_META_ATTR, PARAM_TYPE_BOOLEAN);
M_A_NOT_ADVANCED.add(IS_MANAGED_META_ATTR);
/* allow-migrate */
M_A_POSSIBLE_CHOICES.put(ALLOW_MIGRATE_META_ATTR, PCMK_BOOLEAN_VALUES);
M_A_SHORT_DESC.put(ALLOW_MIGRATE_META_ATTR,
Tools.getString("CRMXML.AllowMigrate.ShortDesc"));
M_A_LONG_DESC.put(ALLOW_MIGRATE_META_ATTR,
Tools.getString("CRMXML.AllowMigrate.LongDesc"));
M_A_DEFAULT.put(ALLOW_MIGRATE_META_ATTR, PCMK_FALSE);
M_A_TYPE.put(ALLOW_MIGRATE_META_ATTR, PARAM_TYPE_BOOLEAN);
/* priority */
M_A_POSSIBLE_CHOICES.put(PRIORITY_META_ATTR,
new String[]{"0", "5", "10"});
M_A_SHORT_DESC.put(PRIORITY_META_ATTR,
Tools.getString("CRMXML.Priority.ShortDesc"));
M_A_LONG_DESC.put(PRIORITY_META_ATTR,
Tools.getString("CRMXML.Priority.LongDesc"));
M_A_DEFAULT.put(PRIORITY_META_ATTR, "0");
M_A_TYPE.put(PRIORITY_META_ATTR, PARAM_TYPE_INTEGER);
/* resource-stickiness since 2.1.4 */
M_A_POSSIBLE_CHOICES.put(RESOURCE_STICKINESS_META_ATTR,
INTEGER_VALUES);
M_A_SHORT_DESC.put(
RESOURCE_STICKINESS_META_ATTR,
Tools.getString("CRMXML.ResourceStickiness.ShortDesc"));
M_A_LONG_DESC.put(
RESOURCE_STICKINESS_META_ATTR,
Tools.getString("CRMXML.ResourceStickiness.LongDesc"));
M_A_DEFAULT.put(RESOURCE_STICKINESS_META_ATTR, "0");
M_A_TYPE.put(RESOURCE_STICKINESS_META_ATTR, PARAM_TYPE_INTEGER);
M_A_NOT_ADVANCED.add(RESOURCE_STICKINESS_META_ATTR);
/* migration-threshold */
M_A_POSSIBLE_CHOICES.put(MIGRATION_THRESHOLD_META_ATTR,
new String[]{DISABLED_STRING, "0", "5", "10"});
M_A_SHORT_DESC.put(
MIGRATION_THRESHOLD_META_ATTR,
Tools.getString("CRMXML.MigrationThreshold.ShortDesc"));
M_A_LONG_DESC.put(
MIGRATION_THRESHOLD_META_ATTR,
Tools.getString("CRMXML.MigrationThreshold.LongDesc"));
M_A_DEFAULT.put(MIGRATION_THRESHOLD_META_ATTR, DISABLED_STRING);
M_A_TYPE.put(MIGRATION_THRESHOLD_META_ATTR, PARAM_TYPE_INTEGER);
/* failure-timeout since 2.1.4 */
M_A_SHORT_DESC.put(FAILURE_TIMEOUT_META_ATTR,
Tools.getString("CRMXML.FailureTimeout.ShortDesc"));
M_A_LONG_DESC.put(FAILURE_TIMEOUT_META_ATTR,
Tools.getString("CRMXML.FailureTimeout.LongDesc"));
M_A_TYPE.put(FAILURE_TIMEOUT_META_ATTR, PARAM_TYPE_TIME);
/* multiple-active */
M_A_POSSIBLE_CHOICES.put(MULTIPLE_ACTIVE_META_ATTR,
new String[]{"stop_start",
"stop_only",
"block"});
M_A_SHORT_DESC.put(MULTIPLE_ACTIVE_META_ATTR,
Tools.getString("CRMXML.MultipleActive.ShortDesc"));
M_A_LONG_DESC.put(MULTIPLE_ACTIVE_META_ATTR,
Tools.getString("CRMXML.MultipleActive.LongDesc"));
M_A_DEFAULT.put(MULTIPLE_ACTIVE_META_ATTR, "stop_start");
/* master-max */
M_A_SHORT_DESC.put(MASTER_MAX_META_ATTR, "M/S Master-Max");
M_A_DEFAULT.put(MASTER_MAX_META_ATTR, "1");
M_A_TYPE.put(MASTER_MAX_META_ATTR, PARAM_TYPE_INTEGER);
M_A_POSSIBLE_CHOICES.put(MASTER_MAX_META_ATTR, INTEGER_VALUES);
M_A_SECTION.put(MASTER_MAX_META_ATTR,
"Master / Slave Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(MASTER_MAX_META_ATTR,
ConfigData.AccessType.GOD);
/* master-node-max */
M_A_SHORT_DESC.put(MASTER_NODE_MAX_META_ATTR, "M/S Master-Node-Max");
M_A_DEFAULT.put(MASTER_NODE_MAX_META_ATTR, "1");
M_A_TYPE.put(MASTER_NODE_MAX_META_ATTR, PARAM_TYPE_INTEGER);
M_A_POSSIBLE_CHOICES.put(MASTER_NODE_MAX_META_ATTR, INTEGER_VALUES);
M_A_SECTION.put(MASTER_NODE_MAX_META_ATTR,
"Master / Slave Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(MASTER_NODE_MAX_META_ATTR,
ConfigData.AccessType.GOD);
/* clone-max */
M_A_SHORT_DESC.put(CLONE_MAX_META_ATTR, "Clone Max");
M_A_DEFAULT.put(CLONE_MAX_META_ATTR, "");
M_A_PREFERRED.put(CLONE_MAX_META_ATTR, "2");
M_A_TYPE.put(CLONE_MAX_META_ATTR, PARAM_TYPE_INTEGER);
M_A_POSSIBLE_CHOICES.put(CLONE_MAX_META_ATTR, INTEGER_VALUES);
M_A_SECTION.put(CLONE_MAX_META_ATTR, "Clone Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(CLONE_MAX_META_ATTR,
ConfigData.AccessType.GOD);
/* clone-node-max */
M_A_SHORT_DESC.put(CLONE_NODE_MAX_META_ATTR, "Clone Node Max");
M_A_DEFAULT.put(CLONE_NODE_MAX_META_ATTR, "1");
M_A_TYPE.put(CLONE_NODE_MAX_META_ATTR, PARAM_TYPE_INTEGER);
M_A_POSSIBLE_CHOICES.put(CLONE_NODE_MAX_META_ATTR, INTEGER_VALUES);
M_A_SECTION.put(CLONE_NODE_MAX_META_ATTR, "Clone Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(CLONE_NODE_MAX_META_ATTR,
ConfigData.AccessType.GOD);
/* notify */
M_A_SHORT_DESC.put(NOTIFY_META_ATTR, "Notify");
M_A_DEFAULT.put(NOTIFY_META_ATTR, PCMK_FALSE);
M_A_PREFERRED.put(NOTIFY_META_ATTR, PCMK_TRUE);
M_A_POSSIBLE_CHOICES.put(NOTIFY_META_ATTR, PCMK_BOOLEAN_VALUES);
M_A_SECTION.put(NOTIFY_META_ATTR, "Clone Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(NOTIFY_META_ATTR,
ConfigData.AccessType.GOD);
/* globally-unique */
M_A_SHORT_DESC.put(GLOBALLY_UNIQUE_META_ATTR, "Globally-Unique");
M_A_DEFAULT.put(GLOBALLY_UNIQUE_META_ATTR, PCMK_FALSE);
M_A_POSSIBLE_CHOICES.put(GLOBALLY_UNIQUE_META_ATTR,
PCMK_BOOLEAN_VALUES);
M_A_SECTION.put(GLOBALLY_UNIQUE_META_ATTR, "Clone Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(GLOBALLY_UNIQUE_META_ATTR,
ConfigData.AccessType.GOD);
/* ordered */
M_A_SHORT_DESC.put(ORDERED_META_ATTR, "Ordered");
M_A_DEFAULT.put(ORDERED_META_ATTR, PCMK_FALSE);
M_A_POSSIBLE_CHOICES.put(ORDERED_META_ATTR, PCMK_BOOLEAN_VALUES);
M_A_SECTION.put(ORDERED_META_ATTR, "Clone Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(ORDERED_META_ATTR,
ConfigData.AccessType.GOD);
/* interleave */
M_A_SHORT_DESC.put(INTERLEAVE_META_ATTR, "Interleave");
M_A_DEFAULT.put(INTERLEAVE_META_ATTR, PCMK_FALSE);
M_A_POSSIBLE_CHOICES.put(INTERLEAVE_META_ATTR, PCMK_BOOLEAN_VALUES);
M_A_SECTION.put(INTERLEAVE_META_ATTR, "Clone Resource Defaults");
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(INTERLEAVE_META_ATTR,
ConfigData.AccessType.GOD);
M_A_PREFERRED.put(INTERLEAVE_META_ATTR, PCMK_TRUE);
/* Group collocated */
M_A_SHORT_DESC.put(GROUP_COLLOCATED_META_ATTR, "Collocated");
M_A_DEFAULT.put(GROUP_COLLOCATED_META_ATTR, PCMK_TRUE);
M_A_POSSIBLE_CHOICES.put(GROUP_COLLOCATED_META_ATTR,
PCMK_BOOLEAN_VALUES);
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(GROUP_COLLOCATED_META_ATTR,
ConfigData.AccessType.ADMIN);
/* group ordered */
M_A_SHORT_DESC.put(GROUP_ORDERED_META_ATTR, "Ordered");
M_A_DEFAULT.put(GROUP_ORDERED_META_ATTR, PCMK_TRUE);
M_A_POSSIBLE_CHOICES.put(GROUP_ORDERED_META_ATTR, PCMK_BOOLEAN_VALUES);
M_A_RSC_DEFAULTS_ACCESS_TYPE.put(GROUP_ORDERED_META_ATTR,
ConfigData.AccessType.ADMIN);
/* ignore defaults for this RAs. It means that default values will be
* saved in the cib. */
IGNORE_DEFAULTS_FOR.add("iSCSITarget");
RA_PARAM_SECTION.put("IPaddr2",
"cidr_netmask",
Tools.getString("CRMXML.OtherOptions"));
RA_PARAM_SECTION.put("VirtualDomain",
"hypervisor",
Tools.getString("CRMXML.OtherOptions"));
}
/** Prepares a new <code>CRMXML</code> object. */
public CRMXML(final Host host, final ServicesInfo ssi) {
super();
this.host = host;
final String[] booleanValues = PCMK_BOOLEAN_VALUES;
final String hbBooleanTrue = booleanValues[0];
final String hbBooleanFalse = booleanValues[1];
/* hostlist choices for stonith */
hostlistChoices.add("");
final String[] hosts = host.getCluster().getHostNames();
if (hosts != null && hosts.length < 8) {
hostlistChoices.add(Tools.join(" ", hosts));
for (final String h : hosts) {
hostlistChoices.add(h);
}
}
/* clones */
pcmkClone = new ResourceAgent(ConfigData.PM_CLONE_SET_NAME,
"",
"clone");
pcmkClone.setMetaDataLoaded(true);
addMetaAttribute(pcmkClone, MASTER_MAX_META_ATTR, null, true);
addMetaAttribute(pcmkClone, MASTER_NODE_MAX_META_ATTR, null, true);
addMetaAttribute(pcmkClone, CLONE_MAX_META_ATTR, null, false);
addMetaAttribute(pcmkClone, CLONE_NODE_MAX_META_ATTR, null, false);
addMetaAttribute(pcmkClone, NOTIFY_META_ATTR, null, false);
addMetaAttribute(pcmkClone, GLOBALLY_UNIQUE_META_ATTR, null, false);
addMetaAttribute(pcmkClone, ORDERED_META_ATTR, null, false);
addMetaAttribute(pcmkClone, INTERLEAVE_META_ATTR, null, false);
addMetaAttribute(hbGroup, GROUP_ORDERED_META_ATTR, null, false);
addMetaAttribute(hbGroup, GROUP_COLLOCATED_META_ATTR, null, false);
/* groups */
final Map<String, String> maParams = getMetaAttrParameters();
for (final String metaAttr : maParams.keySet()) {
addMetaAttribute(pcmkClone,
metaAttr,
maParams.get(metaAttr),
false);
addMetaAttribute(hbGroup,
metaAttr,
maParams.get(metaAttr),
false);
}
/* Hardcoding global params */
/* symmetric cluster */
globalParams.add("symmetric-cluster");
paramGlobalShortDescMap.put("symmetric-cluster", "Symmetric Cluster");
paramGlobalLongDescMap.put("symmetric-cluster", "Symmetric Cluster");
paramGlobalTypeMap.put("symmetric-cluster", PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("symmetric-cluster", hbBooleanFalse);
paramGlobalPossibleChoices.put("symmetric-cluster", booleanValues);
globalRequiredParams.add("symmetric-cluster");
globalNotAdvancedParams.add("symmetric-cluster");
/* stonith enabled */
globalParams.add("stonith-enabled");
paramGlobalShortDescMap.put("stonith-enabled", "Stonith Enabled");
paramGlobalLongDescMap.put("stonith-enabled", "Stonith Enabled");
paramGlobalTypeMap.put("stonith-enabled", PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("stonith-enabled", hbBooleanTrue);
paramGlobalPossibleChoices.put("stonith-enabled", booleanValues);
globalRequiredParams.add("stonith-enabled");
globalNotAdvancedParams.add("stonith-enabled");
/* transition timeout */
globalParams.add("default-action-timeout");
paramGlobalShortDescMap.put("default-action-timeout",
"Transition Timeout");
paramGlobalLongDescMap.put("default-action-timeout",
"Transition Timeout");
paramGlobalTypeMap.put("default-action-timeout", PARAM_TYPE_INTEGER);
paramGlobalDefaultMap.put("default-action-timeout", "20");
paramGlobalPossibleChoices.put("default-action-timeout",
INTEGER_VALUES);
globalRequiredParams.add("default-action-timeout");
/* resource stickiness */
/* special case: is advanced parameter if not set. */
globalParams.add("default-resource-stickiness");
paramGlobalShortDescMap.put("default-resource-stickiness",
"Resource Stickiness");
paramGlobalLongDescMap.put("default-resource-stickiness",
"Resource Stickiness");
paramGlobalTypeMap.put("default-resource-stickiness",
PARAM_TYPE_INTEGER);
paramGlobalPossibleChoices.put("default-resource-stickiness",
INTEGER_VALUES);
paramGlobalDefaultMap.put("default-resource-stickiness", "0");
globalRequiredParams.add("default-resource-stickiness");
/* no quorum policy */
globalParams.add("no-quorum-policy");
paramGlobalShortDescMap.put("no-quorum-policy", "No Quorum Policy");
paramGlobalLongDescMap.put("no-quorum-policy", "No Quorum Policy");
paramGlobalTypeMap.put("no-quorum-policy", PARAM_TYPE_STRING);
paramGlobalDefaultMap.put("no-quorum-policy", "stop");
paramGlobalPossibleChoices.put("no-quorum-policy",
new String[]{"ignore",
"stop",
"freeze",
"suicide"});
globalRequiredParams.add("no-quorum-policy");
globalNotAdvancedParams.add("no-quorum-policy");
/* resource failure stickiness */
globalParams.add("default-resource-failure-stickiness");
paramGlobalShortDescMap.put("default-resource-failure-stickiness",
"Resource Failure Stickiness");
paramGlobalLongDescMap.put("default-resource-failure-stickiness",
"Resource Failure Stickiness");
paramGlobalTypeMap.put("default-resource-failure-stickiness",
PARAM_TYPE_INTEGER);
paramGlobalPossibleChoices.put("default-resource-failure-stickiness",
INTEGER_VALUES);
paramGlobalDefaultMap.put("default-resource-failure-stickiness", "0");
globalRequiredParams.add("default-resource-failure-stickiness");
paramGlobalPossibleChoices.put("placement-strategy",
new String[]{"default",
"utilization",
"minimal",
"balanced"});
final String hbV = host.getHeartbeatVersion();
final String pcmkV = host.getPacemakerVersion();
try {
if (pcmkV != null || Tools.compareVersions(hbV, "2.1.3") >= 0) {
String clusterRecheckInterval = "cluster-recheck-interval";
String dcDeadtime = "dc-deadtime";
String electionTimeout = "election-timeout";
String shutdownEscalation = "shutdown-escalation";
if (Tools.versionBeforePacemaker(host)) {
clusterRecheckInterval = "cluster_recheck_interval";
dcDeadtime = "dc_deadtime";
electionTimeout = "election_timeout";
shutdownEscalation = "shutdown_escalation";
}
final String[] params = {
"stonith-action",
"is-managed-default",
"cluster-delay",
"batch-limit",
"stop-orphan-resources",
"stop-orphan-actions",
"remove-after-stop",
"pe-error-series-max",
"pe-warn-series-max",
"pe-input-series-max",
"startup-fencing",
"start-failure-is-fatal",
dcDeadtime,
clusterRecheckInterval,
electionTimeout,
shutdownEscalation,
"crmd-integration-timeout",
"crmd-finalization-timeout",
"expected-quorum-votes",
"maintenance-mode",
};
globalParams.add("dc-version");
paramGlobalShortDescMap.put("dc-version", "DC Version");
paramGlobalTypeMap.put("dc-version", PARAM_TYPE_LABEL);
paramGlobalAccessTypes.put("dc-version",
ConfigData.AccessType.NEVER);
globalParams.add("cluster-infrastructure");
paramGlobalShortDescMap.put("cluster-infrastructure",
"Cluster Infrastructure");
paramGlobalTypeMap.put("cluster-infrastructure",
PARAM_TYPE_LABEL);
paramGlobalAccessTypes.put("cluster-infrastructure",
ConfigData.AccessType.NEVER);
globalNotAdvancedParams.add("no-quorum-policy");
globalNotAdvancedParams.add("maintenance-mode");
paramGlobalAccessTypes.put("maintenance-mode",
ConfigData.AccessType.OP);
globalNotAdvancedParams.add(clusterRecheckInterval);
for (String param : params) {
globalParams.add(param);
String[] parts = param.split("[-_]");
for (int i = 0; i < parts.length; i++) {
if ("dc".equals(parts[i])) {
parts[i] = "DC";
}
if ("crmd".equals(parts[i])) {
parts[i] = "CRMD";
} else {
parts[i] = Tools.ucfirst(parts[i]);
}
}
final String name = Tools.join(" ", parts);
paramGlobalShortDescMap.put(param, name);
paramGlobalLongDescMap.put(param, name);
paramGlobalTypeMap.put(param, PARAM_TYPE_STRING);
paramGlobalDefaultMap.put(param, "");
}
paramGlobalDefaultMap.put("stonith-action", "reboot");
paramGlobalPossibleChoices.put("stonith-action",
new String[]{"reboot",
"poweroff"});
paramGlobalTypeMap.put("is-managed-default",
PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("is-managed-default", hbBooleanFalse);
paramGlobalPossibleChoices.put("is-managed-default",
booleanValues);
paramGlobalTypeMap.put("stop-orphan-resources",
PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("stop-orphan-resources",
hbBooleanFalse);
paramGlobalPossibleChoices.put("stop-orphan-resources",
booleanValues);
paramGlobalTypeMap.put("stop-orphan-actions",
PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("stop-orphan-actions",
hbBooleanFalse);
paramGlobalPossibleChoices.put("stop-orphan-actions",
booleanValues);
paramGlobalTypeMap.put("remove-after-stop", PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("remove-after-stop", hbBooleanFalse);
paramGlobalPossibleChoices.put("remove-after-stop",
booleanValues);
paramGlobalTypeMap.put("startup-fencing", PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("startup-fencing", hbBooleanFalse);
paramGlobalPossibleChoices.put("startup-fencing",
booleanValues);
paramGlobalTypeMap.put("start-failure-is-fatal",
PARAM_TYPE_BOOLEAN);
paramGlobalDefaultMap.put("start-failure-is-fatal",
hbBooleanFalse);
paramGlobalPossibleChoices.put("start-failure-is-fatal",
booleanValues);
}
} catch (Exceptions.IllegalVersionException e) {
LOG.appWarning("CRMXML: " + e.getMessage(), e);
}
/* Hardcoding colocation params */
colParams.add("rsc-role");
paramColShortDescMap.put("rsc-role", "rsc col role");
paramColLongDescMap.put("rsc-role", "@RSC@ colocation role");
paramColTypeMap.put("rsc-role", PARAM_TYPE_STRING);
paramColPossibleChoices.put("rsc-role", ATTRIBUTE_ROLES);
paramColPossibleChoicesMS.put("rsc-role", ATTRIBUTE_ROLES_MS);
colParams.add("with-rsc-role");
paramColShortDescMap.put("with-rsc-role", "with-rsc col role");
paramColLongDescMap.put("with-rsc-role", "@WITH-RSC@ colocation role");
paramColTypeMap.put("with-rsc-role", PARAM_TYPE_STRING);
paramColPossibleChoices.put("with-rsc-role", ATTRIBUTE_ROLES);
paramColPossibleChoicesMS.put("with-rsc-role", ATTRIBUTE_ROLES_MS);
colParams.add(SCORE_STRING);
paramColShortDescMap.put(SCORE_STRING, "Score");
paramColLongDescMap.put(SCORE_STRING, "Score");
paramColTypeMap.put(SCORE_STRING, PARAM_TYPE_INTEGER);
paramColDefaultMap.put(SCORE_STRING, null);
paramColPreferredMap.put(SCORE_STRING, INFINITY_STRING);
paramColPossibleChoices.put(SCORE_STRING, INTEGER_VALUES);
/* Hardcoding order params */
ordParams.add("first-action");
paramOrdShortDescMap.put("first-action", "first order action");
paramOrdLongDescMap.put("first-action", "@FIRST-RSC@ order action");
paramOrdTypeMap.put("first-action", PARAM_TYPE_STRING);
paramOrdPossibleChoices.put("first-action", ATTRIBUTE_ACTIONS);
paramOrdPossibleChoicesMS.put("first-action", ATTRIBUTE_ACTIONS_MS);
paramOrdPreferredMap.put(SCORE_STRING, INFINITY_STRING);
paramOrdDefaultMap.put("first-action", null);
ordParams.add("then-action");
paramOrdShortDescMap.put("then-action", "then order action");
paramOrdLongDescMap.put("then-action", "@THEN-RSC@ order action");
paramOrdTypeMap.put("then-action", PARAM_TYPE_STRING);
paramOrdPossibleChoices.put("then-action", ATTRIBUTE_ACTIONS);
paramOrdPossibleChoicesMS.put("then-action", ATTRIBUTE_ACTIONS_MS);
paramOrdDefaultMap.put("then-action", null);
ordParams.add("symmetrical");
paramOrdShortDescMap.put("symmetrical", "Symmetrical");
paramOrdLongDescMap.put("symmetrical", "Symmetrical");
paramOrdTypeMap.put("symmetrical", PARAM_TYPE_BOOLEAN);
paramOrdDefaultMap.put("symmetrical", hbBooleanTrue);
paramOrdPossibleChoices.put("symmetrical", booleanValues);
ordParams.add(SCORE_STRING);
paramOrdShortDescMap.put(SCORE_STRING, "Score");
paramOrdLongDescMap.put(SCORE_STRING, "Score");
paramOrdTypeMap.put(SCORE_STRING, PARAM_TYPE_INTEGER);
paramOrdPossibleChoices.put(SCORE_STRING, INTEGER_VALUES);
paramOrdDefaultMap.put(SCORE_STRING, null);
/* resource sets */
rscSetOrdParams.add(SCORE_STRING);
rscSetColParams.add(SCORE_STRING);
rscSetOrdConnectionParams.add("action");
paramOrdShortDescMap.put("action", "order action");
paramOrdLongDescMap.put("action", "order action");
paramOrdTypeMap.put("action", PARAM_TYPE_STRING);
paramOrdPossibleChoices.put("action", ATTRIBUTE_ACTIONS);
paramOrdPossibleChoicesMS.put("action", ATTRIBUTE_ACTIONS_MS);
paramOrdDefaultMap.put("action", null);
rscSetOrdConnectionParams.add("sequential");
paramOrdShortDescMap.put("sequential", "sequential");
paramOrdLongDescMap.put("sequential", "sequential");
paramOrdTypeMap.put("sequential", PARAM_TYPE_BOOLEAN);
paramOrdDefaultMap.put("sequential", hbBooleanTrue);
paramOrdPossibleChoices.put("sequential", booleanValues);
paramOrdPreferredMap.put("sequential", hbBooleanFalse);
rscSetOrdConnectionParams.add(REQUIRE_ALL_ATTR);
paramOrdShortDescMap.put(REQUIRE_ALL_ATTR, "require all");
paramOrdLongDescMap.put(REQUIRE_ALL_ATTR, "require all");
paramOrdTypeMap.put(REQUIRE_ALL_ATTR, PARAM_TYPE_BOOLEAN);
paramOrdDefaultMap.put(REQUIRE_ALL_ATTR, REQUIRE_ALL_TRUE);
paramOrdPossibleChoices.put(REQUIRE_ALL_ATTR, booleanValues);
rscSetColConnectionParams.add("role");
paramColShortDescMap.put("role", "col role");
paramColLongDescMap.put("role", "colocation role");
paramColTypeMap.put("role", PARAM_TYPE_STRING);
paramColPossibleChoices.put("role", ATTRIBUTE_ROLES);
paramColPossibleChoicesMS.put("role", ATTRIBUTE_ROLES_MS);
rscSetColConnectionParams.add("sequential");
paramColShortDescMap.put("sequential", "sequential");
paramColLongDescMap.put("sequential", "sequential");
paramColTypeMap.put("sequential", PARAM_TYPE_BOOLEAN);
paramColDefaultMap.put("sequential", hbBooleanTrue);
paramColPossibleChoices.put("sequential", booleanValues);
paramColPreferredMap.put("sequential", hbBooleanFalse);
hbGroup.setMetaDataLoaded(true);
initOCFMetaDataQuick();
initOCFMetaDataConfigured();
LOG.debug("CRMXML: cluster loaded");
final Thread t = new Thread(new Runnable() {
@Override
public void run() {
initOCFMetaDataAll();
final String hn = host.getName();
final String text =
Tools.getString("CRMXML.GetRAMetaData.Done");
Tools.startProgressIndicator(hn, text);
ssi.setAllResources(ssi.getBrowser().getClusterStatus(),
CRM.LIVE);
final Info li =
ssi.getBrowser().getClusterViewPanel().getLastSelectedInfo();
if (li instanceof ServiceInfo) {
ssi.getBrowser().getClusterViewPanel()
.reloadRightComponent();
}
Tools.stopProgressIndicator(hn, text);
LOG.debug("CRMXML: RAs loaded");
final RoboTest.Test autoTest =
Tools.getConfigData().getAutoTest();
if (autoTest != null) {
RoboTest.startTest(autoTest,
ssi.getBrowser().getCluster());
}
}
});
t.start();
}
/** Initialize resource agents WITHOUT their meta data. */
private void initOCFMetaDataQuick() {
final String command =
host.getDistCommand("Heartbeat.getOCFParametersQuick",
(ConvertCmdCallback) null);
final SSH.SSHOutput ret =
Tools.execCommandProgressIndicator(
host,
command,
null, /* ExecCallback */
false, /* outputVisible */
Tools.getString("CRMXML.GetRAMetaData"),
60000);
boolean linbitDrbdPresent0 = false;
boolean drbddiskPresent0 = false;
if (ret.getExitCode() != 0) {
drbddiskPresent = drbddiskPresent0;
linbitDrbdPresent = linbitDrbdPresent0;
return;
}
final String output = ret.getOutput();
if (output == null) {
drbddiskPresent = drbddiskPresent0;
linbitDrbdPresent = linbitDrbdPresent0;
return;
}
final String[] lines = output.split("\\r?\\n");
final Pattern mp = Pattern.compile("^master:\\s*(.*?)\\s*$");
final Pattern cp = Pattern.compile("^class:\\s*(.*?)\\s*$");
final Pattern pp = Pattern.compile("^provider:\\s*(.*?)\\s*$");
final Pattern sp = Pattern.compile("^ra:\\s*(.*?)\\s*$");
final StringBuilder xml = new StringBuilder("");
String resourceClass = null;
String provider = null;
String serviceName = null;
final boolean masterSlave = false; /* is probably m/s ...*/
for (int i = 0; i < lines.length; i++) {
final Matcher cm = cp.matcher(lines[i]);
if (cm.matches()) {
resourceClass = cm.group(1);
continue;
}
final Matcher pm = pp.matcher(lines[i]);
if (pm.matches()) {
provider = pm.group(1);
continue;
}
final Matcher sm = sp.matcher(lines[i]);
if (sm.matches()) {
serviceName = sm.group(1);
}
if (serviceName != null) {
xml.append(lines[i]);
xml.append('\n');
if ("drbddisk".equals(serviceName)) {
drbddiskPresent0 = true;
} else if ("drbd".equals(serviceName)
&& "linbit".equals(provider)) {
linbitDrbdPresent0 = true;
}
ResourceAgent ra;
if ("drbddisk".equals(serviceName)
&& ResourceAgent.HEARTBEAT_CLASS.equals(resourceClass)) {
ra = hbDrbddisk;
ra.setMetaDataLoaded(true);
setLSBResourceAgent(serviceName, resourceClass, ra);
} else if ("drbd".equals(serviceName)
&& ResourceAgent.OCF_CLASS.equals(resourceClass)
&& "linbit".equals(provider)) {
ra = hbLinbitDrbd;
} else {
ra = new ResourceAgent(serviceName,
provider,
resourceClass);
if (IGNORE_DEFAULTS_FOR.contains(serviceName)) {
ra.setIgnoreDefaults(true);
}
if (ResourceAgent.SERVICE_CLASSES.contains(resourceClass)
|| ResourceAgent.HEARTBEAT_CLASS.equals(
resourceClass)) {
ra.setMetaDataLoaded(true);
setLSBResourceAgent(serviceName, resourceClass, ra);
}
}
serviceToResourceAgentMap.put(serviceName,
provider,
resourceClass,
ra);
List<ResourceAgent> raList =
classToServicesMap.get(resourceClass);
if (raList == null) {
raList = new ArrayList<ResourceAgent>();
classToServicesMap.put(resourceClass, raList);
}
raList.add(ra);
serviceName = null;
xml.delete(0, xml.length());
}
}
drbddiskPresent = drbddiskPresent0;
linbitDrbdPresent = linbitDrbdPresent0;
}
/**
* Initialize resource agents with their meta data, the configured ones.
* For faster start up.
*/
private void initOCFMetaDataConfigured() {
initOCFMetaData(
host.getDistCommand("Heartbeat.getOCFParametersConfigured",
(ConvertCmdCallback) null));
}
/** Initialize resource agents with their meta data. */
private void initOCFMetaDataAll() {
initOCFMetaData(host.getDistCommand("Heartbeat.getOCFParameters",
(ConvertCmdCallback) null));
}
/** Initialize resource agents with their meta data. */
private void initOCFMetaData(final String command) {
final SSH.SSHOutput ret = Tools.execCommand(host,
command,
null, /* ExecCallback */
false, /* outputVisible */
300000);
if (ret.getExitCode() != 0) {
return;
}
final String output = ret.getOutput();
if (output == null) {
return;
}
final String[] lines = output.split("\\r?\\n");
final Pattern pp = Pattern.compile("^provider:\\s*(.*?)\\s*$");
final Pattern mp = Pattern.compile("^master:\\s*(.*?)\\s*$");
final Pattern bp =
Pattern.compile("<resource-agent.*\\s+name=\"(.*?)\".*");
final Pattern sp = Pattern.compile("^ra-name:\\s*(.*?)\\s*$");
final Pattern ep = Pattern.compile("</resource-agent>");
final StringBuilder xml = new StringBuilder("");
String provider = null;
String serviceName = null;
boolean nextRA = false;
boolean masterSlave = false; /* is probably m/s ...*/
for (int i = 0; i < lines.length; i++) {
/*
<resource-agent name="AudibleAlarm">
...
</resource-agent>
*/
final Matcher pm = pp.matcher(lines[i]);
if (pm.matches()) {
provider = pm.group(1);
continue;
}
final Matcher mm = mp.matcher(lines[i]);
if (mm.matches()) {
if ("".equals(mm.group(1))) {
masterSlave = false;
} else {
masterSlave = true;
}
continue;
}
final Matcher sm = sp.matcher(lines[i]);
if (sm.matches()) {
serviceName = sm.group(1);
continue;
}
final Matcher m = bp.matcher(lines[i]);
if (m.matches()) {
nextRA = true;
}
if (nextRA) {
xml.append(lines[i]);
xml.append('\n');
final Matcher m2 = ep.matcher(lines[i]);
if (m2.matches()) {
parseMetaData(serviceName,
provider,
xml.toString(),
masterSlave);
serviceName = null;
nextRA = false;
xml.delete(0, xml.length());
}
}
}
if (!drbddiskPresent) {
LOG.appWarning("initOCFMetaData: drbddisk heartbeat script is not present");
}
}
/** Returns choices for check box. (True, False). */
public String[] getCheckBoxChoices(final ResourceAgent ra,
final String param) {
final String paramDefault = getParamDefault(ra, param);
return getCheckBoxChoices(paramDefault);
}
/**
* Returns choices for check box. (True, False).
* The problem is, that heartbeat kept changing the lower and upper case in
* the true and false values.
*/
private String[] getCheckBoxChoices(final String paramDefault) {
if (paramDefault != null) {
if ("yes".equals(paramDefault) || "no".equals(paramDefault)) {
return new String[]{"yes", "no"};
} else if ("Yes".equals(paramDefault)
|| "No".equals(paramDefault)) {
return new String[]{"Yes", "No"};
} else if (PCMK_TRUE.equals(paramDefault)
|| PCMK_FALSE.equals(paramDefault)) {
return PCMK_BOOLEAN_VALUES.clone();
} else if ("True".equals(paramDefault)
|| "False".equals(paramDefault)) {
return new String[]{"True", "False"};
}
}
return PCMK_BOOLEAN_VALUES.clone();
}
/**
* Returns all services as array of strings, sorted, with filesystem and
* ipaddr in the begining.
*/
public List<ResourceAgent> getServices(final String cl) {
final List<ResourceAgent> services = classToServicesMap.get(cl);
if (services == null) {
return new ArrayList<ResourceAgent>();
}
Collections.sort(services,
new Comparator<ResourceAgent>() {
public int compare(final ResourceAgent s1,
final ResourceAgent s2) {
return s1.getName().compareToIgnoreCase(
s2.getName());
}
});
return services;
}
/**
* Returns parameters for service. Parameters are obtained from
* ocf meta-data.
*/
public List<String> getParameters(final ResourceAgent ra,
final boolean master) {
/* return cached values */
return ra.getParameters(master);
}
/** Returns global parameters. */
public String[] getGlobalParameters() {
if (globalParams != null) {
return globalParams.toArray(new String[globalParams.size()]);
}
return null;
}
/** Return version of the service ocf script. */
public String getVersion(final ResourceAgent ra) {
return ra.getVersion();
}
/** Return short description of the service. */
public String getShortDesc(final ResourceAgent ra) {
return ra.getShortDesc();
}
/** Return long description of the service. */
public String getLongDesc(final ResourceAgent ra) {
return ra.getLongDesc();
}
/** Returns short description of the global parameter. */
public String getGlobalParamShortDesc(final String param) {
String shortDesc = paramGlobalShortDescMap.get(param);
if (shortDesc == null) {
shortDesc = param;
}
return shortDesc;
}
/** Returns short description of the service parameter. */
public String getParamShortDesc(final ResourceAgent ra,
final String param) {
return ra.getParamShortDesc(param);
}
/** Returns long description of the global parameter. */
public String getGlobalParamLongDesc(final String param) {
final String shortDesc = getGlobalParamShortDesc(param);
String longDesc = paramGlobalLongDescMap.get(param);
if (longDesc == null) {
longDesc = "";
}
return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc);
}
/** Returns long description of the parameter and service. */
public String getParamLongDesc(final ResourceAgent ra,
final String param) {
final String shortDesc = getParamShortDesc(ra, param);
String longDesc = ra.getParamLongDesc(param);
if (longDesc == null) {
longDesc = "";
}
return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc);
}
/**
* Returns type of a global parameter. It can be string, integer, boolean...
*/
public String getGlobalParamType(final String param) {
return paramGlobalTypeMap.get(param);
}
/** Returns type of the parameter. It can be string, integer, boolean... */
public String getParamType(final ResourceAgent ra, final String param) {
return ra.getParamType(param);
}
/** Returns default value for the global parameter. */
public String getGlobalParamDefault(final String param) {
return paramGlobalDefaultMap.get(param);
}
/** Returns the preferred value for the global parameter. */
public String getGlobalParamPreferred(final String param) {
return paramGlobalPreferredMap.get(param);
}
/** Returns the preferred value for this parameter. */
public String getParamPreferred(final ResourceAgent ra,
final String param) {
return ra.getParamPreferred(param);
}
/** Returns default value for this parameter. */
public String getParamDefault(final ResourceAgent ra, final String param) {
return ra.getParamDefault(param);
}
/**
* Returns possible choices for a global parameter, that will be displayed
* in the combo box.
*/
public String[] getGlobalParamPossibleChoices(final String param) {
return paramGlobalPossibleChoices.get(param);
}
/**
* Returns possible choices for a parameter, that will be displayed in
* the combo box.
*/
public String[] getParamPossibleChoices(final ResourceAgent ra,
final String param,
final boolean ms) {
if (ms) {
return ra.getParamPossibleChoicesMS(param);
} else {
return ra.getParamPossibleChoices(param);
}
}
/** Checks if the global parameter is advanced. */
public boolean isGlobalAdvanced(final String param) {
return !globalNotAdvancedParams.contains(param);
}
/** Returns the global parameter's access type. */
public ConfigData.AccessType getGlobalAccessType(final String param) {
final ConfigData.AccessType at = paramGlobalAccessTypes.get(param);
if (at == null) {
return ConfigData.AccessType.ADMIN; /* default access type */
}
return at;
}
/** Checks if parameter is required or not. */
public boolean isGlobalRequired(final String param) {
return globalRequiredParams.contains(param);
}
/** Checks if parameter is advanced or not. */
public boolean isAdvanced(final ResourceAgent ra, final String param) {
if (isMetaAttr(ra, param)) {
if (ra == hbGroup) {
return !GROUP_M_A_NOT_ADVANCED.contains(param);
} else if (ra == pcmkClone) {
return true;
}
return !M_A_NOT_ADVANCED.contains(param);
}
if (RA_PARAM_SECTION.containsKey(ra.getName(), param)) {
return false;
}
return !isRequired(ra, param);
}
/** Returns access type of the parameter. */
public ConfigData.AccessType getAccessType(final ResourceAgent ra,
final String param) {
if (isMetaAttr(ra, param)) {
final ConfigData.AccessType accessType =
M_A_ACCESS_TYPE.get(param);
if (accessType != null) {
return accessType;
}
}
return ConfigData.AccessType.ADMIN;
}
/** Checks if parameter is required or not. */
public boolean isRequired(final ResourceAgent ra, final String param) {
return ra.isRequired(param);
}
/** Returns whether the parameter is meta attribute or not. */
public boolean isMetaAttr(final ResourceAgent ra, final String param) {
return ra.isParamMetaAttr(param);
}
/** Returns whether the parameter expects an integer value. */
public boolean isInteger(final ResourceAgent ra, final String param) {
final String type = getParamType(ra, param);
return PARAM_TYPE_INTEGER.equals(type);
}
/** Returns whether the parameter is read only label value. */
public boolean isLabel(final ResourceAgent ra, final String param) {
final String type = getParamType(ra, param);
return PARAM_TYPE_LABEL.equals(type);
}
/** Returns whether the parameter expects a boolean value. */
public boolean isBoolean(final ResourceAgent ra, final String param) {
final String type = getParamType(ra, param);
return PARAM_TYPE_BOOLEAN.equals(type);
}
/** Returns whether the global parameter expects an integer value. */
public boolean isGlobalInteger(final String param) {
final String type = getGlobalParamType(param);
return PARAM_TYPE_INTEGER.equals(type);
}
/** Returns whether the global parameter expects a label value. */
public boolean isGlobalLabel(final String param) {
final String type = getGlobalParamType(param);
return PARAM_TYPE_LABEL.equals(type);
}
/** Returns whether the global parameter expects a boolean value. */
public boolean isGlobalBoolean(final String param) {
final String type = getGlobalParamType(param);
return PARAM_TYPE_BOOLEAN.equals(type);
}
/** Whether the service parameter is of the time type. */
public boolean isTimeType(final ResourceAgent ra, final String param) {
final String type = getParamType(ra, param);
return PARAM_TYPE_TIME.equals(type);
}
/** Whether the global parameter is of the time type. */
public boolean isGlobalTimeType(final String param) {
final String type = getGlobalParamType(param);
return PARAM_TYPE_TIME.equals(type);
}
/**
* Returns name of the section for service and parameter that will be
* displayed.
*/
public String getSection(final ResourceAgent ra, final String param) {
final String section = ra.getSection(param);
if (section != null) {
return section;
}
if (isMetaAttr(ra, param)) {
return Tools.getString("CRMXML.MetaAttrOptions");
} else if (isRequired(ra, param)) {
return Tools.getString("CRMXML.RequiredOptions");
} else {
return Tools.getString("CRMXML.OptionalOptions");
}
}
/**
* Returns name of the section global parameter that will be
* displayed.
*/
public String getGlobalSection(final String param) {
if (isGlobalRequired(param)) {
return Tools.getString("CRMXML.GlobalRequiredOptions");
} else {
return Tools.getString("CRMXML.GlobalOptionalOptions");
}
}
/**
* Converts rsc default parameter to the internal representation, that can
* be different on older cluster software.
*/
private String convertRscDefaultsParam(final String param) {
final String newParam = rscDefaultsMetaAttrs.get(param);
if (newParam == null) {
return param;
}
return newParam;
}
/** Checks meta attribute param. */
public boolean checkMetaAttrParam(final String param, final String value) {
final String newParam = convertRscDefaultsParam(param);
final String type = M_A_TYPE.get(newParam);
final boolean required = isRscDefaultsRequired(newParam);
final boolean metaAttr = true;
return checkParam(type, required, metaAttr, newParam, value);
}
/** Returns section of the rsc defaults meta attribute. */
public String getRscDefaultsSection(final String param) {
final String newParam = convertRscDefaultsParam(param);
final String section = M_A_SECTION.get(newParam);
if (section == null) {
return Tools.getString("CRMXML.RscDefaultsSection");
}
return section;
}
/** Returns default of the meta attribute. */
public String getRscDefaultsDefault(final String param) {
final String newParam = convertRscDefaultsParam(param);
return M_A_DEFAULT.get(newParam);
}
/** Returns preferred of the meta attribute. */
public String getRscDefaultsPreferred(final String param) {
return null;
}
/** Returns preferred of the meta attribute. */
public String[] getRscDefaultsPossibleChoices(final String param) {
final String newParam = convertRscDefaultsParam(param);
return M_A_POSSIBLE_CHOICES.get(newParam);
}
/** Returns choices for check box. (True, False). */
public String[] getRscDefaultsCheckBoxChoices(final String param) {
final String newParam = convertRscDefaultsParam(param);
final String paramDefault = getRscDefaultsDefault(newParam);
return getCheckBoxChoices(paramDefault);
}
/** Returns short description of the default meta attr parameter. */
public String getRscDefaultsShortDesc(final String param) {
final String newParam = convertRscDefaultsParam(param);
return M_A_SHORT_DESC.get(newParam);
}
/** Return long description of the default meta attr parameter. */
public String getRscDefaultsLongDesc(final String param) {
final String newParam = convertRscDefaultsParam(param);
return M_A_LONG_DESC.get(newParam);
}
/**
* Returns type of the meta attribute.
* It can be string, integer, boolean...
*/
public String getRscDefaultsType(final String param) {
final String newParam = convertRscDefaultsParam(param);
return M_A_TYPE.get(newParam);
}
/** Checks if parameter is advanced. */
public boolean isRscDefaultsAdvanced(final String param) {
final String newParam = convertRscDefaultsParam(param);
return !M_A_NOT_ADVANCED.contains(newParam);
}
/** Returns access type of the meta attribute. */
public ConfigData.AccessType getRscDefaultsAccessType(final String param) {
final String newParam = convertRscDefaultsParam(param);
final ConfigData.AccessType at =
M_A_RSC_DEFAULTS_ACCESS_TYPE.get(newParam);
if (at == null) {
return ConfigData.AccessType.ADMIN;
}
return at;
}
/** Checks if parameter is required or not. */
public boolean isRscDefaultsRequired(final String param) {
final String newParam = convertRscDefaultsParam(param);
return false;
}
/** Checks if the meta attr parameter is integer. */
public boolean isRscDefaultsInteger(final String param) {
final String newParam = convertRscDefaultsParam(param);
final String type = getRscDefaultsType(newParam);
return PARAM_TYPE_INTEGER.equals(type);
}
/** Returns whether meta attr parameter is label. */
public boolean isRscDefaultsLabel(final String param) {
final String newParam = convertRscDefaultsParam(param);
final String type = getRscDefaultsType(newParam);
return PARAM_TYPE_LABEL.equals(type);
}
/** Checks if the meta attr parameter is boolean. */
public boolean isRscDefaultsBoolean(final String param) {
final String newParam = convertRscDefaultsParam(param);
final String type = getRscDefaultsType(newParam);
return PARAM_TYPE_BOOLEAN.equals(type);
}
/** Whether the rsc default parameter is of the time type. */
public boolean isRscDefaultsTimeType(final String param) {
final String newParam = convertRscDefaultsParam(param);
final String type = getRscDefaultsType(newParam);
return PARAM_TYPE_TIME.equals(type);
}
/**
* Checks parameter of the specified ra according to its type.
* Returns false if value does not fit the type.
*/
public boolean checkParam(final ResourceAgent ra,
final String param,
final String value) {
final String type = getParamType(ra, param);
final boolean required = isRequired(ra, param);
final boolean metaAttr = isMetaAttr(ra, param);
return checkParam(type, required, metaAttr, param, value);
}
/**
* Checks parameter according to its type. Returns false if value does
* not fit the type.
*/
private boolean checkParam(final String type,
final boolean required,
final boolean metaAttr,
final String param,
String value) {
if (metaAttr
&& isRscDefaultsInteger(param)
&& DISABLED_STRING.equals(value)) {
value = "";
}
boolean correctValue = true;
if (PARAM_TYPE_BOOLEAN.equals(type)) {
if (!"yes".equals(value) && !"no".equals(value)
&& !PCMK_TRUE.equals(value)
&& !PCMK_FALSE.equals(value)
&& !"True".equals(value)
&& !"False".equals(value)) {
correctValue = false;
}
} else if (PARAM_TYPE_INTEGER.equals(type)) {
final Pattern p =
Pattern.compile("^(-?\\d*|(-|\\+)?" + INFINITY_STRING + ")$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if (PARAM_TYPE_TIME.equals(type)) {
final Pattern p =
Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if ((value == null || "".equals(value)) && required) {
correctValue = false;
}
return correctValue;
}
/**
* Checks global parameter according to its type. Returns false if value
* does not fit the type.
*/
public boolean checkGlobalParam(final String param, final String value) {
final String type = getGlobalParamType(param);
boolean correctValue = true;
if (PARAM_TYPE_BOOLEAN.equals(type)) {
if (!"yes".equals(value) && !"no".equals(value)
&& !PCMK_TRUE.equals(value)
&& !PCMK_FALSE.equals(value)
&& !"True".equals(value)
&& !"False".equals(value)) {
correctValue = false;
}
} else if (PARAM_TYPE_INTEGER.equals(type)) {
final Pattern p =
Pattern.compile("^(-?\\d*|(-|\\+)?" + INFINITY_STRING + ")$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if (PARAM_TYPE_TIME.equals(type)) {
final Pattern p =
Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if ((value == null || "".equals(value))
&& isGlobalRequired(param)) {
correctValue = false;
}
return correctValue;
}
/** Adds meta attribute to the resource agent. */
private void addMetaAttribute(final ResourceAgent ra,
final String name,
String newName,
final boolean masterSlave) {
if (newName == null) {
newName = name;
}
if (masterSlave) {
ra.addMasterParameter(name);
} else {
ra.addParameter(name);
}
ra.setParamIsMetaAttr(name, true);
ra.setParamRequired(name, false);
ra.setParamPossibleChoices(name, M_A_POSSIBLE_CHOICES.get(newName));
ra.setParamPossibleChoicesMS(name,
M_A_POSSIBLE_CHOICES_MS.get(newName));
ra.setParamShortDesc(name, M_A_SHORT_DESC.get(newName));
ra.setParamLongDesc(name, M_A_LONG_DESC.get(newName));
ra.setParamDefault(name, M_A_DEFAULT.get(newName));
ra.setParamType(name, M_A_TYPE.get(newName));
ra.setParamPreferred(name, M_A_PREFERRED.get(newName));
}
/**
* Returns meta attribute parameters. The key is always, how the parameter
* is called in the cluster manager and value how it is stored in the GUI.
*/
private Map<String, String> getMetaAttrParameters() {
if (metaAttrParams != null) {
return metaAttrParams;
}
metaAttrParams = new LinkedHashMap<String, String>();
if (Tools.versionBeforePacemaker(host)) {
metaAttrParams.put("target_role", TARGET_ROLE_META_ATTR);
metaAttrParams.put("is_managed", IS_MANAGED_META_ATTR);
} else {
metaAttrParams.put(TARGET_ROLE_META_ATTR, null);
metaAttrParams.put(IS_MANAGED_META_ATTR, null);
}
metaAttrParams.put(MIGRATION_THRESHOLD_META_ATTR, null);
metaAttrParams.put(PRIORITY_META_ATTR, null);
metaAttrParams.put(MULTIPLE_ACTIVE_META_ATTR, null);
metaAttrParams.put(ALLOW_MIGRATE_META_ATTR, null);
final String hbV = host.getHeartbeatVersion();
final String pcmkV = host.getPacemakerVersion();
try {
if (pcmkV != null || Tools.compareVersions(hbV, "2.1.4") >= 0) {
metaAttrParams.put(RESOURCE_STICKINESS_META_ATTR, null);
metaAttrParams.put(FAILURE_TIMEOUT_META_ATTR, null);
}
} catch (Exceptions.IllegalVersionException e) {
LOG.appWarning("getMetaAttrParameters: " + e.getMessage(), e);
}
return metaAttrParams;
}
/**
* Returns meta attribute parameters. The key is always, how the parameter
* is called in the cluster manager and value how it is stored in the GUI.
*/
public Map<String, String> getRscDefaultsParameters() {
if (rscDefaultsMetaAttrs != null) {
return rscDefaultsMetaAttrs;
}
rscDefaultsMetaAttrs = new LinkedHashMap<String, String>();
if (Tools.versionBeforePacemaker(host)) {
/* no rsc defaults in older versions. */
return rscDefaultsMetaAttrs;
}
for (final String param : getMetaAttrParameters().keySet()) {
rscDefaultsMetaAttrs.put(param, getMetaAttrParameters().get(param));
}
/* Master / Slave */
rscDefaultsMetaAttrs.put(MASTER_MAX_META_ATTR, null);
rscDefaultsMetaAttrs.put(MASTER_NODE_MAX_META_ATTR, null);
/* Clone */
rscDefaultsMetaAttrs.put(CLONE_MAX_META_ATTR, null);
rscDefaultsMetaAttrs.put(CLONE_NODE_MAX_META_ATTR, null);
rscDefaultsMetaAttrs.put(NOTIFY_META_ATTR, null);
rscDefaultsMetaAttrs.put(GLOBALLY_UNIQUE_META_ATTR, null);
rscDefaultsMetaAttrs.put(ORDERED_META_ATTR, null);
rscDefaultsMetaAttrs.put(INTERLEAVE_META_ATTR, null);
return rscDefaultsMetaAttrs;
}
/** Parses the parameters. */
private void parseParameters(final ResourceAgent ra,
final Node parametersNode) {
final NodeList parameters = parametersNode.getChildNodes();
for (int i = 0; i < parameters.getLength(); i++) {
final Node parameterNode = parameters.item(i);
if (parameterNode.getNodeName().equals("parameter")) {
final String param = getAttribute(parameterNode, "name");
final String required = getAttribute(parameterNode, "required");
ra.addParameter(param);
if (required != null && required.equals("1")) {
ra.setParamRequired(param, true);
}
/* <longdesc lang="en"> */
final Node longdescParamNode = getChildNode(parameterNode,
"longdesc");
if (longdescParamNode != null) {
final String longDesc = getText(longdescParamNode);
ra.setParamLongDesc(param, Tools.trimText(longDesc));
}
/* <shortdesc lang="en"> */
final Node shortdescParamNode = getChildNode(parameterNode,
"shortdesc");
if (shortdescParamNode != null) {
final String shortDesc = getText(shortdescParamNode);
ra.setParamShortDesc(param, shortDesc);
}
/* <content> */
final Node contentParamNode = getChildNode(parameterNode,
"content");
if (contentParamNode != null) {
final String type = getAttribute(contentParamNode, "type");
String defaultValue = getAttribute(contentParamNode,
"default");
if (defaultValue == null && ra.isStonith()
&& PARAM_TYPE_BOOLEAN.equals(type)) {
defaultValue = PCMK_FALSE;
}
if (ra.isIPaddr() && "nic".equals(param)) {
// workaround for default value in IPaddr and IPaddr2
defaultValue = "";
}
if ("force_stop".equals(param)
&& "0".equals(defaultValue)) {
// Workaround, default is "0" and should be false
defaultValue = "false";
}
if ("".equals(defaultValue)
&& "force_clones".equals(param)) {
defaultValue = "false";
}
if (ra.isPingService()) {
/* workaround: all types are integer in this ras. */
ra.setProbablyClone(true);
if ("host_list".equals(param)) {
ra.setParamRequired(param, true);
}
} else {
ra.setParamType(param, type);
}
if (ra.isStonith() && PARAM_TYPE_BOOLEAN.equals(type)
&& defaultValue == null) {
}
ra.setParamDefault(param, defaultValue);
}
if (ra.isStonith()
&& ("hostlist".equals(param))) {
ra.setParamPossibleChoices(
param,
hostlistChoices.toArray(
new String[hostlistChoices.size()]));
}
final String section = RA_PARAM_SECTION.get(ra.getName(),
param);
if (section != null) {
ra.setSection(param, section);
}
}
}
if (ra.isStonith()) {
/* stonith-timeout */
ra.addParameter(STONITH_TIMEOUT_INSTANCE_ATTR);
ra.setParamShortDesc(STONITH_TIMEOUT_INSTANCE_ATTR,
Tools.getString("CRMXML.stonith-timeout.ShortDesc"));
ra.setParamLongDesc(STONITH_TIMEOUT_INSTANCE_ATTR,
Tools.getString("CRMXML.stonith-timeout.LongDesc"));
ra.setParamType(STONITH_TIMEOUT_INSTANCE_ATTR, PARAM_TYPE_TIME);
ra.setParamDefault(STONITH_TIMEOUT_INSTANCE_ATTR, "");
/* priority */
// TODO: priority or stonith-priority?
ra.addParameter(STONITH_PRIORITY_INSTANCE_ATTR);
ra.setParamShortDesc(STONITH_PRIORITY_INSTANCE_ATTR,
Tools.getString("CRMXML.stonith-priority.ShortDesc"));
ra.setParamLongDesc(STONITH_PRIORITY_INSTANCE_ATTR,
Tools.getString("CRMXML.stonith-priority.LongDesc"));
ra.setParamPossibleChoices(STONITH_PRIORITY_INSTANCE_ATTR,
new String[]{"0", "5", "10"});
ra.setParamType(STONITH_PRIORITY_INSTANCE_ATTR, PARAM_TYPE_INTEGER);
ra.setParamDefault(STONITH_PRIORITY_INSTANCE_ATTR, "0");
/* pcmk_host_check for stonithd */
ra.addParameter(PCMK_HOST_CHECK_PARAM);
ra.setParamPossibleChoices(PCMK_HOST_CHECK_PARAM,
new String[]{"", PCMK_HOST_CHECK_DYNAMIC, PCMK_HOST_CHECK_STATIC});
ra.setParamShortDesc(PCMK_HOST_CHECK_PARAM,
Tools.getString("CRMXML.pcmk_host_check.ShortDesc"));
ra.setParamLongDesc(PCMK_HOST_CHECK_PARAM,
Tools.getString("CRMXML.pcmk_host_check.LongDesc"));
ra.setParamDefault(PCMK_HOST_CHECK_PARAM, PCMK_HOST_CHECK_DYNAMIC);
ra.setParamType(PCMK_HOST_CHECK_PARAM, PARAM_TYPE_STRING);
/* pcmk_host_list for stonithd */
ra.addParameter(PCMK_HOST_LIST_PARAM);
ra.setParamShortDesc(PCMK_HOST_LIST_PARAM,
Tools.getString("CRMXML.pcmk_host_list.ShortDesc"));
ra.setParamLongDesc(PCMK_HOST_LIST_PARAM,
Tools.getString("CRMXML.pcmk_host_list.LongDesc"));
ra.setParamType(PCMK_HOST_LIST_PARAM, PARAM_TYPE_STRING);
ra.setParamPossibleChoices(
PCMK_HOST_LIST_PARAM,
hostlistChoices.toArray(
new String[hostlistChoices.size()]));
/* pcmk_host_map for stonithd */
ra.addParameter(PCMK_HOST_MAP_PARAM);
ra.setParamShortDesc(PCMK_HOST_MAP_PARAM,
Tools.getString("CRMXML.pcmk_host_map.ShortDesc"));
ra.setParamLongDesc(PCMK_HOST_MAP_PARAM,
Tools.getString("CRMXML.pcmk_host_map.LongDesc"));
ra.setParamType(PCMK_HOST_MAP_PARAM, PARAM_TYPE_STRING);
}
final Map<String, String> maParams = getMetaAttrParameters();
for (final String metaAttr : maParams.keySet()) {
addMetaAttribute(ra, metaAttr, maParams.get(metaAttr), false);
}
}
/** Parses the actions node. */
private void parseActions(final ResourceAgent ra,
final Node actionsNode) {
final NodeList actions = actionsNode.getChildNodes();
for (int i = 0; i < actions.getLength(); i++) {
final Node actionNode = actions.item(i);
if (actionNode.getNodeName().equals("action")) {
final String name = getAttribute(actionNode, "name");
if ("status ".equals(name)) {
/* workaround for iSCSITarget RA */
continue;
}
final String depth = getAttribute(actionNode, "depth");
final String timeout = getAttribute(actionNode, "timeout");
final String interval = getAttribute(actionNode, "interval");
final String startDelay = getAttribute(actionNode,
"start-delay");
final String role = getAttribute(actionNode, "role");
ra.addOperationDefault(name, "depth", depth);
ra.addOperationDefault(name, "timeout", timeout);
ra.addOperationDefault(name, "interval", interval);
ra.addOperationDefault(name, "start-delay", startDelay);
ra.addOperationDefault(name, "role", role);
}
}
ra.addOperationDefault("monitor", PAR_CHECK_LEVEL, "");
}
/** Parses the actions node that is list of values for action param. */
private void parseStonithActions(final ResourceAgent ra,
final Node actionsNode) {
final NodeList actionNodes = actionsNode.getChildNodes();
final List<String> actions = new ArrayList<String>();
for (int i = 0; i < actionNodes.getLength(); i++) {
final Node actionNode = actionNodes.item(i);
if (actionNode.getNodeName().equals("action")) {
final String name = getAttribute(actionNode, "name");
actions.add(name);
}
}
ra.setParamPossibleChoices(
FENCING_ACTION_PARAM,
actions.toArray(
new String[actions.size()]));
}
/**
* Parses meta-data xml for parameters for service and fills up the hashes
* "CRM Daemon"s are global config options.
*/
void parseMetaData(final String serviceName,
final String provider,
final String xml,
final boolean masterSlave) {
final Document document = getXMLDocument(xml);
if (document == null) {
return;
}
/* get root <resource-agent> */
final Node raNode = getChildNode(document, "resource-agent");
if (raNode == null) {
return;
}
/* class */
String resourceClass = getAttribute(raNode, "class");
if (resourceClass == null) {
resourceClass = ResourceAgent.OCF_CLASS;
}
final ResourceAgent ra = serviceToResourceAgentMap.get(serviceName,
provider,
resourceClass);
if (ra == null) {
LOG.appWarning("parseMetaData: cannot save meta-data for: "
+ resourceClass
+ ":" + provider
+ ":" + serviceName);
return;
}
if (ra.isMetaDataLoaded()) {
return;
}
if (ResourceAgent.SERVICE_CLASSES.contains(resourceClass)
|| ResourceAgent.HEARTBEAT_CLASS.equals(resourceClass)) {
setLSBResourceAgent(serviceName, resourceClass, ra);
} else {
/* <version> */
final Node versionNode = getChildNode(raNode, "version");
if (versionNode != null) {
ra.setVersion(getText(versionNode));
}
/* <longdesc lang="en"> */
final Node longdescNode = getChildNode(raNode, "longdesc");
if (longdescNode != null) {
ra.setLongDesc(Tools.trimText(getText(longdescNode)));
}
/* <shortdesc lang="en"> */
final Node shortdescNode = getChildNode(raNode, "shortdesc");
if (shortdescNode != null) {
ra.setShortDesc(getText(shortdescNode));
}
/* <parameters> */
final Node parametersNode = getChildNode(raNode, "parameters");
if (parametersNode != null) {
parseParameters(ra, parametersNode);
}
/* <actions> */
final Node actionsNode = getChildNode(raNode, "actions");
if (actionsNode != null) {
if (ra.isStonith()
&& ra.hasParameter(FENCING_ACTION_PARAM)) {
parseStonithActions(ra, actionsNode);
} else {
parseActions(ra, actionsNode);
}
}
ra.setProbablyMasterSlave(masterSlave);
}
ra.setMetaDataLoaded(true);
}
/** Set resource agent to be used as LSB script. */
private void setLSBResourceAgent(final String serviceName,
final String raClass,
final ResourceAgent ra) {
ra.setVersion("0.0");
if (ResourceAgent.LSB_CLASS.equals(raClass)) {
ra.setLongDesc("LSB resource.");
ra.setShortDesc("/etc/init.d/" + serviceName);
} else if (ResourceAgent.SERVICE_CLASSES.contains(raClass)) {
ra.setLongDesc(raClass);
ra.setShortDesc(serviceName);
} else if (ResourceAgent.HEARTBEAT_CLASS.equals(raClass)) {
ra.setLongDesc("Heartbeat 1 RA.");
ra.setShortDesc("/etc/ha.d/resource.d/" + serviceName);
}
for (int i = 1; i < 11; i++) {
final String param = Integer.toString(i);
ra.addParameter(param);
ra.setParamLongDesc(param, param);
ra.setParamShortDesc(param, param);
ra.setParamType(param, "string");
ra.setParamDefault(param, "");
}
/* <actions> */
for (final String name
: new String[]{"start", "stop", "status", "meta-data"}) {
ra.addOperationDefault(name, "timeout", "15");
}
final String monitorName = "monitor";
ra.addOperationDefault(monitorName, "timeout", "15");
ra.addOperationDefault(monitorName, "interval", "15");
ra.addOperationDefault(monitorName, "start-delay", "15");
ra.setProbablyMasterSlave(false);
}
/**
* Parses crm meta data, only to get long descriptions and default values
* for advanced options.
* Strange stuff
*
* which can be pengine or crmd
*/
void parseClusterMetaData(final String xml) {
final Document document = getXMLDocument(xml);
if (document == null) {
return;
}
/* get root <metadata> */
final Node metadataNode = getChildNode(document, "metadata");
if (metadataNode == null) {
return;
}
/* get <resource-agent> */
final NodeList resAgents = metadataNode.getChildNodes();
final String[] booleanValues = PCMK_BOOLEAN_VALUES;
for (int i = 0; i < resAgents.getLength(); i++) {
final Node resAgentNode = resAgents.item(i);
if (!resAgentNode.getNodeName().equals("resource-agent")) {
continue;
}
/* <parameters> */
final Node parametersNode = getChildNode(resAgentNode,
"parameters");
if (parametersNode == null) {
return;
}
final NodeList parameters = parametersNode.getChildNodes();
for (int j = 0; j < parameters.getLength(); j++) {
final Node parameterNode = parameters.item(j);
if (parameterNode.getNodeName().equals("parameter")) {
final String param = getAttribute(parameterNode, "name");
final String required =
getAttribute(parameterNode, "required");
if (!globalParams.contains(param)) {
globalParams.add(param);
}
if (required != null && required.equals("1")
&& !globalRequiredParams.contains(param)) {
globalRequiredParams.add(param);
}
/* <longdesc lang="en"> */
final Node longdescParamNode = getChildNode(parameterNode,
"longdesc");
if (longdescParamNode != null) {
final String longDesc = getText(longdescParamNode);
paramGlobalLongDescMap.put(param,
Tools.trimText(longDesc));
}
/* <content> */
final Node contentParamNode = getChildNode(parameterNode,
"content");
if (contentParamNode != null) {
final String type = getAttribute(contentParamNode,
"type");
String defaultValue = getAttribute(contentParamNode,
"default");
paramGlobalTypeMap.put(param, type);
if (PARAM_TYPE_TIME.equals(type)) {
final Pattern p = Pattern.compile("^(\\d+)s$");
final Matcher m = p.matcher(defaultValue);
if (m.matches()) {
defaultValue = m.group(1);
}
}
if (!"expected-quorum-votes".equals(param)) {
// TODO: workaround
paramGlobalDefaultMap.put(param, defaultValue);
}
if (PARAM_TYPE_BOOLEAN.equals(type)) {
paramGlobalPossibleChoices.put(param,
booleanValues);
}
if (PARAM_TYPE_INTEGER.equals(type)) {
paramGlobalPossibleChoices.put(param,
INTEGER_VALUES);
}
}
}
}
}
/* stonith timeout, workaround, because of param type comming wrong
* from pacemaker */
paramGlobalTypeMap.put("stonith-timeout", PARAM_TYPE_TIME);
}
/**
* Returns the heartbeat service object for the specified service name and
* heartbeat class.
*/
public ResourceAgent getResourceAgent(final String serviceName,
final String provider,
final String raClass) {
final ResourceAgent ra = serviceToResourceAgentMap.get(serviceName,
provider,
raClass);
if (ra == null) {
final ResourceAgent notInstalledRA =
new ResourceAgent(serviceName, provider, raClass);
if (ResourceAgent.SERVICE_CLASSES.contains(raClass)
|| ResourceAgent.HEARTBEAT_CLASS.equals(raClass)) {
setLSBResourceAgent(serviceName, raClass, notInstalledRA);
} else {
LOG.appWarning("getResourceAgent: " + raClass
+ ":" + provider + ":" + serviceName
+ " RA does not exist");
}
serviceToResourceAgentMap.put(serviceName,
provider,
raClass,
notInstalledRA);
return notInstalledRA;
}
return ra;
}
/** Returns the heartbeat service object of the drbddisk service. */
public ResourceAgent getHbDrbddisk() {
return hbDrbddisk;
}
/** Returns the heartbeat service object of the linbit::drbd service. */
public ResourceAgent getHbLinbitDrbd() {
return hbLinbitDrbd;
}
/** Returns the heartbeat service object of the heartbeat group. */
public ResourceAgent getHbGroup() {
return hbGroup;
}
/** Returns the heartbeat service object of the heartbeat clone set. */
public ResourceAgent getHbClone() {
return pcmkClone;
}
/** Parse resource defaults. */
String parseRscDefaults(
final Node rscDefaultsNode,
final Map<String, String> rscDefaultsParams,
final Map<String, String> rscDefaultsParamsNvpairIds) {
final Map<String, String> nvpairIds =
new HashMap<String, String>();
/* <meta_attributtes> */
final Node metaAttrsNode = getChildNode(rscDefaultsNode,
"meta_attributes");
String rscDefaultsId = null;
if (metaAttrsNode != null) {
rscDefaultsId = getAttribute(metaAttrsNode, "id");
NodeList nvpairsMA;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrsNode =
getChildNode(metaAttrsNode, "attributes");
nvpairsMA = attrsNode.getChildNodes();
} else {
nvpairsMA = metaAttrsNode.getChildNodes();
}
/* <nvpair...> */
/* target-role and is-managed */
for (int l = 0; l < nvpairsMA.getLength(); l++) {
final Node maNode = nvpairsMA.item(l);
if (maNode.getNodeName().equals("nvpair")) {
final String nvpairId = getAttribute(maNode, "id");
final String name = getAttribute(maNode, "name");
String value = getAttribute(maNode, "value");
if (TARGET_ROLE_META_ATTR.equals(name)) {
value = value.toLowerCase(Locale.US);
}
rscDefaultsParams.put(name, value);
rscDefaultsParamsNvpairIds.put(name, nvpairId);
}
}
}
return rscDefaultsId;
}
/** Parse op defaults. */
void parseOpDefaults(final Node opDefaultsNode,
final Map<String, String> opDefaultsParams) {
final Map<String, String> nvpairIds =
new HashMap<String, String>();
/* <meta_attributtes> */
final Node metaAttrsNode = getChildNode(opDefaultsNode,
"meta_attributes");
if (metaAttrsNode != null) {
/* <attributtes> only til 2.1.4 */
NodeList nvpairsMA;
if (Tools.versionBeforePacemaker(host)) {
final Node attrsNode =
getChildNode(metaAttrsNode, "attributes");
nvpairsMA = attrsNode.getChildNodes();
} else {
nvpairsMA = metaAttrsNode.getChildNodes();
}
/* <nvpair...> */
for (int l = 0; l < nvpairsMA.getLength(); l++) {
final Node maNode = nvpairsMA.item(l);
if (maNode.getNodeName().equals("nvpair")) {
final String name = getAttribute(maNode, "name");
final String value = getAttribute(maNode, "value");
opDefaultsParams.put(name, value);
}
}
}
}
/** Parses attributes, operations etc. from primitives and clones. */
private void parseAttributes(
final Node resourceNode,
final String crmId,
final Map<String, Map<String, String>> parametersMap,
final Map<String, Map<String, String>> parametersNvpairsIdsMap,
final Map<String, String> resourceInstanceAttrIdMap,
final MultiKeyMap<String, String> operationsMap,
final Map<String, String> metaAttrsIdMap,
final Map<String, String> operationsIdMap,
final Map<String, Map<String, String>> resOpIdsMap,
final Map<String, String> operationsIdRefs,
final Map<String, String> operationsIdtoCRMId,
final Map<String, String> metaAttrsIdRefs,
final Map<String, String> metaAttrsIdToCRMId,
final boolean stonith) {
final Map<String, String> params = new HashMap<String, String>();
parametersMap.put(crmId, params);
final Map<String, String> nvpairIds = new HashMap<String, String>();
parametersNvpairsIdsMap.put(crmId, nvpairIds);
/* <instance_attributes> */
final Node instanceAttrNode = getChildNode(resourceNode,
"instance_attributes");
/* <nvpair...> */
if (instanceAttrNode != null) {
final String iAId = getAttribute(instanceAttrNode, "id");
resourceInstanceAttrIdMap.put(crmId, iAId);
NodeList nvpairsRes;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrNode = getChildNode(instanceAttrNode,
"attributes");
nvpairsRes = attrNode.getChildNodes();
} else {
nvpairsRes = instanceAttrNode.getChildNodes();
}
for (int j = 0; j < nvpairsRes.getLength(); j++) {
final Node optionNode = nvpairsRes.item(j);
if (optionNode.getNodeName().equals("nvpair")) {
final String nvpairId = getAttribute(optionNode, "id");
String name = getAttribute(optionNode, "name");
final String value = getAttribute(optionNode, "value");
if (stonith && "priority".equals(name)) {
/* so it does not clash with meta attr priority */
name = STONITH_PRIORITY_INSTANCE_ATTR;
}
params.put(name, value);
nvpairIds.put(name, nvpairId);
}
}
}
/* <operations> */
final Node operationsNode = getChildNode(resourceNode, "operations");
if (operationsNode != null) {
final String operationsIdRef = getAttribute(operationsNode,
"id-ref");
if (operationsIdRef == null) {
final String operationsId = getAttribute(operationsNode, "id");
operationsIdMap.put(crmId, operationsId);
operationsIdtoCRMId.put(operationsId, crmId);
final Map<String, String> opIds = new HashMap<String, String>();
resOpIdsMap.put(crmId, opIds);
/* <op> */
final NodeList ops = operationsNode.getChildNodes();
for (int k = 0; k < ops.getLength(); k++) {
final Node opNode = ops.item(k);
if (opNode.getNodeName().equals("op")) {
final String opId = getAttribute(opNode, "id");
final String name = getAttribute(opNode, "name");
final String timeout = getAttribute(opNode, "timeout");
final String interval = getAttribute(opNode,
"interval");
final String startDelay = getAttribute(opNode,
"start-delay");
operationsMap.put(crmId, name, "interval", interval);
operationsMap.put(crmId, name, "timeout", timeout);
operationsMap.put(crmId,
name,
"start-delay",
startDelay);
opIds.put(name, opId);
if ("monitor".equals(name)) {
final String checkLevel = parseCheckLevel(opNode);
operationsMap.put(crmId,
name,
PAR_CHECK_LEVEL,
checkLevel);
}
}
}
} else {
operationsIdRefs.put(crmId, operationsIdRef);
}
}
/* <meta_attributtes> */
final Node metaAttrsNode = getChildNode(resourceNode,
"meta_attributes");
if (metaAttrsNode != null) {
final String metaAttrsIdRef = getAttribute(metaAttrsNode, "id-ref");
if (metaAttrsIdRef == null) {
final String metaAttrsId = getAttribute(metaAttrsNode, "id");
metaAttrsIdMap.put(crmId, metaAttrsId);
metaAttrsIdToCRMId.put(metaAttrsId, crmId);
/* <attributtes> only til 2.1.4 */
NodeList nvpairsMA;
if (Tools.versionBeforePacemaker(host)) {
final Node attrsNode =
getChildNode(metaAttrsNode, "attributes");
nvpairsMA = attrsNode.getChildNodes();
} else {
nvpairsMA = metaAttrsNode.getChildNodes();
}
/* <nvpair...> */
/* target-role and is-managed */
for (int l = 0; l < nvpairsMA.getLength(); l++) {
final Node maNode = nvpairsMA.item(l);
if (maNode.getNodeName().equals("nvpair")) {
final String nvpairId = getAttribute(maNode, "id");
final String name = getAttribute(maNode, "name");
String value = getAttribute(maNode, "value");
if (TARGET_ROLE_META_ATTR.equals(name)) {
value = value.toLowerCase(Locale.US);
}
params.put(name, value);
nvpairIds.put(name, nvpairId);
}
}
} else {
metaAttrsIdRefs.put(crmId, metaAttrsIdRef);
}
}
}
/** Parse the OCF_CHECK_LEVEL monitor attribute. */
private String parseCheckLevel(final Node opNode) {
final Node iaNode = getChildNode(opNode, "instance_attributes");
if (iaNode == null) {
return "";
}
final Node nvpairNode = getChildNode(iaNode, "nvpair");
if (nvpairNode == null) {
return "";
}
final String name = getAttribute(nvpairNode, "name");
final String value = getAttribute(nvpairNode, "value");
if (PAR_CHECK_LEVEL.equals(name)) {
return value;
} else {
LOG.appWarning("parseCheckLevel: unexpected instance attribute: "
+ name + " " + value);
return "";
}
}
/** Parses the "group" node. */
private void parseGroup(
final Node groupNode,
final List<String> resList,
final Map<String, List<String>> groupsToResourcesMap,
final Map<String, Map<String, String>> parametersMap,
final Map<String, ResourceAgent> resourceTypeMap,
final Map<String, Map<String, String>> parametersNvpairsIdsMap,
final Map<String, String> resourceInstanceAttrIdMap,
final MultiKeyMap<String, String> operationsMap,
final Map<String, String> metaAttrsIdMap,
final Map<String, String> operationsIdMap,
final Map<String, Map<String, String>> resOpIdsMap,
final Map<String, String> operationsIdRefs,
final Map<String, String> operationsIdtoCRMId,
final Map<String, String> metaAttrsIdRefs,
final Map<String, String> metaAttrsIdToCRMId) {
final NodeList primitives = groupNode.getChildNodes();
final String groupId = getAttribute(groupNode, "id");
final Map<String, String> params =
new HashMap<String, String>();
parametersMap.put(groupId, params);
final Map<String, String> nvpairIds =
new HashMap<String, String>();
parametersNvpairsIdsMap.put(groupId, nvpairIds);
if (resList != null) {
resList.add(groupId);
}
List<String> groupResList = groupsToResourcesMap.get(groupId);
if (groupResList == null) {
groupResList = new ArrayList<String>();
groupsToResourcesMap.put(groupId, groupResList);
}
for (int j = 0; j < primitives.getLength(); j++) {
final Node primitiveNode = primitives.item(j);
if (primitiveNode.getNodeName().equals("primitive")) {
parsePrimitive(primitiveNode,
groupResList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
}
}
/* <meta_attributtes> */
final Node metaAttrsNode = getChildNode(groupNode,
"meta_attributes");
if (metaAttrsNode != null) {
final String metaAttrsIdRef = getAttribute(metaAttrsNode, "id-ref");
if (metaAttrsIdRef == null) {
final String metaAttrsId = getAttribute(metaAttrsNode, "id");
metaAttrsIdMap.put(groupId, metaAttrsId);
metaAttrsIdToCRMId.put(metaAttrsId, groupId);
/* <attributtes> only til 2.1.4 */
NodeList nvpairsMA;
if (Tools.versionBeforePacemaker(host)) {
final Node attrsNode =
getChildNode(metaAttrsNode, "attributes");
nvpairsMA = attrsNode.getChildNodes();
} else {
nvpairsMA = metaAttrsNode.getChildNodes();
}
/* <nvpair...> */
/* target-role and is-managed */
for (int l = 0; l < nvpairsMA.getLength(); l++) {
final Node maNode = nvpairsMA.item(l);
if (maNode.getNodeName().equals("nvpair")) {
final String nvpairId = getAttribute(maNode, "id");
String name = getAttribute(maNode, "name");
String value = getAttribute(maNode, "value");
if (TARGET_ROLE_META_ATTR.equals(name)) {
value = value.toLowerCase(Locale.US);
}
if ("ordered".equals(name)) {
name = GROUP_ORDERED_META_ATTR;
}
params.put(name, value);
nvpairIds.put(name, nvpairId);
}
}
} else {
metaAttrsIdRefs.put(groupId, metaAttrsIdRef);
}
}
}
/** Parses the "primitive" node. */
private void parsePrimitive(
final Node primitiveNode,
final List<String> groupResList,
final Map<String, ResourceAgent> resourceTypeMap,
final Map<String, Map<String, String>> parametersMap,
final Map<String, Map<String, String>> parametersNvpairsIdsMap,
final Map<String, String> resourceInstanceAttrIdMap,
final MultiKeyMap<String, String> operationsMap,
final Map<String, String> metaAttrsIdMap,
final Map<String, String> operationsIdMap,
final Map<String, Map<String, String>> resOpIdsMap,
final Map<String, String> operationsIdRefs,
final Map<String, String> operationsIdtoCRMId,
final Map<String, String> metaAttrsIdRefs,
final Map<String, String> metaAttrsIdToCRMId) {
final String templateId = getAttribute(primitiveNode, "template");
final String crmId = getAttribute(primitiveNode, "id");
if (templateId != null) {
LOG.info("parsePrimitive: templates not implemented, ignoring: "
+ crmId + "/" + templateId);
return;
}
final String raClass = getAttribute(primitiveNode, "class");
String provider = getAttribute(primitiveNode, "provider");
if (provider == null) {
provider = ResourceAgent.HEARTBEAT_PROVIDER;
}
final String type = getAttribute(primitiveNode, "type");
resourceTypeMap.put(crmId, getResourceAgent(type, provider, raClass));
groupResList.add(crmId);
parseAttributes(primitiveNode,
crmId,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId,
ResourceAgent.STONITH_CLASS.equals(raClass));
}
/**
* This class holds parsed status of resource, m/s set, or clone set.
*/
static class ResStatus {
/** On which nodes the resource runs, or is master. */
private final List<String> runningOnNodes;
/** On which nodes the resource is master if it is m/s resource. */
private final List<String> masterOnNodes;
/** On which nodes the resource is slave if it is m/s resource. */
private final List<String> slaveOnNodes;
/** Allocation scores. */
private final Map<String, String> allocationScores;
/** Is managed by CRM. */
private final boolean managed;
/**
* Creates a new ResStatus object.
*/
ResStatus(final List<String> runningOnNodes,
final List<String> masterOnNodes,
final List<String> slaveOnNodes,
final Map<String, String> allocationScores,
final boolean managed) {
this.runningOnNodes = runningOnNodes;
this.masterOnNodes = masterOnNodes;
this.slaveOnNodes = slaveOnNodes;
this.allocationScores = allocationScores;
this.managed = managed;
}
/** Gets on which nodes the resource runs, or is master. */
List<String> getRunningOnNodes() {
return runningOnNodes;
}
/** Gets on which nodes the resource is master if it is m/s resource. */
List<String> getMasterOnNodes() {
return masterOnNodes;
}
/** Gets on which nodes the resource is slave if it is m/s resource. */
List<String> getSlaveOnNodes() {
return slaveOnNodes;
}
/** Returns whether the resoruce is managed. */
boolean isManaged() {
return managed;
}
/** Returns allocation scores. */
Map<String, String> getAllocationScores() {
return allocationScores;
}
}
/** Parse allocation scores. */
private Map<String, String> parseAllocationScores(final NodeList scores) {
final Map<String, String> allocationScores =
new LinkedHashMap<String, String>();
for (int i = 0; i < scores.getLength(); i++) {
final Node scoreNode = scores.item(i);
if (scoreNode.getNodeName().equals("score")) {
final String h = getAttribute(scoreNode, "host");
final String score = getAttribute(scoreNode, "score");
allocationScores.put(h, score);
}
}
return allocationScores;
}
/** Returns a hash with resource information. (running_on) */
Map<String, ResStatus> parseResStatus(final String resStatus) {
final Map<String, ResStatus> resStatusMap =
new HashMap<String, ResStatus>();
final Document document = getXMLDocument(resStatus);
if (document == null) {
return null;
}
/* get root <resource_status> */
final Node statusNode = getChildNode(document, "resource_status");
if (statusNode == null) {
return null;
}
/* <resource...> */
final NodeList resources = statusNode.getChildNodes();
for (int i = 0; i < resources.getLength(); i++) {
final Node resourceNode = resources.item(i);
if (resourceNode.getNodeName().equals("resource")) {
final String id = getAttribute(resourceNode, "id");
final String isManaged = getAttribute(resourceNode, "managed");
final NodeList statusList = resourceNode.getChildNodes();
List<String> runningOnList = null;
List<String> masterOnList = null;
List<String> slaveOnList = null;
boolean managed = false;
if ("managed".equals(isManaged)) {
managed = true;
}
Map<String, String> allocationScores =
new HashMap<String, String>();
for (int j = 0; j < statusList.getLength(); j++) {
final Node setNode = statusList.item(j);
if (TARGET_ROLE_STARTED.equalsIgnoreCase(
setNode.getNodeName())) {
final String node = getText(setNode);
if (runningOnList == null) {
runningOnList = new ArrayList<String>();
}
runningOnList.add(node);
} else if (TARGET_ROLE_MASTER.equalsIgnoreCase(
setNode.getNodeName())) {
final String node = getText(setNode);
if (masterOnList == null) {
masterOnList = new ArrayList<String>();
}
masterOnList.add(node);
} else if (TARGET_ROLE_SLAVE.equalsIgnoreCase(
setNode.getNodeName())) {
final String node = getText(setNode);
if (slaveOnList == null) {
slaveOnList = new ArrayList<String>();
}
slaveOnList.add(node);
} else if ("scores".equals(setNode.getNodeName())) {
allocationScores =
parseAllocationScores(setNode.getChildNodes());
}
}
resStatusMap.put(id, new ResStatus(runningOnList,
masterOnList,
slaveOnList,
allocationScores,
managed));
}
}
return resStatusMap;
}
/** Parses the transient attributes. */
private void parseTransientAttributes(
final String uname,
final Node transientAttrNode,
final MultiKeyMap<String, String> failedMap,
final MultiKeyMap<String, Set<String>> failedClonesMap,
final Map<String, String> pingCountMap) {
/* <instance_attributes> */
final Node instanceAttrNode = getChildNode(transientAttrNode,
"instance_attributes");
/* <nvpair...> */
if (instanceAttrNode != null) {
NodeList nvpairsRes;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrNode = getChildNode(instanceAttrNode,
"attributes");
nvpairsRes = attrNode.getChildNodes();
} else {
nvpairsRes = instanceAttrNode.getChildNodes();
}
for (int j = 0; j < nvpairsRes.getLength(); j++) {
final Node optionNode = nvpairsRes.item(j);
if (optionNode.getNodeName().equals("nvpair")) {
final String name = getAttribute(optionNode, "name");
final String value = getAttribute(optionNode, "value");
/* TODO: last-failure-" */
if ("pingd".equals(name)) {
pingCountMap.put(uname, value);
} else if (name.indexOf(FAIL_COUNT_PREFIX) == 0) {
final String resId =
name.substring(FAIL_COUNT_PREFIX.length());
final String unameLowerCase =
uname.toLowerCase(Locale.US);
failedMap.put(unameLowerCase, resId, value);
final Pattern p = Pattern.compile("(.*):(\\d+)$");
final Matcher m = p.matcher(resId);
if (m.matches()) {
final String crmId = m.group(1);
Set<String> clones =
failedClonesMap.get(unameLowerCase, crmId);
if (clones == null) {
clones = new LinkedHashSet<String>();
failedClonesMap.put(unameLowerCase,
crmId,
clones);
}
clones.add(m.group(2));
failedMap.put(uname.toLowerCase(Locale.US),
crmId,
value);
}
}
}
}
}
}
/** Parses node, to get info like if it is in stand by. */
void parseNode(final String node,
final Node nodeNode,
final MultiKeyMap<String, String> nodeParametersMap) {
/* <instance_attributes> */
final Node instanceAttrNode = getChildNode(nodeNode,
"instance_attributes");
/* <nvpair...> */
if (instanceAttrNode != null) {
NodeList nvpairsRes;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrNode = getChildNode(instanceAttrNode,
"attributes");
nvpairsRes = attrNode.getChildNodes();
} else {
nvpairsRes = instanceAttrNode.getChildNodes();
}
for (int j = 0; j < nvpairsRes.getLength(); j++) {
final Node optionNode = nvpairsRes.item(j);
if (optionNode.getNodeName().equals("nvpair")) {
final String name = getAttribute(optionNode, "name");
final String value = getAttribute(optionNode, "value");
nodeParametersMap.put(node.toLowerCase(Locale.US),
name,
value);
}
}
}
}
/** Parses resource sets. */
private void parseRscSets(
final Node node,
final String colId,
final String ordId,
final List<RscSet> rscSets,
final List<RscSetConnectionData> rscSetConnections) {
final NodeList nodes = node.getChildNodes();
RscSet prevRscSet = null;
int rscSetCount = 0;
int ordPos = 0;
int colPos = 0;
for (int i = 0; i < nodes.getLength(); i++) {
final Node rscSetNode = nodes.item(i);
if (rscSetNode.getNodeName().equals("resource_set")) {
final String id = getAttribute(rscSetNode, "id");
final String sequential = getAttribute(rscSetNode,
"sequential");
final String requireAll = getAttribute(rscSetNode,
REQUIRE_ALL_ATTR);
final String orderAction = getAttribute(rscSetNode, "action");
final String colocationRole = getAttribute(rscSetNode, "role");
final NodeList rscNodes = rscSetNode.getChildNodes();
final List<String> rscIds = new ArrayList<String>();
for (int j = 0; j < rscNodes.getLength(); j++) {
final Node rscRefNode = rscNodes.item(j);
if (rscRefNode.getNodeName().equals("resource_ref")) {
final String rscId = getAttribute(rscRefNode, "id");
rscIds.add(rscId);
}
}
final RscSet rscSet = new RscSet(id,
rscIds,
sequential,
requireAll,
orderAction,
colocationRole);
rscSets.add(rscSet);
if (prevRscSet != null) {
RscSetConnectionData rscSetConnectionData;
if (colId == null) {
/* order */
rscSetConnectionData =
new RscSetConnectionData(prevRscSet,
rscSet,
ordId,
ordPos,
false);
ordPos++;
rscSetConnections.add(0, rscSetConnectionData);
} else {
/* colocation */
rscSetConnectionData =
new RscSetConnectionData(rscSet,
prevRscSet,
colId,
colPos,
true);
colPos++;
rscSetConnections.add(rscSetConnectionData);
}
}
prevRscSet = rscSet;
rscSetCount++;
}
}
if (rscSetCount == 1) {
/* just one, dangling */
RscSetConnectionData rscSetConnectionData;
if (colId == null) {
/* order */
rscSetConnectionData = new RscSetConnectionData(prevRscSet,
null,
ordId,
ordPos,
false);
} else {
/* colocation */
rscSetConnectionData = new RscSetConnectionData(prevRscSet,
null,
colId,
colPos,
true);
}
rscSetConnections.add(rscSetConnectionData);
}
}
/** Returns CibQuery object with information from the cib node. */
CibQuery parseCibQuery(final String query) {
final Document document = getXMLDocument(query);
final CibQuery cibQueryData = new CibQuery();
if (document == null) {
LOG.appWarning("parseCibQuery: cib error: " + query);
return cibQueryData;
}
/* get root <pacemaker> */
final Node pcmkNode = getChildNode(document, "pcmk");
if (pcmkNode == null) {
LOG.appWarning("parseCibQuery: there is no pcmk node");
return cibQueryData;
}
/* get fenced nodes */
final Set<String> fencedNodes = new HashSet<String>();
final Node fencedNode = getChildNode(pcmkNode, "fenced");
if (fencedNode != null) {
final NodeList nodes = fencedNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node hostNode = nodes.item(i);
if (hostNode.getNodeName().equals("node")) {
final String h = getText(hostNode);
if (h != null) {
fencedNodes.add(h.toLowerCase(Locale.US));
}
}
}
}
/* get <cib> */
final Node cibNode = getChildNode(pcmkNode, "cib");
if (cibNode == null) {
LOG.appWarning("parseCibQuery: there is no cib node");
return cibQueryData;
}
/* Designated Co-ordinator */
final String dcUuid = getAttribute(cibNode, "dc-uuid");
//TODO: more attributes are here
/* <configuration> */
final Node confNode = getChildNode(cibNode, "configuration");
if (confNode == null) {
LOG.appWarning("parseCibQuery: there is no configuration node");
return cibQueryData;
}
/* <rsc_defaults> */
final Node rscDefaultsNode = getChildNode(confNode, "rsc_defaults");
String rscDefaultsId = null;
final Map<String, String> rscDefaultsParams =
new HashMap<String, String>();
final Map<String, String> rscDefaultsParamsNvpairIds =
new HashMap<String, String>();
if (rscDefaultsNode != null) {
rscDefaultsId = parseRscDefaults(rscDefaultsNode,
rscDefaultsParams,
rscDefaultsParamsNvpairIds);
}
/* <op_defaults> */
final Node opDefaultsNode = getChildNode(confNode, "op_defaults");
final Map<String, String> opDefaultsParams =
new HashMap<String, String>();
if (opDefaultsNode != null) {
parseOpDefaults(opDefaultsNode, opDefaultsParams);
}
/* <crm_config> */
final Node crmConfNode = getChildNode(confNode, "crm_config");
if (crmConfNode == null) {
LOG.appWarning("parseCibQuery: there is no crm_config node");
return cibQueryData;
}
/* <cluster_property_set> */
final Node cpsNode = getChildNode(crmConfNode, "cluster_property_set");
if (cpsNode == null) {
LOG.appWarning("parseCibQuery: there is no cluster_property_set node");
} else {
NodeList nvpairs;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrNode = getChildNode(cpsNode, "attributes");
nvpairs = attrNode.getChildNodes();
} else {
nvpairs = cpsNode.getChildNodes();
}
final Map<String, String> crmConfMap =
new HashMap<String, String>();
/* <nvpair...> */
for (int i = 0; i < nvpairs.getLength(); i++) {
final Node optionNode = nvpairs.item(i);
if (optionNode.getNodeName().equals("nvpair")) {
final String name = getAttribute(optionNode, "name");
final String value = getAttribute(optionNode, "value");
crmConfMap.put(name, value);
}
}
cibQueryData.setCrmConfig(crmConfMap);
}
/* <nodes> */
/* xml node with cluster node make stupid variable names, but let's
* keep the convention. */
String dc = null;
final MultiKeyMap<String, String> nodeParametersMap =
new MultiKeyMap<String, String>();
final Node nodesNode = getChildNode(confNode, "nodes");
final Map<String, String> nodeOnline = new HashMap<String, String>();
final Map<String, String> nodeID = new HashMap<String, String>();
if (nodesNode != null) {
final NodeList nodes = nodesNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node nodeNode = nodes.item(i);
if (nodeNode.getNodeName().equals("node")) {
/* TODO: doing nothing with the info, just getting the dc,
* for now.
*/
final String id = getAttribute(nodeNode, "id");
final String uname = getAttribute(nodeNode, "uname");
if (!nodeID.containsKey(uname)) {
nodeID.put(uname, id);
}
if (dcUuid != null && dcUuid.equals(id)) {
dc = uname;
}
parseNode(uname, nodeNode, nodeParametersMap);
if (!nodeOnline.containsKey(uname.toLowerCase(Locale.US))) {
nodeOnline.put(uname.toLowerCase(Locale.US), "no");
}
}
}
}
/* <resources> */
final Node resourcesNode = getChildNode(confNode, "resources");
if (resourcesNode == null) {
LOG.appWarning("parseCibQuery: there is no resources node");
return cibQueryData;
}
/* <primitive> */
final Map<String, Map<String, String>> parametersMap =
new HashMap<String, Map<String, String>>();
final Map<String, Map<String, String>> parametersNvpairsIdsMap =
new HashMap<String, Map<String, String>>();
final Map<String, ResourceAgent> resourceTypeMap =
new HashMap<String, ResourceAgent>();
final Set<String> orphanedList = new HashSet<String>();
/* host -> inLRMList list */
final Map<String, Set<String>> inLRMList =
new HashMap<String, Set<String>>();
final Map<String, String> resourceInstanceAttrIdMap =
new HashMap<String, String>();
final MultiKeyMap<String, String> operationsMap =
new MultiKeyMap<String, String>();
final Map<String, String> metaAttrsIdMap =
new HashMap<String, String>();
final Map<String, String> operationsIdMap =
new HashMap<String, String>();
final Map<String, Map<String, String>> resOpIdsMap =
new HashMap<String, Map<String, String>>();
/* must be linked, so that clone from group is before the group itself.
*/
final Map<String, List<String>> groupsToResourcesMap =
new LinkedHashMap<String, List<String>>();
final Map<String, String> cloneToResourceMap =
new HashMap<String, String>();
final List<String> masterList = new ArrayList<String>();
final MultiKeyMap<String, String> failedMap =
new MultiKeyMap<String, String>();
final MultiKeyMap<String, Set<String>> failedClonesMap =
new MultiKeyMap<String, Set<String>>();
final Map<String, String> pingCountMap = new HashMap<String, String>();
groupsToResourcesMap.put("none", new ArrayList<String>());
final NodeList primitivesGroups = resourcesNode.getChildNodes();
final Map<String, String> operationsIdRefs =
new HashMap<String, String>();
final Map<String, String> operationsIdtoCRMId =
new HashMap<String, String>();
final Map<String, String> metaAttrsIdRefs =
new HashMap<String, String>();
final Map<String, String> metaAttrsIdToCRMId =
new HashMap<String, String>();
for (int i = 0; i < primitivesGroups.getLength(); i++) {
final Node primitiveGroupNode = primitivesGroups.item(i);
final String nodeName = primitiveGroupNode.getNodeName();
if ("primitive".equals(nodeName)) {
final List<String> resList =
groupsToResourcesMap.get("none");
parsePrimitive(primitiveGroupNode,
resList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if ("group".equals(nodeName)) {
parseGroup(primitiveGroupNode,
null,
groupsToResourcesMap,
parametersMap,
resourceTypeMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if ("master".equals(nodeName)
|| "master_slave".equals(nodeName)
|| "clone".equals(nodeName)) {
final NodeList primitives = primitiveGroupNode.getChildNodes();
final String cloneId = getAttribute(primitiveGroupNode, "id");
List<String> resList = groupsToResourcesMap.get(cloneId);
if (resList == null) {
resList = new ArrayList<String>();
groupsToResourcesMap.put(cloneId, resList);
}
parseAttributes(primitiveGroupNode,
cloneId,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId,
false);
for (int j = 0; j < primitives.getLength(); j++) {
final Node primitiveNode = primitives.item(j);
if (primitiveNode.getNodeName().equals("primitive")) {
parsePrimitive(primitiveNode,
resList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if (primitiveNode.getNodeName().equals("group")) {
parseGroup(primitiveNode,
resList,
groupsToResourcesMap,
parametersMap,
resourceTypeMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
}
}
if (!resList.isEmpty()) {
cloneToResourceMap.put(cloneId, resList.get(0));
if ("master".equals(nodeName)
|| "master_slave".equals(nodeName)) {
masterList.add(cloneId);
}
}
}
}
/* operationsRefs crm id -> crm id */
final Map<String, String> operationsRefs =
new HashMap<String, String>();
for (final String crmId : operationsIdRefs.keySet()) {
final String idRef = operationsIdRefs.get(crmId);
operationsRefs.put(crmId, operationsIdtoCRMId.get(idRef));
}
/* mettaAttrsRefs crm id -> crm id */
final Map<String, String> metaAttrsRefs = new HashMap<String, String>();
for (final String crmId : metaAttrsIdRefs.keySet()) {
final String idRef = metaAttrsIdRefs.get(crmId);
metaAttrsRefs.put(crmId, metaAttrsIdToCRMId.get(idRef));
}
/* <constraints> */
final Map<String, ColocationData> colocationIdMap =
new LinkedHashMap<String, ColocationData>();
final Map<String, List<ColocationData>> colocationRscMap =
new HashMap<String, List<ColocationData>>();
final Map<String, OrderData> orderIdMap =
new LinkedHashMap<String, OrderData>();
final Map<String, List<RscSet>> orderIdRscSetsMap =
new HashMap<String, List<RscSet>>();
final Map<String, List<RscSet>> colocationIdRscSetsMap =
new HashMap<String, List<RscSet>>();
final List<RscSetConnectionData> rscSetConnections =
new ArrayList<RscSetConnectionData>();
final Map<String, List<OrderData>> orderRscMap =
new HashMap<String, List<OrderData>>();
final Map<String, Map<String, HostLocation>> locationMap =
new HashMap<String, Map<String, HostLocation>>();
final Map<String, HostLocation> pingLocationMap =
new HashMap<String, HostLocation>();
final Map<String, List<String>> locationsIdMap =
new HashMap<String, List<String>>();
final MultiKeyMap<String, String> resHostToLocIdMap =
new MultiKeyMap<String, String>();
final Map<String, String> resPingToLocIdMap =
new HashMap<String, String>();
final Node constraintsNode = getChildNode(confNode, "constraints");
if (constraintsNode != null) {
final NodeList constraints = constraintsNode.getChildNodes();
String rscString = "rsc";
String rscRoleString = "rsc-role";
String withRscString = "with-rsc";
String withRscRoleString = "with-rsc-role";
String firstString = "first";
String thenString = "then";
String firstActionString = "first-action";
String thenActionString = "then-action";
if (Tools.versionBeforePacemaker(host)) {
rscString = "from";
rscRoleString = "from_role";
withRscString = "to";
withRscRoleString = "to_role";
firstString = "to";
thenString = "from";
firstActionString = "to_action";
thenActionString = "action";
}
for (int i = 0; i < constraints.getLength(); i++) {
final Node constraintNode = constraints.item(i);
if (constraintNode.getNodeName().equals("rsc_colocation")) {
final String colId = getAttribute(constraintNode, "id");
final String rsc = getAttribute(constraintNode, rscString);
final String withRsc = getAttribute(constraintNode,
withRscString);
if (rsc == null || withRsc == null) {
final List<RscSet> rscSets = new ArrayList<RscSet>();
parseRscSets(constraintNode,
colId,
null,
rscSets,
rscSetConnections);
colocationIdRscSetsMap.put(colId, rscSets);
}
final String rscRole = getAttribute(constraintNode,
rscRoleString);
final String withRscRole = getAttribute(constraintNode,
withRscRoleString);
final String score = getAttribute(constraintNode,
SCORE_STRING);
final ColocationData colocationData =
new ColocationData(colId,
rsc,
withRsc,
rscRole,
withRscRole,
score);
colocationIdMap.put(colId, colocationData);
List<ColocationData> withs = colocationRscMap.get(rsc);
if (withs == null) {
withs = new ArrayList<ColocationData>();
}
withs.add(colocationData);
colocationRscMap.put(rsc, withs);
} else if (constraintNode.getNodeName().equals("rsc_order")) {
String rscFirst = getAttribute(constraintNode,
firstString);
String rscThen = getAttribute(constraintNode,
thenString);
final String ordId = getAttribute(constraintNode, "id");
if (rscFirst == null || rscThen == null) {
final List<RscSet> rscSets = new ArrayList<RscSet>();
parseRscSets(constraintNode,
null,
ordId,
rscSets,
rscSetConnections);
orderIdRscSetsMap.put(ordId, rscSets);
}
final String score = getAttribute(constraintNode,
SCORE_STRING);
final String symmetrical = getAttribute(constraintNode,
"symmetrical");
String firstAction = getAttribute(constraintNode,
firstActionString);
String thenAction = getAttribute(constraintNode,
thenActionString);
final String type = getAttribute(constraintNode,
"type");
if (type != null && "before".equals(type)) {
/* exchange resoruces */
final String rsc = rscFirst;
rscFirst = rscThen;
rscThen = rsc;
final String act = firstAction;
firstAction = thenAction;
thenAction = act;
}
final OrderData orderData = new OrderData(ordId,
rscFirst,
rscThen,
score,
symmetrical,
firstAction,
thenAction);
orderIdMap.put(ordId, orderData);
List<OrderData> thens = orderRscMap.get(rscFirst);
if (thens == null) {
thens = new ArrayList<OrderData>();
}
thens.add(orderData);
orderRscMap.put(rscFirst, thens);
} else if ("rsc_location".equals(
constraintNode.getNodeName())) {
final String locId = getAttribute(constraintNode, "id");
final String node = getAttribute(constraintNode, "node");
final String rsc = getAttribute(constraintNode, "rsc");
final String score = getAttribute(constraintNode,
SCORE_STRING);
final String role = null; // TODO
List<String> locs = locationsIdMap.get(rsc);
if (locs == null) {
locs = new ArrayList<String>();
locationsIdMap.put(rsc, locs);
}
Map<String, HostLocation> hostScoreMap =
locationMap.get(rsc);
if (hostScoreMap == null) {
hostScoreMap = new HashMap<String, HostLocation>();
locationMap.put(rsc, hostScoreMap);
}
if (node != null) {
resHostToLocIdMap.put(rsc,
node.toLowerCase(Locale.US),
locId);
}
if (score != null) {
hostScoreMap.put(node.toLowerCase(Locale.US),
new HostLocation(score,
"eq",
null,
role));
}
locs.add(locId);
final Node ruleNode = getChildNode(constraintNode,
"rule");
if (ruleNode != null) {
final String score2 = getAttribute(ruleNode,
SCORE_STRING);
final String booleanOp = getAttribute(ruleNode,
"boolean-op");
// TODO: I know only "and", ignoring everything we
// don't know.
final Node expNode = getChildNode(ruleNode,
"expression");
if (expNode != null
&& "expression".equals(expNode.getNodeName())) {
final String attr =
getAttribute(expNode, "attribute");
final String op =
getAttribute(expNode, "operation");
final String type =
getAttribute(expNode, "type");
final String value =
getAttribute(expNode, "value");
if ((booleanOp == null
|| "and".equals(booleanOp))
&& "#uname".equals(attr)
&& value != null) {
hostScoreMap.put(value.toLowerCase(Locale.US),
new HostLocation(score2,
op,
null,
role));
resHostToLocIdMap.put(
rsc,
value.toLowerCase(Locale.US),
locId);
} else if ((booleanOp == null
|| "and".equals(booleanOp))
&& "pingd".equals(attr)) {
pingLocationMap.put(rsc,
new HostLocation(score2,
op,
value,
null));
resPingToLocIdMap.put(rsc, locId);
} else {
LOG.appWarning("parseCibQuery: could not parse rsc_location: " + locId);
}
}
}
}
}
}
/* <status> */
final Node statusNode = getChildNode(cibNode, "status");
final Set<String> nodePending = new HashSet<String>();
if (statusNode != null) {
final String hbV = host.getHeartbeatVersion();
/* <node_state ...> */
final NodeList nodes = statusNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node nodeStateNode = nodes.item(i);
if ("node_state".equals(nodeStateNode.getNodeName())) {
final String uname = getAttribute(nodeStateNode, "uname");
final String id = getAttribute(nodeStateNode, "id");
- if (!id.equals(nodeID.get(uname))) {
+ if (uname == null || !id.equals(nodeID.get(uname))) {
LOG.appWarning("parseCibQuery: skipping " + uname + " " + id);
+ continue;
}
final String ha = getAttribute(nodeStateNode, "ha");
final String join = getAttribute(nodeStateNode, "join");
final String inCCM = getAttribute(nodeStateNode, "in_ccm");
final String crmd = getAttribute(nodeStateNode, "crmd");
if ("member".equals(join)
&& "true".equals(inCCM)
&& !"offline".equals(crmd)) {
nodeOnline.put(uname.toLowerCase(Locale.US), "yes");
} else {
nodeOnline.put(uname.toLowerCase(Locale.US), "no");
}
if ("pending".equals(join)) {
nodePending.add(uname.toLowerCase(Locale.US));
}
final NodeList nodeStates = nodeStateNode.getChildNodes();
/* transient attributes. */
for (int j = 0; j < nodeStates.getLength(); j++) {
final Node nodeStateChild = nodeStates.item(j);
if ("transient_attributes".equals(
nodeStateChild.getNodeName())) {
parseTransientAttributes(uname,
nodeStateChild,
failedMap,
failedClonesMap,
pingCountMap);
}
}
final List<String> resList =
groupsToResourcesMap.get("none");
for (int j = 0; j < nodeStates.getLength(); j++) {
final Node nodeStateChild = nodeStates.item(j);
if ("lrm".equals(nodeStateChild.getNodeName())) {
parseLRM(uname.toLowerCase(Locale.US),
nodeStateChild,
resList,
resourceTypeMap,
parametersMap,
inLRMList,
orphanedList,
failedClonesMap);
}
}
}
}
}
cibQueryData.setDC(dc);
cibQueryData.setNodeParameters(nodeParametersMap);
cibQueryData.setParameters(parametersMap);
cibQueryData.setParametersNvpairsIds(parametersNvpairsIdsMap);
cibQueryData.setResourceType(resourceTypeMap);
cibQueryData.setInLRM(inLRMList);
cibQueryData.setOrphaned(orphanedList);
cibQueryData.setResourceInstanceAttrId(resourceInstanceAttrIdMap);
cibQueryData.setColocationRsc(colocationRscMap);
cibQueryData.setColocationId(colocationIdMap);
cibQueryData.setOrderId(orderIdMap);
cibQueryData.setOrderIdRscSets(orderIdRscSetsMap);
cibQueryData.setColocationIdRscSets(colocationIdRscSetsMap);
cibQueryData.setRscSetConnections(rscSetConnections);
cibQueryData.setOrderRsc(orderRscMap);
cibQueryData.setLocation(locationMap);
cibQueryData.setPingLocation(pingLocationMap);
cibQueryData.setLocationsId(locationsIdMap);
cibQueryData.setResHostToLocId(resHostToLocIdMap);
cibQueryData.setResPingToLocId(resPingToLocIdMap);
cibQueryData.setOperations(operationsMap);
cibQueryData.setOperationsId(operationsIdMap);
cibQueryData.setOperationsRefs(operationsRefs);
cibQueryData.setMetaAttrsId(metaAttrsIdMap);
cibQueryData.setMetaAttrsRefs(metaAttrsRefs);
cibQueryData.setResOpIds(resOpIdsMap);
cibQueryData.setNodeOnline(nodeOnline);
cibQueryData.setNodePending(nodePending);
cibQueryData.setGroupsToResources(groupsToResourcesMap);
cibQueryData.setCloneToResource(cloneToResourceMap);
cibQueryData.setMasterList(masterList);
cibQueryData.setFailed(failedMap);
cibQueryData.setFailedClones(failedClonesMap);
cibQueryData.setPingCount(pingCountMap);
cibQueryData.setRscDefaultsId(rscDefaultsId);
cibQueryData.setRscDefaultsParams(rscDefaultsParams);
cibQueryData.setRscDefaultsParamsNvpairIds(rscDefaultsParamsNvpairIds);
cibQueryData.setOpDefaultsParams(opDefaultsParams);
cibQueryData.setFencedNodes(fencedNodes);
return cibQueryData;
}
/** Returns order parameters. */
public String[] getOrderParameters() {
if (ordParams != null) {
return ordParams.toArray(new String[ordParams.size()]);
}
return null;
}
/** Returns order parameters for resource sets. */
public String[] getRscSetOrderParameters() {
if (rscSetOrdParams != null) {
return rscSetOrdParams.toArray(new String[rscSetOrdParams.size()]);
}
return null;
}
/** Returns order parameters for resource sets. (Shown when an edge
* is clicked, resource_set tag). */
public String[] getRscSetOrdConnectionParameters() {
if (rscSetOrdConnectionParams != null) {
return rscSetOrdConnectionParams.toArray(
new String[rscSetOrdConnectionParams.size()]);
}
return null;
}
/** Checks if parameter is required or not. */
public boolean isOrderRequired(final String param) {
return ordRequiredParams.contains(param);
}
/** Returns short description of the order parameter. */
public String getOrderParamShortDesc(final String param) {
String shortDesc = paramOrdShortDescMap.get(param);
if (shortDesc == null) {
shortDesc = param;
}
return shortDesc;
}
/** Returns long description of the order parameter. */
public String getOrderParamLongDesc(final String param) {
final String shortDesc = getOrderParamShortDesc(param);
String longDesc = paramOrdLongDescMap.get(param);
if (longDesc == null) {
longDesc = "";
}
return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc);
}
/**
* Returns type of a order parameter. It can be string, integer, boolean...
*/
public String getOrderParamType(final String param) {
return paramOrdTypeMap.get(param);
}
/** Returns default value for the order parameter. */
public String getOrderParamDefault(final String param) {
return paramOrdDefaultMap.get(param);
}
/** Returns the preferred value for the order parameter. */
public String getOrderParamPreferred(final String param) {
return paramOrdPreferredMap.get(param);
}
/**
* Returns possible choices for a order parameter, that will be displayed
* in the combo box.
*/
public String[] getOrderParamPossibleChoices(final String param,
final boolean ms) {
if (ms) {
return paramOrdPossibleChoicesMS.get(param);
} else {
return paramOrdPossibleChoices.get(param);
}
}
/** Returns whether the order parameter expects an integer value. */
public boolean isOrderInteger(final String param) {
final String type = getOrderParamType(param);
return PARAM_TYPE_INTEGER.equals(type);
}
/** Returns whether the order parameter expects a label value. */
public boolean isOrderLabel(final String param) {
final String type = getOrderParamType(param);
return PARAM_TYPE_LABEL.equals(type);
}
/** Returns whether the order parameter expects a boolean value. */
public boolean isOrderBoolean(final String param) {
final String type = getOrderParamType(param);
return PARAM_TYPE_BOOLEAN.equals(type);
}
/** Whether the order parameter is of the time type. */
public boolean isOrderTimeType(final String param) {
final String type = getOrderParamType(param);
return PARAM_TYPE_TIME.equals(type);
}
/**
* Returns name of the section order parameter that will be
* displayed.
*/
public String getOrderSection(final String param) {
return Tools.getString("CRMXML.OrderSectionParams");
}
/**
* Checks order parameter according to its type. Returns false if value
* does not fit the type.
*/
public boolean checkOrderParam(final String param, final String value) {
final String type = getOrderParamType(param);
boolean correctValue = true;
if (PARAM_TYPE_BOOLEAN.equals(type)) {
if (!"yes".equals(value) && !"no".equals(value)
&& !PCMK_TRUE.equals(value)
&& !PCMK_FALSE.equals(value)
&& !"True".equals(value)
&& !"False".equals(value)) {
correctValue = false;
}
} else if (PARAM_TYPE_INTEGER.equals(type)) {
final Pattern p =
Pattern.compile("^(-?\\d*|(-|\\+)?" + INFINITY_STRING + ")$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if (PARAM_TYPE_TIME.equals(type)) {
final Pattern p =
Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if ((value == null || "".equals(value))
&& isOrderRequired(param)) {
correctValue = false;
}
return correctValue;
}
/** Returns colocation parameters. */
public String[] getColocationParameters() {
if (colParams != null) {
return colParams.toArray(new String[colParams.size()]);
}
return null;
}
/** Returns colocation parameters for resource sets. (Shown when a
* placeholder is clicked, rsc_colocation tag). */
public String[] getRscSetColocationParameters() {
if (rscSetColParams != null) {
return rscSetColParams.toArray(new String[rscSetColParams.size()]);
}
return null;
}
/** Returns colocation parameters for resource sets. (Shown when an edge
* is clicked, resource_set tag). */
public String[] getRscSetColConnectionParameters() {
if (rscSetColConnectionParams != null) {
return rscSetColConnectionParams.toArray(
new String[rscSetColConnectionParams.size()]);
}
return null;
}
/** Checks if parameter is required or not. */
public boolean isColocationRequired(final String param) {
return colRequiredParams.contains(param);
}
/** Returns short description of the colocation parameter. */
public String getColocationParamShortDesc(final String param) {
String shortDesc = paramColShortDescMap.get(param);
if (shortDesc == null) {
shortDesc = param;
}
return shortDesc;
}
/** Returns long description of the colocation parameter. */
public String getColocationParamLongDesc(final String param) {
final String shortDesc = getColocationParamShortDesc(param);
String longDesc = paramColLongDescMap.get(param);
if (longDesc == null) {
longDesc = "";
}
return Tools.html("<b>" + shortDesc + "</b>\n" + longDesc);
}
/** Returns type of a colocation parameter. It can be string, integer... */
public String getColocationParamType(final String param) {
return paramColTypeMap.get(param);
}
/** Returns default value for the colocation parameter. */
public String getColocationParamDefault(final String param) {
return paramColDefaultMap.get(param);
}
/** Returns the preferred value for the colocation parameter. */
public String getColocationParamPreferred(final String param) {
return paramColPreferredMap.get(param);
}
/**
* Returns possible choices for a colocation parameter, that will be
* displayed in the combo box.
*/
public String[] getColocationParamPossibleChoices(final String param,
final boolean ms) {
if (ms) {
return paramColPossibleChoicesMS.get(param);
} else {
return paramColPossibleChoices.get(param);
}
}
/** Returns whether the colocation parameter expects an integer value. */
public boolean isColocationInteger(final String param) {
final String type = getColocationParamType(param);
return PARAM_TYPE_INTEGER.equals(type);
}
/** Returns whether the colocation parameter expects a label value. */
public boolean isColocationLabel(final String param) {
final String type = getColocationParamType(param);
return PARAM_TYPE_LABEL.equals(type);
}
/** Returns whether the colocation parameter expects a boolean value. */
public boolean isColocationBoolean(final String param) {
final String type = getOrderParamType(param);
return PARAM_TYPE_BOOLEAN.equals(type);
}
/** Whether the colocation parameter is of the time type. */
public boolean isColocationTimeType(final String param) {
final String type = getColocationParamType(param);
return PARAM_TYPE_TIME.equals(type);
}
/**
* Returns name of the section colocation parameter that will be
* displayed.
*/
public String getColocationSection(final String param) {
return Tools.getString("CRMXML.ColocationSectionParams");
}
/**
* Checks colocation parameter according to its type. Returns false if value
* does not fit the type.
*/
public boolean checkColocationParam(final String param,
final String value) {
final String type = getColocationParamType(param);
boolean correctValue = true;
if (PARAM_TYPE_BOOLEAN.equals(type)) {
if (!"yes".equals(value) && !"no".equals(value)
&& !PCMK_TRUE.equals(value)
&& !PCMK_FALSE.equals(value)
&& !"True".equals(value)
&& !"False".equals(value)) {
correctValue = false;
}
} else if (PARAM_TYPE_INTEGER.equals(type)) {
final Pattern p =
Pattern.compile("^(-?\\d*|(-|\\+)?" + INFINITY_STRING + ")$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if (PARAM_TYPE_TIME.equals(type)) {
final Pattern p =
Pattern.compile("^-?\\d*(ms|msec|us|usec|s|sec|m|min|h|hr)?$");
final Matcher m = p.matcher(value);
if (!m.matches()) {
correctValue = false;
}
} else if ((value == null || "".equals(value))
&& isColocationRequired(param)) {
correctValue = false;
}
return correctValue;
}
/** Returns whether drbddisk ra is present. */
public boolean isDrbddiskPresent() {
return drbddiskPresent;
}
/** Returns whether linbit::drbd ra is present. */
public boolean isLinbitDrbdPresent() {
return linbitDrbdPresent;
}
/** Get resources that were removed but are in LRM. */
void parseLRM(final String unameLowerCase,
final Node lrmNode,
final List<String> resList,
final Map<String, ResourceAgent> resourceTypeMap,
final Map<String, Map<String, String>> parametersMap,
final Map<String, Set<String>> inLRMList,
final Set<String> orphanedList,
final MultiKeyMap<String, Set<String>> failedClonesMap) {
final Node lrmResourcesNode = getChildNode(lrmNode, "lrm_resources");
final NodeList lrmResources = lrmResourcesNode.getChildNodes();
for (int j = 0; j < lrmResources.getLength(); j++) {
final Node rscNode = lrmResources.item(j);
if ("lrm_resource".equals(rscNode.getNodeName())) {
final String resId = getAttribute(rscNode, "id");
final Pattern p = Pattern.compile("(.*):(\\d+)$");
final Matcher m = p.matcher(resId);
String crmId;
if (m.matches()) {
crmId = m.group(1);
Set<String> clones = failedClonesMap.get(unameLowerCase,
crmId);
if (clones == null) {
clones = new LinkedHashSet<String>();
failedClonesMap.put(unameLowerCase, crmId, clones);
}
clones.add(m.group(2));
} else {
crmId = resId;
}
if (!resourceTypeMap.containsKey(crmId)) {
final String raClass = getAttribute(rscNode, "class");
String provider = getAttribute(rscNode, "provider");
if (provider == null) {
provider = ResourceAgent.HEARTBEAT_PROVIDER;
}
final String type = getAttribute(rscNode, "type");
resourceTypeMap.put(crmId, getResourceAgent(type,
provider,
raClass));
resList.add(crmId);
parametersMap.put(crmId, new HashMap<String, String>());
orphanedList.add(crmId);
}
/* it is in LRM */
Set<String> inLRMOnHost = inLRMList.get(unameLowerCase);
if (inLRMOnHost == null) {
inLRMOnHost = new HashSet<String>();
inLRMList.put(unameLowerCase, inLRMOnHost);
}
inLRMOnHost.add(crmId);
}
}
}
/** Class that holds colocation data. */
public static final class ColocationData {
/** Colocation id. */
private final String id;
/** Colocation resource 1. */
private final String rsc;
/** Colocation resource 2. */
private final String withRsc;
/** Resource 1 role. */
private final String rscRole;
/** Resource 2 role. */
private final String withRscRole;
/** Colocation score. */
private final String score;
/** Creates new ColocationData object. */
ColocationData(final String id,
final String rsc,
final String withRsc,
final String rscRole,
final String withRscRole,
final String score) {
this.id = id;
this.rsc = rsc;
this.withRsc = withRsc;
this.rscRole = rscRole;
this.withRscRole = withRscRole;
this.score = score;
}
/** Returns colocation id. */
public String getId() {
return id;
}
/** Returns colocation rsc. */
public String getRsc() {
return rsc;
}
/** Returns colocation with-rsc. */
public String getWithRsc() {
return withRsc;
}
/** Returns colocation rsc role. */
public String getRscRole() {
return rscRole;
}
/** Returns colocation with-rsc role. */
public String getWithRscRole() {
return withRscRole;
}
/** Returns colocation score. */
public String getScore() {
return score;
}
}
/** Class that holds order data. */
public static final class OrderData {
/** Order id. */
private final String id;
/** Order resource 1. */
private final String rscFirst;
/** Order resource 2. */
private final String rscThen;
/** Order score. */
private final String score;
/** Symmetical. */
private final String symmetrical;
/** Action of the first resource. */
private final String firstAction;
/** Action of the second resource. */
private final String thenAction;
/** Creates new OrderData object. */
OrderData(final String id,
final String rscFirst,
final String rscThen,
final String score,
final String symmetrical,
final String firstAction,
final String thenAction) {
this.id = id;
this.rscFirst = rscFirst;
this.rscThen = rscThen;
this.score = score;
this.symmetrical = symmetrical;
this.firstAction = firstAction;
this.thenAction = thenAction;
}
/** Returns order id. */
public String getId() {
return id;
}
/** Returns order first rsc. */
String getRscFirst() {
return rscFirst;
}
/** Returns order then rsc. */
public String getRscThen() {
return rscThen;
}
/** Returns order score. */
public String getScore() {
return score;
}
/** Returns order symmetrical attribute. */
public String getSymmetrical() {
return symmetrical;
}
/** Returns order action for "first" resource. */
public String getFirstAction() {
return firstAction;
}
/** Returns order action for "then" resource. */
public String getThenAction() {
return thenAction;
}
}
/** Class that holds resource set data. */
public static final class RscSet {
/** Resource set id. */
private final String id;
/** Resources in this set. */
private final List<String> rscIds;
/** Resource ids lock. */
private final ReadWriteLock mRscIdsLock = new ReentrantReadWriteLock();
/** Resource ids read lock. */
private final Lock mRscIdsReadLock = mRscIdsLock.readLock();
/** Resource ids write lock. */
private final Lock mRscIdsWriteLock = mRscIdsLock.writeLock();
/** String whether the resource set is sequential or not. */
private final String sequential;
/** And/or resource set feature. */
private final String requireAll;
/** order action. */
private final String orderAction;
/** colocation role. */
private final String colocationRole;
/** Creates new RscSet object. */
public RscSet(final String id,
final List<String> rscIds,
final String sequential,
final String requireAll,
final String orderAction,
final String colocationRole) {
this.id = id;
this.rscIds = rscIds;
this.sequential = sequential;
this.requireAll = requireAll;
this.orderAction = orderAction;
this.colocationRole = colocationRole;
}
/** Returns resource set id. */
public String getId() {
return id;
}
/** Returns resources in this set. */
public List<String> getRscIds() {
final List<String> copy = new ArrayList<String>();
mRscIdsReadLock.lock();
try {
for (final String rscId : rscIds) {
copy.add(rscId);
}
} finally {
mRscIdsReadLock.unlock();
}
return copy;
}
/** Returns whether the resource set is sequential or not. */
public String getSequential() {
return sequential;
}
/** Returns whether all resources in the resource set are required to
* be started. */
public String getRequireAll() {
return requireAll;
}
/** Returns whether this resource set is subset of the supplied
* resource set. */
public boolean isSubsetOf(final RscSet oRscSet) {
if (oRscSet == null) {
return false;
}
final List<String> oRscIds = oRscSet.getRscIds();
mRscIdsReadLock.lock();
if (rscIds.isEmpty()) {
mRscIdsReadLock.unlock();
return false;
}
for (final String rscId : rscIds) {
if (!oRscIds.contains(rscId)) {
mRscIdsReadLock.unlock();
return false;
}
}
mRscIdsReadLock.unlock();
return true;
}
/** Returns whether this resource set is equal to the supplied
* resource set. The order of ids doesn't matter. */
boolean equals(final RscSet oRscSet) {
if (oRscSet == null) {
return false;
}
final List<String> oRscIds = oRscSet.getRscIds();
mRscIdsReadLock.lock();
try {
if (oRscIds.size() != rscIds.size()) {
return false;
}
for (final String rscId : rscIds) {
if (!oRscIds.contains(rscId)) {
return false;
}
}
} finally {
mRscIdsReadLock.unlock();
}
return true;
}
/** Adds one id to rsc ids. */
public void addRscId(final String id) {
mRscIdsWriteLock.lock();
try {
rscIds.add(id);
} finally {
mRscIdsWriteLock.unlock();
}
}
/** Return whether rsc ids are empty. */
boolean isRscIdsEmpty() {
mRscIdsReadLock.lock();
try {
return rscIds.isEmpty();
} finally {
mRscIdsReadLock.unlock();
}
}
/** String represantation of the resources set. */
@Override
public String toString() {
final StringBuilder s = new StringBuilder(20);
s.append("rscset id: ");
s.append(id);
s.append(" ids: ");
s.append(rscIds);
return s.toString();
}
/** Returns order action. */
public String getOrderAction() {
return orderAction;
}
/** Returns colocation role. */
public String getColocationRole() {
return colocationRole;
}
/** Returns whether the resouce set is sequential. */
public boolean isSequential() {
return sequential == null || "true".equals(sequential);
}
/** Returns whether the resouce set requires all resources to be
* started . */
public boolean isRequireAll() {
return requireAll == null || REQUIRE_ALL_TRUE.equals(requireAll);
}
}
/** Class that holds data between two resource sests. */
public static final class RscSetConnectionData {
/** Resource set 1. */
private RscSet rscSet1;
/** Resource set 2. */
private RscSet rscSet2;
/** Colocation id. */
private String constraintId;
/** Position in the resoruce set. */
private final int connectionPos;
/** Whether it is colocation. */
private final boolean colocation;
/** Creates new RscSetConnectionData object. */
RscSetConnectionData(final RscSet rscSet1,
final RscSet rscSet2,
final String constraintId,
final int connectionPos,
final boolean colocation) {
this.rscSet1 = rscSet1;
this.rscSet2 = rscSet2;
this.constraintId = constraintId;
this.connectionPos = connectionPos;
this.colocation = colocation;
}
/** Returns resource set 1. */
public RscSet getRscSet1() {
return rscSet1;
}
/** Returns resource set 2. */
public RscSet getRscSet2() {
return rscSet2;
}
/** Returns order or constraint id. */
public String getConstraintId() {
return constraintId;
}
/** Returns order or constraint id. */
public void setConstraintId(final String constraintId) {
this.constraintId = constraintId;
}
/** Returns whether it is colocation. */
public boolean isColocation() {
return colocation;
}
/** Returns whether two resource sets are equal. */
private boolean rscSetsAreEqual(final RscSet set1, final RscSet set2) {
if (set1 == set2) {
return true;
}
if (set1 == null || set2 == null) {
return false;
}
return set1.equals(set2);
}
/** Whether the two resource sets are equal. */
boolean equals(final RscSetConnectionData oRdata) {
final RscSet oRscSet1 = oRdata.getRscSet1();
final RscSet oRscSet2 = oRdata.getRscSet2();
return oRdata.isColocation() == colocation
&& rscSetsAreEqual(rscSet1, oRscSet1)
&& rscSetsAreEqual(rscSet2, oRscSet2);
}
/** Whether the two resource sets are equal,
even if they are reversed. */
public boolean equalsReversed(final RscSetConnectionData oRdata) {
final RscSet oRscSet1 = oRdata.getRscSet1();
final RscSet oRscSet2 = oRdata.getRscSet2();
return oRdata.isColocation() == colocation
&& ((rscSet1 == null /* when it's reversed. */
&& oRscSet2 == null
&& rscSetsAreEqual(rscSet2, oRscSet1))
|| (rscSet2 == null
&& oRscSet1 == null
&& rscSetsAreEqual(rscSet1, oRscSet2)));
}
/** Returns whether the same palceholder should be used. */
public boolean samePlaceholder(final RscSetConnectionData oRdata) {
if (oRdata.isColocation() == colocation) {
/* exactly the same */
return equals(oRdata);
}
final RscSet oRscSet1 = oRdata.getRscSet1();
final RscSet oRscSet2 = oRdata.getRscSet2();
/* is subset only if both are zero */
if ((rscSet1 == oRscSet1
|| rscSet1 == null
|| oRscSet1 == null
|| rscSet1.isSubsetOf(oRscSet1)
|| oRscSet1.isSubsetOf(rscSet1))
&& (rscSet2 == oRscSet2
|| rscSet2 == null
|| oRscSet2 == null
|| rscSet2.isSubsetOf(oRscSet2)
|| oRscSet2.isSubsetOf(rscSet2))) {
/* at least one subset without rscset being null. */
if ((rscSet1 != null && rscSet1.isSubsetOf(oRscSet1))
|| (oRscSet1 != null && oRscSet1.isSubsetOf(rscSet1))
|| (rscSet2 != null && rscSet2.isSubsetOf(oRscSet2))
|| (oRscSet2 != null && oRscSet2.isSubsetOf(rscSet2))) {
return true;
}
}
if ((rscSet1 == oRscSet2
|| rscSet1 == null
|| oRscSet2 == null
|| rscSet1.isSubsetOf(oRscSet2)
|| oRscSet2.isSubsetOf(rscSet1))
&& (rscSet2 == oRscSet1
|| rscSet2 == null
|| oRscSet1 == null
|| rscSet2.isSubsetOf(oRscSet1)
|| oRscSet1.isSubsetOf(rscSet2))) {
if ((rscSet1 != null && rscSet1.isSubsetOf(oRscSet2))
|| (oRscSet2 != null && oRscSet2.isSubsetOf(rscSet1))
|| (rscSet2 != null && rscSet2.isSubsetOf(oRscSet1))
|| (oRscSet1 != null && oRscSet1.isSubsetOf(rscSet2))) {
return true;
}
}
return false;
}
/** Reverse resource sets. */
public void reverse() {
final RscSet old1 = rscSet1;
rscSet1 = rscSet2;
rscSet2 = old1;
}
/** Returns whether it is an empty connection. */
public boolean isEmpty() {
if ((rscSet1 == null || rscSet1.isRscIdsEmpty())
&& (rscSet2 == null || rscSet2.isRscIdsEmpty())) {
return true;
}
return false;
}
/** Returns connection position. */
public int getConnectionPos() {
return connectionPos;
}
/** String represantation of the resource set data. */
@Override
public String toString() {
final StringBuilder s = new StringBuilder(100);
s.append("rsc set conn id: ");
s.append(constraintId);
if (colocation) {
s.append(" (colocation)");
} else {
s.append(" (order)");
}
s.append("\n (rscset1: ");
if (rscSet1 == null) {
s.append("null");
} else {
s.append(rscSet1.toString());
}
s.append(") \n (rscset2: ");
if (rscSet2 == null) {
s.append("null");
} else {
s.append(rscSet2.toString());
}
s.append(") ");
return s.toString();
}
}
}
| false | true | CibQuery parseCibQuery(final String query) {
final Document document = getXMLDocument(query);
final CibQuery cibQueryData = new CibQuery();
if (document == null) {
LOG.appWarning("parseCibQuery: cib error: " + query);
return cibQueryData;
}
/* get root <pacemaker> */
final Node pcmkNode = getChildNode(document, "pcmk");
if (pcmkNode == null) {
LOG.appWarning("parseCibQuery: there is no pcmk node");
return cibQueryData;
}
/* get fenced nodes */
final Set<String> fencedNodes = new HashSet<String>();
final Node fencedNode = getChildNode(pcmkNode, "fenced");
if (fencedNode != null) {
final NodeList nodes = fencedNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node hostNode = nodes.item(i);
if (hostNode.getNodeName().equals("node")) {
final String h = getText(hostNode);
if (h != null) {
fencedNodes.add(h.toLowerCase(Locale.US));
}
}
}
}
/* get <cib> */
final Node cibNode = getChildNode(pcmkNode, "cib");
if (cibNode == null) {
LOG.appWarning("parseCibQuery: there is no cib node");
return cibQueryData;
}
/* Designated Co-ordinator */
final String dcUuid = getAttribute(cibNode, "dc-uuid");
//TODO: more attributes are here
/* <configuration> */
final Node confNode = getChildNode(cibNode, "configuration");
if (confNode == null) {
LOG.appWarning("parseCibQuery: there is no configuration node");
return cibQueryData;
}
/* <rsc_defaults> */
final Node rscDefaultsNode = getChildNode(confNode, "rsc_defaults");
String rscDefaultsId = null;
final Map<String, String> rscDefaultsParams =
new HashMap<String, String>();
final Map<String, String> rscDefaultsParamsNvpairIds =
new HashMap<String, String>();
if (rscDefaultsNode != null) {
rscDefaultsId = parseRscDefaults(rscDefaultsNode,
rscDefaultsParams,
rscDefaultsParamsNvpairIds);
}
/* <op_defaults> */
final Node opDefaultsNode = getChildNode(confNode, "op_defaults");
final Map<String, String> opDefaultsParams =
new HashMap<String, String>();
if (opDefaultsNode != null) {
parseOpDefaults(opDefaultsNode, opDefaultsParams);
}
/* <crm_config> */
final Node crmConfNode = getChildNode(confNode, "crm_config");
if (crmConfNode == null) {
LOG.appWarning("parseCibQuery: there is no crm_config node");
return cibQueryData;
}
/* <cluster_property_set> */
final Node cpsNode = getChildNode(crmConfNode, "cluster_property_set");
if (cpsNode == null) {
LOG.appWarning("parseCibQuery: there is no cluster_property_set node");
} else {
NodeList nvpairs;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrNode = getChildNode(cpsNode, "attributes");
nvpairs = attrNode.getChildNodes();
} else {
nvpairs = cpsNode.getChildNodes();
}
final Map<String, String> crmConfMap =
new HashMap<String, String>();
/* <nvpair...> */
for (int i = 0; i < nvpairs.getLength(); i++) {
final Node optionNode = nvpairs.item(i);
if (optionNode.getNodeName().equals("nvpair")) {
final String name = getAttribute(optionNode, "name");
final String value = getAttribute(optionNode, "value");
crmConfMap.put(name, value);
}
}
cibQueryData.setCrmConfig(crmConfMap);
}
/* <nodes> */
/* xml node with cluster node make stupid variable names, but let's
* keep the convention. */
String dc = null;
final MultiKeyMap<String, String> nodeParametersMap =
new MultiKeyMap<String, String>();
final Node nodesNode = getChildNode(confNode, "nodes");
final Map<String, String> nodeOnline = new HashMap<String, String>();
final Map<String, String> nodeID = new HashMap<String, String>();
if (nodesNode != null) {
final NodeList nodes = nodesNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node nodeNode = nodes.item(i);
if (nodeNode.getNodeName().equals("node")) {
/* TODO: doing nothing with the info, just getting the dc,
* for now.
*/
final String id = getAttribute(nodeNode, "id");
final String uname = getAttribute(nodeNode, "uname");
if (!nodeID.containsKey(uname)) {
nodeID.put(uname, id);
}
if (dcUuid != null && dcUuid.equals(id)) {
dc = uname;
}
parseNode(uname, nodeNode, nodeParametersMap);
if (!nodeOnline.containsKey(uname.toLowerCase(Locale.US))) {
nodeOnline.put(uname.toLowerCase(Locale.US), "no");
}
}
}
}
/* <resources> */
final Node resourcesNode = getChildNode(confNode, "resources");
if (resourcesNode == null) {
LOG.appWarning("parseCibQuery: there is no resources node");
return cibQueryData;
}
/* <primitive> */
final Map<String, Map<String, String>> parametersMap =
new HashMap<String, Map<String, String>>();
final Map<String, Map<String, String>> parametersNvpairsIdsMap =
new HashMap<String, Map<String, String>>();
final Map<String, ResourceAgent> resourceTypeMap =
new HashMap<String, ResourceAgent>();
final Set<String> orphanedList = new HashSet<String>();
/* host -> inLRMList list */
final Map<String, Set<String>> inLRMList =
new HashMap<String, Set<String>>();
final Map<String, String> resourceInstanceAttrIdMap =
new HashMap<String, String>();
final MultiKeyMap<String, String> operationsMap =
new MultiKeyMap<String, String>();
final Map<String, String> metaAttrsIdMap =
new HashMap<String, String>();
final Map<String, String> operationsIdMap =
new HashMap<String, String>();
final Map<String, Map<String, String>> resOpIdsMap =
new HashMap<String, Map<String, String>>();
/* must be linked, so that clone from group is before the group itself.
*/
final Map<String, List<String>> groupsToResourcesMap =
new LinkedHashMap<String, List<String>>();
final Map<String, String> cloneToResourceMap =
new HashMap<String, String>();
final List<String> masterList = new ArrayList<String>();
final MultiKeyMap<String, String> failedMap =
new MultiKeyMap<String, String>();
final MultiKeyMap<String, Set<String>> failedClonesMap =
new MultiKeyMap<String, Set<String>>();
final Map<String, String> pingCountMap = new HashMap<String, String>();
groupsToResourcesMap.put("none", new ArrayList<String>());
final NodeList primitivesGroups = resourcesNode.getChildNodes();
final Map<String, String> operationsIdRefs =
new HashMap<String, String>();
final Map<String, String> operationsIdtoCRMId =
new HashMap<String, String>();
final Map<String, String> metaAttrsIdRefs =
new HashMap<String, String>();
final Map<String, String> metaAttrsIdToCRMId =
new HashMap<String, String>();
for (int i = 0; i < primitivesGroups.getLength(); i++) {
final Node primitiveGroupNode = primitivesGroups.item(i);
final String nodeName = primitiveGroupNode.getNodeName();
if ("primitive".equals(nodeName)) {
final List<String> resList =
groupsToResourcesMap.get("none");
parsePrimitive(primitiveGroupNode,
resList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if ("group".equals(nodeName)) {
parseGroup(primitiveGroupNode,
null,
groupsToResourcesMap,
parametersMap,
resourceTypeMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if ("master".equals(nodeName)
|| "master_slave".equals(nodeName)
|| "clone".equals(nodeName)) {
final NodeList primitives = primitiveGroupNode.getChildNodes();
final String cloneId = getAttribute(primitiveGroupNode, "id");
List<String> resList = groupsToResourcesMap.get(cloneId);
if (resList == null) {
resList = new ArrayList<String>();
groupsToResourcesMap.put(cloneId, resList);
}
parseAttributes(primitiveGroupNode,
cloneId,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId,
false);
for (int j = 0; j < primitives.getLength(); j++) {
final Node primitiveNode = primitives.item(j);
if (primitiveNode.getNodeName().equals("primitive")) {
parsePrimitive(primitiveNode,
resList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if (primitiveNode.getNodeName().equals("group")) {
parseGroup(primitiveNode,
resList,
groupsToResourcesMap,
parametersMap,
resourceTypeMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
}
}
if (!resList.isEmpty()) {
cloneToResourceMap.put(cloneId, resList.get(0));
if ("master".equals(nodeName)
|| "master_slave".equals(nodeName)) {
masterList.add(cloneId);
}
}
}
}
/* operationsRefs crm id -> crm id */
final Map<String, String> operationsRefs =
new HashMap<String, String>();
for (final String crmId : operationsIdRefs.keySet()) {
final String idRef = operationsIdRefs.get(crmId);
operationsRefs.put(crmId, operationsIdtoCRMId.get(idRef));
}
/* mettaAttrsRefs crm id -> crm id */
final Map<String, String> metaAttrsRefs = new HashMap<String, String>();
for (final String crmId : metaAttrsIdRefs.keySet()) {
final String idRef = metaAttrsIdRefs.get(crmId);
metaAttrsRefs.put(crmId, metaAttrsIdToCRMId.get(idRef));
}
/* <constraints> */
final Map<String, ColocationData> colocationIdMap =
new LinkedHashMap<String, ColocationData>();
final Map<String, List<ColocationData>> colocationRscMap =
new HashMap<String, List<ColocationData>>();
final Map<String, OrderData> orderIdMap =
new LinkedHashMap<String, OrderData>();
final Map<String, List<RscSet>> orderIdRscSetsMap =
new HashMap<String, List<RscSet>>();
final Map<String, List<RscSet>> colocationIdRscSetsMap =
new HashMap<String, List<RscSet>>();
final List<RscSetConnectionData> rscSetConnections =
new ArrayList<RscSetConnectionData>();
final Map<String, List<OrderData>> orderRscMap =
new HashMap<String, List<OrderData>>();
final Map<String, Map<String, HostLocation>> locationMap =
new HashMap<String, Map<String, HostLocation>>();
final Map<String, HostLocation> pingLocationMap =
new HashMap<String, HostLocation>();
final Map<String, List<String>> locationsIdMap =
new HashMap<String, List<String>>();
final MultiKeyMap<String, String> resHostToLocIdMap =
new MultiKeyMap<String, String>();
final Map<String, String> resPingToLocIdMap =
new HashMap<String, String>();
final Node constraintsNode = getChildNode(confNode, "constraints");
if (constraintsNode != null) {
final NodeList constraints = constraintsNode.getChildNodes();
String rscString = "rsc";
String rscRoleString = "rsc-role";
String withRscString = "with-rsc";
String withRscRoleString = "with-rsc-role";
String firstString = "first";
String thenString = "then";
String firstActionString = "first-action";
String thenActionString = "then-action";
if (Tools.versionBeforePacemaker(host)) {
rscString = "from";
rscRoleString = "from_role";
withRscString = "to";
withRscRoleString = "to_role";
firstString = "to";
thenString = "from";
firstActionString = "to_action";
thenActionString = "action";
}
for (int i = 0; i < constraints.getLength(); i++) {
final Node constraintNode = constraints.item(i);
if (constraintNode.getNodeName().equals("rsc_colocation")) {
final String colId = getAttribute(constraintNode, "id");
final String rsc = getAttribute(constraintNode, rscString);
final String withRsc = getAttribute(constraintNode,
withRscString);
if (rsc == null || withRsc == null) {
final List<RscSet> rscSets = new ArrayList<RscSet>();
parseRscSets(constraintNode,
colId,
null,
rscSets,
rscSetConnections);
colocationIdRscSetsMap.put(colId, rscSets);
}
final String rscRole = getAttribute(constraintNode,
rscRoleString);
final String withRscRole = getAttribute(constraintNode,
withRscRoleString);
final String score = getAttribute(constraintNode,
SCORE_STRING);
final ColocationData colocationData =
new ColocationData(colId,
rsc,
withRsc,
rscRole,
withRscRole,
score);
colocationIdMap.put(colId, colocationData);
List<ColocationData> withs = colocationRscMap.get(rsc);
if (withs == null) {
withs = new ArrayList<ColocationData>();
}
withs.add(colocationData);
colocationRscMap.put(rsc, withs);
} else if (constraintNode.getNodeName().equals("rsc_order")) {
String rscFirst = getAttribute(constraintNode,
firstString);
String rscThen = getAttribute(constraintNode,
thenString);
final String ordId = getAttribute(constraintNode, "id");
if (rscFirst == null || rscThen == null) {
final List<RscSet> rscSets = new ArrayList<RscSet>();
parseRscSets(constraintNode,
null,
ordId,
rscSets,
rscSetConnections);
orderIdRscSetsMap.put(ordId, rscSets);
}
final String score = getAttribute(constraintNode,
SCORE_STRING);
final String symmetrical = getAttribute(constraintNode,
"symmetrical");
String firstAction = getAttribute(constraintNode,
firstActionString);
String thenAction = getAttribute(constraintNode,
thenActionString);
final String type = getAttribute(constraintNode,
"type");
if (type != null && "before".equals(type)) {
/* exchange resoruces */
final String rsc = rscFirst;
rscFirst = rscThen;
rscThen = rsc;
final String act = firstAction;
firstAction = thenAction;
thenAction = act;
}
final OrderData orderData = new OrderData(ordId,
rscFirst,
rscThen,
score,
symmetrical,
firstAction,
thenAction);
orderIdMap.put(ordId, orderData);
List<OrderData> thens = orderRscMap.get(rscFirst);
if (thens == null) {
thens = new ArrayList<OrderData>();
}
thens.add(orderData);
orderRscMap.put(rscFirst, thens);
} else if ("rsc_location".equals(
constraintNode.getNodeName())) {
final String locId = getAttribute(constraintNode, "id");
final String node = getAttribute(constraintNode, "node");
final String rsc = getAttribute(constraintNode, "rsc");
final String score = getAttribute(constraintNode,
SCORE_STRING);
final String role = null; // TODO
List<String> locs = locationsIdMap.get(rsc);
if (locs == null) {
locs = new ArrayList<String>();
locationsIdMap.put(rsc, locs);
}
Map<String, HostLocation> hostScoreMap =
locationMap.get(rsc);
if (hostScoreMap == null) {
hostScoreMap = new HashMap<String, HostLocation>();
locationMap.put(rsc, hostScoreMap);
}
if (node != null) {
resHostToLocIdMap.put(rsc,
node.toLowerCase(Locale.US),
locId);
}
if (score != null) {
hostScoreMap.put(node.toLowerCase(Locale.US),
new HostLocation(score,
"eq",
null,
role));
}
locs.add(locId);
final Node ruleNode = getChildNode(constraintNode,
"rule");
if (ruleNode != null) {
final String score2 = getAttribute(ruleNode,
SCORE_STRING);
final String booleanOp = getAttribute(ruleNode,
"boolean-op");
// TODO: I know only "and", ignoring everything we
// don't know.
final Node expNode = getChildNode(ruleNode,
"expression");
if (expNode != null
&& "expression".equals(expNode.getNodeName())) {
final String attr =
getAttribute(expNode, "attribute");
final String op =
getAttribute(expNode, "operation");
final String type =
getAttribute(expNode, "type");
final String value =
getAttribute(expNode, "value");
if ((booleanOp == null
|| "and".equals(booleanOp))
&& "#uname".equals(attr)
&& value != null) {
hostScoreMap.put(value.toLowerCase(Locale.US),
new HostLocation(score2,
op,
null,
role));
resHostToLocIdMap.put(
rsc,
value.toLowerCase(Locale.US),
locId);
} else if ((booleanOp == null
|| "and".equals(booleanOp))
&& "pingd".equals(attr)) {
pingLocationMap.put(rsc,
new HostLocation(score2,
op,
value,
null));
resPingToLocIdMap.put(rsc, locId);
} else {
LOG.appWarning("parseCibQuery: could not parse rsc_location: " + locId);
}
}
}
}
}
}
/* <status> */
final Node statusNode = getChildNode(cibNode, "status");
final Set<String> nodePending = new HashSet<String>();
if (statusNode != null) {
final String hbV = host.getHeartbeatVersion();
/* <node_state ...> */
final NodeList nodes = statusNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node nodeStateNode = nodes.item(i);
if ("node_state".equals(nodeStateNode.getNodeName())) {
final String uname = getAttribute(nodeStateNode, "uname");
final String id = getAttribute(nodeStateNode, "id");
if (!id.equals(nodeID.get(uname))) {
LOG.appWarning("parseCibQuery: skipping " + uname + " " + id);
}
final String ha = getAttribute(nodeStateNode, "ha");
final String join = getAttribute(nodeStateNode, "join");
final String inCCM = getAttribute(nodeStateNode, "in_ccm");
final String crmd = getAttribute(nodeStateNode, "crmd");
if ("member".equals(join)
&& "true".equals(inCCM)
&& !"offline".equals(crmd)) {
nodeOnline.put(uname.toLowerCase(Locale.US), "yes");
} else {
nodeOnline.put(uname.toLowerCase(Locale.US), "no");
}
if ("pending".equals(join)) {
nodePending.add(uname.toLowerCase(Locale.US));
}
final NodeList nodeStates = nodeStateNode.getChildNodes();
/* transient attributes. */
for (int j = 0; j < nodeStates.getLength(); j++) {
final Node nodeStateChild = nodeStates.item(j);
if ("transient_attributes".equals(
nodeStateChild.getNodeName())) {
parseTransientAttributes(uname,
nodeStateChild,
failedMap,
failedClonesMap,
pingCountMap);
}
}
final List<String> resList =
groupsToResourcesMap.get("none");
for (int j = 0; j < nodeStates.getLength(); j++) {
final Node nodeStateChild = nodeStates.item(j);
if ("lrm".equals(nodeStateChild.getNodeName())) {
parseLRM(uname.toLowerCase(Locale.US),
nodeStateChild,
resList,
resourceTypeMap,
parametersMap,
inLRMList,
orphanedList,
failedClonesMap);
}
}
}
}
}
cibQueryData.setDC(dc);
cibQueryData.setNodeParameters(nodeParametersMap);
cibQueryData.setParameters(parametersMap);
cibQueryData.setParametersNvpairsIds(parametersNvpairsIdsMap);
cibQueryData.setResourceType(resourceTypeMap);
cibQueryData.setInLRM(inLRMList);
cibQueryData.setOrphaned(orphanedList);
cibQueryData.setResourceInstanceAttrId(resourceInstanceAttrIdMap);
cibQueryData.setColocationRsc(colocationRscMap);
cibQueryData.setColocationId(colocationIdMap);
cibQueryData.setOrderId(orderIdMap);
cibQueryData.setOrderIdRscSets(orderIdRscSetsMap);
cibQueryData.setColocationIdRscSets(colocationIdRscSetsMap);
cibQueryData.setRscSetConnections(rscSetConnections);
cibQueryData.setOrderRsc(orderRscMap);
cibQueryData.setLocation(locationMap);
cibQueryData.setPingLocation(pingLocationMap);
cibQueryData.setLocationsId(locationsIdMap);
cibQueryData.setResHostToLocId(resHostToLocIdMap);
cibQueryData.setResPingToLocId(resPingToLocIdMap);
cibQueryData.setOperations(operationsMap);
cibQueryData.setOperationsId(operationsIdMap);
cibQueryData.setOperationsRefs(operationsRefs);
cibQueryData.setMetaAttrsId(metaAttrsIdMap);
cibQueryData.setMetaAttrsRefs(metaAttrsRefs);
cibQueryData.setResOpIds(resOpIdsMap);
cibQueryData.setNodeOnline(nodeOnline);
cibQueryData.setNodePending(nodePending);
cibQueryData.setGroupsToResources(groupsToResourcesMap);
cibQueryData.setCloneToResource(cloneToResourceMap);
cibQueryData.setMasterList(masterList);
cibQueryData.setFailed(failedMap);
cibQueryData.setFailedClones(failedClonesMap);
cibQueryData.setPingCount(pingCountMap);
cibQueryData.setRscDefaultsId(rscDefaultsId);
cibQueryData.setRscDefaultsParams(rscDefaultsParams);
cibQueryData.setRscDefaultsParamsNvpairIds(rscDefaultsParamsNvpairIds);
cibQueryData.setOpDefaultsParams(opDefaultsParams);
cibQueryData.setFencedNodes(fencedNodes);
return cibQueryData;
}
| CibQuery parseCibQuery(final String query) {
final Document document = getXMLDocument(query);
final CibQuery cibQueryData = new CibQuery();
if (document == null) {
LOG.appWarning("parseCibQuery: cib error: " + query);
return cibQueryData;
}
/* get root <pacemaker> */
final Node pcmkNode = getChildNode(document, "pcmk");
if (pcmkNode == null) {
LOG.appWarning("parseCibQuery: there is no pcmk node");
return cibQueryData;
}
/* get fenced nodes */
final Set<String> fencedNodes = new HashSet<String>();
final Node fencedNode = getChildNode(pcmkNode, "fenced");
if (fencedNode != null) {
final NodeList nodes = fencedNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node hostNode = nodes.item(i);
if (hostNode.getNodeName().equals("node")) {
final String h = getText(hostNode);
if (h != null) {
fencedNodes.add(h.toLowerCase(Locale.US));
}
}
}
}
/* get <cib> */
final Node cibNode = getChildNode(pcmkNode, "cib");
if (cibNode == null) {
LOG.appWarning("parseCibQuery: there is no cib node");
return cibQueryData;
}
/* Designated Co-ordinator */
final String dcUuid = getAttribute(cibNode, "dc-uuid");
//TODO: more attributes are here
/* <configuration> */
final Node confNode = getChildNode(cibNode, "configuration");
if (confNode == null) {
LOG.appWarning("parseCibQuery: there is no configuration node");
return cibQueryData;
}
/* <rsc_defaults> */
final Node rscDefaultsNode = getChildNode(confNode, "rsc_defaults");
String rscDefaultsId = null;
final Map<String, String> rscDefaultsParams =
new HashMap<String, String>();
final Map<String, String> rscDefaultsParamsNvpairIds =
new HashMap<String, String>();
if (rscDefaultsNode != null) {
rscDefaultsId = parseRscDefaults(rscDefaultsNode,
rscDefaultsParams,
rscDefaultsParamsNvpairIds);
}
/* <op_defaults> */
final Node opDefaultsNode = getChildNode(confNode, "op_defaults");
final Map<String, String> opDefaultsParams =
new HashMap<String, String>();
if (opDefaultsNode != null) {
parseOpDefaults(opDefaultsNode, opDefaultsParams);
}
/* <crm_config> */
final Node crmConfNode = getChildNode(confNode, "crm_config");
if (crmConfNode == null) {
LOG.appWarning("parseCibQuery: there is no crm_config node");
return cibQueryData;
}
/* <cluster_property_set> */
final Node cpsNode = getChildNode(crmConfNode, "cluster_property_set");
if (cpsNode == null) {
LOG.appWarning("parseCibQuery: there is no cluster_property_set node");
} else {
NodeList nvpairs;
if (Tools.versionBeforePacemaker(host)) {
/* <attributtes> only til 2.1.4 */
final Node attrNode = getChildNode(cpsNode, "attributes");
nvpairs = attrNode.getChildNodes();
} else {
nvpairs = cpsNode.getChildNodes();
}
final Map<String, String> crmConfMap =
new HashMap<String, String>();
/* <nvpair...> */
for (int i = 0; i < nvpairs.getLength(); i++) {
final Node optionNode = nvpairs.item(i);
if (optionNode.getNodeName().equals("nvpair")) {
final String name = getAttribute(optionNode, "name");
final String value = getAttribute(optionNode, "value");
crmConfMap.put(name, value);
}
}
cibQueryData.setCrmConfig(crmConfMap);
}
/* <nodes> */
/* xml node with cluster node make stupid variable names, but let's
* keep the convention. */
String dc = null;
final MultiKeyMap<String, String> nodeParametersMap =
new MultiKeyMap<String, String>();
final Node nodesNode = getChildNode(confNode, "nodes");
final Map<String, String> nodeOnline = new HashMap<String, String>();
final Map<String, String> nodeID = new HashMap<String, String>();
if (nodesNode != null) {
final NodeList nodes = nodesNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node nodeNode = nodes.item(i);
if (nodeNode.getNodeName().equals("node")) {
/* TODO: doing nothing with the info, just getting the dc,
* for now.
*/
final String id = getAttribute(nodeNode, "id");
final String uname = getAttribute(nodeNode, "uname");
if (!nodeID.containsKey(uname)) {
nodeID.put(uname, id);
}
if (dcUuid != null && dcUuid.equals(id)) {
dc = uname;
}
parseNode(uname, nodeNode, nodeParametersMap);
if (!nodeOnline.containsKey(uname.toLowerCase(Locale.US))) {
nodeOnline.put(uname.toLowerCase(Locale.US), "no");
}
}
}
}
/* <resources> */
final Node resourcesNode = getChildNode(confNode, "resources");
if (resourcesNode == null) {
LOG.appWarning("parseCibQuery: there is no resources node");
return cibQueryData;
}
/* <primitive> */
final Map<String, Map<String, String>> parametersMap =
new HashMap<String, Map<String, String>>();
final Map<String, Map<String, String>> parametersNvpairsIdsMap =
new HashMap<String, Map<String, String>>();
final Map<String, ResourceAgent> resourceTypeMap =
new HashMap<String, ResourceAgent>();
final Set<String> orphanedList = new HashSet<String>();
/* host -> inLRMList list */
final Map<String, Set<String>> inLRMList =
new HashMap<String, Set<String>>();
final Map<String, String> resourceInstanceAttrIdMap =
new HashMap<String, String>();
final MultiKeyMap<String, String> operationsMap =
new MultiKeyMap<String, String>();
final Map<String, String> metaAttrsIdMap =
new HashMap<String, String>();
final Map<String, String> operationsIdMap =
new HashMap<String, String>();
final Map<String, Map<String, String>> resOpIdsMap =
new HashMap<String, Map<String, String>>();
/* must be linked, so that clone from group is before the group itself.
*/
final Map<String, List<String>> groupsToResourcesMap =
new LinkedHashMap<String, List<String>>();
final Map<String, String> cloneToResourceMap =
new HashMap<String, String>();
final List<String> masterList = new ArrayList<String>();
final MultiKeyMap<String, String> failedMap =
new MultiKeyMap<String, String>();
final MultiKeyMap<String, Set<String>> failedClonesMap =
new MultiKeyMap<String, Set<String>>();
final Map<String, String> pingCountMap = new HashMap<String, String>();
groupsToResourcesMap.put("none", new ArrayList<String>());
final NodeList primitivesGroups = resourcesNode.getChildNodes();
final Map<String, String> operationsIdRefs =
new HashMap<String, String>();
final Map<String, String> operationsIdtoCRMId =
new HashMap<String, String>();
final Map<String, String> metaAttrsIdRefs =
new HashMap<String, String>();
final Map<String, String> metaAttrsIdToCRMId =
new HashMap<String, String>();
for (int i = 0; i < primitivesGroups.getLength(); i++) {
final Node primitiveGroupNode = primitivesGroups.item(i);
final String nodeName = primitiveGroupNode.getNodeName();
if ("primitive".equals(nodeName)) {
final List<String> resList =
groupsToResourcesMap.get("none");
parsePrimitive(primitiveGroupNode,
resList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if ("group".equals(nodeName)) {
parseGroup(primitiveGroupNode,
null,
groupsToResourcesMap,
parametersMap,
resourceTypeMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if ("master".equals(nodeName)
|| "master_slave".equals(nodeName)
|| "clone".equals(nodeName)) {
final NodeList primitives = primitiveGroupNode.getChildNodes();
final String cloneId = getAttribute(primitiveGroupNode, "id");
List<String> resList = groupsToResourcesMap.get(cloneId);
if (resList == null) {
resList = new ArrayList<String>();
groupsToResourcesMap.put(cloneId, resList);
}
parseAttributes(primitiveGroupNode,
cloneId,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId,
false);
for (int j = 0; j < primitives.getLength(); j++) {
final Node primitiveNode = primitives.item(j);
if (primitiveNode.getNodeName().equals("primitive")) {
parsePrimitive(primitiveNode,
resList,
resourceTypeMap,
parametersMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
} else if (primitiveNode.getNodeName().equals("group")) {
parseGroup(primitiveNode,
resList,
groupsToResourcesMap,
parametersMap,
resourceTypeMap,
parametersNvpairsIdsMap,
resourceInstanceAttrIdMap,
operationsMap,
metaAttrsIdMap,
operationsIdMap,
resOpIdsMap,
operationsIdRefs,
operationsIdtoCRMId,
metaAttrsIdRefs,
metaAttrsIdToCRMId);
}
}
if (!resList.isEmpty()) {
cloneToResourceMap.put(cloneId, resList.get(0));
if ("master".equals(nodeName)
|| "master_slave".equals(nodeName)) {
masterList.add(cloneId);
}
}
}
}
/* operationsRefs crm id -> crm id */
final Map<String, String> operationsRefs =
new HashMap<String, String>();
for (final String crmId : operationsIdRefs.keySet()) {
final String idRef = operationsIdRefs.get(crmId);
operationsRefs.put(crmId, operationsIdtoCRMId.get(idRef));
}
/* mettaAttrsRefs crm id -> crm id */
final Map<String, String> metaAttrsRefs = new HashMap<String, String>();
for (final String crmId : metaAttrsIdRefs.keySet()) {
final String idRef = metaAttrsIdRefs.get(crmId);
metaAttrsRefs.put(crmId, metaAttrsIdToCRMId.get(idRef));
}
/* <constraints> */
final Map<String, ColocationData> colocationIdMap =
new LinkedHashMap<String, ColocationData>();
final Map<String, List<ColocationData>> colocationRscMap =
new HashMap<String, List<ColocationData>>();
final Map<String, OrderData> orderIdMap =
new LinkedHashMap<String, OrderData>();
final Map<String, List<RscSet>> orderIdRscSetsMap =
new HashMap<String, List<RscSet>>();
final Map<String, List<RscSet>> colocationIdRscSetsMap =
new HashMap<String, List<RscSet>>();
final List<RscSetConnectionData> rscSetConnections =
new ArrayList<RscSetConnectionData>();
final Map<String, List<OrderData>> orderRscMap =
new HashMap<String, List<OrderData>>();
final Map<String, Map<String, HostLocation>> locationMap =
new HashMap<String, Map<String, HostLocation>>();
final Map<String, HostLocation> pingLocationMap =
new HashMap<String, HostLocation>();
final Map<String, List<String>> locationsIdMap =
new HashMap<String, List<String>>();
final MultiKeyMap<String, String> resHostToLocIdMap =
new MultiKeyMap<String, String>();
final Map<String, String> resPingToLocIdMap =
new HashMap<String, String>();
final Node constraintsNode = getChildNode(confNode, "constraints");
if (constraintsNode != null) {
final NodeList constraints = constraintsNode.getChildNodes();
String rscString = "rsc";
String rscRoleString = "rsc-role";
String withRscString = "with-rsc";
String withRscRoleString = "with-rsc-role";
String firstString = "first";
String thenString = "then";
String firstActionString = "first-action";
String thenActionString = "then-action";
if (Tools.versionBeforePacemaker(host)) {
rscString = "from";
rscRoleString = "from_role";
withRscString = "to";
withRscRoleString = "to_role";
firstString = "to";
thenString = "from";
firstActionString = "to_action";
thenActionString = "action";
}
for (int i = 0; i < constraints.getLength(); i++) {
final Node constraintNode = constraints.item(i);
if (constraintNode.getNodeName().equals("rsc_colocation")) {
final String colId = getAttribute(constraintNode, "id");
final String rsc = getAttribute(constraintNode, rscString);
final String withRsc = getAttribute(constraintNode,
withRscString);
if (rsc == null || withRsc == null) {
final List<RscSet> rscSets = new ArrayList<RscSet>();
parseRscSets(constraintNode,
colId,
null,
rscSets,
rscSetConnections);
colocationIdRscSetsMap.put(colId, rscSets);
}
final String rscRole = getAttribute(constraintNode,
rscRoleString);
final String withRscRole = getAttribute(constraintNode,
withRscRoleString);
final String score = getAttribute(constraintNode,
SCORE_STRING);
final ColocationData colocationData =
new ColocationData(colId,
rsc,
withRsc,
rscRole,
withRscRole,
score);
colocationIdMap.put(colId, colocationData);
List<ColocationData> withs = colocationRscMap.get(rsc);
if (withs == null) {
withs = new ArrayList<ColocationData>();
}
withs.add(colocationData);
colocationRscMap.put(rsc, withs);
} else if (constraintNode.getNodeName().equals("rsc_order")) {
String rscFirst = getAttribute(constraintNode,
firstString);
String rscThen = getAttribute(constraintNode,
thenString);
final String ordId = getAttribute(constraintNode, "id");
if (rscFirst == null || rscThen == null) {
final List<RscSet> rscSets = new ArrayList<RscSet>();
parseRscSets(constraintNode,
null,
ordId,
rscSets,
rscSetConnections);
orderIdRscSetsMap.put(ordId, rscSets);
}
final String score = getAttribute(constraintNode,
SCORE_STRING);
final String symmetrical = getAttribute(constraintNode,
"symmetrical");
String firstAction = getAttribute(constraintNode,
firstActionString);
String thenAction = getAttribute(constraintNode,
thenActionString);
final String type = getAttribute(constraintNode,
"type");
if (type != null && "before".equals(type)) {
/* exchange resoruces */
final String rsc = rscFirst;
rscFirst = rscThen;
rscThen = rsc;
final String act = firstAction;
firstAction = thenAction;
thenAction = act;
}
final OrderData orderData = new OrderData(ordId,
rscFirst,
rscThen,
score,
symmetrical,
firstAction,
thenAction);
orderIdMap.put(ordId, orderData);
List<OrderData> thens = orderRscMap.get(rscFirst);
if (thens == null) {
thens = new ArrayList<OrderData>();
}
thens.add(orderData);
orderRscMap.put(rscFirst, thens);
} else if ("rsc_location".equals(
constraintNode.getNodeName())) {
final String locId = getAttribute(constraintNode, "id");
final String node = getAttribute(constraintNode, "node");
final String rsc = getAttribute(constraintNode, "rsc");
final String score = getAttribute(constraintNode,
SCORE_STRING);
final String role = null; // TODO
List<String> locs = locationsIdMap.get(rsc);
if (locs == null) {
locs = new ArrayList<String>();
locationsIdMap.put(rsc, locs);
}
Map<String, HostLocation> hostScoreMap =
locationMap.get(rsc);
if (hostScoreMap == null) {
hostScoreMap = new HashMap<String, HostLocation>();
locationMap.put(rsc, hostScoreMap);
}
if (node != null) {
resHostToLocIdMap.put(rsc,
node.toLowerCase(Locale.US),
locId);
}
if (score != null) {
hostScoreMap.put(node.toLowerCase(Locale.US),
new HostLocation(score,
"eq",
null,
role));
}
locs.add(locId);
final Node ruleNode = getChildNode(constraintNode,
"rule");
if (ruleNode != null) {
final String score2 = getAttribute(ruleNode,
SCORE_STRING);
final String booleanOp = getAttribute(ruleNode,
"boolean-op");
// TODO: I know only "and", ignoring everything we
// don't know.
final Node expNode = getChildNode(ruleNode,
"expression");
if (expNode != null
&& "expression".equals(expNode.getNodeName())) {
final String attr =
getAttribute(expNode, "attribute");
final String op =
getAttribute(expNode, "operation");
final String type =
getAttribute(expNode, "type");
final String value =
getAttribute(expNode, "value");
if ((booleanOp == null
|| "and".equals(booleanOp))
&& "#uname".equals(attr)
&& value != null) {
hostScoreMap.put(value.toLowerCase(Locale.US),
new HostLocation(score2,
op,
null,
role));
resHostToLocIdMap.put(
rsc,
value.toLowerCase(Locale.US),
locId);
} else if ((booleanOp == null
|| "and".equals(booleanOp))
&& "pingd".equals(attr)) {
pingLocationMap.put(rsc,
new HostLocation(score2,
op,
value,
null));
resPingToLocIdMap.put(rsc, locId);
} else {
LOG.appWarning("parseCibQuery: could not parse rsc_location: " + locId);
}
}
}
}
}
}
/* <status> */
final Node statusNode = getChildNode(cibNode, "status");
final Set<String> nodePending = new HashSet<String>();
if (statusNode != null) {
final String hbV = host.getHeartbeatVersion();
/* <node_state ...> */
final NodeList nodes = statusNode.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
final Node nodeStateNode = nodes.item(i);
if ("node_state".equals(nodeStateNode.getNodeName())) {
final String uname = getAttribute(nodeStateNode, "uname");
final String id = getAttribute(nodeStateNode, "id");
if (uname == null || !id.equals(nodeID.get(uname))) {
LOG.appWarning("parseCibQuery: skipping " + uname + " " + id);
continue;
}
final String ha = getAttribute(nodeStateNode, "ha");
final String join = getAttribute(nodeStateNode, "join");
final String inCCM = getAttribute(nodeStateNode, "in_ccm");
final String crmd = getAttribute(nodeStateNode, "crmd");
if ("member".equals(join)
&& "true".equals(inCCM)
&& !"offline".equals(crmd)) {
nodeOnline.put(uname.toLowerCase(Locale.US), "yes");
} else {
nodeOnline.put(uname.toLowerCase(Locale.US), "no");
}
if ("pending".equals(join)) {
nodePending.add(uname.toLowerCase(Locale.US));
}
final NodeList nodeStates = nodeStateNode.getChildNodes();
/* transient attributes. */
for (int j = 0; j < nodeStates.getLength(); j++) {
final Node nodeStateChild = nodeStates.item(j);
if ("transient_attributes".equals(
nodeStateChild.getNodeName())) {
parseTransientAttributes(uname,
nodeStateChild,
failedMap,
failedClonesMap,
pingCountMap);
}
}
final List<String> resList =
groupsToResourcesMap.get("none");
for (int j = 0; j < nodeStates.getLength(); j++) {
final Node nodeStateChild = nodeStates.item(j);
if ("lrm".equals(nodeStateChild.getNodeName())) {
parseLRM(uname.toLowerCase(Locale.US),
nodeStateChild,
resList,
resourceTypeMap,
parametersMap,
inLRMList,
orphanedList,
failedClonesMap);
}
}
}
}
}
cibQueryData.setDC(dc);
cibQueryData.setNodeParameters(nodeParametersMap);
cibQueryData.setParameters(parametersMap);
cibQueryData.setParametersNvpairsIds(parametersNvpairsIdsMap);
cibQueryData.setResourceType(resourceTypeMap);
cibQueryData.setInLRM(inLRMList);
cibQueryData.setOrphaned(orphanedList);
cibQueryData.setResourceInstanceAttrId(resourceInstanceAttrIdMap);
cibQueryData.setColocationRsc(colocationRscMap);
cibQueryData.setColocationId(colocationIdMap);
cibQueryData.setOrderId(orderIdMap);
cibQueryData.setOrderIdRscSets(orderIdRscSetsMap);
cibQueryData.setColocationIdRscSets(colocationIdRscSetsMap);
cibQueryData.setRscSetConnections(rscSetConnections);
cibQueryData.setOrderRsc(orderRscMap);
cibQueryData.setLocation(locationMap);
cibQueryData.setPingLocation(pingLocationMap);
cibQueryData.setLocationsId(locationsIdMap);
cibQueryData.setResHostToLocId(resHostToLocIdMap);
cibQueryData.setResPingToLocId(resPingToLocIdMap);
cibQueryData.setOperations(operationsMap);
cibQueryData.setOperationsId(operationsIdMap);
cibQueryData.setOperationsRefs(operationsRefs);
cibQueryData.setMetaAttrsId(metaAttrsIdMap);
cibQueryData.setMetaAttrsRefs(metaAttrsRefs);
cibQueryData.setResOpIds(resOpIdsMap);
cibQueryData.setNodeOnline(nodeOnline);
cibQueryData.setNodePending(nodePending);
cibQueryData.setGroupsToResources(groupsToResourcesMap);
cibQueryData.setCloneToResource(cloneToResourceMap);
cibQueryData.setMasterList(masterList);
cibQueryData.setFailed(failedMap);
cibQueryData.setFailedClones(failedClonesMap);
cibQueryData.setPingCount(pingCountMap);
cibQueryData.setRscDefaultsId(rscDefaultsId);
cibQueryData.setRscDefaultsParams(rscDefaultsParams);
cibQueryData.setRscDefaultsParamsNvpairIds(rscDefaultsParamsNvpairIds);
cibQueryData.setOpDefaultsParams(opDefaultsParams);
cibQueryData.setFencedNodes(fencedNodes);
return cibQueryData;
}
|
diff --git a/guice-bootstrap/src/test/java/com/maxifier/guice/bootstrap/groovy/GroovyModuleTest.java b/guice-bootstrap/src/test/java/com/maxifier/guice/bootstrap/groovy/GroovyModuleTest.java
index 43fdb37..5d472cb 100644
--- a/guice-bootstrap/src/test/java/com/maxifier/guice/bootstrap/groovy/GroovyModuleTest.java
+++ b/guice-bootstrap/src/test/java/com/maxifier/guice/bootstrap/groovy/GroovyModuleTest.java
@@ -1,67 +1,63 @@
package com.maxifier.guice.bootstrap.groovy;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.magenta.guice.bootstrap.xml.*;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.FileInputStream;
import java.io.InputStream;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Test
public class GroovyModuleTest {
@DataProvider(name = "files")
public Object[][] fileNames() {
return new Object[][]{
{"groovy/test.groovy"}
};
}
@Test(dataProvider = "files")
public void testGroovyModule(String fileName) {
InputStream resourceAsStream = GroovyModuleTest.class.getClassLoader().getResourceAsStream(fileName);
- Binding binding = new Binding();
- binding.setVariable("client", "forbes");
- binding.setVariable("binder", binder);
GroovyShell shell = new GroovyShell();
shell.setProperty("client", "forbes");
- shell.setProperty("binder", binder);
GroovyModule gModule = new GroovyModule(resourceAsStream, shell);
Injector inj = Guice.createInjector(gModule);
//from FooModule
inj.getInstance(Foo.class);
//just component
assertTrue(inj.getInstance(TestInterface.class) instanceof First);
//just component with annotation
assertTrue(inj.getInstance(Key.get(TestInterface.class, TestAnnotation.class)) instanceof Second);
//test constant
inj.getInstance(Key.get(String.class, Constant.class));
//test alone
inj.getInstance(Alone.class);
//test in SINGLETON scope
In in1 = inj.getInstance(In.class);
In in2 = inj.getInstance(In.class);
assertTrue(in1 instanceof InImpl);
assertTrue(in2 instanceof InImpl);
assertTrue(in1 == in2);
assertEquals(((InImpl) in1).getProperty(), "testValue");
assertEquals(((InImpl) in1).getWeight(), 523.23);
//test asEager
inj.getInstance(AsEager.class);
//test constant
inj.getInstance(Key.get(String.class, Names.named("test.name")));
}
}
| false | true | public void testGroovyModule(String fileName) {
InputStream resourceAsStream = GroovyModuleTest.class.getClassLoader().getResourceAsStream(fileName);
Binding binding = new Binding();
binding.setVariable("client", "forbes");
binding.setVariable("binder", binder);
GroovyShell shell = new GroovyShell();
shell.setProperty("client", "forbes");
shell.setProperty("binder", binder);
GroovyModule gModule = new GroovyModule(resourceAsStream, shell);
Injector inj = Guice.createInjector(gModule);
//from FooModule
inj.getInstance(Foo.class);
//just component
assertTrue(inj.getInstance(TestInterface.class) instanceof First);
//just component with annotation
assertTrue(inj.getInstance(Key.get(TestInterface.class, TestAnnotation.class)) instanceof Second);
//test constant
inj.getInstance(Key.get(String.class, Constant.class));
//test alone
inj.getInstance(Alone.class);
//test in SINGLETON scope
In in1 = inj.getInstance(In.class);
In in2 = inj.getInstance(In.class);
assertTrue(in1 instanceof InImpl);
assertTrue(in2 instanceof InImpl);
assertTrue(in1 == in2);
assertEquals(((InImpl) in1).getProperty(), "testValue");
assertEquals(((InImpl) in1).getWeight(), 523.23);
//test asEager
inj.getInstance(AsEager.class);
//test constant
inj.getInstance(Key.get(String.class, Names.named("test.name")));
}
| public void testGroovyModule(String fileName) {
InputStream resourceAsStream = GroovyModuleTest.class.getClassLoader().getResourceAsStream(fileName);
GroovyShell shell = new GroovyShell();
shell.setProperty("client", "forbes");
GroovyModule gModule = new GroovyModule(resourceAsStream, shell);
Injector inj = Guice.createInjector(gModule);
//from FooModule
inj.getInstance(Foo.class);
//just component
assertTrue(inj.getInstance(TestInterface.class) instanceof First);
//just component with annotation
assertTrue(inj.getInstance(Key.get(TestInterface.class, TestAnnotation.class)) instanceof Second);
//test constant
inj.getInstance(Key.get(String.class, Constant.class));
//test alone
inj.getInstance(Alone.class);
//test in SINGLETON scope
In in1 = inj.getInstance(In.class);
In in2 = inj.getInstance(In.class);
assertTrue(in1 instanceof InImpl);
assertTrue(in2 instanceof InImpl);
assertTrue(in1 == in2);
assertEquals(((InImpl) in1).getProperty(), "testValue");
assertEquals(((InImpl) in1).getWeight(), 523.23);
//test asEager
inj.getInstance(AsEager.class);
//test constant
inj.getInstance(Key.get(String.class, Names.named("test.name")));
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java
index ffb8a5547..d6162a2dc 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/TreeWalker.java
@@ -1,558 +1,558 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2004 Oliver Burn
//
// 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.puppycrawl.tools.checkstyle;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import antlr.RecognitionException;
import antlr.TokenStreamException;
import antlr.TokenStreamRecognitionException;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.Context;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.Utils;
import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaRecognizer;
import com.puppycrawl.tools.checkstyle.grammars.GeneratedJava14Recognizer;
import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaLexer;
import com.puppycrawl.tools.checkstyle.grammars.GeneratedJava14Lexer;
/**
* Responsible for walking an abstract syntax tree and notifying interested
* checks at each each node.
*
* @author Oliver Burn
* @version 1.0
*/
public final class TreeWalker
extends AbstractFileSetCheck
{
/**
* Overrides ANTLR error reporting so we completely control
* checkstyle's output during parsing. This is important because
* we try parsing with several grammers (with/without support for
* <code>assert</code>). We must not write any error messages when
* parsing fails because with the next grammar it might succeed
* and the user will be confused.
*/
private static final class SilentJava14Recognizer
extends GeneratedJava14Recognizer
{
/**
* Creates a new <code>SilentJava14Recognizer</code> instance.
*
* @param aLexer the tokenstream the recognizer operates on.
*/
private SilentJava14Recognizer(GeneratedJava14Lexer aLexer)
{
super(aLexer);
}
/**
* Parser error-reporting function, does nothing.
* @param aRex the exception to be reported
*/
public void reportError(RecognitionException aRex)
{
}
/**
* Parser error-reporting function, does nothing.
* @param aMsg the error message
*/
public void reportError(String aMsg)
{
}
/**
* Parser warning-reporting function, does nothing.
* @param aMsg the error message
*/
public void reportWarning(String aMsg)
{
}
}
/** default distance between tab stops */
private static final int DEFAULT_TAB_WIDTH = 8;
/** maps from token name to checks */
private final Map mTokenToChecks = new HashMap();
/** all the registered checks */
private final Set mAllChecks = new HashSet();
/** the distance between tab stops */
private int mTabWidth = DEFAULT_TAB_WIDTH;
/** cache file **/
private PropertyCacheFile mCache = new PropertyCacheFile(null, null);
/** class loader to resolve classes with. **/
private ClassLoader mClassLoader;
/** context of child components */
private Context mChildContext;
/** a factory for creating submodules (i.e. the Checks) */
private ModuleFactory mModuleFactory;
/**
* Creates a new <code>TreeWalker</code> instance.
*/
public TreeWalker()
{
setFileExtensions(new String[]{"java"});
}
/** @param aTabWidth the distance between tab stops */
public void setTabWidth(int aTabWidth)
{
mTabWidth = aTabWidth;
}
/** @param aFileName the cache file */
public void setCacheFile(String aFileName)
{
final Configuration configuration = getConfiguration();
mCache = new PropertyCacheFile(configuration, aFileName);
}
/** @param aClassLoader class loader to resolve classes with. */
public void setClassLoader(ClassLoader aClassLoader)
{
mClassLoader = aClassLoader;
}
/**
* Sets the module factory for creating child modules (Checks).
* @param aModuleFactory the factory
*/
public void setModuleFactory(ModuleFactory aModuleFactory)
{
mModuleFactory = aModuleFactory;
}
/** @see com.puppycrawl.tools.checkstyle.api.Configurable */
public void finishLocalSetup()
{
DefaultContext checkContext = new DefaultContext();
checkContext.add("classLoader", mClassLoader);
checkContext.add("messages", getMessageCollector());
checkContext.add("severity", getSeverity());
// TODO: hmmm.. this looks less than elegant
// we have just parsed the string,
// now we're recreating it only to parse it again a few moments later
checkContext.add("tabWidth", String.valueOf(mTabWidth));
mChildContext = checkContext;
}
/**
* Instantiates, configures and registers a Check that is specified
* in the provided configuration.
* @see com.puppycrawl.tools.checkstyle.api.AutomaticBean
*/
public void setupChild(Configuration aChildConf)
throws CheckstyleException
{
// TODO: improve the error handing
final String name = aChildConf.getName();
final Object module = mModuleFactory.createModule(name);
if (!(module instanceof Check)) {
throw new CheckstyleException(
"TreeWalker is not allowed as a parent of " + name);
}
final Check c = (Check) module;
c.contextualize(mChildContext);
c.configure(aChildConf);
c.init();
registerCheck(c);
}
/**
* Processes a specified file and reports all errors found.
* @param aFile the file to process
**/
private void process(File aFile)
{
// check if already checked and passed the file
final String fileName = aFile.getPath();
final long timestamp = aFile.lastModified();
if (mCache.alreadyChecked(fileName, timestamp)) {
return;
}
try {
getMessageDispatcher().fireFileStarted(fileName);
final String[] lines = Utils.getLines(fileName, getCharset());
final FileContents contents = new FileContents(fileName, lines);
final DetailAST rootAST = TreeWalker.parse(contents);
walk(rootAST, contents);
}
catch (FileNotFoundException fnfe) {
Utils.getExceptionLogger()
.debug("FileNotFoundException occured.", fnfe);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.fileNotFound",
null,
this.getClass()));
}
catch (IOException ioe) {
Utils.getExceptionLogger().debug("IOException occured.", ioe);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {ioe.getMessage()},
this.getClass()));
}
catch (RecognitionException re) {
Utils.getExceptionLogger()
.debug("RecognitionException occured.", re);
getMessageCollector().add(
new LocalizedMessage(
re.getLine(),
re.getColumn(),
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()},
this.getClass()));
}
catch (TokenStreamRecognitionException tre) {
Utils.getExceptionLogger()
.debug("TokenStreamRecognitionException occured.", tre);
final RecognitionException re = tre.recog;
if (re != null) {
getMessageCollector().add(
new LocalizedMessage(
re.getLine(),
re.getColumn(),
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()},
this.getClass()));
}
else {
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[]
- {"TokenStreamRecognitionException occured."},
+ {"TokenStreamRecognitionException occured."},
this.getClass()));
}
}
catch (TokenStreamException te) {
Utils.getExceptionLogger()
.debug("TokenStreamException occured.", te);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {te.getMessage()},
this.getClass()));
}
catch (Throwable err) {
Utils.getExceptionLogger().debug("Throwable occured.", err);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {"" + err},
this.getClass()));
}
if (getMessageCollector().size() == 0) {
mCache.checkedOk(fileName, timestamp);
}
else {
fireErrors(fileName);
}
getMessageDispatcher().fireFileFinished(fileName);
}
/**
* Register a check for a given configuration.
* @param aCheck the check to register
* @throws CheckstyleException if an error occurs
*/
private void registerCheck(Check aCheck)
throws CheckstyleException
{
int[] tokens = new int[] {}; //safety initialization
final Set checkTokens = aCheck.getTokenNames();
if (!checkTokens.isEmpty()) {
tokens = aCheck.getRequiredTokens();
//register configured tokens
final int acceptableTokens[] = aCheck.getAcceptableTokens();
Arrays.sort(acceptableTokens);
final Iterator it = checkTokens.iterator();
while (it.hasNext()) {
final String token = (String) it.next();
try {
final int tokenId = TokenTypes.getTokenId(token);
if (Arrays.binarySearch(acceptableTokens, tokenId) >= 0) {
registerCheck(token, aCheck);
}
// TODO: else log warning
}
catch (IllegalArgumentException ex) {
throw new CheckstyleException("illegal token \""
+ token + "\" in check " + aCheck, ex);
}
}
}
else {
tokens = aCheck.getDefaultTokens();
}
for (int i = 0; i < tokens.length; i++) {
registerCheck(tokens[i], aCheck);
}
mAllChecks.add(aCheck);
}
/**
* Register a check for a specified token id.
* @param aTokenID the id of the token
* @param aCheck the check to register
*/
private void registerCheck(int aTokenID, Check aCheck)
{
registerCheck(TokenTypes.getTokenName(aTokenID), aCheck);
}
/**
* Register a check for a specified token name
* @param aToken the name of the token
* @param aCheck the check to register
*/
private void registerCheck(String aToken, Check aCheck)
{
ArrayList visitors = (ArrayList) mTokenToChecks.get(aToken);
if (visitors == null) {
visitors = new ArrayList();
mTokenToChecks.put(aToken, visitors);
}
visitors.add(aCheck);
}
/**
* Initiates the walk of an AST.
* @param aAST the root AST
* @param aContents the contents of the file the AST was generated from
*/
private void walk(DetailAST aAST, FileContents aContents)
{
getMessageCollector().reset();
notifyBegin(aAST, aContents);
// empty files are not flagged by javac, will yield aAST == null
if (aAST != null) {
process(aAST);
}
notifyEnd(aAST);
}
/**
* Notify interested checks that about to begin walking a tree.
* @param aRootAST the root of the tree
* @param aContents the contents of the file the AST was generated from
*/
private void notifyBegin(DetailAST aRootAST, FileContents aContents)
{
final Iterator it = mAllChecks.iterator();
while (it.hasNext()) {
final Check check = (Check) it.next();
check.setFileContents(aContents);
check.beginTree(aRootAST);
}
}
/**
* Notify checks that finished walking a tree.
* @param aRootAST the root of the tree
*/
private void notifyEnd(DetailAST aRootAST)
{
final Iterator it = mAllChecks.iterator();
while (it.hasNext()) {
final Check check = (Check) it.next();
check.finishTree(aRootAST);
}
}
/**
* Recursively processes a node calling interested checks at each node.
* @param aAST the node to start from
*/
private void process(DetailAST aAST)
{
if (aAST == null) {
return;
}
notifyVisit(aAST);
final DetailAST child = (DetailAST) aAST.getFirstChild();
if (child != null) {
process(child);
}
notifyLeave(aAST);
final DetailAST sibling = (DetailAST) aAST.getNextSibling();
if (sibling != null) {
process(sibling);
}
}
/**
* Notify interested checks that visiting a node.
* @param aAST the node to notify for
*/
private void notifyVisit(DetailAST aAST)
{
final ArrayList visitors =
(ArrayList) mTokenToChecks.get(
TokenTypes.getTokenName(aAST.getType()));
if (visitors != null) {
for (int i = 0; i < visitors.size(); i++) {
final Check check = (Check) visitors.get(i);
check.visitToken(aAST);
}
}
}
/**
* Notify interested checks that leaving a node.
* @param aAST the node to notify for
*/
private void notifyLeave(DetailAST aAST)
{
final ArrayList visitors =
(ArrayList) mTokenToChecks.get(
TokenTypes.getTokenName(aAST.getType()));
if (visitors != null) {
for (int i = 0; i < visitors.size(); i++) {
final Check check = (Check) visitors.get(i);
check.leaveToken(aAST);
}
}
}
/**
* Static helper method to parses a Java source file.
* @param aContents contains the contents of the file
* @throws RecognitionException if parsing failed
* @throws TokenStreamException if lexing failed
* @return the root of the AST
*/
public static DetailAST parse(FileContents aContents)
throws RecognitionException, TokenStreamException
{
DetailAST rootAST;
try {
// try the 1.4 grammar first, this will succeed for
// all code that compiles without any warnings in JDK 1.4,
// that should cover most cases
final Reader sar = new StringArrayReader(aContents.getLines());
final GeneratedJava14Lexer jl = new GeneratedJava14Lexer(sar);
jl.setFilename(aContents.getFilename());
jl.setCommentListener(aContents);
final GeneratedJava14Recognizer jr =
new SilentJava14Recognizer(jl);
jr.setFilename(aContents.getFilename());
jr.setASTNodeClass(DetailAST.class.getName());
jr.compilationUnit();
rootAST = (DetailAST) jr.getAST();
}
catch (RecognitionException re) {
// Parsing might have failed because the checked
// file contains "assert" as an identifier. Retry with a
// grammar that treats "assert" as an identifier
// and not as a keyword
// Arghh - the pain - duplicate code!
final Reader sar = new StringArrayReader(aContents.getLines());
final GeneratedJavaLexer jl = new GeneratedJavaLexer(sar);
jl.setFilename(aContents.getFilename());
jl.setCommentListener(aContents);
final GeneratedJavaRecognizer jr = new GeneratedJavaRecognizer(jl);
jr.setFilename(aContents.getFilename());
jr.setASTNodeClass(DetailAST.class.getName());
jr.compilationUnit();
rootAST = (DetailAST) jr.getAST();
}
return rootAST;
}
/** @see com.puppycrawl.tools.checkstyle.api.FileSetCheck */
public void process(File[] aFiles)
{
File[] javaFiles = filter(aFiles);
for (int i = 0; i < javaFiles.length; i++) {
process(javaFiles[i]);
}
}
/**
* @see com.puppycrawl.tools.checkstyle.api.FileSetCheck
*/
public void destroy()
{
for (Iterator it = mAllChecks.iterator(); it.hasNext();) {
final Check c = (Check) it.next();
c.destroy();
}
mCache.destroy();
super.destroy();
}
}
| true | true | private void process(File aFile)
{
// check if already checked and passed the file
final String fileName = aFile.getPath();
final long timestamp = aFile.lastModified();
if (mCache.alreadyChecked(fileName, timestamp)) {
return;
}
try {
getMessageDispatcher().fireFileStarted(fileName);
final String[] lines = Utils.getLines(fileName, getCharset());
final FileContents contents = new FileContents(fileName, lines);
final DetailAST rootAST = TreeWalker.parse(contents);
walk(rootAST, contents);
}
catch (FileNotFoundException fnfe) {
Utils.getExceptionLogger()
.debug("FileNotFoundException occured.", fnfe);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.fileNotFound",
null,
this.getClass()));
}
catch (IOException ioe) {
Utils.getExceptionLogger().debug("IOException occured.", ioe);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {ioe.getMessage()},
this.getClass()));
}
catch (RecognitionException re) {
Utils.getExceptionLogger()
.debug("RecognitionException occured.", re);
getMessageCollector().add(
new LocalizedMessage(
re.getLine(),
re.getColumn(),
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()},
this.getClass()));
}
catch (TokenStreamRecognitionException tre) {
Utils.getExceptionLogger()
.debug("TokenStreamRecognitionException occured.", tre);
final RecognitionException re = tre.recog;
if (re != null) {
getMessageCollector().add(
new LocalizedMessage(
re.getLine(),
re.getColumn(),
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()},
this.getClass()));
}
else {
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[]
{"TokenStreamRecognitionException occured."},
this.getClass()));
}
}
catch (TokenStreamException te) {
Utils.getExceptionLogger()
.debug("TokenStreamException occured.", te);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {te.getMessage()},
this.getClass()));
}
catch (Throwable err) {
Utils.getExceptionLogger().debug("Throwable occured.", err);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {"" + err},
this.getClass()));
}
if (getMessageCollector().size() == 0) {
mCache.checkedOk(fileName, timestamp);
}
else {
fireErrors(fileName);
}
getMessageDispatcher().fireFileFinished(fileName);
}
| private void process(File aFile)
{
// check if already checked and passed the file
final String fileName = aFile.getPath();
final long timestamp = aFile.lastModified();
if (mCache.alreadyChecked(fileName, timestamp)) {
return;
}
try {
getMessageDispatcher().fireFileStarted(fileName);
final String[] lines = Utils.getLines(fileName, getCharset());
final FileContents contents = new FileContents(fileName, lines);
final DetailAST rootAST = TreeWalker.parse(contents);
walk(rootAST, contents);
}
catch (FileNotFoundException fnfe) {
Utils.getExceptionLogger()
.debug("FileNotFoundException occured.", fnfe);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.fileNotFound",
null,
this.getClass()));
}
catch (IOException ioe) {
Utils.getExceptionLogger().debug("IOException occured.", ioe);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {ioe.getMessage()},
this.getClass()));
}
catch (RecognitionException re) {
Utils.getExceptionLogger()
.debug("RecognitionException occured.", re);
getMessageCollector().add(
new LocalizedMessage(
re.getLine(),
re.getColumn(),
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()},
this.getClass()));
}
catch (TokenStreamRecognitionException tre) {
Utils.getExceptionLogger()
.debug("TokenStreamRecognitionException occured.", tre);
final RecognitionException re = tre.recog;
if (re != null) {
getMessageCollector().add(
new LocalizedMessage(
re.getLine(),
re.getColumn(),
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {re.getMessage()},
this.getClass()));
}
else {
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[]
{"TokenStreamRecognitionException occured."},
this.getClass()));
}
}
catch (TokenStreamException te) {
Utils.getExceptionLogger()
.debug("TokenStreamException occured.", te);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {te.getMessage()},
this.getClass()));
}
catch (Throwable err) {
Utils.getExceptionLogger().debug("Throwable occured.", err);
getMessageCollector().add(
new LocalizedMessage(
0,
Defn.CHECKSTYLE_BUNDLE,
"general.exception",
new String[] {"" + err},
this.getClass()));
}
if (getMessageCollector().size() == 0) {
mCache.checkedOk(fileName, timestamp);
}
else {
fireErrors(fileName);
}
getMessageDispatcher().fireFileFinished(fileName);
}
|
diff --git a/src/net/sf/freecol/common/model/Tile.java b/src/net/sf/freecol/common/model/Tile.java
index c79c24949..692b69ef5 100644
--- a/src/net/sf/freecol/common/model/Tile.java
+++ b/src/net/sf/freecol/common/model/Tile.java
@@ -1,2293 +1,2298 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.Specification;
import net.sf.freecol.common.model.Map.CircleIterator;
import net.sf.freecol.common.model.Map.Position;
import org.w3c.dom.Element;
/**
* Represents a single tile on the <code>Map</code>.
*
* @see Map
*/
public final class Tile extends FreeColGameObject implements Location, Named, Ownable {
private static final Logger logger = Logger.getLogger(Tile.class.getName());
// Indians' claims on the tile may be one of the following:
public static final int CLAIM_NONE = 0, CLAIM_VISITED = 1, CLAIM_CLAIMED = 2;
private TileType type;
private boolean lostCityRumour;
private int x, y;
private Position position;
private int indianClaim;
/** The player that consider this tile to be their land. */
private Player owner;
/**
* A pointer to the settlement located on this tile or 'null' if there is no
* settlement on this tile.
*/
private Settlement settlement;
/**
* Stores all Improvements and Resources (if any)
*/
private TileItemContainer tileItemContainer;
private UnitContainer unitContainer;
/** The number of adjacent land tiles, if this is an ocean tile */
private int landCount = Integer.MIN_VALUE;
/** The fish bonus of this tile, if it is an ocean tile */
private int fishBonus = Integer.MIN_VALUE;
/**
* Indicates which colony or Indian settlement that owns this tile ('null'
* indicates no owner). A colony owns the tile it is located on, and every
* tile with a worker on it. Note that while units and settlements are owned
* by a player, a tile is owned by a settlement.
*/
private Settlement owningSettlement;
/**
* Stores each player's image of this tile. Only initialized when needed.
*/
private PlayerExploredTile[] playerExploredTiles = null;
public static int NUMBER_OF_TYPES;
private List<TileItem> tileItems;
/**
* A constructor to use.
*
* @param game The <code>Game</code> this <code>Tile</code> belongs to.
* @param type The type.
* @param locX The x-position of this tile on the map.
* @param locY The y-position of this tile on the map.
*/
public Tile(Game game, TileType type, int locX, int locY) {
super(game);
this.type = type;
this.indianClaim = CLAIM_NONE;
unitContainer = new UnitContainer(game, this);
tileItemContainer = new TileItemContainer(game, this);
lostCityRumour = false;
x = locX;
y = locY;
position = new Position(x, y);
owningSettlement = null;
settlement = null;
if (!isViewShared()) {
playerExploredTiles = new PlayerExploredTile[Player.NUMBER_OF_PLAYERS];
}
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param game The <code>Game</code> this <code>Tile</code> should be
* created in.
* @param in The input stream containing the XML.
* @throws XMLStreamException if a problem was encountered during parsing.
*/
public Tile(Game game, XMLStreamReader in) throws XMLStreamException {
super(game, in);
if (!isViewShared()) {
playerExploredTiles = new PlayerExploredTile[Player.NUMBER_OF_PLAYERS];
}
readFromXML(in);
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param game The <code>Game</code> this <code>Tile</code> should be
* created in.
* @param e An XML-element that will be used to initialize this object.
*/
public Tile(Game game, Element e) {
super(game, e);
if (!isViewShared()) {
playerExploredTiles = new PlayerExploredTile[Player.NUMBER_OF_PLAYERS];
}
readFromXMLElement(e);
}
/**
* Initiates a new <code>Tile</code> with the given ID. The object should
* later be initialized by calling either
* {@link #readFromXML(XMLStreamReader)} or
* {@link #readFromXMLElement(Element)}.
*
* @param game The <code>Game</code> in which this object belong.
* @param id The unique identifier for this object.
*/
public Tile(Game game, String id) {
super(game, id);
if (!isViewShared()) {
playerExploredTiles = new PlayerExploredTile[Player.NUMBER_OF_PLAYERS];
}
}
// ------------------------------------------------------------ static methods
/**
* Initializes the important Types for quick reference - performed by Specification.java
* @param numberOfTypes Initializer for NUMBER_OF_TYPES
*/
public static void initialize(int numberOfTypes) {
NUMBER_OF_TYPES = numberOfTypes;
}
public boolean isViewShared() {
return (getGame().getViewOwner() != null);
}
// TODO: what's this supposed to do?
public int getBasicWorkTurns() {
if (type == null) {
return 0;
}
return type.getBasicWorkTurns();
}
/**
* Gets the name of this tile, or shows "unexplored" if not explored by player.
*
* @return The name as a <code>String</code>.
*/
public String getName() {
if (isViewShared()) {
if (isExplored()) {
return getType().getName();
} else {
return Messages.message("unexplored");
}
} else {
Player player = getGame().getCurrentPlayer();
if (player != null) {
if (playerExploredTiles[player.getIndex()] != null) {
PlayerExploredTile pet = playerExploredTiles[player.getIndex()];
if (pet.explored) {
return getType().getName();
}
}
return Messages.message("unexplored");
} else {
logger.warning("player == null");
return null;
}
}
}
/**
* Returns a description of the <code>Tile</code>, with the name of the tile
* and any improvements on it (road/plow/etc) from <code>TileItemContainer</code>.
* @return The description label for this tile
*/
public String getLabel() {
return getName() + tileItemContainer.getLabel();
}
/**
* Returns the name of this location.
*
* @return The name of this location.
*/
public String getLocationName() {
if (settlement == null) {
Settlement nearSettlement = null;
int radius = 8; // more than 8 tiles away is no longer "near"
CircleIterator mapIterator = getMap().getCircleIterator(getPosition(), true, radius);
while (mapIterator.hasNext()) {
nearSettlement = getMap().getTile(mapIterator.nextPosition()).getSettlement();
if (nearSettlement != null && nearSettlement instanceof Colony) {
String name = ((Colony) nearSettlement).getName();
return getName() + " ("
+ Messages.message("nearLocation","%location%", name) + ")";
}
}
return getName();
} else {
return settlement.getLocationName();
}
}
/**
* Gets the distance in tiles between this <code>Tile</code> and the
* specified one.
*
* @param tile The <code>Tile</code> to check the distance to.
* @return Distance
*/
public int getDistanceTo(Tile tile) {
return getGame().getMap().getDistance(getPosition(), tile.getPosition());
}
public GoodsContainer getGoodsContainer() {
return null;
}
public TileItemContainer getTileItemContainer() {
return tileItemContainer;
}
public List<TileImprovement> getTileImprovements() {
return tileItemContainer.getImprovements();
}
/**
* Gets the total value of all treasure trains on this <code>Tile</code>.
*
* @return The total value of all treasure trains on this <code>Tile</code>
* or <code>0</code> if there are no treasure trains at all.
*/
public int getUnitTreasureAmount() {
int amount = 0;
Iterator<Unit> ui = getUnitIterator();
while (ui.hasNext()) {
Unit u = ui.next();
if (u.canCarryTreasure()) {
amount += u.getTreasureAmount();
}
}
return amount;
}
/**
* Returns the treasure train carrying the largest treasure located on this
* <code>Tile</code>.
*
* @return The best treasure train or <code>null</code> if no treasure
* train is located on this <code>Tile</code>.
*/
public Unit getBestTreasureTrain() {
Unit bestTreasureTrain = null;
Iterator<Unit> ui = getUnitIterator();
while (ui.hasNext()) {
Unit u = ui.next();
if (u.canCarryTreasure()
&& (bestTreasureTrain == null || bestTreasureTrain.getTreasureAmount() < u.getTreasureAmount())) {
bestTreasureTrain = u;
}
}
return bestTreasureTrain;
}
/**
* Calculates the value of a future colony at this tile.
*
* @return The value of a future colony located on this tile. This value is
* used by the AI when deciding where to build a new colony.
*/
public int getColonyValue() {
if (!isLand()) {
return 0;
} else if (potential(Goods.FOOD) < 2) {
return 0;
} else if (getSettlement() != null) {
return 0;
} else {
int value = potential(Goods.FOOD) * 3;
boolean nearbyTileHasForest = false;
boolean nearbyTileIsOcean = false;
for (Tile tile : getGame().getMap().getSurroundingTiles(this, 1)) {
if (tile.getColony() != null) {
// can't build next to colony
return 0;
} else if (tile.getSettlement() != null) {
// can build next to an indian settlement
value -= 10;
} else {
if (tile.isLand()) {
for (int i = 0; i < Goods.NUMBER_OF_TYPES; i++) {
value += tile.potential(i);
}
if (tile.isForested()) {
nearbyTileHasForest = true;
}
} else {
nearbyTileIsOcean = true;
value += tile.potential(Goods.FOOD);
}
if (tile.hasResource()) {
value += 20;
}
if (tile.getOwner() != null &&
tile.getOwner() != getGame().getCurrentPlayer()) {
// tile is already owned by someone (and not by us!)
if (tile.getOwner().isEuropean()) {
value -= 20;
} else {
value -= 5;
}
}
}
}
if (hasResource()) {
value -= 10;
}
if (isForested()) {
value -= 5;
}
if (!nearbyTileHasForest) {
value -= 30;
}
if (!nearbyTileIsOcean) {
// TODO: Uncomment when wagon train code has been written:
// value -= 20;
value = 0;
}
return Math.max(0, value);
}
}
/**
* Gets the <code>Unit</code> that is currently defending this
* <code>Tile</code>.
*
* @param attacker The target that would be attacking this tile.
* @return The <code>Unit</code> that has been choosen to defend this
* tile.
*/
public Unit getDefendingUnit(Unit attacker) {
Unit defender = null;
float defensePower = -1.0f;
for(Unit nextUnit : unitContainer.getUnitsClone()) {
float tmpPower = nextUnit.getDefensePower(attacker);
if (this.isLand() != nextUnit.isNaval()
&& (tmpPower > defensePower)) {
defender = nextUnit;
defensePower = tmpPower;
}
}
if (getSettlement() != null) {
if (defender == null || defender.isColonist() && !defender.isArmed() && !defender.isMounted()) {
return settlement.getDefendingUnit(attacker);
}
return defender;
}
return defender;
}
/**
* Returns the cost of moving onto this tile from a given <code>Tile</code>.
*
* <br>
* <br>
*
* This method does not take special unit behavior into account. Use
* {@link Unit#getMoveCost} whenever it is possible.
*
* @param fromTile The <code>Tile</code> the moving {@link Unit} comes
* from.
* @return The cost of moving the unit.
* @see Unit#getMoveCost
*/
public int getMoveCost(Tile fromTile) {
return tileItemContainer.getMoveCost(getType().getBasicMoveCost(), fromTile);
}
/**
* Disposes all units on this <code>Tile</code>.
*/
public void disposeAllUnits() {
unitContainer.disposeAllUnits();
updatePlayerExploredTiles();
}
/**
* Gets the first <code>Unit</code> on this tile.
*
* @return The first <code>Unit</code> on this tile.
*/
public Unit getFirstUnit() {
return unitContainer.getFirstUnit();
}
/**
* Gets the last <code>Unit</code> on this tile.
*
* @return The last <code>Unit</code> on this tile.
*/
public Unit getLastUnit() {
return unitContainer.getLastUnit();
}
/**
* Returns the total amount of Units at this Location. This also includes
* units in a carrier
*
* @return The total amount of Units at this Location.
*/
public int getTotalUnitCount() {
return unitContainer.getTotalUnitCount();
}
/**
* Checks if this <code>Tile</code> contains the specified
* <code>Locatable</code>.
*
* @param locatable The <code>Locatable</code> to test the presence of.
* @return
* <ul>
* <li><i>true</i> if the specified <code>Locatable</code> is
* on this <code>Tile</code> and
* <li><i>false</i> otherwise.
* </ul>
*/
public boolean contains(Locatable locatable) {
if (locatable instanceof Unit) {
return unitContainer.contains((Unit) locatable);
} else if (locatable instanceof TileItem) {
return tileItemContainer.contains((TileItem) locatable);
}
logger.warning("Tile.contains(" + locatable + ") Not implemented yet!");
return false;
}
/**
* Gets the <code>Map</code> in which this <code>Tile</code> belongs.
*
* @return The <code>Map</code>.
*/
public Map getMap() {
return getGame().getMap();
}
/**
* Check if the tile has been explored.
*
* @return true iff tile is known.
*/
public boolean isExplored() {
return type != null;
}
/**
* Returns 'true' if this Tile is a land Tile, 'false' otherwise.
*
* @return 'true' if this Tile is a land Tile, 'false' otherwise.
*/
public boolean isLand() {
return type != null && !type.isWater();
}
/**
* Returns 'true' if this Tile is forested.
*
* @return 'true' if this Tile is forested.
*/
public boolean isForested() {
return type != null && type.isForested();
}
/**
* Returns 'true' if this Tile has a road.
*
* @return 'true' if this Tile has a road.
*/
public boolean hasRoad() {
return getTileItemContainer().hasRoad() || (getSettlement() != null);
}
public TileImprovement getRoad() {
return getTileItemContainer().getRoad();
}
public boolean hasRiver() {
return getTileItemContainer().hasRiver();
}
/**
* Returns 'true' if this Tile has been plowed.
*
* @return 'true' if this Tile has been plowed.
*
* TODO: remove as soon as alternative is clear
*
* @deprecated Plowing is an specification dependent improvement type and should not be needed.
*/
public boolean isPlowed() {
return hasImprovement(FreeCol.getSpecification().getTileImprovementType("model.improvement.Plow"));
}
/**
* Returns 'true' if this Tile has a resource on it.
*
* @return 'true' if this Tile has a resource on it.
*/
public boolean hasResource() {
return getTileItemContainer().hasResource();
}
/**
* Returns the type of this Tile. Returns UNKNOWN if the type of this Tile
* is unknown.
*
* @return The type of this Tile.
*/
public TileType getType() {
return type;
}
/**
* Returns the TileType of this Tile.
*//*
public TileType getTileType() {
return FreeCol.getSpecification().tileType(type);
}
*/
/**
* The nation that consider this tile to be their property.
*
* @return The player owning this tile.
*/
public Player getOwner() {
return owner;
}
/**
* Sets the nation that should consider this tile to be their property.
*
* @param owner The player, new owner of this tile.
* @see #getOwner
*/
public void setOwner(Player owner) {
this.owner = owner;
updatePlayerExploredTiles();
}
/**
* Makes the given player take the ownership of this <code>Tile</code>.
* The tension level is modified accordingly.
*
* @param player The <code>Player</code>.
*/
public void takeOwnership(Player player) {
if (player.getLandPrice(this) > 0) {
Player otherPlayer = getOwner();
if (otherPlayer != null) {
if (!otherPlayer.isEuropean()) {
otherPlayer.modifyTension(player, Tension.TENSION_ADD_LAND_TAKEN);
}
} else {
logger.warning("Could not find player with nation: " + getOwner());
}
}
setOwner(player);
updatePlayerExploredTiles();
}
/**
* Returns the river on this <code>Tile</code> if any
* @return River <code>TileImprovement</code>
*/
public TileImprovement getRiver() {
return tileItemContainer.getRiver();
}
/**
* Returns the style of a river <code>TileImprovement</code> on this <code>Tile</code>.
*
* @return an <code>int</code> value
*/
public int getRiverStyle() {
return tileItemContainer.getRiverStyle();
}
/**
* Adds a river to this tile.
*
* @param magnitude The magnitude of the river at this point
*/
public void addRiver(int magnitude) {
tileItemContainer.addRiver(magnitude);
}
public void setRiverMagnitude(int magnitude) {
tileItemContainer.setRiverMagnitude(magnitude);
}
public void updateRiver() {
tileItemContainer.updateRiver();
}
/**
* Return the number of land tiles adjacent to this one.
*
* @return an <code>int</code> value
*/
public int getLandCount() {
if (landCount < 0) {
landCount = 0;
Iterator<Position> tileIterator = getMap().getAdjacentIterator(getPosition());
while (tileIterator.hasNext()) {
if (getMap().getTile(tileIterator.next()).isLand()) {
landCount++;
}
}
}
return landCount;
}
/**
* Return the fish bonus of this tile. The fish bonus is zero if
* this is a land tile. Otherwise it depends on the number of
* adjacent land tiles and the rivers on these tiles (if any).
*
* @return an <code>int</code> value
*/
public int getFishBonus() {
if (fishBonus < 0) {
fishBonus = 0;
if (!isLand()) {
Iterator<Position> tileIterator = getMap().getAdjacentIterator(getPosition());
while (tileIterator.hasNext()) {
Tile t = getMap().getTile(tileIterator.next());
if (t.isLand()) {
fishBonus++;
}
if (t.hasRiver()) {
fishBonus += t.getRiver().getMagnitude();
}
}
}
}
return fishBonus;
}
/**
* Returns the claim on this Tile.
*
* @return The claim on this Tile.
*/
public int getClaim() {
return indianClaim;
}
/**
* Sets the claim on this Tile.
*
* @param claim The claim on this Tile.
*/
public void setClaim(int claim) {
indianClaim = claim;
updatePlayerExploredTiles();
}
/**
* Puts a <code>Settlement</code> on this <code>Tile</code>. A
* <code>Tile</code> can only have one <code>Settlement</code> located
* on it. The <code>Settlement</code> will also become the owner of this
* <code>Tile</code>.
*
* @param s The <code>Settlement</code> that shall be located on this
* <code>Tile</code>.
* @see #getSettlement
*/
public void setSettlement(Settlement s) {
settlement = s;
owningSettlement = s;
setLostCityRumour(false);
updatePlayerExploredTiles();
}
/**
* Gets the <code>Settlement</code> located on this <code>Tile</code>.
*
* @return The <code>Settlement</code> that is located on this
* <code>Tile</code> or <i>null</i> if no <code>Settlement</code>
* apply.
* @see #setSettlement
*/
public Settlement getSettlement() {
return settlement;
}
/**
* Gets the <code>Colony</code> located on this <code>Tile</code>. Only
* a convenience method for {@link #getSettlement} that makes sure that
* the settlement is a colony.
*
* @return The <code>Colony</code> that is located on this
* <code>Tile</code> or <i>null</i> if no <code>Colony</code>
* apply.
* @see #getSettlement
*/
public Colony getColony() {
if (settlement != null && settlement instanceof Colony) {
return ((Colony) settlement);
}
return null;
}
/**
* Sets the owner of this tile. A <code>Settlement</code> become an owner
* of a <code>Tile</code> when having workers placed on it.
*
* @param owner The Settlement that owns this tile.
* @see #getOwner
*/
public void setOwningSettlement(Settlement owner) {
this.owningSettlement = owner;
updatePlayerExploredTiles();
}
/**
* Gets the owner of this tile.
*
* @return The Settlement that owns this tile.
* @see #setOwner
*/
public Settlement getOwningSettlement() {
return owningSettlement;
}
/**
* Sets the <code>Resource</code> for this <code>Tile</code>
*/
public void setResource(ResourceType r) {
if (r == null) {
return;
}
Resource resource = new Resource(getGame(), this, r);
tileItemContainer.addTileItem(resource);
updatePlayerExploredTiles();
}
/**
* Sets the type for this Tile.
*
* @param t The new TileType for this Tile.
*/
public void setType(TileType t) {
if (t == null) {
throw new IllegalStateException("Tile type must be valid");
}
type = t;
getTileItemContainer().clear();
if (!isLand()) {
settlement = null;
}
updatePlayerExploredTiles();
}
/**
* Returns the x-coordinate of this Tile.
*
* @return The x-coordinate of this Tile.
*/
public int getX() {
return x;
}
/**
* Returns the y-coordinate of this Tile.
*
* @return The y-coordinate of this Tile.
*/
public int getY() {
return y;
}
/**
* Gets the <code>Position</code> of this <code>Tile</code>.
*
* @return The <code>Position</code> of this <code>Tile</code>.
*/
public Position getPosition() {
return position;
}
/**
* Returns true if there is a lost city rumour on this tile.
*
* @return True or false.
*/
public boolean hasLostCityRumour() {
return lostCityRumour;
}
/**
* Sets the lost city rumour for this tile.
*
* @param rumour If <code>true</code> then this <code>Tile</code> will
* have a lost city rumour. The type of rumour will be determined
* by the server.
*/
public void setLostCityRumour(boolean rumour) {
lostCityRumour = rumour;
if (!isLand() && rumour) {
logger.warning("Setting lost city rumour to Ocean.");
// Get the first land type from TileTypeList
for (TileType t : FreeCol.getSpecification().getTileTypeList()) {
if (!t.isWater()) {
setType(t);
break;
}
}
}
updatePlayerExploredTiles();
}
/**
* Check if the tile type is suitable for a <code>Settlement</code>,
* either by a <code>Colony</code> or an <code>IndianSettlement</code>.
*
* @return true if tile suitable for settlement
*/
public boolean isSettleable() {
return getType().canSettle();
}
/**
* Check to see if this tile can be used to construct a new
* <code>Colony</code>. If there is a colony here or in a tile next to
* this one, it is unsuitable for colonization.
*
* @return true if tile is suitable for colonization, false otherwise
*/
public boolean isColonizeable() {
if (!isSettleable()) {
return false;
}
if (settlement != null) {
return false;
}
for (int direction = Map.N; direction <= Map.NW; direction++) {
Tile otherTile = getMap().getNeighbourOrNull(direction, this);
if (otherTile != null) {
Settlement set = otherTile.getSettlement();
if ((set != null) && (set.getOwner().isEuropean())) {
return false;
}
}
}
return true;
}
/**
* Gets a <code>Unit</code> that can become active. This is preferably a
* <code>Unit</code> not currently preforming any work.
*
* @return A <code>Unit</code> with <code>movesLeft > 0</code> or
* <i>null</i> if no such <code>Unit</code> is located on this
* <code>Tile</code>.
*/
public Unit getMovableUnit() {
if (getFirstUnit() != null) {
Iterator<Unit> unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
Iterator<Unit> childUnitIterator = u.getUnitIterator();
while (childUnitIterator.hasNext()) {
Unit childUnit = childUnitIterator.next();
if ((childUnit.getMovesLeft() > 0) && (childUnit.getState() == Unit.ACTIVE)) {
return childUnit;
}
}
if ((u.getMovesLeft() > 0) && (u.getState() == Unit.ACTIVE)) {
return u;
}
}
} else {
return null;
}
Iterator<Unit> unitIterator = getUnitIterator();
while (unitIterator.hasNext()) {
Unit u = unitIterator.next();
Iterator<Unit> childUnitIterator = u.getUnitIterator();
while (childUnitIterator.hasNext()) {
Unit childUnit = childUnitIterator.next();
if ((childUnit.getMovesLeft() > 0)) {
return childUnit;
}
}
if (u.getMovesLeft() > 0) {
return u;
}
}
return null;
}
/**
* Gets the <code>Tile</code> where this <code>Location</code> is
* located or null if no <code>Tile</code> applies.
*
* @return This <code>Tile</code>.
*/
public Tile getTile() {
return this;
}
/**
* Adds a <code>Locatable</code> to this Location.
*
* @param locatable The <code>Locatable</code> to add to this Location.
*/
public void add(Locatable locatable) {
if (locatable instanceof Unit) {
unitContainer.addUnit((Unit) locatable);
} else if (locatable instanceof TileItem) {
tileItemContainer.addTileItem((TileItem) locatable);
} else {
logger.warning("Tried to add an unrecognized 'Locatable' to a tile.");
}
updatePlayerExploredTiles();
}
/**
* Removes a <code>Locatable</code> from this Location.
*
* @param locatable The <code>Locatable</code> to remove from this
* Location.
*/
public void remove(Locatable locatable) {
if (locatable instanceof Unit) {
unitContainer.removeUnit((Unit) locatable);
} else if (locatable instanceof TileItem) {
tileItemContainer.addTileItem((TileItem) locatable);
} else {
logger.warning("Tried to remove an unrecognized 'Locatable' from a tile.");
}
updatePlayerExploredTiles();
}
/**
* Returns the amount of units at this <code>Location</code>.
*
* @return The amount of units at this <code>Location</code>.
*/
public int getUnitCount() {
return unitContainer.getUnitCount();
}
/**
* Gets a
* <code>List/code> of every <code>Unit</code> directly located on this
* <code>Tile</code>. This does not include <code>Unit</code>s located in a
* <code>Settlement</code> or on another <code>Unit</code> on this <code>Tile</code>.
*
* @return The <code>List</code>.
*/
public List<Unit> getUnitList() {
return unitContainer.getUnitsClone();
}
/**
* Gets an <code>Iterator</code> of every <code>Unit</code> directly
* located on this <code>Tile</code>. This does not include
* <code>Unit</code>s located in a <code>Settlement</code> or on
* another <code>Unit</code> on this <code>Tile</code>.
*
* @return The <code>Iterator</code>.
*/
public Iterator<Unit> getUnitIterator() {
return getUnitList().iterator();
}
/**
* Gets a <code>List/code> of every <code>TileItem</code> located on this <code>Tile</code>.
*
* @return The <code>List</code>.
*/
public List<TileItem> getTileItemList() {
return tileItems;
}
/**
* Gets an <code>Iterator</code> of every <code>TileItem</code>
* located on this <code>Tile</code>.
*
* @return The <code>Iterator</code>.
*/
public Iterator<TileItem> getTileItemIterator() {
return getTileItemList().iterator();
}
/**
* Checks whether or not the specified locatable may be added to this
* <code>Location</code>.
*
* @param locatable The <code>Locatable</code> to test the addabillity of.
* @return <i>true</i>.
*/
public boolean canAdd(Locatable locatable) {
return true;
}
/**
* The potential of this tile to produce a certain type of goods.
*
* @param goodsType The type of goods to check the potential for.
* @return The normal potential of this tile to produce that amount of
* goods.
*/
public int potential(GoodsType goodsType) {
return getTileTypePotential(getType(), goodsType, getTileItemContainer(), getFishBonus());
}
/**
* The potential of this tile to produce a certain type of goods.
*
* @param goodsIndex The index of the goods to check the potential for.
* @return The normal potential of this tile to produce that amount of
* goods.
*/
public int potential(int goodsIndex) {
return potential(FreeCol.getSpecification().getGoodsType(goodsIndex));
}
/**
* Gets the maximum potential for producing the given type of goods. The
* maximum potential is the potential of a tile after the tile has been
* plowed/built road on.
*
* @param goodsType The type of goods.
* @return The maximum potential.
*/
public int getMaximumPotential(GoodsType goodsType) {
// If we consider maximum potential to the effect of having
// all possible improvements done, iterate through the
// improvements and get the bonuses of all related ones. If
// there are options to change tiletype using an improvement,
// consider that too.
// Assortment of valid TileTypes and their respective
// TileItemContainers, including this one
List<TileType> tileTypes = new ArrayList<TileType>();
List<TileItemContainer> tiContainers = new ArrayList<TileItemContainer>();
List<TileImprovementType> tiList = FreeCol.getSpecification().getTileImprovementTypeList();
tileTypes.add(getType());
// Get a clone of the tileitemcontainer for calculation
tiContainers.add(getTileItemContainer().clone());
// Add to the list the various possible tile type changes
for (TileImprovementType impType : tiList) {
if (impType.getChange(getType()) != null) {
// There is an option to change TileType
tileTypes.add(impType.getChange(getType()));
// Clone container with the natural improvements of this tile (without resource)
tiContainers.add(getTileItemContainer().clone(false, true));
}
}
int maxProduction = 0;
// For each combination, fill the tiContainers with anything that would increase production of oodsType
for (int i = 0; i < tiContainers.size() ; i++) {
TileType t = tileTypes.get(i);
TileItemContainer tic = tiContainers.get(i);
for (TileImprovementType impType : tiList) {
if (impType.isNatural() || !impType.isTileTypeAllowed(t)) {
continue;
}
if (tic.findTileImprovementType(impType) != null) {
continue;
}
if (impType.getBonus(goodsType) > 0) {
tic.addTileItem(new TileImprovement(getGame(), this, impType));
}
}
maxProduction = Math.max(getTileTypePotential(t, goodsType, tic, getFishBonus()), maxProduction);
}
return maxProduction;
}
/**
* Checks whether this <code>Tile</code> can have a road or not. This
* method will return <code>false</code> if a road has already been built.
*
* @return The result.
*/
public boolean canGetRoad() {
return isLand() && !tileItemContainer.hasRoad();
}
/**
* Finds the TileImprovement of a given Type, or null if there is no match.
*/
public TileImprovement findTileImprovementType(TileImprovementType type) {
return tileItemContainer.findTileImprovementType(type);
}
/**
* Will check whether this tile has a completed improvement of the given
* type.
*
* Useful for checking whether the tile for instance has a road or is
* plowed.
*
* @param type
* The type to check for.
* @return Whether the tile has the improvement and the improvement is
* completed.
*/
public boolean hasImprovement(TileImprovementType type) {
return tileItemContainer.hasImprovement(type);
}
/**
* Calculates the potential of a certain <code>GoodsType</code>.
*
* @param tileType
* The <code>TileType</code>.
* @param goodsType
* The <code>GoodsType</code> to check the potential for.
* @param tiContainer
* The <code>TileItemContainer</code> with any TileItems to
* give bonuses.
* @param fishBonus
* The Bonus Fish to be considered if valid
* @return The amount of goods.
*/
public static int getTileTypePotential(TileType tileType, GoodsType goodsType, TileItemContainer tiContainer, int fishBonus) {
if (!goodsType.isFarmed()) {
return 0;
}
// Get tile potential + bonus if any
int potential = tileType.getPotential(goodsType);
if (tileType.isWater() && goodsType == Goods.FISH) {
potential += fishBonus;
}
if (tiContainer != null) {
potential = tiContainer.getTotalBonusPotential(goodsType, potential);
}
return potential;
}
/**
* Finds the top three outputs based on TileType, TileItemContainer and FishBonus if any
* @param tileType The <code>TileType/code>
* @param tiContainer The <code>TileItemContainer</code>
* @param fishBonus The Bonus Fish to be considered if valid
* @return The sorted top three of the outputs.
*/
public static GoodsType[] getSortedGoodsTop(TileType tileType, TileItemContainer tiContainer, int fishBonus) {
GoodsType[] top = new GoodsType[3];
int[] val = new int[3];
List<GoodsType> goodsTypeList = FreeCol.getSpecification().getGoodsTypeList();
for (GoodsType g : goodsTypeList) {
int potential = getTileTypePotential(tileType, g, tiContainer, fishBonus);
// Higher than the lowest saved value (which is 0 by default)
if (potential > val[2]) {
// Find highest spot to put this item
for (int i = 0; i < 3; i++) {
if (potential > val[i]) {
// Shift and move down
for (int j = 2; j > i; j--) {
top[j] = top[j-1];
val[j] = val[j-1];
}
top[i] = g;
val[i] = potential;
break;
}
}
}
}
return top;
}
public List<GoodsType> getSortedGoodsList(final TileType tileType, final TileItemContainer tiContainer, final int fishBonus) {
List<GoodsType> goodsTypeList = FreeCol.getSpecification().getGoodsTypeList();
Collections.sort(goodsTypeList, new Comparator<GoodsType>() {
public int compare(GoodsType o, GoodsType p) {
return getTileTypePotential(tileType, p, tiContainer, fishBonus) - getTileTypePotential(tileType, o, tiContainer, fishBonus);
}
});
return goodsTypeList;
}
/**
* The type of primary good (food) this tile produces best (used for Town Commons
* squares).
*
* @return The type of primary good best produced by this tile.
*
* @TODO: This might fail if the tile produces more other stuff than food.
*
*/
public GoodsType primaryGoods() {
if (type == null) {
return null;
}
GoodsType[] top = getSortedGoodsTop(type, tileItemContainer, getFishBonus());
for (GoodsType g : top) {
if (g != null && g.isFoodType()) {
return g;
}
}
return null;
}
/**
* The type of secondary good (non-food) this tile produces best (used for Town Commons
* squares).
*
* @return The type of secondary good best produced by this tile (or null if none found).
*/
public GoodsType secondaryGoods() {
if (type == null) {
return null;
}
GoodsType[] top = getSortedGoodsTop(type, tileItemContainer, getFishBonus());
for (GoodsType g : top) {
if (g == null || g.isFoodType()) {
continue;
}
return g;
}
return null;
}
/**
* The type of secondary good (non-food) this <code>TileType</code> produces best.
* (used for Colopedia)
*
* @return The type of secondary good best produced by this tile.
*/
public static GoodsType secondaryGoods(TileType type) {
GoodsType top = null;
int val = 0;
List<GoodsType> goodsTypeList = FreeCol.getSpecification().getGoodsTypeList();
for (GoodsType g : goodsTypeList) {
if (!g.isFoodType()) {
int potential = type.getPotential(g);
if (potential > val) {
val = potential;
top = g;
}
}
}
return top;
}
/**
* The defense/ambush bonus of this tile.
* <p>
* Note that the defense bonus is relative to the unit base strength,
* not to the cumulative strength.
*
* @return The defense modifier (in percent) of this tile.
*/
public int defenseBonus() {
if (type == null || type.getDefenceBonus() == null) {
return 0;
}
return (int) type.getDefenceBonus().getValue();
}
public Modifier getDefenceBonus() {
return type.getDefenceBonus();
}
/**
* This method is called only when a new turn is beginning. It will reduce the quantity of
* the bonus <code>Resource</code> that is on the tile, if any and if applicable.
* @see ResourceType
* @see ColonyTile#newTurn
*/
public void expendResource(GoodsType goodsType, Settlement settlement) {
if (hasResource() && tileItemContainer.getResource().getQuantity() != -1) {
Resource resource = tileItemContainer.getResource();
// Potential of this Tile and Improvements
int potential = getTileTypePotential(getType(), goodsType, null, getFishBonus())
+ tileItemContainer.getImprovementBonusPotential(goodsType);
if (resource.useQuantity(goodsType, potential) == 0) {
addModelMessage(this, "model.tile.resourceExhausted",
new String[][] {
{ "%resource%", resource.getName() },
{ "%colony%", ((Colony) settlement).getName() } },
ModelMessage.WARNING);
}
}
}
/**
* This method writes an XML-representation of this object to the given
* stream.
*
* <br>
* <br>
*
* Only attributes visible to the given <code>Player</code> will be added
* to that representation if <code>showAll</code> is set to
* <code>false</code>.
*
* @param out The target stream.
* @param player The <code>Player</code> this XML-representation should be
* made for, or <code>null</code> if
* <code>showAll == true</code>.
* @param showAll Only attributes visible to <code>player</code> will be
* added to the representation if <code>showAll</code> is set
* to <i>false</i>.
* @param toSavedGame If <code>true</code> then information that is only
* needed when saving a game is added.
* @throws XMLStreamException if there are any problems writing to the
* stream.
*/
protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
throws XMLStreamException {
// Start element:
out.writeStartElement(getXMLElementTagName());
if (toSavedGame && !showAll) {
logger.warning("toSavedGame is true, but showAll is false");
}
PlayerExploredTile pet = null;
if (!(showAll)) {
// We're sending the Tile from the server to the client and showAll
// is false.
if (player != null) {
if (playerExploredTiles[player.getIndex()] != null) {
pet = playerExploredTiles[player.getIndex()];
}
} else {
logger.warning("player == null");
}
}
out.writeAttribute("ID", getId());
out.writeAttribute("x", Integer.toString(x));
out.writeAttribute("y", Integer.toString(y));
if (type != null) {
out.writeAttribute("type", getType().getId());
}
boolean lostCity = (pet == null) ? lostCityRumour : pet.hasLostCityRumour();
out.writeAttribute("lostCityRumour", Boolean.toString(lostCity));
if (owner != null) {
if (getGame().isClientTrusted() || showAll || player.canSee(this)) {
out.writeAttribute("owner", owner.getId());
} else if (pet != null) {
out.writeAttribute("owner", pet.getOwner().getId());
}
}
if ((getGame().isClientTrusted() || showAll || player.canSee(this)) && (owningSettlement != null)) {
out.writeAttribute("owningSettlement", owningSettlement.getId());
}
if (settlement != null) {
if (pet == null || getGame().isClientTrusted() || showAll || settlement.getOwner() == player) {
settlement.toXML(out, player, showAll, toSavedGame);
} else {
if (getColony() != null) {
if (!player.canSee(getTile())) {
if (pet.getColonyUnitCount() != 0) {
out.writeStartElement(Colony.getXMLElementTagName());
out.writeAttribute("ID", getColony().getId());
out.writeAttribute("name", getColony().getName());
out.writeAttribute("owner", getColony().getOwner().getId());
out.writeAttribute("tile", getId());
out.writeAttribute("unitCount", Integer.toString(pet.getColonyUnitCount()));
- Building b = getColony().getStockade();
- out.writeStartElement(Building.getXMLElementTagName());
- out.writeAttribute("ID", b.getId());
- out.writeAttribute("colony", getColony().getId());
- out.writeAttribute("buildingType", Integer.toString(pet.getColonyStockadeLevel()));
- out.writeEndElement();
+ Building stockade = getColony().getStockade();
+ if (stockade != null) {
+ stockade.toXML(out);
+ /*
+ out.writeStartElement(Building.getXMLElementTagName());
+ out.writeAttribute("ID", stockade.getId());
+ out.writeAttribute("colony", getColony().getId());
+ out.writeAttribute("buildingType", Integer.toString(pet.getColonyStockadeLevel()));
+ out.writeEndElement();
+ */
+ }
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), getColony());
emptyGoodsContainer.setFakeID(getColony().getGoodsContainer().getId());
emptyGoodsContainer.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
} // Else: Colony not discovered.
} else {
settlement.toXML(out, player, showAll, toSavedGame);
}
} else if (getSettlement() instanceof IndianSettlement) {
final IndianSettlement is = (IndianSettlement) getSettlement();
out.writeStartElement(IndianSettlement.getXMLElementTagName());
out.writeAttribute("ID", getSettlement().getId());
out.writeAttribute("tile", getId());
out.writeAttribute("owner", getSettlement().getOwner().getId());
out.writeAttribute("tribe", Integer.toString(is.getTribe()));
out.writeAttribute("kind", Integer.toString(is.getKind()));
out.writeAttribute("isCapital", Boolean.toString(is.isCapital()));
if (pet.getSkill() != null) {
out.writeAttribute("learnableSkill", Integer.toString(pet.getSkill().getIndex()));
}
if (pet.getHighlyWantedGoods() != null) {
out.writeAttribute("highlyWantedGoods", pet.getHighlyWantedGoods().getId());
out.writeAttribute("wantedGoods1", pet.getWantedGoods1().getId());
out.writeAttribute("wantedGoods2", pet.getWantedGoods2().getId());
}
out.writeAttribute("hasBeenVisited", Boolean.toString(pet.hasBeenVisited()));
int[] tensionArray = new int[Player.NUMBER_OF_PLAYERS];
for (int i = 0; i < tensionArray.length; i++) {
tensionArray[i] = is.getAlarm(i).getValue();
}
toArrayElement("alarm", tensionArray, out);
if (pet.getMissionary() != null) {
out.writeStartElement("missionary");
pet.getMissionary().toXML(out, player, false, false);
out.writeEndElement();
}
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), getSettlement());
emptyUnitContainer.setFakeID(is.getUnitContainer().getId());
emptyUnitContainer.toXML(out, player, showAll, toSavedGame);
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), is);
emptyGoodsContainer.setFakeID(is.getGoodsContainer().getId());
emptyGoodsContainer.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
} else {
logger.warning("Unknown type of settlement: " + getSettlement());
}
}
}
// Check if the player can see the tile:
// Do not show enemy units or any tileitems on a tile out-of-sight.
if (getGame().isClientTrusted() || showAll
|| (player.canSee(this) && (settlement == null || settlement.getOwner() == player))
|| !getGameOptions().getBoolean(GameOptions.UNIT_HIDING) && player.canSee(this)) {
unitContainer.toXML(out, player, showAll, toSavedGame);
tileItemContainer.toXML(out, player, showAll, toSavedGame);
} else {
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), this);
emptyUnitContainer.setFakeID(unitContainer.getId());
emptyUnitContainer.toXML(out, player, showAll, toSavedGame);
TileItemContainer emptyTileItemContainer = new TileItemContainer(getGame(), this);
emptyTileItemContainer.setFakeID(tileItemContainer.getId());
emptyTileItemContainer.toXML(out, player, showAll, toSavedGame);
}
if (toSavedGame) {
for (int i = 0; i < playerExploredTiles.length; i++) {
if (playerExploredTiles[i] != null && playerExploredTiles[i].isExplored()) {
playerExploredTiles[i].toXML(out, player, showAll, toSavedGame);
}
}
}
out.writeEndElement();
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param in The input stream with the XML.
*/
protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException {
setId(in.getAttributeValue(null, "ID"));
x = Integer.parseInt(in.getAttributeValue(null, "x"));
y = Integer.parseInt(in.getAttributeValue(null, "y"));
position = new Position(x, y);
String typeStr = in.getAttributeValue(null, "type");
if (typeStr != null) {
type = FreeCol.getSpecification().getTileType(typeStr);
}
final String lostCityRumourStr = in.getAttributeValue(null, "lostCityRumour");
if (lostCityRumourStr != null) {
lostCityRumour = Boolean.valueOf(lostCityRumourStr).booleanValue();
} else {
lostCityRumour = false;
}
final String ownerStr = in.getAttributeValue(null, "owner");
if (ownerStr != null) {
owner = (Player) getGame().getFreeColGameObject(ownerStr);
} else {
owner = null;
}
final String owningSettlementStr = in.getAttributeValue(null, "owningSettlement");
if (owningSettlementStr != null) {
owningSettlement = (Settlement) getGame().getFreeColGameObject(owningSettlementStr);
if (owningSettlement == null) {
if (owningSettlementStr.startsWith(IndianSettlement.getXMLElementTagName())) {
owningSettlement = new IndianSettlement(getGame(), owningSettlementStr);
} else if (owningSettlementStr.startsWith(Colony.getXMLElementTagName())) {
owningSettlement = new Colony(getGame(), owningSettlementStr);
} else {
logger.warning("Unknown type of Settlement.");
}
}
} else {
owningSettlement = null;
}
boolean settlementSent = false;
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (in.getLocalName().equals(Colony.getXMLElementTagName())) {
settlement = (Settlement) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (settlement != null) {
settlement.readFromXML(in);
} else {
settlement = new Colony(getGame(), in);
}
settlementSent = true;
} else if (in.getLocalName().equals(IndianSettlement.getXMLElementTagName())) {
settlement = (Settlement) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (settlement != null) {
settlement.readFromXML(in);
} else {
settlement = new IndianSettlement(getGame(), in);
}
settlementSent = true;
} else if (in.getLocalName().equals(UnitContainer.getXMLElementTagName())) {
unitContainer = (UnitContainer) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (unitContainer != null) {
unitContainer.readFromXML(in);
} else {
unitContainer = new UnitContainer(getGame(), this, in);
}
} else if (in.getLocalName().equals(TileItemContainer.getXMLElementTagName())) {
tileItemContainer = (TileItemContainer) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (tileItemContainer != null) {
tileItemContainer.readFromXML(in);
} else {
tileItemContainer = new TileItemContainer(getGame(), this, in);
}
} else if (in.getLocalName().equals("playerExploredTile")) {
// Only from a savegame:
if (playerExploredTiles[Integer.parseInt(in.getAttributeValue(null, "nation"))] == null) {
PlayerExploredTile pet = new PlayerExploredTile(in);
playerExploredTiles[pet.getNation()] = pet;
} else {
playerExploredTiles[Integer.parseInt(in.getAttributeValue(null, "nation"))].readFromXML(in);
}
}
}
if (!settlementSent && settlement != null) {
settlement.dispose();
}
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "tile".
*/
public static String getXMLElementTagName() {
return "tile";
}
/**
* Gets the <code>PlayerExploredTile</code> for the given
* <code>Player</code>.
*
* @param player The <code>Player</code>.
* @see PlayerExploredTile
*/
private PlayerExploredTile getPlayerExploredTile(Player player) {
if (playerExploredTiles == null) {
return null;
}
return playerExploredTiles[player.getIndex()];
}
/**
* Creates a <code>PlayerExploredTile</code> for the given
* <code>Player</code>.
*
* @param player The <code>Player</code>.
* @see PlayerExploredTile
*/
private void createPlayerExploredTile(Player player) {
playerExploredTiles[player.getIndex()] = new PlayerExploredTile(player.getIndex(), getTileItemContainer());
}
/**
* Updates the information about this <code>Tile</code> for the given
* <code>Player</code>.
*
* @param player The <code>Player</code>.
*/
public void updatePlayerExploredTile(Player player) {
int nation = player.getIndex();
if (playerExploredTiles == null || getGame().getViewOwner() != null) {
return;
}
if (playerExploredTiles[nation] == null && !player.isEuropean()) {
return;
}
if (playerExploredTiles[nation] == null) {
logger.warning("'playerExploredTiles' for " + player.getName() + " is 'null'.");
throw new IllegalStateException("'playerExploredTiles' for " + player.getName()
+ " (index " + player.getIndex() + ") "
+ " is 'null'. " + player.canSee(this) + ", "
+ isExploredBy(player) + " ::: " + getPosition());
}
playerExploredTiles[nation].getTileItemInfo(tileItemContainer);
playerExploredTiles[nation].setLostCityRumour(lostCityRumour);
playerExploredTiles[nation].setOwner(owner);
if (getColony() != null) {
playerExploredTiles[nation].setColonyUnitCount(getSettlement().getUnitCount());
// TODO stockade may now be null, but is 0 the right way to set this?
// This might as well be a mistake in the spec.
Building stockade = getColony().getStockade();
if (stockade != null){
playerExploredTiles[nation].setColonyStockadeLevel(stockade.getType().getIndex());
} else {
playerExploredTiles[nation].setColonyStockadeLevel(0);
}
} else if (getSettlement() != null) {
playerExploredTiles[nation].setMissionary(((IndianSettlement) getSettlement()).getMissionary());
/*
* These attributes should not be updated by this method: skill,
* highlyWantedGoods, wantedGoods1 and wantedGoods2
*/
} else {
playerExploredTiles[nation].setColonyUnitCount(0);
}
}
/**
* Updates the <code>PlayerExploredTile</code> for each player. This
* update will only be performed if the player
* {@link Player#canSee(Tile) can see} this <code>Tile</code>.
*/
public void updatePlayerExploredTiles() {
if (playerExploredTiles == null || getGame().getViewOwner() != null) {
return;
}
Iterator<Player> it = getGame().getPlayerIterator();
while (it.hasNext()) {
Player p = it.next();
if (playerExploredTiles[p.getIndex()] == null && !p.isEuropean()) {
continue;
}
if (p.canSee(this)) {
updatePlayerExploredTile(p);
}
}
}
/**
* Updates the information about this <code>Tile</code> for the given
* <code>Player</code>.
*
* @param nation The {@link Player#getNation nation} identifying the
* <code>Player</code>.
*/
public void updatePlayerExploredTile(int nation) {
updatePlayerExploredTile(getGame().getPlayer(nation));
}
/**
* Checks if this <code>Tile</code> has been explored by the given
* <code>Player</code>.
*
* @param player The <code>Player</code>.
* @return <code>true</code> if this <code>Tile</code> has been explored
* by the given <code>Player</code> and <code>false</code>
* otherwise.
*/
public boolean isExploredBy(Player player) {
if (player.isIndian()) {
return true;
}
if (playerExploredTiles[player.getIndex()] == null || !isExplored()) {
return false;
}
return getPlayerExploredTile(player).isExplored();
}
/**
* Sets this <code>Tile</code> to be explored by the given
* <code>Player</code>.
*
* @param player The <code>Player</code>.
* @param explored <code>true</code> if this <code>Tile</code> should be
* explored by the given <code>Player</code> and
* <code>false</code> otherwise.
*/
public void setExploredBy(Player player, boolean explored) {
if (player.isIndian()) {
return;
}
if (playerExploredTiles[player.getIndex()] == null) {
createPlayerExploredTile(player);
}
getPlayerExploredTile(player).setExplored(explored);
updatePlayerExploredTile(player);
}
/**
* Updates the skill available from the <code>IndianSettlement</code>
* located on this <code>Tile</code>.
* <p>
*
* @param player The <code>Player</code> which should get the updated
* information.
* @exception NullPointerException If there is no settlement on this
* <code>Tile</code>.
* @exception ClassCastException If the <code>Settlement</code> on this
* <code>Tile</code> is not an
* <code>IndianSettlement</code>.
* @see IndianSettlement
*/
public void updateIndianSettlementSkill(Player player) {
IndianSettlement is = (IndianSettlement) getSettlement();
PlayerExploredTile pet = getPlayerExploredTile(player);
pet.setSkill(is.getLearnableSkill());
pet.setVisited();
}
/**
* Updates the information about the <code>IndianSettlement</code> located
* on this <code>Tile</code>.
* <p>
*
* @param player The <code>Player</code> which should get the updated
* information.
* @exception NullPointerException If there is no settlement on this
* <code>Tile</code>.
* @exception ClassCastException If the <code>Settlement</code> on this
* <code>Tile</code> is not an
* <code>IndianSettlement</code>.
* @see IndianSettlement
*/
public void updateIndianSettlementInformation(Player player) {
if (player.isIndian()) {
return;
}
PlayerExploredTile playerExploredTile = getPlayerExploredTile(player);
IndianSettlement is = (IndianSettlement) getSettlement();
playerExploredTile.setSkill(is.getLearnableSkill());
playerExploredTile.setHighlyWantedGoods(is.getHighlyWantedGoods());
playerExploredTile.setWantedGoods1(is.getWantedGoods1());
playerExploredTile.setWantedGoods2(is.getWantedGoods2());
playerExploredTile.setVisited();
}
/**
* This class contains the data visible to a specific player.
*
* <br>
* <br>
*
* Sometimes a tile contains information that should not be given to a
* player. For instance; a settlement that was built after the player last
* viewed the tile.
*
* <br>
* <br>
*
* The <code>toXMLElement</code> of {@link Tile} uses information from
* this class to hide information that is not available.
*/
public class PlayerExploredTile {
private int nation;
private boolean explored = false;
private Player owner;
// All known TileItems
private Resource resource;
private List<TileImprovement> improvements;
private TileImprovement road;
private TileImprovement river;
// Colony data:
private int colonyUnitCount = 0, colonyStockadeLevel;
// IndianSettlement data:
private UnitType skill = null;
private GoodsType highlyWantedGoods = null, wantedGoods1 = null, wantedGoods2 = null;
private boolean settlementVisited = false;
private Unit missionary = null;
// private Settlement settlement;
private boolean lostCityRumour;
/**
* Creates a new <code>PlayerExploredTile</code>.
*
* @param nation The nation.
*/
public PlayerExploredTile(int nation, TileItemContainer tic) {
this.nation = nation;
getTileItemInfo(tic);
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param in The XML stream to read the data from.
* @throws XMLStreamException if an error occured during parsing.
*/
public PlayerExploredTile(XMLStreamReader in) throws XMLStreamException {
readFromXML(in);
}
/**
* Copies given TileItemContainer
* @param tic The <code>TileItemContainer</code> to copy from
*/
public void getTileItemInfo(TileItemContainer tic) {
resource = tic.getResource();
improvements = tic.getImprovements();
road = tic.getRoad();
river = tic.getRiver();
}
public void setColonyUnitCount(int colonyUnitCount) {
this.colonyUnitCount = colonyUnitCount;
}
public int getColonyUnitCount() {
return colonyUnitCount;
}
public void setColonyStockadeLevel(int colonyStockadeLevel) {
this.colonyStockadeLevel = colonyStockadeLevel;
}
public int getColonyStockadeLevel() {
return colonyStockadeLevel;
}
/*
public void setRoad(boolean road) {
this.road = road;
}
*/
public boolean hasRoad() {
return (road != null);
}
public TileImprovement getRoad() {
return road;
}
public boolean hasRiver() {
return (river != null);
}
public TileImprovement getRiver() {
return river;
}
public void setLostCityRumour(boolean lostCityRumour) {
this.lostCityRumour = lostCityRumour;
}
public boolean hasLostCityRumour() {
return lostCityRumour;
}
public void setExplored(boolean explored) {
this.explored = explored;
}
public void setSkill(UnitType newSkill) {
this.skill = newSkill;
}
public UnitType getSkill() {
return skill;
}
public void setOwner(Player owner) {
this.owner = owner;
}
public Player getOwner() {
return owner;
}
public void setHighlyWantedGoods(GoodsType highlyWantedGoods) {
this.highlyWantedGoods = highlyWantedGoods;
}
public GoodsType getHighlyWantedGoods() {
return highlyWantedGoods;
}
public void setWantedGoods1(GoodsType wantedGoods1) {
this.wantedGoods1 = wantedGoods1;
}
public GoodsType getWantedGoods1() {
return wantedGoods1;
}
public void setWantedGoods2(GoodsType wantedGoods2) {
this.wantedGoods2 = wantedGoods2;
}
public GoodsType getWantedGoods2() {
return wantedGoods2;
}
public void setMissionary(Unit missionary) {
this.missionary = missionary;
}
public Unit getMissionary() {
return missionary;
}
private void setVisited() {
settlementVisited = true;
}
private boolean hasBeenVisited() {
return settlementVisited;
}
// TODO: find out what this is supposed to do
public int getBasicWorkTurns() {
return 0;
}
// TODO: find out what this is supposed to do
public int getAddWorkTurns() {
return 0;
}
/**
* Checks if this <code>Tile</code> has been explored.
*
* @return <i>true</i> if the tile has been explored.
*/
public boolean isExplored() {
return explored;
}
/**
* Gets the nation owning this object.
*
* @return The nation of this <code>PlayerExploredTile</code>.
*/
public int getNation() {
return nation;
}
/**
* This method writes an XML-representation of this object to the given
* stream.
*
* <br>
* <br>
*
* Only attributes visible to the given <code>Player</code> will be
* added to that representation if <code>showAll</code> is set to
* <code>false</code>.
*
* @param out The target stream.
* @param player The <code>Player</code> this XML-representation
* should be made for, or <code>null</code> if
* <code>showAll == true</code>.
* @param showAll Only attributes visible to <code>player</code> will
* be added to the representation if <code>showAll</code>
* is set to <i>false</i>.
* @param toSavedGame If <code>true</code> then information that is
* only needed when saving a game is added.
* @throws XMLStreamException if there are any problems writing to the
* stream.
*/
public void toXML(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
throws XMLStreamException {
// Start element:
out.writeStartElement("playerExploredTile");
out.writeAttribute("nation", Integer.toString(nation));
if (!explored) {
out.writeAttribute("explored", Boolean.toString(explored));
}
if (Tile.this.hasLostCityRumour()) {
out.writeAttribute("lostCityRumour", Boolean.toString(lostCityRumour));
}
if (Tile.this.getOwner() != owner && owner != null) {
out.writeAttribute("owner", owner.getId());
}
if (colonyUnitCount != 0) {
out.writeAttribute("colonyUnitCount", Integer.toString(colonyUnitCount));
out.writeAttribute("colonyStockadeLevel", Integer.toString(colonyStockadeLevel));
}
if (skill != null) {
out.writeAttribute("learnableSkill", Integer.toString(skill.getIndex()));
}
out.writeAttribute("settlementVisited", Boolean.toString(settlementVisited));
if (highlyWantedGoods != null) {
out.writeAttribute("highlyWantedGoods", Integer.toString(highlyWantedGoods.getIndex()));
out.writeAttribute("wantedGoods1", Integer.toString(wantedGoods1.getIndex()));
out.writeAttribute("wantedGoods2", Integer.toString(wantedGoods2.getIndex()));
}
if (missionary != null) {
out.writeStartElement("missionary");
missionary.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
}
if (hasResource()) {
resource.toXML(out, player, showAll, toSavedGame);
}
for (TileImprovement t : improvements) {
t.toXML(out, player, showAll, toSavedGame);
}
out.writeEndElement();
}
/**
* Initialize this object from an XML-representation of this object.
*
* @param in The input stream with the XML.
* @throws XMLStreamException if an error occured during parsing.
*/
public void readFromXML(XMLStreamReader in) throws XMLStreamException {
nation = Integer.parseInt(in.getAttributeValue(null, "nation"));
final String exploredStr = in.getAttributeValue(null, "explored");
if (exploredStr != null) {
explored = Boolean.valueOf(exploredStr).booleanValue();
} else {
explored = true;
}
final String lostCityRumourStr = in.getAttributeValue(null, "lostCityRumour");
if (lostCityRumourStr != null) {
lostCityRumour = Boolean.valueOf(lostCityRumourStr).booleanValue();
} else {
lostCityRumour = Tile.this.hasLostCityRumour();
}
final String ownerStr = in.getAttributeValue(null, "owner");
if (ownerStr != null) {
owner = (Player) getGame().getFreeColGameObject(ownerStr);
} else {
owner = Tile.this.getOwner();
}
final String colonyUnitCountStr = in.getAttributeValue(null, "colonyUnitCount");
if (colonyUnitCountStr != null) {
colonyUnitCount = Integer.parseInt(colonyUnitCountStr);
colonyStockadeLevel = Integer.parseInt(in.getAttributeValue(null, "colonyStockadeLevel"));
} else {
colonyUnitCount = 0;
}
Specification spec = FreeCol.getSpecification();
final String learnableSkillStr = in.getAttributeValue(null, "learnableSkill");
if (learnableSkillStr != null) {
skill = spec.getUnitType(Integer.parseInt(learnableSkillStr));
} else {
skill = null;
}
settlementVisited = Boolean.valueOf(in.getAttributeValue(null, "settlementVisited")).booleanValue();
final String highlyWantedGoodsStr = in.getAttributeValue(null, "highlyWantedGoods");
if (highlyWantedGoodsStr != null) {
highlyWantedGoods = spec.getGoodsType(Integer.parseInt(highlyWantedGoodsStr));
wantedGoods1 = spec.getGoodsType(Integer.parseInt(in.getAttributeValue(null, "wantedGoods1")));
wantedGoods2 = spec.getGoodsType(Integer.parseInt(in.getAttributeValue(null, "wantedGoods2")));
} else {
highlyWantedGoods = null;
wantedGoods1 = null;
wantedGoods2 = null;
}
missionary = null;
TileItemContainer tileItemContainer = new TileItemContainer(getGame(), Tile.this);
while (in.nextTag() != XMLStreamConstants.END_ELEMENT) {
if (in.getLocalName().equals("missionary")) {
in.nextTag();
missionary = (Unit) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (missionary == null) {
missionary = new Unit(getGame(), in);
} else {
missionary.readFromXML(in);
}
} else if (in.getLocalName().equals(Resource.getXMLElementTagName())) {
Resource resource = (Resource) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (resource != null) {
resource.readFromXML(in);
} else {
resource = new Resource(getGame(), in);
}
tileItemContainer.addTileItem(resource);
} else if (in.getLocalName().equals(TileImprovement.getXMLElementTagName())) {
TileImprovement ti = (TileImprovement) getGame().getFreeColGameObject(in.getAttributeValue(null, "ID"));
if (ti != null) {
ti.readFromXML(in);
} else {
ti = new TileImprovement(getGame(), in);
}
tileItemContainer.addTileItem(ti);
}
}
getTileItemInfo(tileItemContainer);
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "playerExploredTile".
*/
/*
* public static String getXMLElementTagName() { return
* "playerExploredTile"; }
*/
}
/**
* Returns the number of turns it takes for a non-expert pioneer to perform
* the given <code>TileImprovementType</code>. It will check if it is valid
* for this <code>TileType</code>.
*
* @param workType The <code>TileImprovementType</code>
*
* @return The number of turns it should take a non-expert pioneer to finish
* the work.
*/
public int getWorkAmount(TileImprovementType workType) {
if (workType == null) {
return -1;
}
if (!workType.isTileAllowed(this)) {
return -1;
}
// Return the basic work turns + additional work turns
return (getType().getBasicWorkTurns() + workType.getAddWorkTurns());
}
/**
* Returns the unit who is occupying the tile
* @return the unit who is occupying the tile
* @see #isOccupied()
*/
public Unit getOccupyingUnit() {
Unit unit = getFirstUnit();
Player owner = null;
if (owningSettlement != null) {
owner = owningSettlement.getOwner();
}
if (owner != null && unit != null && unit.getOwner() != owner
&& owner.getStance(unit.getOwner()) != Player.ALLIANCE) {
for(Unit enemyUnit : getUnitList()) {
if (enemyUnit.isOffensiveUnit() && enemyUnit.getState() == Unit.FORTIFIED) {
return enemyUnit;
}
}
}
return null;
}
/**
* Checks whether there is a fortified enemy unit in the tile.
* Units can't produce in occupied tiles
* @return <code>true</code> if an fortified enemy unit is in the tile
*/
public boolean isOccupied() {
return getOccupyingUnit() != null;
}
}
| true | true | protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
throws XMLStreamException {
// Start element:
out.writeStartElement(getXMLElementTagName());
if (toSavedGame && !showAll) {
logger.warning("toSavedGame is true, but showAll is false");
}
PlayerExploredTile pet = null;
if (!(showAll)) {
// We're sending the Tile from the server to the client and showAll
// is false.
if (player != null) {
if (playerExploredTiles[player.getIndex()] != null) {
pet = playerExploredTiles[player.getIndex()];
}
} else {
logger.warning("player == null");
}
}
out.writeAttribute("ID", getId());
out.writeAttribute("x", Integer.toString(x));
out.writeAttribute("y", Integer.toString(y));
if (type != null) {
out.writeAttribute("type", getType().getId());
}
boolean lostCity = (pet == null) ? lostCityRumour : pet.hasLostCityRumour();
out.writeAttribute("lostCityRumour", Boolean.toString(lostCity));
if (owner != null) {
if (getGame().isClientTrusted() || showAll || player.canSee(this)) {
out.writeAttribute("owner", owner.getId());
} else if (pet != null) {
out.writeAttribute("owner", pet.getOwner().getId());
}
}
if ((getGame().isClientTrusted() || showAll || player.canSee(this)) && (owningSettlement != null)) {
out.writeAttribute("owningSettlement", owningSettlement.getId());
}
if (settlement != null) {
if (pet == null || getGame().isClientTrusted() || showAll || settlement.getOwner() == player) {
settlement.toXML(out, player, showAll, toSavedGame);
} else {
if (getColony() != null) {
if (!player.canSee(getTile())) {
if (pet.getColonyUnitCount() != 0) {
out.writeStartElement(Colony.getXMLElementTagName());
out.writeAttribute("ID", getColony().getId());
out.writeAttribute("name", getColony().getName());
out.writeAttribute("owner", getColony().getOwner().getId());
out.writeAttribute("tile", getId());
out.writeAttribute("unitCount", Integer.toString(pet.getColonyUnitCount()));
Building b = getColony().getStockade();
out.writeStartElement(Building.getXMLElementTagName());
out.writeAttribute("ID", b.getId());
out.writeAttribute("colony", getColony().getId());
out.writeAttribute("buildingType", Integer.toString(pet.getColonyStockadeLevel()));
out.writeEndElement();
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), getColony());
emptyGoodsContainer.setFakeID(getColony().getGoodsContainer().getId());
emptyGoodsContainer.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
} // Else: Colony not discovered.
} else {
settlement.toXML(out, player, showAll, toSavedGame);
}
} else if (getSettlement() instanceof IndianSettlement) {
final IndianSettlement is = (IndianSettlement) getSettlement();
out.writeStartElement(IndianSettlement.getXMLElementTagName());
out.writeAttribute("ID", getSettlement().getId());
out.writeAttribute("tile", getId());
out.writeAttribute("owner", getSettlement().getOwner().getId());
out.writeAttribute("tribe", Integer.toString(is.getTribe()));
out.writeAttribute("kind", Integer.toString(is.getKind()));
out.writeAttribute("isCapital", Boolean.toString(is.isCapital()));
if (pet.getSkill() != null) {
out.writeAttribute("learnableSkill", Integer.toString(pet.getSkill().getIndex()));
}
if (pet.getHighlyWantedGoods() != null) {
out.writeAttribute("highlyWantedGoods", pet.getHighlyWantedGoods().getId());
out.writeAttribute("wantedGoods1", pet.getWantedGoods1().getId());
out.writeAttribute("wantedGoods2", pet.getWantedGoods2().getId());
}
out.writeAttribute("hasBeenVisited", Boolean.toString(pet.hasBeenVisited()));
int[] tensionArray = new int[Player.NUMBER_OF_PLAYERS];
for (int i = 0; i < tensionArray.length; i++) {
tensionArray[i] = is.getAlarm(i).getValue();
}
toArrayElement("alarm", tensionArray, out);
if (pet.getMissionary() != null) {
out.writeStartElement("missionary");
pet.getMissionary().toXML(out, player, false, false);
out.writeEndElement();
}
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), getSettlement());
emptyUnitContainer.setFakeID(is.getUnitContainer().getId());
emptyUnitContainer.toXML(out, player, showAll, toSavedGame);
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), is);
emptyGoodsContainer.setFakeID(is.getGoodsContainer().getId());
emptyGoodsContainer.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
} else {
logger.warning("Unknown type of settlement: " + getSettlement());
}
}
}
// Check if the player can see the tile:
// Do not show enemy units or any tileitems on a tile out-of-sight.
if (getGame().isClientTrusted() || showAll
|| (player.canSee(this) && (settlement == null || settlement.getOwner() == player))
|| !getGameOptions().getBoolean(GameOptions.UNIT_HIDING) && player.canSee(this)) {
unitContainer.toXML(out, player, showAll, toSavedGame);
tileItemContainer.toXML(out, player, showAll, toSavedGame);
} else {
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), this);
emptyUnitContainer.setFakeID(unitContainer.getId());
emptyUnitContainer.toXML(out, player, showAll, toSavedGame);
TileItemContainer emptyTileItemContainer = new TileItemContainer(getGame(), this);
emptyTileItemContainer.setFakeID(tileItemContainer.getId());
emptyTileItemContainer.toXML(out, player, showAll, toSavedGame);
}
if (toSavedGame) {
for (int i = 0; i < playerExploredTiles.length; i++) {
if (playerExploredTiles[i] != null && playerExploredTiles[i].isExplored()) {
playerExploredTiles[i].toXML(out, player, showAll, toSavedGame);
}
}
}
out.writeEndElement();
}
| protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame)
throws XMLStreamException {
// Start element:
out.writeStartElement(getXMLElementTagName());
if (toSavedGame && !showAll) {
logger.warning("toSavedGame is true, but showAll is false");
}
PlayerExploredTile pet = null;
if (!(showAll)) {
// We're sending the Tile from the server to the client and showAll
// is false.
if (player != null) {
if (playerExploredTiles[player.getIndex()] != null) {
pet = playerExploredTiles[player.getIndex()];
}
} else {
logger.warning("player == null");
}
}
out.writeAttribute("ID", getId());
out.writeAttribute("x", Integer.toString(x));
out.writeAttribute("y", Integer.toString(y));
if (type != null) {
out.writeAttribute("type", getType().getId());
}
boolean lostCity = (pet == null) ? lostCityRumour : pet.hasLostCityRumour();
out.writeAttribute("lostCityRumour", Boolean.toString(lostCity));
if (owner != null) {
if (getGame().isClientTrusted() || showAll || player.canSee(this)) {
out.writeAttribute("owner", owner.getId());
} else if (pet != null) {
out.writeAttribute("owner", pet.getOwner().getId());
}
}
if ((getGame().isClientTrusted() || showAll || player.canSee(this)) && (owningSettlement != null)) {
out.writeAttribute("owningSettlement", owningSettlement.getId());
}
if (settlement != null) {
if (pet == null || getGame().isClientTrusted() || showAll || settlement.getOwner() == player) {
settlement.toXML(out, player, showAll, toSavedGame);
} else {
if (getColony() != null) {
if (!player.canSee(getTile())) {
if (pet.getColonyUnitCount() != 0) {
out.writeStartElement(Colony.getXMLElementTagName());
out.writeAttribute("ID", getColony().getId());
out.writeAttribute("name", getColony().getName());
out.writeAttribute("owner", getColony().getOwner().getId());
out.writeAttribute("tile", getId());
out.writeAttribute("unitCount", Integer.toString(pet.getColonyUnitCount()));
Building stockade = getColony().getStockade();
if (stockade != null) {
stockade.toXML(out);
/*
out.writeStartElement(Building.getXMLElementTagName());
out.writeAttribute("ID", stockade.getId());
out.writeAttribute("colony", getColony().getId());
out.writeAttribute("buildingType", Integer.toString(pet.getColonyStockadeLevel()));
out.writeEndElement();
*/
}
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), getColony());
emptyGoodsContainer.setFakeID(getColony().getGoodsContainer().getId());
emptyGoodsContainer.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
} // Else: Colony not discovered.
} else {
settlement.toXML(out, player, showAll, toSavedGame);
}
} else if (getSettlement() instanceof IndianSettlement) {
final IndianSettlement is = (IndianSettlement) getSettlement();
out.writeStartElement(IndianSettlement.getXMLElementTagName());
out.writeAttribute("ID", getSettlement().getId());
out.writeAttribute("tile", getId());
out.writeAttribute("owner", getSettlement().getOwner().getId());
out.writeAttribute("tribe", Integer.toString(is.getTribe()));
out.writeAttribute("kind", Integer.toString(is.getKind()));
out.writeAttribute("isCapital", Boolean.toString(is.isCapital()));
if (pet.getSkill() != null) {
out.writeAttribute("learnableSkill", Integer.toString(pet.getSkill().getIndex()));
}
if (pet.getHighlyWantedGoods() != null) {
out.writeAttribute("highlyWantedGoods", pet.getHighlyWantedGoods().getId());
out.writeAttribute("wantedGoods1", pet.getWantedGoods1().getId());
out.writeAttribute("wantedGoods2", pet.getWantedGoods2().getId());
}
out.writeAttribute("hasBeenVisited", Boolean.toString(pet.hasBeenVisited()));
int[] tensionArray = new int[Player.NUMBER_OF_PLAYERS];
for (int i = 0; i < tensionArray.length; i++) {
tensionArray[i] = is.getAlarm(i).getValue();
}
toArrayElement("alarm", tensionArray, out);
if (pet.getMissionary() != null) {
out.writeStartElement("missionary");
pet.getMissionary().toXML(out, player, false, false);
out.writeEndElement();
}
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), getSettlement());
emptyUnitContainer.setFakeID(is.getUnitContainer().getId());
emptyUnitContainer.toXML(out, player, showAll, toSavedGame);
GoodsContainer emptyGoodsContainer = new GoodsContainer(getGame(), is);
emptyGoodsContainer.setFakeID(is.getGoodsContainer().getId());
emptyGoodsContainer.toXML(out, player, showAll, toSavedGame);
out.writeEndElement();
} else {
logger.warning("Unknown type of settlement: " + getSettlement());
}
}
}
// Check if the player can see the tile:
// Do not show enemy units or any tileitems on a tile out-of-sight.
if (getGame().isClientTrusted() || showAll
|| (player.canSee(this) && (settlement == null || settlement.getOwner() == player))
|| !getGameOptions().getBoolean(GameOptions.UNIT_HIDING) && player.canSee(this)) {
unitContainer.toXML(out, player, showAll, toSavedGame);
tileItemContainer.toXML(out, player, showAll, toSavedGame);
} else {
UnitContainer emptyUnitContainer = new UnitContainer(getGame(), this);
emptyUnitContainer.setFakeID(unitContainer.getId());
emptyUnitContainer.toXML(out, player, showAll, toSavedGame);
TileItemContainer emptyTileItemContainer = new TileItemContainer(getGame(), this);
emptyTileItemContainer.setFakeID(tileItemContainer.getId());
emptyTileItemContainer.toXML(out, player, showAll, toSavedGame);
}
if (toSavedGame) {
for (int i = 0; i < playerExploredTiles.length; i++) {
if (playerExploredTiles[i] != null && playerExploredTiles[i].isExplored()) {
playerExploredTiles[i].toXML(out, player, showAll, toSavedGame);
}
}
}
out.writeEndElement();
}
|
diff --git a/Proj1.java b/Proj1.java
index 68964bc..5512f2b 100644
--- a/Proj1.java
+++ b/Proj1.java
@@ -1,298 +1,298 @@
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.Math;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
/*
* This is the skeleton for CS61c project 1, Fall 2013.
*
* Reminder: DO NOT SHARE CODE OR ALLOW ANOTHER STUDENT TO READ YOURS.
* EVEN FOR DEBUGGING. THIS MEANS YOU.
*
*/
public class Proj1{
/*
* Inputs is a set of (docID, document contents) pairs.
*/
public static class Map1 extends Mapper<WritableComparable, Text, Text, DoublePair> {
/** Regex pattern to find words (alphanumeric + _). */
final static Pattern WORD_PATTERN = Pattern.compile("\\w+");
private String targetGram = null;
private int funcNum = 0;
/*
* Setup gets called exactly once for each mapper, before map() gets called the first time.
* It's a good place to do configuration or setup that can be shared across many calls to map
*/
@Override
public void setup(Context context) {
targetGram = context.getConfiguration().get("targetWord").toLowerCase();
try {
funcNum = Integer.parseInt(context.getConfiguration().get("funcNum"));
} catch (NumberFormatException e) {
/* Do nothing. */
}
}
@Override
public void map(WritableComparable docID, Text docContents, Context context)
throws IOException, InterruptedException {
Matcher matcher = WORD_PATTERN.matcher(docContents.toString());
Func func = funcFromNum(funcNum);
// YOUR CODE HERE
// make a copy of the Matcher for parsing, record indices of targets to list
Matcher copy = WORD_PATTERN.matcher(docContents.toString());
List<Integer> targets = new ArrayList<Integer>();
int count = 0;
while(copy.find()){
String w = copy.group().toLowerCase();
if(w.equals(targetGram))
targets.add(new Integer(count));
count++;
}
if(targets.isEmpty()){
while(matcher.find()){
context.write(new Text(matcher.group()), new DoublePair(1.0, func.f(Double.POSITIVE_INFINITY)));
}
}
else{
count = 0;
while(matcher.find()){
String word = matcher.group().toLowerCase();
// if word is not target word
if(!word.equals(targetGram))
context.write(word, new DoublePair(1.0, func.f(closestDist(targets, count++))));
}
}
}
// helper function to calculate shortest distance between target words and current word
private int closestDist(List<Integer> targets, int d){
int min = Integer.MAX_VALUE;
for(Integer i : targets){
if(Math.abs(d - i.intValue()) < min)
min = Math.abs(d - i.intValue());
}
return min;
}
/** Returns the Func corresponding to FUNCNUM*/
private Func funcFromNum(int funcNum) {
Func func = null;
switch (funcNum) {
case 0:
func = new Func() {
public double f(double d) {
return d == Double.POSITIVE_INFINITY ? 0.0 : 1.0;
}
};
break;
case 1:
func = new Func() {
public double f(double d) {
return d == Double.POSITIVE_INFINITY ? 0.0 : 1.0 + 1.0 / d;
}
};
break;
case 2:
func = new Func() {
public double f(double d) {
return d == Double.POSITIVE_INFINITY ? 0.0 : 1.0 + Math.sqrt(d);
}
};
break;
}
return func;
}
}
/** Here's where you'll be implementing your combiner. It must be non-trivial for you to receive credit. */
public static class Combine1 extends Reducer<Text, Text, Text, Text> {
@Override
public void reduce(Text key, Iterable<Text> values,
Context context) throws IOException, InterruptedException {
// YOUR CODE HERE
}
}
public static class Reduce1 extends Reducer<Text, DoublePair, DoubleWritable, Text> {
@Override
public void reduce(Text key, Iterable<DoublePair> values,
Context context) throws IOException, InterruptedException {
// YOUR CODE HERE
double sum = 0.0;
int count = 0;
for(DoublePair pair : values){
count += pair.getDouble1;
sum += pair.getDouble2;
}
if(sum > 0)
context.write(new DoubleWriteable(sum * pow(Math.log(sum), 3) / count), key);
else
context.write(new DoubleWriteable(0), key);
}
}
public static class Map2 extends Mapper<DoubleWritable, Text, DoubleWritable, Text> {
//maybe do something, maybe don't
}
public static class Reduce2 extends Reducer<DoubleWritable, Text, DoubleWritable, Text> {
int n = 0;
static int N_TO_OUTPUT = 100;
/*
* Setup gets called exactly once for each reducer, before reduce() gets called the first time.
* It's a good place to do configuration or setup that can be shared across many calls to reduce
*/
@Override
protected void setup(Context c) {
n = 0;
}
/*
* Your output should be a in the form of (DoubleWritable score, Text word)
* where score is the co-occurrence value for the word. Your output should be
* sorted from largest co-occurrence to smallest co-occurrence.
*/
@Override
public void reduce(DoubleWritable key, Iterable<Text> values,
Context context) throws IOException, InterruptedException {
// YOUR CODE HERE
}
}
/*
* You shouldn't need to modify this function much. If you think you have a good reason to,
* you might want to discuss with staff.
*
* The skeleton supports several options.
* if you set runJob2 to false, only the first job will run and output will be
* in TextFile format, instead of SequenceFile. This is intended as a debugging aid.
*
* If you set combiner to false, the combiner will not run. This is also
* intended as a debugging aid. Turning on and off the combiner shouldn't alter
* your results. Since the framework doesn't make promises about when it'll
* invoke combiners, it's an error to assume anything about how many times
* values will be combined.
*/
public static void main(String[] rawArgs) throws Exception {
GenericOptionsParser parser = new GenericOptionsParser(rawArgs);
Configuration conf = parser.getConfiguration();
String[] args = parser.getRemainingArgs();
boolean runJob2 = conf.getBoolean("runJob2", true);
boolean combiner = conf.getBoolean("combiner", false);
System.out.println("Target word: " + conf.get("targetWord"));
System.out.println("Function num: " + conf.get("funcNum"));
if(runJob2)
System.out.println("running both jobs");
else
System.out.println("for debugging, only running job 1");
if(combiner)
System.out.println("using combiner");
else
System.out.println("NOT using combiner");
Path inputPath = new Path(args[0]);
Path middleOut = new Path(args[1]);
Path finalOut = new Path(args[2]);
FileSystem hdfs = middleOut.getFileSystem(conf);
int reduceCount = conf.getInt("reduces", 32);
if(hdfs.exists(middleOut)) {
System.err.println("can't run: " + middleOut.toUri().toString() + " already exists");
System.exit(1);
}
if(finalOut.getFileSystem(conf).exists(finalOut) ) {
System.err.println("can't run: " + finalOut.toUri().toString() + " already exists");
System.exit(1);
}
{
Job firstJob = new Job(conf, "job1");
firstJob.setJarByClass(Map1.class);
/* You may need to change things here */
firstJob.setMapOutputKeyClass(Text.class);
- firstJob.setMapOutputValueClass(Text.class);
+ firstJob.setMapOutputValueClass(DoublePair.class);
firstJob.setOutputKeyClass(DoubleWritable.class);
firstJob.setOutputValueClass(Text.class);
/* End region where we expect you to perhaps need to change things. */
firstJob.setMapperClass(Map1.class);
firstJob.setReducerClass(Reduce1.class);
firstJob.setNumReduceTasks(reduceCount);
if(combiner)
firstJob.setCombinerClass(Combine1.class);
firstJob.setInputFormatClass(SequenceFileInputFormat.class);
if(runJob2)
firstJob.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.addInputPath(firstJob, inputPath);
FileOutputFormat.setOutputPath(firstJob, middleOut);
firstJob.waitForCompletion(true);
}
if(runJob2) {
Job secondJob = new Job(conf, "job2");
secondJob.setJarByClass(Map1.class);
/* You may need to change things here */
secondJob.setMapOutputKeyClass(DoubleWritable.class);
secondJob.setMapOutputValueClass(Text.class);
secondJob.setOutputKeyClass(DoubleWritable.class);
secondJob.setOutputValueClass(Text.class);
/* End region where we expect you to perhaps need to change things. */
secondJob.setMapperClass(Map2.class);
secondJob.setReducerClass(Reduce2.class);
secondJob.setInputFormatClass(SequenceFileInputFormat.class);
secondJob.setOutputFormatClass(TextOutputFormat.class);
secondJob.setNumReduceTasks(1);
FileInputFormat.addInputPath(secondJob, middleOut);
FileOutputFormat.setOutputPath(secondJob, finalOut);
secondJob.waitForCompletion(true);
}
}
}
| true | true | public static void main(String[] rawArgs) throws Exception {
GenericOptionsParser parser = new GenericOptionsParser(rawArgs);
Configuration conf = parser.getConfiguration();
String[] args = parser.getRemainingArgs();
boolean runJob2 = conf.getBoolean("runJob2", true);
boolean combiner = conf.getBoolean("combiner", false);
System.out.println("Target word: " + conf.get("targetWord"));
System.out.println("Function num: " + conf.get("funcNum"));
if(runJob2)
System.out.println("running both jobs");
else
System.out.println("for debugging, only running job 1");
if(combiner)
System.out.println("using combiner");
else
System.out.println("NOT using combiner");
Path inputPath = new Path(args[0]);
Path middleOut = new Path(args[1]);
Path finalOut = new Path(args[2]);
FileSystem hdfs = middleOut.getFileSystem(conf);
int reduceCount = conf.getInt("reduces", 32);
if(hdfs.exists(middleOut)) {
System.err.println("can't run: " + middleOut.toUri().toString() + " already exists");
System.exit(1);
}
if(finalOut.getFileSystem(conf).exists(finalOut) ) {
System.err.println("can't run: " + finalOut.toUri().toString() + " already exists");
System.exit(1);
}
{
Job firstJob = new Job(conf, "job1");
firstJob.setJarByClass(Map1.class);
/* You may need to change things here */
firstJob.setMapOutputKeyClass(Text.class);
firstJob.setMapOutputValueClass(Text.class);
firstJob.setOutputKeyClass(DoubleWritable.class);
firstJob.setOutputValueClass(Text.class);
/* End region where we expect you to perhaps need to change things. */
firstJob.setMapperClass(Map1.class);
firstJob.setReducerClass(Reduce1.class);
firstJob.setNumReduceTasks(reduceCount);
if(combiner)
firstJob.setCombinerClass(Combine1.class);
firstJob.setInputFormatClass(SequenceFileInputFormat.class);
if(runJob2)
firstJob.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.addInputPath(firstJob, inputPath);
FileOutputFormat.setOutputPath(firstJob, middleOut);
firstJob.waitForCompletion(true);
}
if(runJob2) {
Job secondJob = new Job(conf, "job2");
secondJob.setJarByClass(Map1.class);
/* You may need to change things here */
secondJob.setMapOutputKeyClass(DoubleWritable.class);
secondJob.setMapOutputValueClass(Text.class);
secondJob.setOutputKeyClass(DoubleWritable.class);
secondJob.setOutputValueClass(Text.class);
/* End region where we expect you to perhaps need to change things. */
secondJob.setMapperClass(Map2.class);
secondJob.setReducerClass(Reduce2.class);
secondJob.setInputFormatClass(SequenceFileInputFormat.class);
secondJob.setOutputFormatClass(TextOutputFormat.class);
secondJob.setNumReduceTasks(1);
FileInputFormat.addInputPath(secondJob, middleOut);
FileOutputFormat.setOutputPath(secondJob, finalOut);
secondJob.waitForCompletion(true);
}
}
| public static void main(String[] rawArgs) throws Exception {
GenericOptionsParser parser = new GenericOptionsParser(rawArgs);
Configuration conf = parser.getConfiguration();
String[] args = parser.getRemainingArgs();
boolean runJob2 = conf.getBoolean("runJob2", true);
boolean combiner = conf.getBoolean("combiner", false);
System.out.println("Target word: " + conf.get("targetWord"));
System.out.println("Function num: " + conf.get("funcNum"));
if(runJob2)
System.out.println("running both jobs");
else
System.out.println("for debugging, only running job 1");
if(combiner)
System.out.println("using combiner");
else
System.out.println("NOT using combiner");
Path inputPath = new Path(args[0]);
Path middleOut = new Path(args[1]);
Path finalOut = new Path(args[2]);
FileSystem hdfs = middleOut.getFileSystem(conf);
int reduceCount = conf.getInt("reduces", 32);
if(hdfs.exists(middleOut)) {
System.err.println("can't run: " + middleOut.toUri().toString() + " already exists");
System.exit(1);
}
if(finalOut.getFileSystem(conf).exists(finalOut) ) {
System.err.println("can't run: " + finalOut.toUri().toString() + " already exists");
System.exit(1);
}
{
Job firstJob = new Job(conf, "job1");
firstJob.setJarByClass(Map1.class);
/* You may need to change things here */
firstJob.setMapOutputKeyClass(Text.class);
firstJob.setMapOutputValueClass(DoublePair.class);
firstJob.setOutputKeyClass(DoubleWritable.class);
firstJob.setOutputValueClass(Text.class);
/* End region where we expect you to perhaps need to change things. */
firstJob.setMapperClass(Map1.class);
firstJob.setReducerClass(Reduce1.class);
firstJob.setNumReduceTasks(reduceCount);
if(combiner)
firstJob.setCombinerClass(Combine1.class);
firstJob.setInputFormatClass(SequenceFileInputFormat.class);
if(runJob2)
firstJob.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.addInputPath(firstJob, inputPath);
FileOutputFormat.setOutputPath(firstJob, middleOut);
firstJob.waitForCompletion(true);
}
if(runJob2) {
Job secondJob = new Job(conf, "job2");
secondJob.setJarByClass(Map1.class);
/* You may need to change things here */
secondJob.setMapOutputKeyClass(DoubleWritable.class);
secondJob.setMapOutputValueClass(Text.class);
secondJob.setOutputKeyClass(DoubleWritable.class);
secondJob.setOutputValueClass(Text.class);
/* End region where we expect you to perhaps need to change things. */
secondJob.setMapperClass(Map2.class);
secondJob.setReducerClass(Reduce2.class);
secondJob.setInputFormatClass(SequenceFileInputFormat.class);
secondJob.setOutputFormatClass(TextOutputFormat.class);
secondJob.setNumReduceTasks(1);
FileInputFormat.addInputPath(secondJob, middleOut);
FileOutputFormat.setOutputPath(secondJob, finalOut);
secondJob.waitForCompletion(true);
}
}
|
diff --git a/source/net/sourceforge/texlipse/model/TexStyleCompletionManager.java b/source/net/sourceforge/texlipse/model/TexStyleCompletionManager.java
index caf059f..d652aac 100644
--- a/source/net/sourceforge/texlipse/model/TexStyleCompletionManager.java
+++ b/source/net/sourceforge/texlipse/model/TexStyleCompletionManager.java
@@ -1,165 +1,165 @@
/*
* $Id$
*
* Copyright (c) 2006 by the TeXlipse team.
* 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 net.sourceforge.texlipse.model;
import java.util.Arrays;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.properties.TexlipseProperties;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ContextInformation;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.graphics.Point;
/**
* Manages style completions.
*
* (still work in progress)
*
* @author Oskar Ojala
*/
public class TexStyleCompletionManager implements IPropertyChangeListener{
// private Map keyValue;
private static TexStyleCompletionManager theInstance;
private String[] STYLETAGS = new String[] {
"\\textbf{", "\\textit{", "\\textrm{", "\\textsf{", "\\textsc", "\\textsl{", "\\texttt{","\\emph{", "{\\huge", "{\\Huge"
};
private String[] STYLELABELS = new String[] {
"bold", "italic", "roman", "sans serif", "small caps", "slanted", "teletype", "emphasize", "huge", "Huge"
};
/**
* Creates a new style completion manager
*/
private TexStyleCompletionManager() {
// this.keyValue = new HashMap();
readSettings();
}
/**
* Returns the instance of the style completion manager
*
* @return The singleton instance
*/
public static TexStyleCompletionManager getInstance() {
if (theInstance == null) {
theInstance = new TexStyleCompletionManager();
TexlipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(theInstance);
}
return theInstance;
}
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(TexlipseProperties.STYLE_COMPLETION_SETTINGS)) {
readSettings();
}
}
/**
* Reads the smart keys defined at the preference page.
*/
private void readSettings() {
String[] props = TexlipsePlugin.getPreferenceArray(TexlipseProperties.STYLE_COMPLETION_SETTINGS);
Arrays.sort(props);
STYLELABELS = new String[props.length];
STYLETAGS = new String[props.length];
for (int i = 0; i < props.length; i++) {
String[] pair = props[i].split("=");
// int index = keys[i].indexOf('=');
// if (index <= 0) {
// continue;
// }
// keyValue.put(keys[i].substring(0, index), keys[i].substring(index+1));
STYLELABELS[i] = pair[0];
STYLETAGS[i] = pair[1];
}
}
/**
* Returns the style completion proposals
*
* @param selectedText The selected text
* @param selectedRange The selected range
* @return An array of completion proposals
*/
public ICompletionProposal[] getStyleCompletions(String selectedText, Point selectedRange) {
/*
ICompletionProposal[] result = new ICompletionProposal[keyValue.size()];
int i=0;
for (Iterator iter = keyValue.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
String value = (String) keyValue.get(key);
String replacement = "{" + key + " " + selectedText + "}";
int cursor = key.length() + 2;
IContextInformation contextInfo = new ContextInformation(null, value+" Style");
result[i] = new CompletionProposal(replacement,
selectedRange.x, selectedRange.y,
cursor, null, value,
contextInfo, replacement);
i++;
}
*/
ICompletionProposal[] result = new ICompletionProposal[STYLELABELS.length];
// Loop through all styles
for (int i = 0; i < STYLETAGS.length; i++) {
String tag = STYLETAGS[i];
// Compute replacement text
String replacement = tag + selectedText + "}";
// Derive cursor position
- int cursor = tag.length() + 1;
+ int cursor = tag.length() + selectedText.length() + 1;
// Compute a suitable context information
IContextInformation contextInfo =
new ContextInformation(null, STYLELABELS[i]+" Style");
// Construct proposal
result[i] = new CompletionProposal(replacement,
selectedRange.x, selectedRange.y,
cursor, null, STYLELABELS[i],
contextInfo, replacement);
}
return result;
}
/**
* Returns the style context.
*
* @return Array of style contexts
*/
public IContextInformation[] getStyleContext() {
ContextInformation[] contextInfos = new ContextInformation[STYLELABELS.length];
// Create one context information item for each style
for (int i = 0; i < STYLELABELS.length; i++) {
contextInfos[i] = new ContextInformation(null, STYLELABELS[i]+" Style");
}
return contextInfos;
}
}
| true | true | public ICompletionProposal[] getStyleCompletions(String selectedText, Point selectedRange) {
/*
ICompletionProposal[] result = new ICompletionProposal[keyValue.size()];
int i=0;
for (Iterator iter = keyValue.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
String value = (String) keyValue.get(key);
String replacement = "{" + key + " " + selectedText + "}";
int cursor = key.length() + 2;
IContextInformation contextInfo = new ContextInformation(null, value+" Style");
result[i] = new CompletionProposal(replacement,
selectedRange.x, selectedRange.y,
cursor, null, value,
contextInfo, replacement);
i++;
}
*/
ICompletionProposal[] result = new ICompletionProposal[STYLELABELS.length];
// Loop through all styles
for (int i = 0; i < STYLETAGS.length; i++) {
String tag = STYLETAGS[i];
// Compute replacement text
String replacement = tag + selectedText + "}";
// Derive cursor position
int cursor = tag.length() + 1;
// Compute a suitable context information
IContextInformation contextInfo =
new ContextInformation(null, STYLELABELS[i]+" Style");
// Construct proposal
result[i] = new CompletionProposal(replacement,
selectedRange.x, selectedRange.y,
cursor, null, STYLELABELS[i],
contextInfo, replacement);
}
return result;
}
| public ICompletionProposal[] getStyleCompletions(String selectedText, Point selectedRange) {
/*
ICompletionProposal[] result = new ICompletionProposal[keyValue.size()];
int i=0;
for (Iterator iter = keyValue.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
String value = (String) keyValue.get(key);
String replacement = "{" + key + " " + selectedText + "}";
int cursor = key.length() + 2;
IContextInformation contextInfo = new ContextInformation(null, value+" Style");
result[i] = new CompletionProposal(replacement,
selectedRange.x, selectedRange.y,
cursor, null, value,
contextInfo, replacement);
i++;
}
*/
ICompletionProposal[] result = new ICompletionProposal[STYLELABELS.length];
// Loop through all styles
for (int i = 0; i < STYLETAGS.length; i++) {
String tag = STYLETAGS[i];
// Compute replacement text
String replacement = tag + selectedText + "}";
// Derive cursor position
int cursor = tag.length() + selectedText.length() + 1;
// Compute a suitable context information
IContextInformation contextInfo =
new ContextInformation(null, STYLELABELS[i]+" Style");
// Construct proposal
result[i] = new CompletionProposal(replacement,
selectedRange.x, selectedRange.y,
cursor, null, STYLELABELS[i],
contextInfo, replacement);
}
return result;
}
|
diff --git a/src/com/tomclaw/mandarin/core/QueryHelper.java b/src/com/tomclaw/mandarin/core/QueryHelper.java
index 5ecb2009..7c1faafa 100644
--- a/src/com/tomclaw/mandarin/core/QueryHelper.java
+++ b/src/com/tomclaw/mandarin/core/QueryHelper.java
@@ -1,503 +1,504 @@
package com.tomclaw.mandarin.core;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.util.Log;
import com.google.gson.Gson;
import com.tomclaw.mandarin.R;
import com.tomclaw.mandarin.core.exceptions.AccountNotFoundException;
import com.tomclaw.mandarin.core.exceptions.BuddyNotFoundException;
import com.tomclaw.mandarin.im.AccountRoot;
import com.tomclaw.mandarin.im.icq.IcqStatusUtil;
import com.tomclaw.mandarin.util.StatusUtil;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: solkin
* Date: 5/9/13
* Time: 2:13 PM
*/
public class QueryHelper {
private static Gson gson;
static {
gson = new Gson();
}
public static List<AccountRoot> getAccounts(Context context, List<AccountRoot> accountRootList) {
// Clearing input list.
accountRootList.clear();
// Obtain specified account. If exist.
Cursor cursor = context.getContentResolver().query(Settings.ACCOUNT_RESOLVER_URI, null, null, null, null);
// Cursor may have more than only one entry.
if (cursor.moveToFirst()) {
// Obtain necessary column index.
int bundleColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_BUNDLE);
int typeColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_TYPE);
int dbIdColumnIndex = cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID);
// Iterate all accounts.
do {
accountRootList.add(createAccountRoot(context, cursor.getString(typeColumnIndex),
cursor.getString(bundleColumnIndex), cursor.getInt(dbIdColumnIndex)));
} while (cursor.moveToNext()); // Trying to move to position.
}
// Closing cursor.
cursor.close();
return accountRootList;
}
/*public static AccountRoot getAccount(ContentResolver contentResolver, int accountDbId) {
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null, null);
// Checking for there is at least one account and switching to it.
if (cursor.moveToFirst()) {
// Obtain necessary column index.
int bundleColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_BUNDLE);
int typeColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_TYPE);
return createAccountRoot(contentResolver, cursor.getString(typeColumnIndex),
cursor.getString(bundleColumnIndex));
}
return null;
}*/
public static int getAccountDbId(ContentResolver contentResolver, String accountType, String userId)
throws AccountNotFoundException {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountType + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + userId + "'", null, null);
// Cursor may have no more than only one entry. But lets check.
if (cursor.moveToFirst()) {
int accountDbId = cursor.getInt(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// Closing cursor.
cursor.close();
return accountDbId;
}
// Closing cursor.
cursor.close();
throw new AccountNotFoundException();
}
private static AccountRoot createAccountRoot(Context context, String className,
String accountRootJson, int accountDbId) {
try {
// Creating account root from bundle.
AccountRoot accountRoot = (AccountRoot) gson.fromJson(accountRootJson,
Class.forName(className));
accountRoot.setContext(context);
accountRoot.setAccountDbId(accountDbId);
accountRoot.actualizeStatus();
return accountRoot;
} catch (ClassNotFoundException e) {
Log.d(Settings.LOG_TAG, "No such class found: " + e.getMessage());
}
return null;
}
public static boolean updateAccount(Context context, AccountRoot accountRoot) {
ContentResolver contentResolver = context.getContentResolver();
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountRoot.getAccountType() + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + accountRoot.getUserId() + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.moveToFirst()) {
long accountDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// Closing cursor.
cursor.close();
// We must update account. Name, password, status, bundle.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ACCOUNT_NAME, accountRoot.getUserNick());
contentValues.put(GlobalProvider.ACCOUNT_USER_PASSWORD, accountRoot.getUserPassword());
contentValues.put(GlobalProvider.ACCOUNT_STATUS, accountRoot.getStatusIndex());
contentValues.put(GlobalProvider.ACCOUNT_CONNECTING, accountRoot.isConnecting() ? 1 : 0);
contentValues.put(GlobalProvider.ACCOUNT_BUNDLE, gson.toJson(accountRoot));
// Update query.
contentResolver.update(Settings.ACCOUNT_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null);
return false;
}
// Closing cursor.
cursor.close();
// No matching account. Creating new account.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ACCOUNT_TYPE, accountRoot.getAccountType());
contentValues.put(GlobalProvider.ACCOUNT_NAME, accountRoot.getUserNick());
contentValues.put(GlobalProvider.ACCOUNT_USER_ID, accountRoot.getUserId());
contentValues.put(GlobalProvider.ACCOUNT_USER_PASSWORD, accountRoot.getUserPassword());
contentValues.put(GlobalProvider.ACCOUNT_STATUS, accountRoot.getStatusIndex());
contentValues.put(GlobalProvider.ACCOUNT_CONNECTING, accountRoot.isConnecting() ? 1 : 0);
contentValues.put(GlobalProvider.ACCOUNT_BUNDLE, gson.toJson(accountRoot));
contentResolver.insert(Settings.ACCOUNT_RESOLVER_URI, contentValues);
// Setting up account db id.
try {
accountRoot.setAccountDbId(getAccountDbId(contentResolver, accountRoot.getAccountType(),
accountRoot.getUserId()));
accountRoot.setContext(context);
} catch (AccountNotFoundException e) {
// Hey, I'm inserted it 3 lines ago!
Log.d(Settings.LOG_TAG, "updateAccount method: no accounts after inserting.");
}
return true;
}
public static boolean updateAccountStatus(ContentResolver contentResolver, AccountRoot accountRoot,
int statusIndex, boolean isConnecting) {
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountRoot.getAccountType() + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + accountRoot.getUserId() + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.moveToFirst()) {
long accountDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// Closing cursor.
cursor.close();
// We must update account. Status, connecting flag.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ACCOUNT_STATUS, accountRoot.getStatusIndex());
contentValues.put(GlobalProvider.ACCOUNT_BUNDLE, gson.toJson(accountRoot));
// Update query.
contentResolver.update(Settings.ACCOUNT_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null);
return true;
}
// Closing cursor.
cursor.close();
return false;
}
public static boolean removeAccount(ContentResolver contentResolver, String accountType, String userId) {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ACCOUNT_TYPE + "='" + accountType + "'" + " AND "
+ GlobalProvider.ACCOUNT_USER_ID + "='" + userId + "'", null, null);
// Cursor may have no more than only one entry. But lets check.
if (cursor.moveToFirst()) {
do {
long accountDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
// Removing roster groups.
contentResolver.delete(Settings.GROUP_RESOLVER_URI,
GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID + "=" + accountDbId, null);
// Removing roster buddies.
contentResolver.delete(Settings.BUDDY_RESOLVER_URI,
GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID + "=" + accountDbId, null);
// Removing all the history.
contentResolver.delete(Settings.HISTORY_RESOLVER_URI,
GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID + "=" + accountDbId, null);
} while (cursor.moveToNext());
}
// Closing cursor.
cursor.close();
// And remove account.
return contentResolver.delete(Settings.ACCOUNT_RESOLVER_URI, GlobalProvider.ACCOUNT_TYPE + "='"
+ accountType + "'" + " AND " + GlobalProvider.ACCOUNT_USER_ID + "='"
+ userId + "'", null) != 0;
}
public static void modifyDialog(ContentResolver contentResolver, int buddyDbId, boolean isOpened) {
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ROSTER_BUDDY_DIALOG, isOpened ? 1 : 0);
modifyBuddy(contentResolver, buddyDbId, contentValues);
}
public static void modifyFavorite(ContentResolver contentResolver, int buddyDbId, boolean isFavorite) {
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ROSTER_BUDDY_FAVORITE, isFavorite ? 1 : 0);
modifyBuddy(contentResolver, buddyDbId, contentValues);
}
public static boolean checkDialog(ContentResolver contentResolver, int buddyDbId) {
boolean dialogFlag = false;
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
GlobalProvider.ROW_AUTO_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.moveToFirst()) {
dialogFlag = cursor.getInt(cursor.getColumnIndex(GlobalProvider.ROSTER_BUDDY_DIALOG)) != 0;
// Closing cursor.
cursor.close();
}
// Closing cursor.
cursor.close();
return dialogFlag;
}
public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, String messageText,
boolean activateDialog) {
insertMessage(contentResolver, appSession, accountDbId, buddyDbId, messageType, cookie, 0, messageText,
activateDialog);
}
public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog) {
Log.d(Settings.LOG_TAG, "insertMessage: type: " + messageType + " message = " + messageText);
// Checking for time specified.
if(messageTime == 0) {
messageTime = System.currentTimeMillis();
}
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.HISTORY_RESOLVER_URI, null,
GlobalProvider.HISTORY_BUDDY_DB_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.getCount() >= 1) {
// Moving cursor to the last (and first) position and checking for operation success.
if (cursor.moveToLast()
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TYPE)) == messageType
&& cursor.getLong(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TIME)) >=
- (messageTime - Settings.MESSAGES_COLLAPSE_DELAY)) {
+ (messageTime - Settings.MESSAGES_COLLAPSE_DELAY)
+ && cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_STATE)) != 1) {
Log.d(Settings.LOG_TAG, "We have cookies!");
// We have cookies!
long messageDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
String cookies = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_COOKIE));
cookies += " " + cookie;
String messagesText = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TEXT));
messagesText += "\n" + messageText;
// Creating content values to update message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookies);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messagesText);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
// Update query.
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + messageDbId + "'", null);
// Closing cursor.
cursor.close();
// Checking for dialog activate needed.
if(activateDialog && !checkDialog(contentResolver, buddyDbId)) {
modifyDialog(contentResolver, buddyDbId, true);
}
return;
}
}
// No matching request message. Insert new message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID, accountDbId);
contentValues.put(GlobalProvider.HISTORY_BUDDY_DB_ID, buddyDbId);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TYPE, messageType);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookie);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TIME, messageTime);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messageText);
contentResolver.insert(Settings.HISTORY_RESOLVER_URI, contentValues);
// Closing cursor.
cursor.close();
// Checking for dialog activate needed.
if(activateDialog && !checkDialog(contentResolver, buddyDbId)) {
modifyDialog(contentResolver, buddyDbId, true);
}
}
public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
String userId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog)
throws BuddyNotFoundException {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID + "='" + accountDbId + "'" + " AND "
+ GlobalProvider.ROSTER_BUDDY_ID + "='" + userId + "'", null, null);
// Cursor may have more than only one entry.
// TODO: check for at least one buddy present.
if (cursor.moveToFirst()) {
final int BUDDY_DB_ID_COLUMN = cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID);
// Cycling all the identical buddies in different groups.
do {
int buddyDbId = cursor.getInt(BUDDY_DB_ID_COLUMN);
// Plain message query.
insertMessage(contentResolver, appSession, accountDbId,
buddyDbId, messageType, cookie, messageTime, messageText, activateDialog);
} while(cursor.moveToNext());
// Closing cursor.
cursor.close();
} else {
// Closing cursor.
cursor.close();
throw new BuddyNotFoundException();
}
}
public static void updateMessage(ContentResolver contentResolver, String cookie, int messageState) {
// Plain message modify by cookies.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, messageState);
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.HISTORY_MESSAGE_COOKIE + " LIKE '%" + cookie + "%'", null);
}
private static void modifyBuddy(ContentResolver contentResolver, int buddyDbId, ContentValues contentValues) {
contentResolver.update(Settings.BUDDY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + buddyDbId + "'", null);
}
public static void modifyBuddyStatus(ContentResolver contentResolver, int accountDbId, String buddyId,
int buddyStatusIndex) throws BuddyNotFoundException {
// Obtain account db id.
Cursor cursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID + "='" + accountDbId + "'" + " AND "
+ GlobalProvider.ROSTER_BUDDY_ID + "='" + buddyId + "'", null, null);
// Cursor may have more than only one entry.
if (cursor.moveToFirst()) {
final int BUDDY_DB_ID_COLUMN = cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID);
// Cycling all the identical buddies in different groups.
do {
int buddyDbId = cursor.getInt(BUDDY_DB_ID_COLUMN);
// Plain buddy modify.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.ROSTER_BUDDY_STATUS, buddyStatusIndex);
modifyBuddy(contentResolver, buddyDbId, contentValues);
} while(cursor.moveToNext());
// Closing cursor.
cursor.close();
} else {
// Closing cursor.
cursor.close();
throw new BuddyNotFoundException();
}
}
public static void updateOrCreateBuddy(ContentResolver contentResolver, int accountDbId, String accountType,
long updateTime, String groupName,
String buddyId, String buddyNick, String buddyStatus) {
ContentValues buddyValues = new ContentValues();
buddyValues.put(GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID, accountDbId);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_ACCOUNT_TYPE, accountType);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_ID, buddyId);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_NICK, buddyNick);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_GROUP, groupName);
// buddyValues.put(GlobalProvider.ROSTER_BUDDY_GROUP_ID, groupDbId);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_STATUS, IcqStatusUtil.getStatusIndex(buddyStatus));
buddyValues.put(GlobalProvider.ROSTER_BUDDY_DIALOG, 0);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_FAVORITE, 0);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_UPDATE_TIME, updateTime);
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append(GlobalProvider.ROSTER_BUDDY_ID).append("=='").append(buddyId).append("'")
.append(" AND ")
.append(GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID).append("==").append(accountDbId);
Cursor buddyCursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
queryBuilder.toString(), null,
GlobalProvider.ROW_AUTO_ID.concat(" ASC LIMIT 1"));
if (buddyCursor.moveToFirst()) {
long buddyDbId = buddyCursor.getLong(buddyCursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
int buddyDialogFlag = buddyCursor.getInt(buddyCursor.getColumnIndex(GlobalProvider.ROSTER_BUDDY_DIALOG));
int buddyFavorite = buddyCursor.getInt(buddyCursor.getColumnIndex(GlobalProvider.ROSTER_BUDDY_FAVORITE));
// Update dialog and favorite flags.
buddyValues.put(GlobalProvider.ROSTER_BUDDY_DIALOG, buddyDialogFlag);
buddyValues.put(GlobalProvider.ROSTER_BUDDY_FAVORITE, buddyFavorite);
// Update this row.
queryBuilder.setLength(0);
queryBuilder.append(GlobalProvider.ROW_AUTO_ID).append("=='").append(buddyDbId).append("'");
contentResolver.update(Settings.BUDDY_RESOLVER_URI, buddyValues,
queryBuilder.toString(), null);
} else {
contentResolver.insert(Settings.BUDDY_RESOLVER_URI, buddyValues);
}
buddyCursor.close();
}
public static void updateOrCreateGroup(ContentResolver contentResolver, int accountDbId, long updateTime,
String groupName, int groupId) {
StringBuilder queryBuilder = new StringBuilder();
ContentValues groupValues = new ContentValues();
groupValues.put(GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID, accountDbId);
groupValues.put(GlobalProvider.ROSTER_GROUP_NAME, groupName);
groupValues.put(GlobalProvider.ROSTER_GROUP_ID, groupId);
groupValues.put(GlobalProvider.ROSTER_GROUP_TYPE, GlobalProvider.GROUP_TYPE_DEFAULT);
groupValues.put(GlobalProvider.ROSTER_GROUP_UPDATE_TIME, updateTime);
// Trying to update group
queryBuilder.append(GlobalProvider.ROSTER_GROUP_ID).append("=='").append(groupId).append("'")
.append(" AND ")
.append(GlobalProvider.ROSTER_GROUP_ACCOUNT_DB_ID).append("==").append(accountDbId);
int groupsModified = contentResolver.update(Settings.GROUP_RESOLVER_URI, groupValues,
queryBuilder.toString(), null);
// Checking for there is no such group.
if (groupsModified == 0) {
contentResolver.insert(Settings.GROUP_RESOLVER_URI, groupValues);
}
}
public static void moveOutdatedBuddies(ContentResolver contentResolver, Resources resources,
int accountDbId, long updateTime) {
String recycleString = resources.getString(R.string.recycle);
StringBuilder queryBuilder = new StringBuilder();
// Move all deleted buddies to recycle.
queryBuilder.append(GlobalProvider.ROSTER_BUDDY_UPDATE_TIME).append("!=").append(updateTime)
.append(" AND ")
.append(GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID).append("==").append(accountDbId);
Cursor removedCursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
queryBuilder.toString(), null, null);
if(removedCursor.moveToFirst()) {
// Checking and creating recycle.
queryBuilder.setLength(0);
queryBuilder.append(GlobalProvider.ROSTER_GROUP_TYPE).append("=='")
.append(GlobalProvider.GROUP_TYPE_SYSTEM).append("'").append(" AND ")
.append(GlobalProvider.ROSTER_GROUP_ID).append("==").append(GlobalProvider.GROUP_ID_RECYCLE);
Cursor recycleCursor = contentResolver.query(Settings.GROUP_RESOLVER_URI, null,
queryBuilder.toString(), null, null);
if(!recycleCursor.moveToFirst()) {
ContentValues recycleValues = new ContentValues();
recycleValues.put(GlobalProvider.ROSTER_GROUP_NAME, recycleString);
recycleValues.put(GlobalProvider.ROSTER_GROUP_TYPE, GlobalProvider.GROUP_TYPE_SYSTEM);
recycleValues.put(GlobalProvider.ROSTER_GROUP_ID, GlobalProvider.GROUP_ID_RECYCLE);
recycleValues.put(GlobalProvider.ROSTER_GROUP_UPDATE_TIME, updateTime);
contentResolver.insert(Settings.GROUP_RESOLVER_URI, recycleValues);
}
recycleCursor.close();
// Move, move, move!
ContentValues moveValues = new ContentValues();
moveValues.put(GlobalProvider.ROSTER_BUDDY_GROUP, recycleString);
moveValues.put(GlobalProvider.ROSTER_BUDDY_GROUP_ID, GlobalProvider.GROUP_ID_RECYCLE);
moveValues.put(GlobalProvider.ROSTER_BUDDY_STATUS, StatusUtil.STATUS_OFFLINE);
queryBuilder.setLength(0);
queryBuilder.append(GlobalProvider.ROSTER_BUDDY_UPDATE_TIME).append("!=").append(updateTime)
.append(" AND ")
.append(GlobalProvider.ROSTER_BUDDY_ACCOUNT_DB_ID).append("==").append(accountDbId);
int movedBuddies = contentResolver.update(Settings.BUDDY_RESOLVER_URI, moveValues,
queryBuilder.toString(), null);
Log.d(Settings.LOG_TAG, "moved to recycle: " + movedBuddies);
}
removedCursor.close();
}
public static String getBuddyNick(ContentResolver contentResolver, int buddyDbId)
throws BuddyNotFoundException {
// Obtain specified buddy. If exist.
Cursor cursor = contentResolver.query(Settings.BUDDY_RESOLVER_URI, null,
GlobalProvider.ROW_AUTO_ID + "='" + buddyDbId + "'", null, null);
// Checking for there is at least one buddy and switching to it.
if (cursor.moveToFirst()) {
// Obtain necessary column index.
int nickColumnIndex = cursor.getColumnIndex(GlobalProvider.ROSTER_BUDDY_NICK);
String buddyNick = cursor.getString(nickColumnIndex);
// Closing cursor.
cursor.close();
return buddyNick;
}
throw new BuddyNotFoundException();
}
public static String getAccountName(ContentResolver contentResolver, int accountDbId)
throws AccountNotFoundException {
// Obtain specified account. If exist.
Cursor cursor = contentResolver.query(Settings.ACCOUNT_RESOLVER_URI, null,
GlobalProvider.ROW_AUTO_ID + "='" + accountDbId + "'", null, null);
// Checking for there is at least one account and switching to it.
if (cursor.moveToFirst()) {
// Obtain necessary column index.
int nameColumnIndex = cursor.getColumnIndex(GlobalProvider.ACCOUNT_NAME);
String accountName = cursor.getString(nameColumnIndex);
// Closing cursor.
cursor.close();
return accountName;
}
throw new AccountNotFoundException();
}
}
| true | true | public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog) {
Log.d(Settings.LOG_TAG, "insertMessage: type: " + messageType + " message = " + messageText);
// Checking for time specified.
if(messageTime == 0) {
messageTime = System.currentTimeMillis();
}
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.HISTORY_RESOLVER_URI, null,
GlobalProvider.HISTORY_BUDDY_DB_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.getCount() >= 1) {
// Moving cursor to the last (and first) position and checking for operation success.
if (cursor.moveToLast()
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TYPE)) == messageType
&& cursor.getLong(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TIME)) >=
(messageTime - Settings.MESSAGES_COLLAPSE_DELAY)) {
Log.d(Settings.LOG_TAG, "We have cookies!");
// We have cookies!
long messageDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
String cookies = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_COOKIE));
cookies += " " + cookie;
String messagesText = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TEXT));
messagesText += "\n" + messageText;
// Creating content values to update message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookies);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messagesText);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
// Update query.
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + messageDbId + "'", null);
// Closing cursor.
cursor.close();
// Checking for dialog activate needed.
if(activateDialog && !checkDialog(contentResolver, buddyDbId)) {
modifyDialog(contentResolver, buddyDbId, true);
}
return;
}
}
// No matching request message. Insert new message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID, accountDbId);
contentValues.put(GlobalProvider.HISTORY_BUDDY_DB_ID, buddyDbId);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TYPE, messageType);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookie);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TIME, messageTime);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messageText);
contentResolver.insert(Settings.HISTORY_RESOLVER_URI, contentValues);
// Closing cursor.
cursor.close();
// Checking for dialog activate needed.
if(activateDialog && !checkDialog(contentResolver, buddyDbId)) {
modifyDialog(contentResolver, buddyDbId, true);
}
}
| public static void insertMessage(ContentResolver contentResolver, String appSession, int accountDbId,
int buddyDbId, int messageType, String cookie, long messageTime,
String messageText, boolean activateDialog) {
Log.d(Settings.LOG_TAG, "insertMessage: type: " + messageType + " message = " + messageText);
// Checking for time specified.
if(messageTime == 0) {
messageTime = System.currentTimeMillis();
}
// Obtaining cursor with message to such buddy, of such type and not later, than two minutes.
Cursor cursor = contentResolver.query(Settings.HISTORY_RESOLVER_URI, null,
GlobalProvider.HISTORY_BUDDY_DB_ID + "='" + buddyDbId + "'", null, null);
// Cursor may have no more than only one entry. But we will check one and more.
if (cursor.getCount() >= 1) {
// Moving cursor to the last (and first) position and checking for operation success.
if (cursor.moveToLast()
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TYPE)) == messageType
&& cursor.getLong(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TIME)) >=
(messageTime - Settings.MESSAGES_COLLAPSE_DELAY)
&& cursor.getInt(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_STATE)) != 1) {
Log.d(Settings.LOG_TAG, "We have cookies!");
// We have cookies!
long messageDbId = cursor.getLong(cursor.getColumnIndex(GlobalProvider.ROW_AUTO_ID));
String cookies = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_COOKIE));
cookies += " " + cookie;
String messagesText = cursor.getString(cursor.getColumnIndex(GlobalProvider.HISTORY_MESSAGE_TEXT));
messagesText += "\n" + messageText;
// Creating content values to update message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookies);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messagesText);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
// Update query.
contentResolver.update(Settings.HISTORY_RESOLVER_URI, contentValues,
GlobalProvider.ROW_AUTO_ID + "='" + messageDbId + "'", null);
// Closing cursor.
cursor.close();
// Checking for dialog activate needed.
if(activateDialog && !checkDialog(contentResolver, buddyDbId)) {
modifyDialog(contentResolver, buddyDbId, true);
}
return;
}
}
// No matching request message. Insert new message.
ContentValues contentValues = new ContentValues();
contentValues.put(GlobalProvider.HISTORY_BUDDY_ACCOUNT_DB_ID, accountDbId);
contentValues.put(GlobalProvider.HISTORY_BUDDY_DB_ID, buddyDbId);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TYPE, messageType);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_COOKIE, cookie);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_STATE, 2);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TIME, messageTime);
contentValues.put(GlobalProvider.HISTORY_MESSAGE_TEXT, messageText);
contentResolver.insert(Settings.HISTORY_RESOLVER_URI, contentValues);
// Closing cursor.
cursor.close();
// Checking for dialog activate needed.
if(activateDialog && !checkDialog(contentResolver, buddyDbId)) {
modifyDialog(contentResolver, buddyDbId, true);
}
}
|
diff --git a/loci/formats/TiffTools.java b/loci/formats/TiffTools.java
index 5c6576f6a..1ef06b90b 100644
--- a/loci/formats/TiffTools.java
+++ b/loci/formats/TiffTools.java
@@ -1,2520 +1,2521 @@
//
// TiffTools.java
//
/*
LOCI Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan,
Eric Kjellman and Brian Loranger.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.*;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.nio.*;
import java.util.*;
import loci.formats.codec.*;
/**
* A utility class for manipulating TIFF files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/TiffTools.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/TiffTools.java">SVN</a></dd></dl>
*
* @author Curtis Rueden ctrueden at wisc.edu
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert linkert at wisc.edu
* @author Chris Allan callan at blackcat.ca
*/
public final class TiffTools {
// -- Constants --
private static final boolean DEBUG = false;
/** The number of bytes in each IFD entry. */
public static final int BYTES_PER_ENTRY = 12;
// non-IFD tags (for internal use)
public static final int LITTLE_ENDIAN = 0;
public static final int VALID_BITS = 1;
// IFD types
public static final int BYTE = 1;
public static final int ASCII = 2;
public static final int SHORT = 3;
public static final int LONG = 4;
public static final int RATIONAL = 5;
public static final int SBYTE = 6;
public static final int UNDEFINED = 7;
public static final int SSHORT = 8;
public static final int SLONG = 9;
public static final int SRATIONAL = 10;
public static final int FLOAT = 11;
public static final int DOUBLE = 12;
public static final int[] BYTES_PER_ELEMENT = {
-1, // invalid type
1, // BYTE
1, // ASCII
2, // SHORT
4, // LONG
8, // RATIONAL
1, // SBYTE
1, // UNDEFINED
2, // SSHORT
4, // SLONG
8, // SRATIONAL
4, // FLOAT
8, // DOUBLE
};
// IFD tags
public static final int NEW_SUBFILE_TYPE = 254;
public static final int SUBFILE_TYPE = 255;
public static final int IMAGE_WIDTH = 256;
public static final int IMAGE_LENGTH = 257;
public static final int BITS_PER_SAMPLE = 258;
public static final int COMPRESSION = 259;
public static final int PHOTOMETRIC_INTERPRETATION = 262;
public static final int THRESHHOLDING = 263;
public static final int CELL_WIDTH = 264;
public static final int CELL_LENGTH = 265;
public static final int FILL_ORDER = 266;
public static final int DOCUMENT_NAME = 269;
public static final int IMAGE_DESCRIPTION = 270;
public static final int MAKE = 271;
public static final int MODEL = 272;
public static final int STRIP_OFFSETS = 273;
public static final int ORIENTATION = 274;
public static final int SAMPLES_PER_PIXEL = 277;
public static final int ROWS_PER_STRIP = 278;
public static final int STRIP_BYTE_COUNTS = 279;
public static final int MIN_SAMPLE_VALUE = 280;
public static final int MAX_SAMPLE_VALUE = 281;
public static final int X_RESOLUTION = 282;
public static final int Y_RESOLUTION = 283;
public static final int PLANAR_CONFIGURATION = 284;
public static final int PAGE_NAME = 285;
public static final int X_POSITION = 286;
public static final int Y_POSITION = 287;
public static final int FREE_OFFSETS = 288;
public static final int FREE_BYTE_COUNTS = 289;
public static final int GRAY_RESPONSE_UNIT = 290;
public static final int GRAY_RESPONSE_CURVE = 291;
public static final int T4_OPTIONS = 292;
public static final int T6_OPTIONS = 293;
public static final int RESOLUTION_UNIT = 296;
public static final int PAGE_NUMBER = 297;
public static final int TRANSFER_FUNCTION = 301;
public static final int SOFTWARE = 305;
public static final int DATE_TIME = 306;
public static final int ARTIST = 315;
public static final int HOST_COMPUTER = 316;
public static final int PREDICTOR = 317;
public static final int WHITE_POINT = 318;
public static final int PRIMARY_CHROMATICITIES = 319;
public static final int COLOR_MAP = 320;
public static final int HALFTONE_HINTS = 321;
public static final int TILE_WIDTH = 322;
public static final int TILE_LENGTH = 323;
public static final int TILE_OFFSETS = 324;
public static final int TILE_BYTE_COUNTS = 325;
public static final int INK_SET = 332;
public static final int INK_NAMES = 333;
public static final int NUMBER_OF_INKS = 334;
public static final int DOT_RANGE = 336;
public static final int TARGET_PRINTER = 337;
public static final int EXTRA_SAMPLES = 338;
public static final int SAMPLE_FORMAT = 339;
public static final int S_MIN_SAMPLE_VALUE = 340;
public static final int S_MAX_SAMPLE_VALUE = 341;
public static final int TRANSFER_RANGE = 342;
public static final int JPEG_PROC = 512;
public static final int JPEG_INTERCHANGE_FORMAT = 513;
public static final int JPEG_INTERCHANGE_FORMAT_LENGTH = 514;
public static final int JPEG_RESTART_INTERVAL = 515;
public static final int JPEG_LOSSLESS_PREDICTORS = 517;
public static final int JPEG_POINT_TRANSFORMS = 518;
public static final int JPEG_Q_TABLES = 519;
public static final int JPEG_DC_TABLES = 520;
public static final int JPEG_AC_TABLES = 521;
public static final int Y_CB_CR_COEFFICIENTS = 529;
public static final int Y_CB_CR_SUB_SAMPLING = 530;
public static final int Y_CB_CR_POSITIONING = 531;
public static final int REFERENCE_BLACK_WHITE = 532;
public static final int COPYRIGHT = 33432;
// compression types
public static final int UNCOMPRESSED = 1;
public static final int CCITT_1D = 2;
public static final int GROUP_3_FAX = 3;
public static final int GROUP_4_FAX = 4;
public static final int LZW = 5;
//public static final int JPEG = 6;
public static final int JPEG = 7;
public static final int PACK_BITS = 32773;
public static final int PROPRIETARY_DEFLATE = 32946;
public static final int DEFLATE = 8;
public static final int THUNDERSCAN = 32809;
public static final int NIKON = 34713;
public static final int LURAWAVE = -1;
// photometric interpretation types
public static final int WHITE_IS_ZERO = 0;
public static final int BLACK_IS_ZERO = 1;
public static final int RGB = 2;
public static final int RGB_PALETTE = 3;
public static final int TRANSPARENCY_MASK = 4;
public static final int CMYK = 5;
public static final int Y_CB_CR = 6;
public static final int CIE_LAB = 8;
public static final int CFA_ARRAY = -32733;
// TIFF header constants
public static final int MAGIC_NUMBER = 42;
public static final int LITTLE = 0x49;
public static final int BIG = 0x4d;
// -- Constructor --
private TiffTools() { }
// -- TiffTools API methods --
/**
* Tests the given data block to see if it represents
* the first few bytes of a TIFF file.
*/
public static boolean isValidHeader(byte[] block) {
return checkHeader(block) != null;
}
/**
* Checks the TIFF header.
* @return true if little-endian,
* false if big-endian,
* or null if not a TIFF.
*/
public static Boolean checkHeader(byte[] block) {
if (block.length < 4) return null;
// byte order must be II or MM
boolean littleEndian = block[0] == LITTLE && block[1] == LITTLE; // II
boolean bigEndian = block[0] == BIG && block[1] == BIG; // MM
if (!littleEndian && !bigEndian) return null;
// check magic number (42)
short magic = DataTools.bytesToShort(block, 2, littleEndian);
if (magic != MAGIC_NUMBER) return null;
return new Boolean(littleEndian);
}
/** Gets whether the TIFF information in the given IFD is little-endian. */
public static boolean isLittleEndian(Hashtable ifd) throws FormatException {
return ((Boolean)
getIFDValue(ifd, LITTLE_ENDIAN, true, Boolean.class)).booleanValue();
}
// --------------------------- Reading TIFF files ---------------------------
// -- IFD parsing methods --
/**
* Gets all IFDs within the given TIFF file, or null
* if the given file is not a valid TIFF file.
*/
public static Hashtable[] getIFDs(RandomAccessStream in) throws IOException {
// check TIFF header
Boolean result = checkHeader(in);
if (result == null) return null;
long offset = getFirstOffset(in);
// compute maximum possible number of IFDs, for loop safety
// each IFD must have at least one directory entry, which means that
// each IFD must be at least 2 + 12 + 4 = 18 bytes in length
long ifdMax = (in.length() - 8) / 18;
// read in IFDs
Vector v = new Vector();
for (long ifdNum=0; ifdNum<ifdMax; ifdNum++) {
Hashtable ifd = getIFD(in, ifdNum, offset);
if (ifd == null || ifd.size() <= 1) break;
v.add(ifd);
offset = in.readInt();
if (offset <= 0 || offset >= in.length()) break;
}
Hashtable[] ifds = new Hashtable[v.size()];
v.copyInto(ifds);
return ifds;
}
/**
* Gets the first IFD within the given TIFF file, or null
* if the given file is not a valid TIFF file.
*/
public static Hashtable getFirstIFD(RandomAccessStream in) throws IOException
{
// check TIFF header
Boolean result = checkHeader(in);
if (result == null) return null;
long offset = getFirstOffset(in);
return getIFD(in, 0, offset);
}
/**
* Retrieve a given entry from the first IFD in a stream.
*
* @param in the stream to retrieve the entry from.
* @param tag the tag of the entry to be retrieved.
* @return an object representing the entry's fields.
* @throws IOException when there is an error accessing the stream <i>in</i>.
*/
public static TiffIFDEntry getFirstIFDEntry(RandomAccessStream in, int tag)
throws IOException
{
// First lets re-position the file pointer by checking the TIFF header
Boolean result = checkHeader(in);
if (result == null) return null;
// Get the offset of the first IFD
long offset = getFirstOffset(in);
// The following loosely resembles the logic of getIFD()...
in.seek(offset);
int numEntries = in.readShort();
if (numEntries < 0) numEntries += 65536;
for (int i = 0; i < numEntries; i++) {
in.seek(offset + // The beginning of the IFD
2 + // The width of the initial numEntries field
(BYTES_PER_ENTRY * i));
int entryTag = in.readShort();
if (entryTag < 0) entryTag += 65536;
// Skip this tag unless it matches the one we want
if (entryTag != tag) continue;
// Parse the entry's "Type"
int entryType = in.readShort();
if (entryType < 0) entryType += 65536;
// Parse the entry's "ValueCount"
int valueCount = in.readInt();
if (valueCount < 0) {
throw new RuntimeException("Count of '" + valueCount + "' unexpected.");
}
// Parse the entry's "ValueOffset"
int valueOffset = in.readInt();
return new TiffIFDEntry(entryTag, entryType, valueCount, valueOffset);
}
throw new UnknownTagException();
}
/**
* Checks the TIFF header.
* @return true if little-endian,
* false if big-endian,
* or null if not a TIFF.
*/
public static Boolean checkHeader(RandomAccessStream in) throws IOException {
if (DEBUG) debug("getIFDs: reading IFD entries");
// start at the beginning of the file
in.seek(0);
byte[] header = new byte[4];
in.readFully(header);
Boolean b = checkHeader(header);
if (b != null) in.order(b.booleanValue());
return b;
}
/**
* Gets offset to the first IFD, or -1 if stream is not TIFF.
* Assumes the stream is positioned properly (checkHeader just called).
*/
public static long getFirstOffset(RandomAccessStream in)
throws IOException
{
// get offset to first IFD
return in.readInt();
}
/** Gets the IFD stored at the given offset. */
public static Hashtable getIFD(RandomAccessStream in,
long ifdNum, long offset) throws IOException
{
Hashtable ifd = new Hashtable();
// save little-endian flag to internal LITTLE_ENDIAN tag
ifd.put(new Integer(LITTLE_ENDIAN), new Boolean(in.isLittleEndian()));
// read in directory entries for this IFD
if (DEBUG) {
debug("getIFDs: seeking IFD #" + ifdNum + " at " + offset);
}
in.seek((int) offset);
int numEntries = in.readShort();
if (numEntries < 0) numEntries += 65536;
if (DEBUG) debug("getIFDs: " + numEntries + " directory entries to read");
if (numEntries == 0 || numEntries == 1) return ifd;
for (int i=0; i<numEntries; i++) {
in.seek((int) (offset + 2 + 12 * i));
int tag = in.readShort();
if (tag < 0) tag += 65536;
int type = in.readShort();
if (type < 0) type += 65536;
int count = in.readInt();
if (DEBUG) {
debug("getIFDs: read " + getIFDTagName(tag) +
" (type=" + getIFDTypeName(type) + "; count=" + count + ")");
}
if (count < 0) return null; // invalid data
Object value = null;
if (type == BYTE) {
// 8-bit unsigned integer
if (count > 4) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Short((byte) in.read());
else {
short[] bytes = new short[count];
for (int j=0; j<count; j++) {
bytes[j] = (byte) in.read();
if (bytes[j] < 0) bytes[j] += 255;
}
value = bytes;
}
}
else if (type == ASCII) {
// 8-bit byte that contain a 7-bit ASCII code;
// the last byte must be NUL (binary zero)
byte[] ascii = new byte[count];
if (count > 4) {
long pointer = in.readInt();
in.seek((int) pointer);
}
in.read(ascii);
// count number of null terminators
int nullCount = 0;
for (int j=0; j<count; j++) {
if (ascii[j] == 0 || j == count - 1) nullCount++;
}
// convert character array to array of strings
String[] strings = nullCount == 1 ? null : new String[nullCount];
String s = null;
int c = 0, ndx = -1;
for (int j=0; j<count; j++) {
if (ascii[j] == 0) {
s = new String(ascii, ndx + 1, j - ndx - 1);
ndx = j;
}
else if (j == count - 1) {
// handle non-null-terminated strings
s = new String(ascii, ndx + 1, j - ndx);
}
else s = null;
if (strings != null && s != null) strings[c++] = s;
}
value = strings == null ? (Object) s : strings;
}
else if (type == SHORT) {
// 16-bit (2-byte) unsigned integer
if (count > 2) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Integer(in.readShort());
else {
int[] shorts = new int[count];
for (int j=0; j<count; j++) {
shorts[j] = in.readShort();
if (shorts[j] < 0) shorts[j] += 65536;
}
value = shorts;
}
}
else if (type == LONG) {
// 32-bit (4-byte) unsigned integer
if (count > 1) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Long(in.readInt());
else {
long[] longs = new long[count];
for (int j=0; j<count; j++) longs[j] = in.readInt();
value = longs;
}
}
else if (type == RATIONAL || type == SRATIONAL) {
// Two LONGs: the first represents the numerator of a fraction;
// the second, the denominator
// Two SLONG's: the first represents the numerator of a fraction,
// the second the denominator
long pointer = in.readInt();
in.seek((int) pointer);
if (count == 1) value = new TiffRational(in.readInt(), in.readInt());
else {
TiffRational[] rationals = new TiffRational[count];
for (int j=0; j<count; j++) {
rationals[j] = new TiffRational(in.readInt(), in.readInt());
}
value = rationals;
}
}
else if (type == SBYTE || type == UNDEFINED) {
// SBYTE: An 8-bit signed (twos-complement) integer
// UNDEFINED: An 8-bit byte that may contain anything,
// depending on the definition of the field
if (count > 4) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Byte((byte) in.read());
else {
byte[] sbytes = new byte[count];
in.readFully(sbytes);
value = sbytes;
}
}
else if (type == SSHORT) {
// A 16-bit (2-byte) signed (twos-complement) integer
if (count > 2) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Short(in.readShort());
else {
short[] sshorts = new short[count];
for (int j=0; j<count; j++) sshorts[j] = in.readShort();
value = sshorts;
}
}
else if (type == SLONG) {
// A 32-bit (4-byte) signed (twos-complement) integer
if (count > 1) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Integer(in.readInt());
else {
int[] slongs = new int[count];
for (int j=0; j<count; j++) slongs[j] = in.readInt();
value = slongs;
}
}
else if (type == FLOAT) {
// Single precision (4-byte) IEEE format
if (count > 1) {
long pointer = in.readInt();
in.seek((int) pointer);
}
if (count == 1) value = new Float(in.readFloat());
else {
float[] floats = new float[count];
for (int j=0; j<count; j++) floats[j] = in.readFloat();
value = floats;
}
}
else if (type == DOUBLE) {
// Double precision (8-byte) IEEE format
long pointer = in.readInt();
in.seek((int) pointer);
if (count == 1) value = new Double(in.readDouble());
else {
double[] doubles = new double[count];
for (int j=0; j<count; j++) {
doubles[j] = in.readDouble();
}
value = doubles;
}
}
if (value != null) ifd.put(new Integer(tag), value);
}
in.seek((int) (offset + 2 + 12 * numEntries));
return ifd;
}
/** Gets the name of the IFD tag encoded by the given number. */
public static String getIFDTagName(int tag) { return getFieldName(tag); }
/** Gets the name of the IFD type encoded by the given number. */
public static String getIFDTypeName(int type) { return getFieldName(type); }
/**
* This method uses reflection to scan the values of this class's
* static fields, returning the first matching field's name. It is
* probably not very efficient, and is mainly intended for debugging.
*/
public static String getFieldName(int value) {
Field[] fields = TiffTools.class.getFields();
for (int i=0; i<fields.length; i++) {
try {
if (fields[i].getInt(null) == value) return fields[i].getName();
}
catch (Exception exc) { }
}
return "" + value;
}
/** Gets the given directory entry value from the specified IFD. */
public static Object getIFDValue(Hashtable ifd, int tag) {
return ifd.get(new Integer(tag));
}
/**
* Gets the given directory entry value from the specified IFD,
* performing some error checking.
*/
public static Object getIFDValue(Hashtable ifd,
int tag, boolean checkNull, Class checkClass) throws FormatException
{
Object value = ifd.get(new Integer(tag));
if (checkNull && value == null) {
throw new FormatException(
getIFDTagName(tag) + " directory entry not found");
}
if (checkClass != null && value != null &&
!checkClass.isInstance(value))
{
// wrap object in array of length 1, if appropriate
Class cType = checkClass.getComponentType();
Object array = null;
if (cType == value.getClass()) {
array = Array.newInstance(value.getClass(), 1);
Array.set(array, 0, value);
}
if (cType == boolean.class && value instanceof Boolean) {
array = Array.newInstance(boolean.class, 1);
Array.setBoolean(array, 0, ((Boolean) value).booleanValue());
}
else if (cType == byte.class && value instanceof Byte) {
array = Array.newInstance(byte.class, 1);
Array.setByte(array, 0, ((Byte) value).byteValue());
}
else if (cType == char.class && value instanceof Character) {
array = Array.newInstance(char.class, 1);
Array.setChar(array, 0, ((Character) value).charValue());
}
else if (cType == double.class && value instanceof Double) {
array = Array.newInstance(double.class, 1);
Array.setDouble(array, 0, ((Double) value).doubleValue());
}
else if (cType == float.class && value instanceof Float) {
array = Array.newInstance(float.class, 1);
Array.setFloat(array, 0, ((Float) value).floatValue());
}
else if (cType == int.class && value instanceof Integer) {
array = Array.newInstance(int.class, 1);
Array.setInt(array, 0, ((Integer) value).intValue());
}
else if (cType == long.class && value instanceof Long) {
array = Array.newInstance(long.class, 1);
Array.setLong(array, 0, ((Long) value).longValue());
}
else if (cType == short.class && value instanceof Short) {
array = Array.newInstance(short.class, 1);
Array.setShort(array, 0, ((Short) value).shortValue());
}
if (array != null) return array;
throw new FormatException(getIFDTagName(tag) +
" directory entry is the wrong type (got " +
value.getClass().getName() + ", expected " + checkClass.getName());
}
return value;
}
/**
* Gets the given directory entry value in long format from the
* specified IFD, performing some error checking.
*/
public static long getIFDLongValue(Hashtable ifd, int tag,
boolean checkNull, long defaultValue) throws FormatException
{
long value = defaultValue;
Number number = (Number) getIFDValue(ifd, tag, checkNull, Number.class);
if (number != null) value = number.longValue();
return value;
}
/**
* Gets the given directory entry value in int format from the
* specified IFD, or -1 if the given directory does not exist.
*/
public static int getIFDIntValue(Hashtable ifd, int tag) {
int value = -1;
try {
value = getIFDIntValue(ifd, tag, false, -1);
}
catch (FormatException exc) { }
return value;
}
/**
* Gets the given directory entry value in int format from the
* specified IFD, performing some error checking.
*/
public static int getIFDIntValue(Hashtable ifd, int tag,
boolean checkNull, int defaultValue) throws FormatException
{
int value = defaultValue;
Number number = (Number) getIFDValue(ifd, tag, checkNull, Number.class);
if (number != null) value = number.intValue();
return value;
}
/**
* Gets the given directory entry value in rational format from the
* specified IFD, performing some error checking.
*/
public static TiffRational getIFDRationalValue(Hashtable ifd, int tag,
boolean checkNull) throws FormatException
{
return (TiffRational) getIFDValue(ifd, tag, checkNull, TiffRational.class);
}
/**
* Gets the given directory entry values in long format
* from the specified IFD, performing some error checking.
*/
public static long[] getIFDLongArray(Hashtable ifd,
int tag, boolean checkNull) throws FormatException
{
Object value = getIFDValue(ifd, tag, checkNull, null);
long[] results = null;
if (value instanceof long[]) results = (long[]) value;
else if (value instanceof Number) {
results = new long[] {((Number) value).longValue()};
}
else if (value instanceof Number[]) {
Number[] numbers = (Number[]) value;
results = new long[numbers.length];
for (int i=0; i<results.length; i++) results[i] = numbers[i].longValue();
}
else if (value instanceof int[]) { // convert int[] to long[]
int[] integers = (int[]) value;
results = new long[integers.length];
for (int i=0; i<integers.length; i++) results[i] = integers[i];
}
else if (value != null) {
throw new FormatException(getIFDTagName(tag) +
" directory entry is the wrong type (got " +
value.getClass().getName() +
", expected Number, long[], Number[] or int[])");
}
return results;
}
/**
* Gets the given directory entry values in int format
* from the specified IFD, performing some error checking.
*/
public static int[] getIFDIntArray(Hashtable ifd,
int tag, boolean checkNull) throws FormatException
{
Object value = getIFDValue(ifd, tag, checkNull, null);
int[] results = null;
if (value instanceof int[]) results = (int[]) value;
else if (value instanceof Number) {
results = new int[] {((Number) value).intValue()};
}
else if (value instanceof Number[]) {
Number[] numbers = (Number[]) value;
results = new int[numbers.length];
for (int i=0; i<results.length; i++) results[i] = numbers[i].intValue();
}
else if (value != null) {
throw new FormatException(getIFDTagName(tag) +
" directory entry is the wrong type (got " +
value.getClass().getName() + ", expected Number, int[] or Number[])");
}
return results;
}
/**
* Gets the given directory entry values in short format
* from the specified IFD, performing some error checking.
*/
public static short[] getIFDShortArray(Hashtable ifd,
int tag, boolean checkNull) throws FormatException
{
Object value = getIFDValue(ifd, tag, checkNull, null);
short[] results = null;
if (value instanceof short[]) results = (short[]) value;
else if (value instanceof Number) {
results = new short[] {((Number) value).shortValue()};
}
else if (value instanceof Number[]) {
Number[] numbers = (Number[]) value;
results = new short[numbers.length];
for (int i=0; i<results.length; i++) {
results[i] = numbers[i].shortValue();
}
}
else if (value != null) {
throw new FormatException(getIFDTagName(tag) +
" directory entry is the wrong type (got " +
value.getClass().getName() +
", expected Number, short[] or Number[])");
}
return results;
}
// -- Image reading methods --
/** Reads the image defined in the given IFD from the specified file. */
public static byte[][] getSamples(Hashtable ifd, RandomAccessStream in)
throws FormatException, IOException
{
int samplesPerPixel = getSamplesPerPixel(ifd);
int photoInterp = getPhotometricInterpretation(ifd);
if (samplesPerPixel == 1 && (photoInterp == RGB_PALETTE ||
photoInterp == CFA_ARRAY))
{
samplesPerPixel = 3;
}
int bpp = getBitsPerSample(ifd)[0];
while ((bpp % 8) != 0) bpp++;
bpp /= 8;
long width = getImageWidth(ifd);
long length = getImageLength(ifd);
byte[] b = new byte[(int) (width * length * samplesPerPixel * bpp)];
getSamples(ifd, in, b);
byte[][] samples = new byte[samplesPerPixel][(int) (width * length * bpp)];
for (int i=0; i<samplesPerPixel; i++) {
System.arraycopy(b, (int) (i*width*length*bpp), samples[i], 0,
samples[i].length);
}
b = null;
return samples;
}
public static byte[] getSamples(Hashtable ifd, RandomAccessStream in,
byte[] buf) throws FormatException, IOException
{
if (DEBUG) debug("parsing IFD entries");
// get internal non-IFD entries
boolean littleEndian = isLittleEndian(ifd);
in.order(littleEndian);
// get relevant IFD entries
long imageWidth = getImageWidth(ifd);
long imageLength = getImageLength(ifd);
int[] bitsPerSample = getBitsPerSample(ifd);
int samplesPerPixel = getSamplesPerPixel(ifd);
int compression = getCompression(ifd);
int photoInterp = getPhotometricInterpretation(ifd);
long[] stripOffsets = getStripOffsets(ifd);
long[] stripByteCounts = getStripByteCounts(ifd);
long[] rowsPerStripArray = getRowsPerStrip(ifd);
boolean fakeByteCounts = stripByteCounts == null;
boolean fakeRPS = rowsPerStripArray == null;
boolean isTiled = stripOffsets == null;
- long maxValue = getIFDLongValue(ifd, MAX_SAMPLE_VALUE, false, 0);
+ long[] maxes = getIFDLongArray(ifd, MAX_SAMPLE_VALUE, false);
+ long maxValue = maxes == null ? 0 : maxes[0];
if (ifd.get(new Integer(VALID_BITS)) == null && bitsPerSample[0] > 0) {
int[] validBits = bitsPerSample;
if (photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY) {
int vb = validBits[0];
validBits = new int[3];
for (int i=0; i<validBits.length; i++) validBits[i] = vb;
}
putIFDValue(ifd, VALID_BITS, validBits);
}
if (isTiled) {
stripOffsets = getIFDLongArray(ifd, TILE_OFFSETS, true);
stripByteCounts = getIFDLongArray(ifd, TILE_BYTE_COUNTS, true);
rowsPerStripArray = new long[] {imageLength};
}
else if (fakeByteCounts) {
// technically speaking, this shouldn't happen (since TIFF writers are
// required to write the StripByteCounts tag), but we'll support it
// anyway
// don't rely on RowsPerStrip, since it's likely that if the file doesn't
// have the StripByteCounts tag, it also won't have the RowsPerStrip tag
stripByteCounts = new long[stripOffsets.length];
stripByteCounts[0] = stripOffsets[0];
for (int i=1; i<stripByteCounts.length; i++) {
stripByteCounts[i] = stripOffsets[i] - stripByteCounts[i-1];
}
}
boolean lastBitsZero = bitsPerSample[bitsPerSample.length - 1] == 0;
if (fakeRPS && !isTiled) {
// create a false rowsPerStripArray if one is not present
// it's sort of a cheap hack, but here's how it's done:
// RowsPerStrip = stripByteCounts / (imageLength * bitsPerSample)
// since stripByteCounts and bitsPerSample are arrays, we have to
// iterate through each item
rowsPerStripArray = new long[bitsPerSample.length];
long temp = stripByteCounts[0];
stripByteCounts = new long[bitsPerSample.length];
for (int i=0; i<stripByteCounts.length; i++) stripByteCounts[i] = temp;
temp = bitsPerSample[0];
if (temp == 0) temp = 8;
bitsPerSample = new int[bitsPerSample.length];
for (int i=0; i<bitsPerSample.length; i++) bitsPerSample[i] = (int) temp;
temp = stripOffsets[0];
stripOffsets = new long[bitsPerSample.length];
for (int i=0; i<bitsPerSample.length; i++) {
stripOffsets[i] = i == 0 ? temp :
stripOffsets[i - 1] + stripByteCounts[i];
}
// we have two files that reverse the endianness for BitsPerSample,
// StripOffsets, and StripByteCounts
if (bitsPerSample[0] > 64) {
byte[] bps = new byte[2];
byte[] stripOffs = new byte[4];
byte[] byteCounts = new byte[4];
if (littleEndian) {
bps[0] = (byte) (bitsPerSample[0] & 0xff);
bps[1] = (byte) ((bitsPerSample[0] >>> 8) & 0xff);
int ndx = stripOffsets.length - 1;
stripOffs[0] = (byte) (stripOffsets[ndx] & 0xff);
stripOffs[1] = (byte) ((stripOffsets[ndx] >>> 8) & 0xff);
stripOffs[2] = (byte) ((stripOffsets[ndx] >>> 16) & 0xff);
stripOffs[3] = (byte) ((stripOffsets[ndx] >>> 24) & 0xff);
ndx = stripByteCounts.length - 1;
byteCounts[0] = (byte) (stripByteCounts[ndx] & 0xff);
byteCounts[1] = (byte) ((stripByteCounts[ndx] >>> 8) & 0xff);
byteCounts[2] = (byte) ((stripByteCounts[ndx] >>> 16) & 0xff);
byteCounts[3] = (byte) ((stripByteCounts[ndx] >>> 24) & 0xff);
}
else {
bps[1] = (byte) ((bitsPerSample[0] >>> 16) & 0xff);
bps[0] = (byte) ((bitsPerSample[0] >>> 24) & 0xff);
stripOffs[3] = (byte) (stripOffsets[0] & 0xff);
stripOffs[2] = (byte) ((stripOffsets[0] >>> 8) & 0xff);
stripOffs[1] = (byte) ((stripOffsets[0] >>> 16) & 0xff);
stripOffs[0] = (byte) ((stripOffsets[0] >>> 24) & 0xff);
byteCounts[3] = (byte) (stripByteCounts[0] & 0xff);
byteCounts[2] = (byte) ((stripByteCounts[0] >>> 8) & 0xff);
byteCounts[1] = (byte) ((stripByteCounts[0] >>> 16) & 0xff);
byteCounts[0] = (byte) ((stripByteCounts[0] >>> 24) & 0xff);
}
bitsPerSample[0] = DataTools.bytesToInt(bps, !littleEndian);
stripOffsets[0] = DataTools.bytesToInt(stripOffs, !littleEndian);
stripByteCounts[0] = DataTools.bytesToInt(byteCounts, !littleEndian);
}
if (rowsPerStripArray.length == 1 && stripByteCounts[0] !=
(imageWidth * imageLength * (bitsPerSample[0] / 8)) &&
compression == UNCOMPRESSED)
{
for (int i=0; i<stripByteCounts.length; i++) {
stripByteCounts[i] =
imageWidth * imageLength * (bitsPerSample[i] / 8);
stripOffsets[0] = (int) (in.length() - stripByteCounts[0] -
48 * imageWidth);
if (i != 0) {
stripOffsets[i] = stripOffsets[i - 1] + stripByteCounts[i];
}
in.seek((int) stripOffsets[i]);
in.read(buf, (int) (i*imageWidth), (int) imageWidth);
boolean isZero = true;
for (int j=0; j<imageWidth; j++) {
if (buf[(int) (i*imageWidth + j)] != 0) {
isZero = false;
break;
}
}
while (isZero) {
stripOffsets[i] -= imageWidth;
in.seek((int) stripOffsets[i]);
in.read(buf, (int) (i*imageWidth), (int) imageWidth);
for (int j=0; j<imageWidth; j++) {
if (buf[(int) (i*imageWidth + j)] != 0) {
isZero = false;
stripOffsets[i] -= (stripByteCounts[i] - imageWidth);
break;
}
}
}
}
}
for (int i=0; i<bitsPerSample.length; i++) {
// case 1: we're still within bitsPerSample array bounds
if (i < bitsPerSample.length) {
if (i == samplesPerPixel) {
bitsPerSample[i] = 0;
lastBitsZero = true;
}
// remember that the universe collapses when we divide by 0
if (bitsPerSample[i] != 0) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[i] / 8));
}
else if (bitsPerSample[i] == 0 && i > 0) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[i - 1] / 8));
bitsPerSample[i] = bitsPerSample[i - 1];
}
else {
throw new FormatException("BitsPerSample is 0");
}
}
// case 2: we're outside bitsPerSample array bounds
else if (i >= bitsPerSample.length) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[bitsPerSample.length - 1] / 8));
}
}
samplesPerPixel = stripOffsets.length;
}
if (lastBitsZero) {
bitsPerSample[bitsPerSample.length - 1] = 0;
samplesPerPixel--;
}
TiffRational xResolution = getIFDRationalValue(ifd, X_RESOLUTION, false);
TiffRational yResolution = getIFDRationalValue(ifd, Y_RESOLUTION, false);
int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1);
int resolutionUnit = getIFDIntValue(ifd, RESOLUTION_UNIT, false, 2);
if (xResolution == null || yResolution == null) resolutionUnit = 0;
int[] colorMap = getIFDIntArray(ifd, COLOR_MAP, false);
int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1);
// If the subsequent color maps are empty, use the first IFD's color map
if (colorMap == null) {
colorMap = getIFDIntArray(getFirstIFD(in), COLOR_MAP, false);
}
// use special color map for YCbCr
if (photoInterp == Y_CB_CR) {
int[] tempColorMap = getIFDIntArray(ifd, Y_CB_CR_COEFFICIENTS, false);
int[] refBlackWhite = getIFDIntArray(ifd, REFERENCE_BLACK_WHITE, false);
colorMap = new int[tempColorMap.length + refBlackWhite.length];
System.arraycopy(tempColorMap, 0, colorMap, 0, tempColorMap.length);
System.arraycopy(refBlackWhite, 0, colorMap, tempColorMap.length,
refBlackWhite.length);
}
if (DEBUG) {
StringBuffer sb = new StringBuffer();
sb.append("IFD directory entry values:");
sb.append("\n\tLittleEndian=");
sb.append(littleEndian);
sb.append("\n\tImageWidth=");
sb.append(imageWidth);
sb.append("\n\tImageLength=");
sb.append(imageLength);
sb.append("\n\tBitsPerSample=");
sb.append(bitsPerSample[0]);
for (int i=1; i<bitsPerSample.length; i++) {
sb.append(",");
sb.append(bitsPerSample[i]);
}
sb.append("\n\tSamplesPerPixel=");
sb.append(samplesPerPixel);
sb.append("\n\tCompression=");
sb.append(compression);
sb.append("\n\tPhotometricInterpretation=");
sb.append(photoInterp);
sb.append("\n\tStripOffsets=");
sb.append(stripOffsets[0]);
for (int i=1; i<stripOffsets.length; i++) {
sb.append(",");
sb.append(stripOffsets[i]);
}
sb.append("\n\tRowsPerStrip=");
sb.append(rowsPerStripArray[0]);
for (int i=1; i<rowsPerStripArray.length; i++) {
sb.append(",");
sb.append(rowsPerStripArray[i]);
}
sb.append("\n\tStripByteCounts=");
sb.append(stripByteCounts[0]);
for (int i=1; i<stripByteCounts.length; i++) {
sb.append(",");
sb.append(stripByteCounts[i]);
}
sb.append("\n\tXResolution=");
sb.append(xResolution);
sb.append("\n\tYResolution=");
sb.append(yResolution);
sb.append("\n\tPlanarConfiguration=");
sb.append(planarConfig);
sb.append("\n\tResolutionUnit=");
sb.append(resolutionUnit);
sb.append("\n\tColorMap=");
if (colorMap == null) sb.append("null");
else {
sb.append(colorMap[0]);
for (int i=1; i<colorMap.length; i++) {
sb.append(",");
sb.append(colorMap[i]);
}
}
sb.append("\n\tPredictor=");
sb.append(predictor);
debug(sb.toString());
}
for (int i=0; i<samplesPerPixel; i++) {
if (bitsPerSample[i] < 1) {
throw new FormatException("Illegal BitsPerSample (" +
bitsPerSample[i] + ")");
}
// don't support odd numbers of bits (except for 1)
else if (bitsPerSample[i] % 2 != 0 && bitsPerSample[i] != 1) {
throw new FormatException("Sorry, unsupported BitsPerSample (" +
bitsPerSample[i] + ")");
}
}
if (bitsPerSample.length < samplesPerPixel) {
throw new FormatException("BitsPerSample length (" +
bitsPerSample.length + ") does not match SamplesPerPixel (" +
samplesPerPixel + ")");
}
else if (photoInterp == TRANSPARENCY_MASK) {
throw new FormatException(
"Sorry, Transparency Mask PhotometricInterpretation is not supported");
}
else if (photoInterp == Y_CB_CR) {
throw new FormatException(
"Sorry, YCbCr PhotometricInterpretation is not supported");
}
else if (photoInterp == CIE_LAB) {
throw new FormatException(
"Sorry, CIELAB PhotometricInterpretation is not supported");
}
else if (photoInterp != WHITE_IS_ZERO &&
photoInterp != BLACK_IS_ZERO && photoInterp != RGB &&
photoInterp != RGB_PALETTE && photoInterp != CMYK &&
photoInterp != Y_CB_CR && photoInterp != CFA_ARRAY)
{
throw new FormatException("Unknown PhotometricInterpretation (" +
photoInterp + ")");
}
long rowsPerStrip = rowsPerStripArray[0];
for (int i=1; i<rowsPerStripArray.length; i++) {
if (rowsPerStrip != rowsPerStripArray[i]) {
throw new FormatException(
"Sorry, non-uniform RowsPerStrip is not supported");
}
}
long numStrips = (imageLength + rowsPerStrip - 1) / rowsPerStrip;
if (isTiled) numStrips = stripOffsets.length;
if (planarConfig == 2) numStrips *= samplesPerPixel;
if (stripOffsets.length < numStrips) {
throw new FormatException("StripOffsets length (" +
stripOffsets.length + ") does not match expected " +
"number of strips (" + numStrips + ")");
}
if (stripByteCounts.length < numStrips) {
throw new FormatException("StripByteCounts length (" +
stripByteCounts.length + ") does not match expected " +
"number of strips (" + numStrips + ")");
}
if (imageWidth > Integer.MAX_VALUE || imageLength > Integer.MAX_VALUE ||
imageWidth * imageLength > Integer.MAX_VALUE)
{
throw new FormatException("Sorry, ImageWidth x ImageLength > " +
Integer.MAX_VALUE + " is not supported (" +
imageWidth + " x " + imageLength + ")");
}
int numSamples = (int) (imageWidth * imageLength);
if (planarConfig != 1 && planarConfig != 2) {
throw new FormatException(
"Unknown PlanarConfiguration (" + planarConfig + ")");
}
// read in image strips
if (DEBUG) {
debug("reading image data (samplesPerPixel=" +
samplesPerPixel + "; numSamples=" + numSamples + ")");
}
if (samplesPerPixel == 1 &&
(photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY))
{
samplesPerPixel = 3;
}
if (photoInterp == CFA_ARRAY) {
int[] tempMap = new int[colorMap.length + 2];
System.arraycopy(colorMap, 0, tempMap, 0, colorMap.length);
tempMap[tempMap.length - 2] = (int) imageWidth;
tempMap[tempMap.length - 1] = (int) imageLength;
colorMap = tempMap;
}
//if (planarConfig == 2) numSamples *= samplesPerPixel;
short[][] samples = new short[samplesPerPixel][numSamples];
byte[] altBytes = new byte[0];
if (bitsPerSample[0] == 16) littleEndian = !littleEndian;
if (isTiled) {
long tileWidth = getIFDLongValue(ifd, TILE_WIDTH, true, 0);
long tileLength = getIFDLongValue(ifd, TILE_LENGTH, true, 0);
byte[] data = new byte[(int) stripByteCounts[0] * stripOffsets.length];
int row = 0;
int col = 0;
int bytes = bitsPerSample[0] / 8;
for (int i=0; i<stripOffsets.length; i++) {
byte[] b = new byte[(int) stripByteCounts[i]];
in.seek(stripOffsets[i]);
in.read(b);
b = uncompress(b, compression);
int rowBytes = (int) (tileWidth *
(stripByteCounts[0] / (tileWidth*tileLength)));
for (int j=0; j<tileLength; j++) {
int len = rowBytes;
if (col*bytes + rowBytes > imageWidth*bytes) {
len = (int) (imageWidth*bytes - col*bytes);
}
System.arraycopy(b, j*rowBytes, data,
(int) ((row+j)*imageWidth*bytes + col*bytes), len);
}
// update row and column
col += (int) tileWidth;
if (col >= imageWidth) {
row += (int) tileLength;
col = 0;
}
}
undifference(data, bitsPerSample, imageWidth, planarConfig, predictor);
unpackBytes(samples, 0, data, bitsPerSample, photoInterp, colorMap,
littleEndian, maxValue, planarConfig, 0, 1, imageWidth);
}
else {
int overallOffset = 0;
for (int strip=0, row=0; strip<numStrips; strip++, row+=rowsPerStrip) {
try {
if (DEBUG) debug("reading image strip #" + strip);
in.seek((int) stripOffsets[strip]);
if (stripByteCounts[strip] > Integer.MAX_VALUE) {
throw new FormatException("Sorry, StripByteCounts > " +
Integer.MAX_VALUE + " is not supported");
}
byte[] bytes = new byte[(int) stripByteCounts[strip]];
in.read(bytes);
if (compression != PACK_BITS) {
bytes = uncompress(bytes, compression);
undifference(bytes, bitsPerSample,
imageWidth, planarConfig, predictor);
int offset = (int) (imageWidth * row);
if (planarConfig == 2) {
offset = overallOffset / samplesPerPixel;
}
unpackBytes(samples, offset, bytes, bitsPerSample,
photoInterp, colorMap, littleEndian, maxValue, planarConfig,
strip, (int) numStrips, imageWidth);
overallOffset += bytes.length / bitsPerSample.length;
}
else {
// concatenate contents of bytes to altBytes
byte[] tempPackBits = new byte[altBytes.length];
System.arraycopy(altBytes, 0, tempPackBits, 0, altBytes.length);
altBytes = new byte[altBytes.length + bytes.length];
System.arraycopy(tempPackBits, 0, altBytes, 0, tempPackBits.length);
System.arraycopy(bytes, 0, altBytes,
tempPackBits.length, bytes.length);
}
}
catch (Exception e) {
if (strip == 0) {
if (e instanceof FormatException) throw (FormatException) e;
else throw new FormatException(e);
}
byte[] bytes = new byte[samples[0].length];
undifference(bytes, bitsPerSample, imageWidth, planarConfig,
predictor);
int offset = (int) (imageWidth * row);
if (planarConfig == 2) offset = overallOffset / samplesPerPixel;
unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp,
colorMap, littleEndian, maxValue, planarConfig,
strip, (int) numStrips, imageWidth);
overallOffset += bytes.length / bitsPerSample.length;
}
}
}
// only do this if the image uses PackBits compression
if (altBytes.length != 0) {
altBytes = uncompress(altBytes, compression);
undifference(altBytes, bitsPerSample,
imageWidth, planarConfig, predictor);
unpackBytes(samples, (int) imageWidth, altBytes, bitsPerSample,
photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1,
imageWidth);
}
// construct field
if (DEBUG) debug("constructing image");
// Since the lowest common denominator for all pixel operations is "byte"
// we're going to normalize everything to byte.
if (bitsPerSample[0] == 12) bitsPerSample[0] = 16;
if (photoInterp == CFA_ARRAY) {
samples =
ImageTools.demosaic(samples, (int) imageWidth, (int) imageLength);
}
if (bitsPerSample[0] == 16) {
int pt = 0;
for (int i = 0; i < samplesPerPixel; i++) {
for (int j = 0; j < numSamples; j++) {
buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8);
buf[pt++] = (byte) (samples[i][j] & 0xff);
}
}
}
else if (bitsPerSample[0] == 32) {
int pt = 0;
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<numSamples; j++) {
buf[pt++] = (byte) ((samples[i][j] & 0xff000000) >> 24);
buf[pt++] = (byte) ((samples[i][j] & 0xff0000) >> 16);
buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8);
buf[pt++] = (byte) (samples[i][j] & 0xff);
}
}
}
else {
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<numSamples; j++) {
buf[j + i*numSamples] = (byte) samples[i][j];
}
}
}
return buf;
}
/** Reads the image defined in the given IFD from the specified file. */
public static BufferedImage getImage(Hashtable ifd, RandomAccessStream in)
throws FormatException, IOException
{
// construct field
if (DEBUG) debug("constructing image");
byte[][] samples = getSamples(ifd, in);
int[] bitsPerSample = getBitsPerSample(ifd);
long imageWidth = getImageWidth(ifd);
long imageLength = getImageLength(ifd);
int samplesPerPixel = getSamplesPerPixel(ifd);
int photoInterp = getPhotometricInterpretation(ifd);
int[] validBits = getIFDIntArray(ifd, VALID_BITS, false);
if (photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY) {
samplesPerPixel = 3;
}
if (bitsPerSample[0] == 16 || bitsPerSample[0] == 12) {
// First wrap the byte arrays and then use the features of the
// ByteBuffer to transform to a ShortBuffer. Finally, use the ShortBuffer
// bulk get method to copy the data into a usable form for makeImage().
int len = samples.length == 2 ? 3 : samples.length;
short[][] sampleData = new short[len][samples[0].length / 2];
for (int i = 0; i < samplesPerPixel; i++) {
ShortBuffer sampleBuf = ByteBuffer.wrap(samples[i]).asShortBuffer();
sampleBuf.get(sampleData[i]);
}
// Now make our image.
return ImageTools.makeImage(sampleData,
(int) imageWidth, (int) imageLength, validBits);
}
else if (bitsPerSample[0] == 24) {
int[][] intData = new int[samplesPerPixel][samples[0].length / 3];
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<intData[i].length; j++) {
intData[i][j] = DataTools.bytesToInt(samples[i], j*3, 3,
isLittleEndian(ifd));
}
}
return ImageTools.makeImage(intData, (int) imageWidth, (int) imageLength);
}
else if (bitsPerSample[0] == 32) {
int type = getIFDIntValue(ifd, SAMPLE_FORMAT);
if (type == 3) {
// float data
float[][] floatData = new float[samplesPerPixel][samples[0].length / 4];
for (int i=0; i<samplesPerPixel; i++) {
FloatBuffer sampleBuf = ByteBuffer.wrap(samples[i]).asFloatBuffer();
sampleBuf.get(floatData[i]);
}
return ImageTools.makeImage(floatData,
(int) imageWidth, (int) imageLength, validBits);
}
else {
// int data
int[][] intData = new int[samplesPerPixel][samples[0].length / 4];
for (int i=0; i<samplesPerPixel; i++) {
IntBuffer sampleBuf = ByteBuffer.wrap(samples[i]).asIntBuffer();
sampleBuf.get(intData[i]);
}
byte[][] shortData = new byte[samplesPerPixel][intData[0].length];
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<shortData[0].length; j++) {
shortData[i][j] = (byte) intData[i][j];
}
}
return ImageTools.makeImage(shortData,
(int) imageWidth, (int) imageLength, validBits);
}
}
if (samplesPerPixel == 1) {
return ImageTools.makeImage(samples[0], (int) imageWidth,
(int) imageLength, 1, false, validBits);
}
if (samples.length == 2) {
byte[][] s = new byte[3][samples[0].length];
System.arraycopy(samples[0], 0, s[0], 0, s[0].length);
System.arraycopy(samples[1], 0, s[1], 0, s[1].length);
samples = s;
}
return ImageTools.makeImage(samples, (int) imageWidth, (int) imageLength,
validBits);
}
/**
* Extracts pixel information from the given byte array according to the
* bits per sample, photometric interpretation, and the specified byte
* ordering.
* No error checking is performed.
* This method is tailored specifically for planar (separated) images.
*/
public static void planarUnpack(short[][] samples, int startIndex,
byte[] bytes, int[] bitsPerSample, int photoInterp, boolean littleEndian,
int strip, int numStrips) throws FormatException
{
int numChannels = bitsPerSample.length; // this should always be 3
if (bitsPerSample[bitsPerSample.length - 1] == 0) numChannels--;
// determine which channel the strip belongs to
int channelNum = strip / (numStrips / numChannels);
startIndex = (strip % (numStrips / numChannels)) * bytes.length;
int index = 0;
int counter = 0;
for (int j=0; j<bytes.length; j++) {
int numBytes = bitsPerSample[0] / 8;
if (bitsPerSample[0] % 8 != 0) {
// bits per sample is not a multiple of 8
//
// while images in this category are not in violation of baseline TIFF
// specs, it's a bad idea to write bits per sample values that aren't
// divisible by 8
if (index == bytes.length) {
//throw new FormatException("bad index : i = " + i + ", j = " + j);
index--;
}
short b = bytes[index];
index++;
int offset = (bitsPerSample[0] * (samples.length*j + channelNum)) % 8;
if (offset <= (8 - (bitsPerSample[0] % 8))) {
index--;
}
if (channelNum == 0) counter++;
if (counter % 4 == 0 && channelNum == 0) {
index++;
}
int ndx = startIndex + j;
if (ndx >= samples[channelNum].length) {
ndx = samples[channelNum].length - 1;
}
samples[channelNum][ndx] = (short) (b < 0 ? 256 + b : b);
if (photoInterp == WHITE_IS_ZERO || photoInterp == CMYK) {
samples[channelNum][ndx] =
(short) (Integer.MAX_VALUE - samples[channelNum][ndx]);
}
}
else if (numBytes == 1) {
float b = bytes[index];
index++;
int ndx = startIndex + j;
samples[channelNum][ndx] = (short) (b < 0 ? 256 + b : b);
if (photoInterp == WHITE_IS_ZERO) { // invert color value
samples[channelNum][ndx] =
(short) (Integer.MAX_VALUE - samples[channelNum][ndx]);
}
else if (photoInterp == CMYK) {
samples[channelNum][ndx] =
(short) (Integer.MAX_VALUE - samples[channelNum][ndx]);
}
}
else {
byte[] b = new byte[numBytes];
if (numBytes + index < bytes.length) {
System.arraycopy(bytes, index, b, 0, numBytes);
}
else {
System.arraycopy(bytes, bytes.length - numBytes, b, 0, numBytes);
}
index += numBytes;
int ndx = startIndex + j;
if (ndx >= samples[0].length) ndx = samples[0].length - 1;
samples[channelNum][ndx] =
(short) DataTools.bytesToLong(b, !littleEndian);
if (photoInterp == WHITE_IS_ZERO) { // invert color value
long max = 1;
for (int q=0; q<numBytes; q++) max *= 8;
samples[channelNum][ndx] = (short) (max - samples[channelNum][ndx]);
}
else if (photoInterp == CMYK) {
samples[channelNum][ndx] =
(short) (Integer.MAX_VALUE - samples[channelNum][ndx]);
}
}
}
}
/**
* Extracts pixel information from the given byte array according to the
* bits per sample, photometric interpretation and color map IFD directory
* entry values, and the specified byte ordering.
* No error checking is performed.
*/
public static void unpackBytes(short[][] samples, int startIndex,
byte[] bytes, int[] bitsPerSample, int photoInterp, int[] colorMap,
boolean littleEndian, long maxValue, int planar, int strip, int numStrips,
long imageWidth) throws FormatException
{
if (planar == 2) {
planarUnpack(samples, startIndex, bytes, bitsPerSample, photoInterp,
littleEndian, strip, numStrips);
return;
}
int totalBits = 0;
for (int i=0; i<bitsPerSample.length; i++) totalBits += bitsPerSample[i];
int sampleCount = 8 * bytes.length / totalBits;
if (DEBUG) {
debug("unpacking " + sampleCount + " samples (startIndex=" + startIndex +
"; totalBits=" + totalBits + "; numBytes=" + bytes.length + ")");
}
if (startIndex + sampleCount > samples[0].length) {
int trunc = startIndex + sampleCount - samples[0].length;
if (DEBUG) debug("WARNING: truncated " + trunc + " extra samples");
sampleCount -= trunc;
}
// rules on incrementing the index:
// 1) if the planar configuration is set to 1 (interleaved), then add one
// to the index
// 2) if the planar configuration is set to 2 (separated), then go to
// j + (i*(bytes.length / sampleCount))
int bps0 = bitsPerSample[0];
int bpsPow = (int) Math.pow(2, bps0);
int numBytes = bps0 / 8;
boolean noDiv8 = bps0 % 8 != 0;
boolean bps8 = bps0 == 8;
boolean bps16 = bps0 == 16;
if (photoInterp == CFA_ARRAY) {
imageWidth = colorMap[colorMap.length - 2];
}
int row = 0, col = 0;
if (imageWidth != 0) row = startIndex / (int) imageWidth;
int cw = 0;
int ch = 0;
if (photoInterp == CFA_ARRAY) {
byte[] c = new byte[2];
c[0] = (byte) colorMap[0];
c[1] = (byte) colorMap[1];
cw = DataTools.bytesToInt(c, littleEndian);
c[0] = (byte) colorMap[2];
c[1] = (byte) colorMap[3];
ch = DataTools.bytesToInt(c, littleEndian);
int[] tmp = colorMap;
colorMap = new int[tmp.length - 6];
System.arraycopy(tmp, 4, colorMap, 0, colorMap.length);
}
int index = 0;
int count = 0;
BitBuffer bb = new BitBuffer(bytes);
byte[] copyByteArray = new byte[numBytes];
ByteBuffer nioBytes = MappedByteBuffer.wrap(bytes);
if (!littleEndian)
nioBytes.order(ByteOrder.LITTLE_ENDIAN);
for (int j=0; j<sampleCount; j++) {
for (int i=0; i<samples.length; i++) {
if (noDiv8) {
// bits per sample is not a multiple of 8
int ndx = startIndex + j;
short s = 0;
if ((i == 0 && (photoInterp == CFA_ARRAY ||
photoInterp == RGB_PALETTE) || (photoInterp != CFA_ARRAY &&
photoInterp != RGB_PALETTE)))
{
s = (short) bb.getBits(bps0);
if ((ndx % imageWidth) == imageWidth - 1) {
bb.skipBits((imageWidth * bps0 * sampleCount) % 8);
}
}
short b = s;
if (photoInterp != CFA_ARRAY) samples[i][ndx] = s;
if (photoInterp == WHITE_IS_ZERO || photoInterp == CMYK) {
samples[i][ndx] =
(short) (Integer.MAX_VALUE - samples[i][ndx]); // invert colors
}
else if (photoInterp == RGB_PALETTE) {
int x = (int) (b < 0 ? 256 + b : b);
int red = colorMap[x % colorMap.length];
int green = colorMap[(x + bpsPow) %
colorMap.length];
int blue = colorMap[(x + 2*bpsPow) %
colorMap.length];
int[] components = {red, green, blue};
samples[i][ndx] = (short) components[i];
}
else if (photoInterp == CFA_ARRAY) {
if (i == 0) {
int pixelIndex = (int) ((row + (count / cw))*imageWidth + col +
(count % cw));
samples[colorMap[count]][pixelIndex] = s;
count++;
if (count == colorMap.length) {
count = 0;
col += cw*ch;
if (col == imageWidth) col = cw;
else if (col > imageWidth) {
row += ch;
col = 0;
}
}
}
}
}
else if (bps8) {
// special case handles 8-bit data more quickly
//if (planar == 2) { index = j+(i*(bytes.length / samples.length)); }
short b = (short) (bytes[index] & 0xff);
index++;
int ndx = startIndex + j;
samples[i][ndx] = (short) (b < 0 ? Integer.MAX_VALUE + b : b);
if (photoInterp == WHITE_IS_ZERO) { // invert color value
samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]);
}
else if (photoInterp == RGB_PALETTE) {
index--;
int x = (int) (b < 0 ? 256 + b : b);
int cndx = i == 0 ? x : (i == 1 ? (x + bpsPow) : (x + 2*bpsPow));
int cm = colorMap[cndx];
samples[i][ndx] = (short) (maxValue == 0 ? (cm / 256) : cm);
}
else if (photoInterp == CMYK) {
samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]);
}
else if (photoInterp == Y_CB_CR) {
if (i == bitsPerSample.length - 1) {
int lumaRed = colorMap[0];
int lumaGreen = colorMap[1];
int lumaBlue = colorMap[2];
int red = (int)
(samples[2][ndx]*(2 - 2*lumaRed) + samples[0][ndx]);
int blue = (int)
(samples[1][ndx]*(2 - 2*lumaBlue) + samples[0][ndx]);
int green = (int)
(samples[0][ndx] - lumaBlue*blue - lumaRed*red);
if (lumaGreen != 0) green = green / lumaGreen;
samples[0][ndx] = (short) (red - colorMap[4]);
samples[1][ndx] = (short) (green - colorMap[6]);
samples[2][ndx] = (short) (blue - colorMap[8]);
}
}
} // End if (bps8)
else if (bps16) {
int ndx = startIndex + j;
if (numBytes + index < bytes.length) {
samples[i][ndx] = nioBytes.getShort(index);
} else {
samples[i][ndx] = nioBytes.getShort(bytes.length - numBytes);
}
index += numBytes;
if (photoInterp == WHITE_IS_ZERO) { // invert color value
long max = 1;
for (int q=0; q<numBytes; q++) max *= 8;
samples[i][ndx] = (short) (max - samples[i][ndx]);
}
else if (photoInterp == RGB_PALETTE) {
index -= numBytes;
int x = samples[i][ndx]; // this is the index into the color table
int cndx = i == 0 ? x : (i == 1 ? (x + bpsPow) : (x + 2*bpsPow));
int cm = colorMap[cndx];
samples[i][ndx] = (short) (maxValue == 0 ?
(cm % (bpsPow - 1)) : cm);
}
else if (photoInterp == CMYK) {
samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]);
}
} // End if (bps16)
else {
if (numBytes + index < bytes.length) {
System.arraycopy(bytes, index, copyByteArray, 0, numBytes);
}
else {
System.arraycopy(bytes, bytes.length - numBytes, copyByteArray,
0, numBytes);
}
index += numBytes;
int ndx = startIndex + j;
samples[i][ndx] =
(short) DataTools.bytesToLong(copyByteArray, !littleEndian);
if (photoInterp == WHITE_IS_ZERO) { // invert color value
long max = 1;
for (int q=0; q<numBytes; q++) max *= 8;
samples[i][ndx] = (short) (max - samples[i][ndx]);
}
else if (photoInterp == RGB_PALETTE) {
index -= numBytes;
int x = samples[i][ndx]; // this is the index into the color table
int cndx = i == 0 ? x : (i == 1 ? (x + bpsPow) : (x + 2*bpsPow));
int cm = colorMap[cndx];
samples[i][ndx] = (short) (maxValue == 0 ?
(cm % (bpsPow - 1)) : cm);
}
else if (photoInterp == CMYK) {
samples[i][ndx] = (short) (Integer.MAX_VALUE - samples[i][ndx]);
}
} // end else
}
if (photoInterp == RGB_PALETTE) index += (bps0 / 8);
}
}
// -- Decompression methods --
/** Decodes a strip of data compressed with the given compression scheme. */
public static byte[] uncompress(byte[] input, int compression)
throws FormatException, IOException
{
if (compression == UNCOMPRESSED) return input;
else if (compression == CCITT_1D) {
throw new FormatException(
"Sorry, CCITT Group 3 1-Dimensional Modified Huffman " +
"run length encoding compression mode is not supported");
}
else if (compression == GROUP_3_FAX) {
throw new FormatException("Sorry, CCITT T.4 bi-level encoding " +
"(Group 3 Fax) compression mode is not supported");
}
else if (compression == GROUP_4_FAX) {
throw new FormatException("Sorry, CCITT T.6 bi-level encoding " +
"(Group 4 Fax) compression mode is not supported");
}
else if (compression == LZW) {
return new LZWCodec().decompress(input);
}
else if (compression == JPEG) {
throw new FormatException(
"Sorry, JPEG compression mode is not supported");
}
else if (compression == PACK_BITS) {
return new PackbitsCodec().decompress(input);
}
else if (compression == PROPRIETARY_DEFLATE || compression == DEFLATE) {
return new AdobeDeflateCodec().decompress(input);
}
else if (compression == THUNDERSCAN) {
throw new FormatException("Sorry, " +
"Thunderscan compression mode is not supported");
}
else if (compression == NIKON) {
//return new NikonCodec().decompress(input);
throw new FormatException("Sorry, Nikon compression mode is not " +
"supported; we hope to support it in the future");
}
else if (compression == LURAWAVE) {
return new LuraWaveCodec().decompress(input);
}
else {
throw new FormatException(
"Unknown Compression type (" + compression + ")");
}
}
/** Undoes in-place differencing according to the given predictor value. */
public static void undifference(byte[] input, int[] bitsPerSample,
long width, int planarConfig, int predictor) throws FormatException
{
if (predictor == 2) {
if (DEBUG) debug("reversing horizontal differencing");
int len = bitsPerSample.length;
if (bitsPerSample[len - 1] == 0) len = 1;
for (int b=0; b<input.length; b++) {
if (b / len % width == 0) continue;
input[b] += input[b - len];
}
}
else if (predictor != 1) {
throw new FormatException("Unknown Predictor (" + predictor + ")");
}
}
// --------------------------- Writing TIFF files ---------------------------
// -- IFD population methods --
/** Adds a directory entry to an IFD. */
public static void putIFDValue(Hashtable ifd, int tag, Object value) {
ifd.put(new Integer(tag), value);
}
/** Adds a directory entry of type BYTE to an IFD. */
public static void putIFDValue(Hashtable ifd, int tag, short value) {
putIFDValue(ifd, tag, new Short(value));
}
/** Adds a directory entry of type SHORT to an IFD. */
public static void putIFDValue(Hashtable ifd, int tag, int value) {
putIFDValue(ifd, tag, new Integer(value));
}
/** Adds a directory entry of type LONG to an IFD. */
public static void putIFDValue(Hashtable ifd, int tag, long value) {
putIFDValue(ifd, tag, new Long(value));
}
// -- IFD writing methods --
/**
* Writes the given IFD value to the given output object.
* @param ifdOut output object for writing IFD stream
* @param extraBuf buffer to which "extra" IFD information should be written
* @param extraOut data output wrapper for extraBuf (passed for efficiency)
* @param offset global offset to use for IFD offset values
* @param tag IFD tag to write
* @param value IFD value to write
*/
public static void writeIFDValue(DataOutput ifdOut,
ByteArrayOutputStream extraBuf, DataOutputStream extraOut, int offset,
int tag, Object value) throws FormatException, IOException
{
// convert singleton objects into arrays, for simplicity
if (value instanceof Short) {
value = new short[] {((Short) value).shortValue()};
}
else if (value instanceof Integer) {
value = new int[] {((Integer) value).intValue()};
}
else if (value instanceof Long) {
value = new long[] {((Long) value).longValue()};
}
else if (value instanceof TiffRational) {
value = new TiffRational[] {(TiffRational) value};
}
else if (value instanceof Float) {
value = new float[] {((Float) value).floatValue()};
}
else if (value instanceof Double) {
value = new double[] {((Double) value).doubleValue()};
}
// write directory entry to output buffers
ifdOut.writeShort(tag); // tag
if (value instanceof short[]) { // BYTE
short[] q = (short[]) value;
ifdOut.writeShort(BYTE); // type
ifdOut.writeInt(q.length); // count
if (q.length <= 4) {
for (int i=0; i<q.length; i++) ifdOut.writeByte(q[i]); // value(s)
for (int i=q.length; i<4; i++) ifdOut.writeByte(0); // padding
}
else {
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) extraOut.writeByte(q[i]); // values
}
}
else if (value instanceof String) { // ASCII
char[] q = ((String) value).toCharArray();
ifdOut.writeShort(ASCII); // type
ifdOut.writeInt(q.length + 1); // count
if (q.length < 4) {
for (int i=0; i<q.length; i++) ifdOut.writeByte(q[i]); // value(s)
for (int i=q.length; i<4; i++) ifdOut.writeByte(0); // padding
}
else {
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) extraOut.writeByte(q[i]); // values
extraOut.writeByte(0); // concluding NULL byte
}
}
else if (value instanceof int[]) { // SHORT
int[] q = (int[]) value;
ifdOut.writeShort(SHORT); // type
ifdOut.writeInt(q.length); // count
if (q.length <= 2) {
for (int i=0; i<q.length; i++) ifdOut.writeShort(q[i]); // value(s)
for (int i=q.length; i<2; i++) ifdOut.writeShort(0); // padding
}
else {
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) extraOut.writeShort(q[i]); // values
}
}
else if (value instanceof long[]) { // LONG
long[] q = (long[]) value;
ifdOut.writeShort(LONG); // type
ifdOut.writeInt(q.length); // count
if (q.length <= 1) {
if (q.length == 1) ifdOut.writeInt((int) q[0]); // value
else ifdOut.writeInt(0); // padding
}
else {
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) {
extraOut.writeInt((int) q[i]); // values
}
}
}
else if (value instanceof TiffRational[]) { // RATIONAL
TiffRational[] q = (TiffRational[]) value;
ifdOut.writeShort(RATIONAL); // type
ifdOut.writeInt(q.length); // count
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) {
extraOut.writeInt((int) q[i].getNumerator()); // values
extraOut.writeInt((int) q[i].getDenominator()); // values
}
}
else if (value instanceof float[]) { // FLOAT
float[] q = (float[]) value;
ifdOut.writeShort(FLOAT); // type
ifdOut.writeInt(q.length); // count
if (q.length <= 1) {
if (q.length == 1) ifdOut.writeFloat(q[0]); // value
else ifdOut.writeInt(0); // padding
}
else {
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) extraOut.writeFloat(q[i]); // values
}
}
else if (value instanceof double[]) { // DOUBLE
double[] q = (double[]) value;
ifdOut.writeShort(DOUBLE); // type
ifdOut.writeInt(q.length); // count
ifdOut.writeInt(offset + extraBuf.size()); // offset
for (int i=0; i<q.length; i++) extraOut.writeDouble(q[i]); // values
}
else {
throw new FormatException("Unknown IFD value type (" +
value.getClass().getName() + "): " + value);
}
}
/** Convenience method for overwriting a file's first ImageDescription. */
public static void overwriteComment(String id, Object value)
throws FormatException, IOException
{
RandomAccessFile raf = new RandomAccessFile(id, "rw");
overwriteIFDValue(raf, 0, TiffTools.IMAGE_DESCRIPTION, value);
raf.close();
}
/**
* Surgically overwrites an existing IFD value with the given one. This
* method requires that the IFD directory entry already exist. It
* intelligently updates the count field of the entry to match the new
* length. If the new length is longer than the old length, it appends the
* new data to the end of the file and updates the offset field; if not, or
* if the old data is already at the end of the file, it overwrites the old
* data in place.
*/
public static void overwriteIFDValue(RandomAccessFile raf,
int ifd, int tag, Object value) throws FormatException, IOException
{
if (DEBUG) {
debug("overwriteIFDValue (ifd=" + ifd + "; tag=" + tag + "; value=" +
value + ")");
}
byte[] header = new byte[4];
raf.seek(0);
raf.readFully(header);
if (!isValidHeader(header)) {
throw new FormatException("Invalid TIFF header");
}
boolean little = header[0] == LITTLE && header[1] == LITTLE; // II
long offset = 4; // offset to the IFD
int num = 0; // number of directory entries
// skip to the correct IFD
for (int i=0; i<=ifd; i++) {
offset = DataTools.read4UnsignedBytes(raf, little);
if (offset <= 0) {
throw new FormatException("No such IFD (" + ifd + " of " + i + ")");
}
raf.seek(offset);
num = DataTools.read2UnsignedBytes(raf, little);
if (i < ifd) raf.seek(offset + 2 + 12 * num);
}
// search directory entries for proper tag
for (int i=0; i<num; i++) {
int oldTag = DataTools.read2UnsignedBytes(raf, little);
int oldType = DataTools.read2UnsignedBytes(raf, little);
int oldCount = DataTools.read4SignedBytes(raf, little);
int oldOffset = DataTools.read4SignedBytes(raf, little);
if (oldTag == tag) {
// write new value to buffers
ByteArrayOutputStream ifdBuf = new ByteArrayOutputStream(14);
DataOutputStream ifdOut = new DataOutputStream(ifdBuf);
ByteArrayOutputStream extraBuf = new ByteArrayOutputStream();
DataOutputStream extraOut = new DataOutputStream(extraBuf);
writeIFDValue(ifdOut, extraBuf, extraOut, oldOffset, tag, value);
byte[] bytes = ifdBuf.toByteArray();
byte[] extra = extraBuf.toByteArray();
// extract new directory entry parameters
int newTag = DataTools.bytesToInt(bytes, 0, 2, false);
int newType = DataTools.bytesToInt(bytes, 2, 2, false);
int newCount = DataTools.bytesToInt(bytes, 4, false);
int newOffset = DataTools.bytesToInt(bytes, 8, false);
boolean terminate = false;
if (DEBUG) {
debug("overwriteIFDValue:\n\told: (tag=" + oldTag + "; type=" +
oldType + "; count=" + oldCount + "; offset=" + oldOffset +
");\n\tnew: (tag=" + newTag + "; type=" + newType + "; count=" +
newCount + "; offset=" + newOffset + ")");
}
// determine the best way to overwrite the old entry
if (extra.length == 0) {
// new entry is inline; if old entry wasn't, old data is orphaned
// do not override new offset value since data is inline
if (DEBUG) debug("overwriteIFDValue: new entry is inline");
}
else if (oldOffset +
oldCount * BYTES_PER_ELEMENT[oldType] == raf.length())
{
// old entry was already at EOF; overwrite it
newOffset = oldOffset;
terminate = true;
if (DEBUG) debug("overwriteIFDValue: old entry is at EOF");
}
else if (newCount <= oldCount) {
// new entry is as small or smaller than old entry; overwrite it
newOffset = oldOffset;
if (DEBUG) debug("overwriteIFDValue: new entry is <= old entry");
}
else {
// old entry was elsewhere; append to EOF, orphaning old entry
newOffset = (int) raf.length();
if (DEBUG) debug("overwriteIFDValue: old entry will be orphaned");
}
// overwrite old entry
raf.seek(raf.getFilePointer() - 10); // jump back
DataTools.writeShort(raf, newType, little);
DataTools.writeInt(raf, newCount, little);
DataTools.writeInt(raf, newOffset, little);
if (extra.length > 0) {
raf.seek(newOffset);
raf.write(extra);
}
if (terminate) raf.setLength(raf.getFilePointer());
return;
}
}
throw new FormatException("Tag not found (" + getIFDTagName(tag) + ")");
}
// -- Image writing methods --
/**
* Writes the given field to the specified output stream using the given
* byte offset and IFD, in big-endian format.
*
* @param img The field to write
* @param ifd Hashtable representing the TIFF IFD; can be null
* @param out The output stream to which the TIFF data should be written
* @param offset The value to use for specifying byte offsets
* @param last Whether this image is the final IFD entry of the TIFF data
* @return total number of bytes written
*/
public static long writeImage(BufferedImage img, Hashtable ifd,
OutputStream out, int offset, boolean last)
throws FormatException, IOException
{
if (img == null) throw new FormatException("Image is null");
if (DEBUG) debug("writeImage (offset=" + offset + "; last=" + last + ")");
byte[][] values = ImageTools.getPixelBytes(img, false);
int width = img.getWidth();
int height = img.getHeight();
if (values.length < 1 || values.length > 3) {
throw new FormatException("Image has an unsupported " +
"number of range components (" + values.length + ")");
}
if (values.length == 2) {
// pad values with extra set of zeroes
values = new byte[][] {
values[0], values[1], new byte[values[0].length]
};
}
int bytesPerPixel = values[0].length / (width * height);
// populate required IFD directory entries (except strip information)
if (ifd == null) ifd = new Hashtable();
putIFDValue(ifd, IMAGE_WIDTH, width);
putIFDValue(ifd, IMAGE_LENGTH, height);
if (getIFDValue(ifd, BITS_PER_SAMPLE) == null) {
int bps = 8 * bytesPerPixel;
int[] bpsArray = new int[values.length];
Arrays.fill(bpsArray, bps);
putIFDValue(ifd, BITS_PER_SAMPLE, bpsArray);
}
if (img.getRaster().getTransferType() == DataBuffer.TYPE_FLOAT) {
putIFDValue(ifd, SAMPLE_FORMAT, 3);
}
if (getIFDValue(ifd, COMPRESSION) == null) {
putIFDValue(ifd, COMPRESSION, UNCOMPRESSED);
}
if (getIFDValue(ifd, PHOTOMETRIC_INTERPRETATION) == null) {
putIFDValue(ifd, PHOTOMETRIC_INTERPRETATION, values.length == 1 ? 1 : 2);
}
if (getIFDValue(ifd, SAMPLES_PER_PIXEL) == null) {
putIFDValue(ifd, SAMPLES_PER_PIXEL, values.length);
}
if (getIFDValue(ifd, X_RESOLUTION) == null) {
putIFDValue(ifd, X_RESOLUTION, new TiffRational(1, 1)); // no unit
}
if (getIFDValue(ifd, Y_RESOLUTION) == null) {
putIFDValue(ifd, Y_RESOLUTION, new TiffRational(1, 1)); // no unit
}
if (getIFDValue(ifd, RESOLUTION_UNIT) == null) {
putIFDValue(ifd, RESOLUTION_UNIT, 1); // no unit
}
if (getIFDValue(ifd, SOFTWARE) == null) {
putIFDValue(ifd, SOFTWARE, "LOCI Bio-Formats");
}
if (getIFDValue(ifd, IMAGE_DESCRIPTION) == null) {
putIFDValue(ifd, IMAGE_DESCRIPTION, "");
}
// create pixel output buffers
int stripSize = 8192;
int rowsPerStrip = stripSize / (width * bytesPerPixel);
int stripsPerImage = (height + rowsPerStrip - 1) / rowsPerStrip;
int[] bps = (int[]) getIFDValue(ifd, BITS_PER_SAMPLE, true, int[].class);
ByteArrayOutputStream[] stripBuf =
new ByteArrayOutputStream[stripsPerImage];
DataOutputStream[] stripOut = new DataOutputStream[stripsPerImage];
for (int i=0; i<stripsPerImage; i++) {
stripBuf[i] = new ByteArrayOutputStream(stripSize);
stripOut[i] = new DataOutputStream(stripBuf[i]);
}
// write pixel strips to output buffers
for (int y=0; y<height; y++) {
int strip = y / rowsPerStrip;
for (int x=0; x<width; x++) {
int ndx = y * width * bytesPerPixel + x * bytesPerPixel;
for (int c=0; c<values.length; c++) {
int q = values[c][ndx];
if (bps[c] == 8) stripOut[strip].writeByte(q);
else if (bps[c] == 16) {
stripOut[strip].writeByte(q);
stripOut[strip].writeByte(values[c][ndx+1]);
}
else if (bps[c] == 32) {
for (int i=0; i<4; i++) {
stripOut[strip].writeByte(values[c][ndx + i]);
}
}
else {
throw new FormatException("Unsupported bits per sample value (" +
bps[c] + ")");
}
}
}
}
// compress strips according to given differencing and compression schemes
int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1);
int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1);
int compression = getIFDIntValue(ifd, COMPRESSION, false, UNCOMPRESSED);
byte[][] strips = new byte[stripsPerImage][];
for (int i=0; i<stripsPerImage; i++) {
strips[i] = stripBuf[i].toByteArray();
difference(strips[i], bps, width, planarConfig, predictor);
strips[i] = compress(strips[i], compression);
}
// record strip byte counts and offsets
long[] stripByteCounts = new long[stripsPerImage];
long[] stripOffsets = new long[stripsPerImage];
putIFDValue(ifd, STRIP_OFFSETS, stripOffsets);
putIFDValue(ifd, ROWS_PER_STRIP, rowsPerStrip);
putIFDValue(ifd, STRIP_BYTE_COUNTS, stripByteCounts);
Object[] keys = ifd.keySet().toArray();
Arrays.sort(keys); // sort IFD tags in ascending order
int ifdBytes = 2 + 12 * keys.length + 4;
long pixelBytes = 0;
for (int i=0; i<stripsPerImage; i++) {
stripByteCounts[i] = strips[i].length;
stripOffsets[i] = pixelBytes + offset + ifdBytes;
pixelBytes += stripByteCounts[i];
}
// create IFD output buffers
ByteArrayOutputStream ifdBuf = new ByteArrayOutputStream(ifdBytes);
DataOutputStream ifdOut = new DataOutputStream(ifdBuf);
ByteArrayOutputStream extraBuf = new ByteArrayOutputStream();
DataOutputStream extraOut = new DataOutputStream(extraBuf);
offset += ifdBytes + pixelBytes;
// write IFD to output buffers
ifdOut.writeShort(keys.length); // number of directory entries
for (int k=0; k<keys.length; k++) {
Object key = keys[k];
if (!(key instanceof Integer)) {
throw new FormatException("Malformed IFD tag (" + key + ")");
}
if (((Integer) key).intValue() == LITTLE_ENDIAN) continue;
Object value = ifd.get(key);
if (DEBUG) {
String sk = getIFDTagName(((Integer) key).intValue());
String sv = value instanceof int[] ?
("int[" + ((int[]) value).length + "]") : value.toString();
debug("writeImage: writing " + sk + " (value=" + sv + ")");
}
writeIFDValue(ifdOut, extraBuf, extraOut, offset,
((Integer) key).intValue(), value);
}
ifdOut.writeInt(last ? 0 : offset + extraBuf.size()); // offset to next IFD
// flush buffers to output stream
byte[] ifdArray = ifdBuf.toByteArray();
byte[] extraArray = extraBuf.toByteArray();
long numBytes = ifdArray.length + extraArray.length;
out.write(ifdArray);
for (int i=0; i<strips.length; i++) {
out.write(strips[i]);
numBytes += strips[i].length;
}
out.write(extraArray);
return numBytes;
}
/**
* Retrieves the image's width (TIFF tag ImageWidth) from a given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the image's width.
* @throws FormatException if there is a problem parsing the IFD metadata.
*/
public static long getImageWidth(Hashtable ifd) throws FormatException {
return getIFDLongValue(ifd, IMAGE_WIDTH, true, 0);
}
/**
* Retrieves the image's length (TIFF tag ImageLength) from a given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the image's length.
* @throws FormatException if there is a problem parsing the IFD metadata.
*/
public static long getImageLength(Hashtable ifd) throws FormatException {
return getIFDLongValue(ifd, IMAGE_LENGTH, true, 0);
}
/**
* Retrieves the image's bits per sample (TIFF tag BitsPerSample) from a given
* TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the image's bits per sample. The length of the array is equal to
* the number of samples per pixel.
* @throws FormatException if there is a problem parsing the IFD metadata.
* @see #getSamplesPerPixel(Hashtable)
*/
public static int[] getBitsPerSample(Hashtable ifd) throws FormatException {
int[] bitsPerSample = getIFDIntArray(ifd, BITS_PER_SAMPLE, false);
if (bitsPerSample == null) bitsPerSample = new int[] {1};
return bitsPerSample;
}
/**
* Retrieves the number of samples per pixel for the image (TIFF tag
* SamplesPerPixel) from a given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the number of samples per pixel.
* @throws FormatException if there is a problem parsing the IFD metadata.
*/
public static int getSamplesPerPixel(Hashtable ifd) throws FormatException {
return getIFDIntValue(ifd, SAMPLES_PER_PIXEL, false, 1);
}
/**
* Retrieves the image's compression type (TIFF tag Compression) from a
* given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the image's compression type. As of TIFF 6.0 this is one of:
* <ul>
* <li>Uncompressed (1)</li>
* <li>CCITT 1D (2)</li>
* <li>Group 3 Fax (3)</li>
* <li>Group 4 Fax (4)</li>
* <li>LZW (5)</li>
* <li>JPEG (6)</li>
* <li>PackBits (32773)</li>
* </ul>
* @throws FormatException if there is a problem parsing the IFD metadata.
*/
public static int getCompression(Hashtable ifd) throws FormatException {
return getIFDIntValue(ifd, COMPRESSION, false, UNCOMPRESSED);
}
/**
* Retrieves the image's photometric interpretation (TIFF tag
* PhotometricInterpretation) from a given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the image's photometric interpretation. As of TIFF 6.0 this is one
* of:
* <ul>
* <li>WhiteIsZero (0)</li>
* <li>BlackIsZero (1)</li>
* <li>RGB (2)</li>
* <li>RGB Palette (3)</li>
* <li>Transparency mask (4)</li>
* <li>CMYK (5)</li>
* <li>YbCbCr (6)</li>
* <li>CIELab (8)</li>
* </ul>
*
* @throws FormatException if there is a problem parsing the IFD metadata.
*/
public static int getPhotometricInterpretation(Hashtable ifd)
throws FormatException
{
return getIFDIntValue(ifd, PHOTOMETRIC_INTERPRETATION, true, 0);
}
/**
* Retrieves the strip offsets for the image (TIFF tag StripOffsets) from a
* given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the strip offsets for the image. The lenght of the array is equal
* to the number of strips per image. <i>StripsPerImage =
* floor ((ImageLength + RowsPerStrip - 1) / RowsPerStrip)</i>.
* @throws FormatException if there is a problem parsing the IFD metadata.
* @see #getStripByteCounts(Hashtable)
* @see #getRowsPerStrip(Hashtable)
*/
public static long[] getStripOffsets(Hashtable ifd) throws FormatException {
return getIFDLongArray(ifd, STRIP_OFFSETS, false);
}
/**
* Retrieves strip byte counts for the image (TIFF tag StripByteCounts) from a
* given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the byte counts for each strip. The length of the array is equal to
* the number of strips per image. <i>StripsPerImage =
* floor((ImageLength + RowsPerStrip - 1) / RowsPerStrip)</i>.
* @throws FormatException if there is a problem parsing the IFD metadata.
* @see #getStripOffsets(Hashtable)
*/
public static long[] getStripByteCounts(Hashtable ifd) throws FormatException
{
return getIFDLongArray(ifd, STRIP_BYTE_COUNTS, false);
}
/**
* Retrieves the number of rows per strip for image (TIFF tag RowsPerStrip)
* from a given TIFF IFD.
* @param ifd a TIFF IFD hashtable.
* @return the number of rows per strip.
* @throws FormatException if there is a problem parsing the IFD metadata.
*/
public static long[] getRowsPerStrip(Hashtable ifd) throws FormatException {
return getIFDLongArray(ifd, ROWS_PER_STRIP, false);
}
// -- Compression methods --
/** Encodes a strip of data with the given compression scheme. */
public static byte[] compress(byte[] input, int compression)
throws FormatException, IOException
{
if (compression == UNCOMPRESSED) return input;
else if (compression == CCITT_1D) {
throw new FormatException(
"Sorry, CCITT Group 3 1-Dimensional Modified Huffman " +
"run length encoding compression mode is not supported");
}
else if (compression == GROUP_3_FAX) {
throw new FormatException("Sorry, CCITT T.4 bi-level encoding " +
"(Group 3 Fax) compression mode is not supported");
}
else if (compression == GROUP_4_FAX) {
throw new FormatException("Sorry, CCITT T.6 bi-level encoding " +
"(Group 4 Fax) compression mode is not supported");
}
else if (compression == LZW) {
LZWCodec c = new LZWCodec();
return c.compress(input, 0, 0, null, null);
// return Compression.lzwCompress(input);
}
else if (compression == JPEG) {
throw new FormatException(
"Sorry, JPEG compression mode is not supported");
}
else if (compression == PACK_BITS) {
throw new FormatException(
"Sorry, PackBits compression mode is not supported");
}
else {
throw new FormatException(
"Unknown Compression type (" + compression + ")");
}
}
/** Performs in-place differencing according to the given predictor value. */
public static void difference(byte[] input, int[] bitsPerSample,
long width, int planarConfig, int predictor) throws FormatException
{
if (predictor == 2) {
if (DEBUG) debug("performing horizontal differencing");
for (int b=input.length-1; b>=0; b--) {
if (b / bitsPerSample.length % width == 0) continue;
input[b] -= input[b - bitsPerSample.length];
}
}
else if (predictor != 1) {
throw new FormatException("Unknown Predictor (" + predictor + ")");
}
}
// -- Debugging --
/** Prints a debugging message with current time. */
public static void debug(String message) {
LogTools.println(System.currentTimeMillis() + ": " + message);
}
}
| true | true | public static byte[] getSamples(Hashtable ifd, RandomAccessStream in,
byte[] buf) throws FormatException, IOException
{
if (DEBUG) debug("parsing IFD entries");
// get internal non-IFD entries
boolean littleEndian = isLittleEndian(ifd);
in.order(littleEndian);
// get relevant IFD entries
long imageWidth = getImageWidth(ifd);
long imageLength = getImageLength(ifd);
int[] bitsPerSample = getBitsPerSample(ifd);
int samplesPerPixel = getSamplesPerPixel(ifd);
int compression = getCompression(ifd);
int photoInterp = getPhotometricInterpretation(ifd);
long[] stripOffsets = getStripOffsets(ifd);
long[] stripByteCounts = getStripByteCounts(ifd);
long[] rowsPerStripArray = getRowsPerStrip(ifd);
boolean fakeByteCounts = stripByteCounts == null;
boolean fakeRPS = rowsPerStripArray == null;
boolean isTiled = stripOffsets == null;
long maxValue = getIFDLongValue(ifd, MAX_SAMPLE_VALUE, false, 0);
if (ifd.get(new Integer(VALID_BITS)) == null && bitsPerSample[0] > 0) {
int[] validBits = bitsPerSample;
if (photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY) {
int vb = validBits[0];
validBits = new int[3];
for (int i=0; i<validBits.length; i++) validBits[i] = vb;
}
putIFDValue(ifd, VALID_BITS, validBits);
}
if (isTiled) {
stripOffsets = getIFDLongArray(ifd, TILE_OFFSETS, true);
stripByteCounts = getIFDLongArray(ifd, TILE_BYTE_COUNTS, true);
rowsPerStripArray = new long[] {imageLength};
}
else if (fakeByteCounts) {
// technically speaking, this shouldn't happen (since TIFF writers are
// required to write the StripByteCounts tag), but we'll support it
// anyway
// don't rely on RowsPerStrip, since it's likely that if the file doesn't
// have the StripByteCounts tag, it also won't have the RowsPerStrip tag
stripByteCounts = new long[stripOffsets.length];
stripByteCounts[0] = stripOffsets[0];
for (int i=1; i<stripByteCounts.length; i++) {
stripByteCounts[i] = stripOffsets[i] - stripByteCounts[i-1];
}
}
boolean lastBitsZero = bitsPerSample[bitsPerSample.length - 1] == 0;
if (fakeRPS && !isTiled) {
// create a false rowsPerStripArray if one is not present
// it's sort of a cheap hack, but here's how it's done:
// RowsPerStrip = stripByteCounts / (imageLength * bitsPerSample)
// since stripByteCounts and bitsPerSample are arrays, we have to
// iterate through each item
rowsPerStripArray = new long[bitsPerSample.length];
long temp = stripByteCounts[0];
stripByteCounts = new long[bitsPerSample.length];
for (int i=0; i<stripByteCounts.length; i++) stripByteCounts[i] = temp;
temp = bitsPerSample[0];
if (temp == 0) temp = 8;
bitsPerSample = new int[bitsPerSample.length];
for (int i=0; i<bitsPerSample.length; i++) bitsPerSample[i] = (int) temp;
temp = stripOffsets[0];
stripOffsets = new long[bitsPerSample.length];
for (int i=0; i<bitsPerSample.length; i++) {
stripOffsets[i] = i == 0 ? temp :
stripOffsets[i - 1] + stripByteCounts[i];
}
// we have two files that reverse the endianness for BitsPerSample,
// StripOffsets, and StripByteCounts
if (bitsPerSample[0] > 64) {
byte[] bps = new byte[2];
byte[] stripOffs = new byte[4];
byte[] byteCounts = new byte[4];
if (littleEndian) {
bps[0] = (byte) (bitsPerSample[0] & 0xff);
bps[1] = (byte) ((bitsPerSample[0] >>> 8) & 0xff);
int ndx = stripOffsets.length - 1;
stripOffs[0] = (byte) (stripOffsets[ndx] & 0xff);
stripOffs[1] = (byte) ((stripOffsets[ndx] >>> 8) & 0xff);
stripOffs[2] = (byte) ((stripOffsets[ndx] >>> 16) & 0xff);
stripOffs[3] = (byte) ((stripOffsets[ndx] >>> 24) & 0xff);
ndx = stripByteCounts.length - 1;
byteCounts[0] = (byte) (stripByteCounts[ndx] & 0xff);
byteCounts[1] = (byte) ((stripByteCounts[ndx] >>> 8) & 0xff);
byteCounts[2] = (byte) ((stripByteCounts[ndx] >>> 16) & 0xff);
byteCounts[3] = (byte) ((stripByteCounts[ndx] >>> 24) & 0xff);
}
else {
bps[1] = (byte) ((bitsPerSample[0] >>> 16) & 0xff);
bps[0] = (byte) ((bitsPerSample[0] >>> 24) & 0xff);
stripOffs[3] = (byte) (stripOffsets[0] & 0xff);
stripOffs[2] = (byte) ((stripOffsets[0] >>> 8) & 0xff);
stripOffs[1] = (byte) ((stripOffsets[0] >>> 16) & 0xff);
stripOffs[0] = (byte) ((stripOffsets[0] >>> 24) & 0xff);
byteCounts[3] = (byte) (stripByteCounts[0] & 0xff);
byteCounts[2] = (byte) ((stripByteCounts[0] >>> 8) & 0xff);
byteCounts[1] = (byte) ((stripByteCounts[0] >>> 16) & 0xff);
byteCounts[0] = (byte) ((stripByteCounts[0] >>> 24) & 0xff);
}
bitsPerSample[0] = DataTools.bytesToInt(bps, !littleEndian);
stripOffsets[0] = DataTools.bytesToInt(stripOffs, !littleEndian);
stripByteCounts[0] = DataTools.bytesToInt(byteCounts, !littleEndian);
}
if (rowsPerStripArray.length == 1 && stripByteCounts[0] !=
(imageWidth * imageLength * (bitsPerSample[0] / 8)) &&
compression == UNCOMPRESSED)
{
for (int i=0; i<stripByteCounts.length; i++) {
stripByteCounts[i] =
imageWidth * imageLength * (bitsPerSample[i] / 8);
stripOffsets[0] = (int) (in.length() - stripByteCounts[0] -
48 * imageWidth);
if (i != 0) {
stripOffsets[i] = stripOffsets[i - 1] + stripByteCounts[i];
}
in.seek((int) stripOffsets[i]);
in.read(buf, (int) (i*imageWidth), (int) imageWidth);
boolean isZero = true;
for (int j=0; j<imageWidth; j++) {
if (buf[(int) (i*imageWidth + j)] != 0) {
isZero = false;
break;
}
}
while (isZero) {
stripOffsets[i] -= imageWidth;
in.seek((int) stripOffsets[i]);
in.read(buf, (int) (i*imageWidth), (int) imageWidth);
for (int j=0; j<imageWidth; j++) {
if (buf[(int) (i*imageWidth + j)] != 0) {
isZero = false;
stripOffsets[i] -= (stripByteCounts[i] - imageWidth);
break;
}
}
}
}
}
for (int i=0; i<bitsPerSample.length; i++) {
// case 1: we're still within bitsPerSample array bounds
if (i < bitsPerSample.length) {
if (i == samplesPerPixel) {
bitsPerSample[i] = 0;
lastBitsZero = true;
}
// remember that the universe collapses when we divide by 0
if (bitsPerSample[i] != 0) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[i] / 8));
}
else if (bitsPerSample[i] == 0 && i > 0) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[i - 1] / 8));
bitsPerSample[i] = bitsPerSample[i - 1];
}
else {
throw new FormatException("BitsPerSample is 0");
}
}
// case 2: we're outside bitsPerSample array bounds
else if (i >= bitsPerSample.length) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[bitsPerSample.length - 1] / 8));
}
}
samplesPerPixel = stripOffsets.length;
}
if (lastBitsZero) {
bitsPerSample[bitsPerSample.length - 1] = 0;
samplesPerPixel--;
}
TiffRational xResolution = getIFDRationalValue(ifd, X_RESOLUTION, false);
TiffRational yResolution = getIFDRationalValue(ifd, Y_RESOLUTION, false);
int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1);
int resolutionUnit = getIFDIntValue(ifd, RESOLUTION_UNIT, false, 2);
if (xResolution == null || yResolution == null) resolutionUnit = 0;
int[] colorMap = getIFDIntArray(ifd, COLOR_MAP, false);
int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1);
// If the subsequent color maps are empty, use the first IFD's color map
if (colorMap == null) {
colorMap = getIFDIntArray(getFirstIFD(in), COLOR_MAP, false);
}
// use special color map for YCbCr
if (photoInterp == Y_CB_CR) {
int[] tempColorMap = getIFDIntArray(ifd, Y_CB_CR_COEFFICIENTS, false);
int[] refBlackWhite = getIFDIntArray(ifd, REFERENCE_BLACK_WHITE, false);
colorMap = new int[tempColorMap.length + refBlackWhite.length];
System.arraycopy(tempColorMap, 0, colorMap, 0, tempColorMap.length);
System.arraycopy(refBlackWhite, 0, colorMap, tempColorMap.length,
refBlackWhite.length);
}
if (DEBUG) {
StringBuffer sb = new StringBuffer();
sb.append("IFD directory entry values:");
sb.append("\n\tLittleEndian=");
sb.append(littleEndian);
sb.append("\n\tImageWidth=");
sb.append(imageWidth);
sb.append("\n\tImageLength=");
sb.append(imageLength);
sb.append("\n\tBitsPerSample=");
sb.append(bitsPerSample[0]);
for (int i=1; i<bitsPerSample.length; i++) {
sb.append(",");
sb.append(bitsPerSample[i]);
}
sb.append("\n\tSamplesPerPixel=");
sb.append(samplesPerPixel);
sb.append("\n\tCompression=");
sb.append(compression);
sb.append("\n\tPhotometricInterpretation=");
sb.append(photoInterp);
sb.append("\n\tStripOffsets=");
sb.append(stripOffsets[0]);
for (int i=1; i<stripOffsets.length; i++) {
sb.append(",");
sb.append(stripOffsets[i]);
}
sb.append("\n\tRowsPerStrip=");
sb.append(rowsPerStripArray[0]);
for (int i=1; i<rowsPerStripArray.length; i++) {
sb.append(",");
sb.append(rowsPerStripArray[i]);
}
sb.append("\n\tStripByteCounts=");
sb.append(stripByteCounts[0]);
for (int i=1; i<stripByteCounts.length; i++) {
sb.append(",");
sb.append(stripByteCounts[i]);
}
sb.append("\n\tXResolution=");
sb.append(xResolution);
sb.append("\n\tYResolution=");
sb.append(yResolution);
sb.append("\n\tPlanarConfiguration=");
sb.append(planarConfig);
sb.append("\n\tResolutionUnit=");
sb.append(resolutionUnit);
sb.append("\n\tColorMap=");
if (colorMap == null) sb.append("null");
else {
sb.append(colorMap[0]);
for (int i=1; i<colorMap.length; i++) {
sb.append(",");
sb.append(colorMap[i]);
}
}
sb.append("\n\tPredictor=");
sb.append(predictor);
debug(sb.toString());
}
for (int i=0; i<samplesPerPixel; i++) {
if (bitsPerSample[i] < 1) {
throw new FormatException("Illegal BitsPerSample (" +
bitsPerSample[i] + ")");
}
// don't support odd numbers of bits (except for 1)
else if (bitsPerSample[i] % 2 != 0 && bitsPerSample[i] != 1) {
throw new FormatException("Sorry, unsupported BitsPerSample (" +
bitsPerSample[i] + ")");
}
}
if (bitsPerSample.length < samplesPerPixel) {
throw new FormatException("BitsPerSample length (" +
bitsPerSample.length + ") does not match SamplesPerPixel (" +
samplesPerPixel + ")");
}
else if (photoInterp == TRANSPARENCY_MASK) {
throw new FormatException(
"Sorry, Transparency Mask PhotometricInterpretation is not supported");
}
else if (photoInterp == Y_CB_CR) {
throw new FormatException(
"Sorry, YCbCr PhotometricInterpretation is not supported");
}
else if (photoInterp == CIE_LAB) {
throw new FormatException(
"Sorry, CIELAB PhotometricInterpretation is not supported");
}
else if (photoInterp != WHITE_IS_ZERO &&
photoInterp != BLACK_IS_ZERO && photoInterp != RGB &&
photoInterp != RGB_PALETTE && photoInterp != CMYK &&
photoInterp != Y_CB_CR && photoInterp != CFA_ARRAY)
{
throw new FormatException("Unknown PhotometricInterpretation (" +
photoInterp + ")");
}
long rowsPerStrip = rowsPerStripArray[0];
for (int i=1; i<rowsPerStripArray.length; i++) {
if (rowsPerStrip != rowsPerStripArray[i]) {
throw new FormatException(
"Sorry, non-uniform RowsPerStrip is not supported");
}
}
long numStrips = (imageLength + rowsPerStrip - 1) / rowsPerStrip;
if (isTiled) numStrips = stripOffsets.length;
if (planarConfig == 2) numStrips *= samplesPerPixel;
if (stripOffsets.length < numStrips) {
throw new FormatException("StripOffsets length (" +
stripOffsets.length + ") does not match expected " +
"number of strips (" + numStrips + ")");
}
if (stripByteCounts.length < numStrips) {
throw new FormatException("StripByteCounts length (" +
stripByteCounts.length + ") does not match expected " +
"number of strips (" + numStrips + ")");
}
if (imageWidth > Integer.MAX_VALUE || imageLength > Integer.MAX_VALUE ||
imageWidth * imageLength > Integer.MAX_VALUE)
{
throw new FormatException("Sorry, ImageWidth x ImageLength > " +
Integer.MAX_VALUE + " is not supported (" +
imageWidth + " x " + imageLength + ")");
}
int numSamples = (int) (imageWidth * imageLength);
if (planarConfig != 1 && planarConfig != 2) {
throw new FormatException(
"Unknown PlanarConfiguration (" + planarConfig + ")");
}
// read in image strips
if (DEBUG) {
debug("reading image data (samplesPerPixel=" +
samplesPerPixel + "; numSamples=" + numSamples + ")");
}
if (samplesPerPixel == 1 &&
(photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY))
{
samplesPerPixel = 3;
}
if (photoInterp == CFA_ARRAY) {
int[] tempMap = new int[colorMap.length + 2];
System.arraycopy(colorMap, 0, tempMap, 0, colorMap.length);
tempMap[tempMap.length - 2] = (int) imageWidth;
tempMap[tempMap.length - 1] = (int) imageLength;
colorMap = tempMap;
}
//if (planarConfig == 2) numSamples *= samplesPerPixel;
short[][] samples = new short[samplesPerPixel][numSamples];
byte[] altBytes = new byte[0];
if (bitsPerSample[0] == 16) littleEndian = !littleEndian;
if (isTiled) {
long tileWidth = getIFDLongValue(ifd, TILE_WIDTH, true, 0);
long tileLength = getIFDLongValue(ifd, TILE_LENGTH, true, 0);
byte[] data = new byte[(int) stripByteCounts[0] * stripOffsets.length];
int row = 0;
int col = 0;
int bytes = bitsPerSample[0] / 8;
for (int i=0; i<stripOffsets.length; i++) {
byte[] b = new byte[(int) stripByteCounts[i]];
in.seek(stripOffsets[i]);
in.read(b);
b = uncompress(b, compression);
int rowBytes = (int) (tileWidth *
(stripByteCounts[0] / (tileWidth*tileLength)));
for (int j=0; j<tileLength; j++) {
int len = rowBytes;
if (col*bytes + rowBytes > imageWidth*bytes) {
len = (int) (imageWidth*bytes - col*bytes);
}
System.arraycopy(b, j*rowBytes, data,
(int) ((row+j)*imageWidth*bytes + col*bytes), len);
}
// update row and column
col += (int) tileWidth;
if (col >= imageWidth) {
row += (int) tileLength;
col = 0;
}
}
undifference(data, bitsPerSample, imageWidth, planarConfig, predictor);
unpackBytes(samples, 0, data, bitsPerSample, photoInterp, colorMap,
littleEndian, maxValue, planarConfig, 0, 1, imageWidth);
}
else {
int overallOffset = 0;
for (int strip=0, row=0; strip<numStrips; strip++, row+=rowsPerStrip) {
try {
if (DEBUG) debug("reading image strip #" + strip);
in.seek((int) stripOffsets[strip]);
if (stripByteCounts[strip] > Integer.MAX_VALUE) {
throw new FormatException("Sorry, StripByteCounts > " +
Integer.MAX_VALUE + " is not supported");
}
byte[] bytes = new byte[(int) stripByteCounts[strip]];
in.read(bytes);
if (compression != PACK_BITS) {
bytes = uncompress(bytes, compression);
undifference(bytes, bitsPerSample,
imageWidth, planarConfig, predictor);
int offset = (int) (imageWidth * row);
if (planarConfig == 2) {
offset = overallOffset / samplesPerPixel;
}
unpackBytes(samples, offset, bytes, bitsPerSample,
photoInterp, colorMap, littleEndian, maxValue, planarConfig,
strip, (int) numStrips, imageWidth);
overallOffset += bytes.length / bitsPerSample.length;
}
else {
// concatenate contents of bytes to altBytes
byte[] tempPackBits = new byte[altBytes.length];
System.arraycopy(altBytes, 0, tempPackBits, 0, altBytes.length);
altBytes = new byte[altBytes.length + bytes.length];
System.arraycopy(tempPackBits, 0, altBytes, 0, tempPackBits.length);
System.arraycopy(bytes, 0, altBytes,
tempPackBits.length, bytes.length);
}
}
catch (Exception e) {
if (strip == 0) {
if (e instanceof FormatException) throw (FormatException) e;
else throw new FormatException(e);
}
byte[] bytes = new byte[samples[0].length];
undifference(bytes, bitsPerSample, imageWidth, planarConfig,
predictor);
int offset = (int) (imageWidth * row);
if (planarConfig == 2) offset = overallOffset / samplesPerPixel;
unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp,
colorMap, littleEndian, maxValue, planarConfig,
strip, (int) numStrips, imageWidth);
overallOffset += bytes.length / bitsPerSample.length;
}
}
}
// only do this if the image uses PackBits compression
if (altBytes.length != 0) {
altBytes = uncompress(altBytes, compression);
undifference(altBytes, bitsPerSample,
imageWidth, planarConfig, predictor);
unpackBytes(samples, (int) imageWidth, altBytes, bitsPerSample,
photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1,
imageWidth);
}
// construct field
if (DEBUG) debug("constructing image");
// Since the lowest common denominator for all pixel operations is "byte"
// we're going to normalize everything to byte.
if (bitsPerSample[0] == 12) bitsPerSample[0] = 16;
if (photoInterp == CFA_ARRAY) {
samples =
ImageTools.demosaic(samples, (int) imageWidth, (int) imageLength);
}
if (bitsPerSample[0] == 16) {
int pt = 0;
for (int i = 0; i < samplesPerPixel; i++) {
for (int j = 0; j < numSamples; j++) {
buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8);
buf[pt++] = (byte) (samples[i][j] & 0xff);
}
}
}
else if (bitsPerSample[0] == 32) {
int pt = 0;
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<numSamples; j++) {
buf[pt++] = (byte) ((samples[i][j] & 0xff000000) >> 24);
buf[pt++] = (byte) ((samples[i][j] & 0xff0000) >> 16);
buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8);
buf[pt++] = (byte) (samples[i][j] & 0xff);
}
}
}
else {
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<numSamples; j++) {
buf[j + i*numSamples] = (byte) samples[i][j];
}
}
}
return buf;
}
| public static byte[] getSamples(Hashtable ifd, RandomAccessStream in,
byte[] buf) throws FormatException, IOException
{
if (DEBUG) debug("parsing IFD entries");
// get internal non-IFD entries
boolean littleEndian = isLittleEndian(ifd);
in.order(littleEndian);
// get relevant IFD entries
long imageWidth = getImageWidth(ifd);
long imageLength = getImageLength(ifd);
int[] bitsPerSample = getBitsPerSample(ifd);
int samplesPerPixel = getSamplesPerPixel(ifd);
int compression = getCompression(ifd);
int photoInterp = getPhotometricInterpretation(ifd);
long[] stripOffsets = getStripOffsets(ifd);
long[] stripByteCounts = getStripByteCounts(ifd);
long[] rowsPerStripArray = getRowsPerStrip(ifd);
boolean fakeByteCounts = stripByteCounts == null;
boolean fakeRPS = rowsPerStripArray == null;
boolean isTiled = stripOffsets == null;
long[] maxes = getIFDLongArray(ifd, MAX_SAMPLE_VALUE, false);
long maxValue = maxes == null ? 0 : maxes[0];
if (ifd.get(new Integer(VALID_BITS)) == null && bitsPerSample[0] > 0) {
int[] validBits = bitsPerSample;
if (photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY) {
int vb = validBits[0];
validBits = new int[3];
for (int i=0; i<validBits.length; i++) validBits[i] = vb;
}
putIFDValue(ifd, VALID_BITS, validBits);
}
if (isTiled) {
stripOffsets = getIFDLongArray(ifd, TILE_OFFSETS, true);
stripByteCounts = getIFDLongArray(ifd, TILE_BYTE_COUNTS, true);
rowsPerStripArray = new long[] {imageLength};
}
else if (fakeByteCounts) {
// technically speaking, this shouldn't happen (since TIFF writers are
// required to write the StripByteCounts tag), but we'll support it
// anyway
// don't rely on RowsPerStrip, since it's likely that if the file doesn't
// have the StripByteCounts tag, it also won't have the RowsPerStrip tag
stripByteCounts = new long[stripOffsets.length];
stripByteCounts[0] = stripOffsets[0];
for (int i=1; i<stripByteCounts.length; i++) {
stripByteCounts[i] = stripOffsets[i] - stripByteCounts[i-1];
}
}
boolean lastBitsZero = bitsPerSample[bitsPerSample.length - 1] == 0;
if (fakeRPS && !isTiled) {
// create a false rowsPerStripArray if one is not present
// it's sort of a cheap hack, but here's how it's done:
// RowsPerStrip = stripByteCounts / (imageLength * bitsPerSample)
// since stripByteCounts and bitsPerSample are arrays, we have to
// iterate through each item
rowsPerStripArray = new long[bitsPerSample.length];
long temp = stripByteCounts[0];
stripByteCounts = new long[bitsPerSample.length];
for (int i=0; i<stripByteCounts.length; i++) stripByteCounts[i] = temp;
temp = bitsPerSample[0];
if (temp == 0) temp = 8;
bitsPerSample = new int[bitsPerSample.length];
for (int i=0; i<bitsPerSample.length; i++) bitsPerSample[i] = (int) temp;
temp = stripOffsets[0];
stripOffsets = new long[bitsPerSample.length];
for (int i=0; i<bitsPerSample.length; i++) {
stripOffsets[i] = i == 0 ? temp :
stripOffsets[i - 1] + stripByteCounts[i];
}
// we have two files that reverse the endianness for BitsPerSample,
// StripOffsets, and StripByteCounts
if (bitsPerSample[0] > 64) {
byte[] bps = new byte[2];
byte[] stripOffs = new byte[4];
byte[] byteCounts = new byte[4];
if (littleEndian) {
bps[0] = (byte) (bitsPerSample[0] & 0xff);
bps[1] = (byte) ((bitsPerSample[0] >>> 8) & 0xff);
int ndx = stripOffsets.length - 1;
stripOffs[0] = (byte) (stripOffsets[ndx] & 0xff);
stripOffs[1] = (byte) ((stripOffsets[ndx] >>> 8) & 0xff);
stripOffs[2] = (byte) ((stripOffsets[ndx] >>> 16) & 0xff);
stripOffs[3] = (byte) ((stripOffsets[ndx] >>> 24) & 0xff);
ndx = stripByteCounts.length - 1;
byteCounts[0] = (byte) (stripByteCounts[ndx] & 0xff);
byteCounts[1] = (byte) ((stripByteCounts[ndx] >>> 8) & 0xff);
byteCounts[2] = (byte) ((stripByteCounts[ndx] >>> 16) & 0xff);
byteCounts[3] = (byte) ((stripByteCounts[ndx] >>> 24) & 0xff);
}
else {
bps[1] = (byte) ((bitsPerSample[0] >>> 16) & 0xff);
bps[0] = (byte) ((bitsPerSample[0] >>> 24) & 0xff);
stripOffs[3] = (byte) (stripOffsets[0] & 0xff);
stripOffs[2] = (byte) ((stripOffsets[0] >>> 8) & 0xff);
stripOffs[1] = (byte) ((stripOffsets[0] >>> 16) & 0xff);
stripOffs[0] = (byte) ((stripOffsets[0] >>> 24) & 0xff);
byteCounts[3] = (byte) (stripByteCounts[0] & 0xff);
byteCounts[2] = (byte) ((stripByteCounts[0] >>> 8) & 0xff);
byteCounts[1] = (byte) ((stripByteCounts[0] >>> 16) & 0xff);
byteCounts[0] = (byte) ((stripByteCounts[0] >>> 24) & 0xff);
}
bitsPerSample[0] = DataTools.bytesToInt(bps, !littleEndian);
stripOffsets[0] = DataTools.bytesToInt(stripOffs, !littleEndian);
stripByteCounts[0] = DataTools.bytesToInt(byteCounts, !littleEndian);
}
if (rowsPerStripArray.length == 1 && stripByteCounts[0] !=
(imageWidth * imageLength * (bitsPerSample[0] / 8)) &&
compression == UNCOMPRESSED)
{
for (int i=0; i<stripByteCounts.length; i++) {
stripByteCounts[i] =
imageWidth * imageLength * (bitsPerSample[i] / 8);
stripOffsets[0] = (int) (in.length() - stripByteCounts[0] -
48 * imageWidth);
if (i != 0) {
stripOffsets[i] = stripOffsets[i - 1] + stripByteCounts[i];
}
in.seek((int) stripOffsets[i]);
in.read(buf, (int) (i*imageWidth), (int) imageWidth);
boolean isZero = true;
for (int j=0; j<imageWidth; j++) {
if (buf[(int) (i*imageWidth + j)] != 0) {
isZero = false;
break;
}
}
while (isZero) {
stripOffsets[i] -= imageWidth;
in.seek((int) stripOffsets[i]);
in.read(buf, (int) (i*imageWidth), (int) imageWidth);
for (int j=0; j<imageWidth; j++) {
if (buf[(int) (i*imageWidth + j)] != 0) {
isZero = false;
stripOffsets[i] -= (stripByteCounts[i] - imageWidth);
break;
}
}
}
}
}
for (int i=0; i<bitsPerSample.length; i++) {
// case 1: we're still within bitsPerSample array bounds
if (i < bitsPerSample.length) {
if (i == samplesPerPixel) {
bitsPerSample[i] = 0;
lastBitsZero = true;
}
// remember that the universe collapses when we divide by 0
if (bitsPerSample[i] != 0) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[i] / 8));
}
else if (bitsPerSample[i] == 0 && i > 0) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[i - 1] / 8));
bitsPerSample[i] = bitsPerSample[i - 1];
}
else {
throw new FormatException("BitsPerSample is 0");
}
}
// case 2: we're outside bitsPerSample array bounds
else if (i >= bitsPerSample.length) {
rowsPerStripArray[i] = (long) stripByteCounts[i] /
(imageWidth * (bitsPerSample[bitsPerSample.length - 1] / 8));
}
}
samplesPerPixel = stripOffsets.length;
}
if (lastBitsZero) {
bitsPerSample[bitsPerSample.length - 1] = 0;
samplesPerPixel--;
}
TiffRational xResolution = getIFDRationalValue(ifd, X_RESOLUTION, false);
TiffRational yResolution = getIFDRationalValue(ifd, Y_RESOLUTION, false);
int planarConfig = getIFDIntValue(ifd, PLANAR_CONFIGURATION, false, 1);
int resolutionUnit = getIFDIntValue(ifd, RESOLUTION_UNIT, false, 2);
if (xResolution == null || yResolution == null) resolutionUnit = 0;
int[] colorMap = getIFDIntArray(ifd, COLOR_MAP, false);
int predictor = getIFDIntValue(ifd, PREDICTOR, false, 1);
// If the subsequent color maps are empty, use the first IFD's color map
if (colorMap == null) {
colorMap = getIFDIntArray(getFirstIFD(in), COLOR_MAP, false);
}
// use special color map for YCbCr
if (photoInterp == Y_CB_CR) {
int[] tempColorMap = getIFDIntArray(ifd, Y_CB_CR_COEFFICIENTS, false);
int[] refBlackWhite = getIFDIntArray(ifd, REFERENCE_BLACK_WHITE, false);
colorMap = new int[tempColorMap.length + refBlackWhite.length];
System.arraycopy(tempColorMap, 0, colorMap, 0, tempColorMap.length);
System.arraycopy(refBlackWhite, 0, colorMap, tempColorMap.length,
refBlackWhite.length);
}
if (DEBUG) {
StringBuffer sb = new StringBuffer();
sb.append("IFD directory entry values:");
sb.append("\n\tLittleEndian=");
sb.append(littleEndian);
sb.append("\n\tImageWidth=");
sb.append(imageWidth);
sb.append("\n\tImageLength=");
sb.append(imageLength);
sb.append("\n\tBitsPerSample=");
sb.append(bitsPerSample[0]);
for (int i=1; i<bitsPerSample.length; i++) {
sb.append(",");
sb.append(bitsPerSample[i]);
}
sb.append("\n\tSamplesPerPixel=");
sb.append(samplesPerPixel);
sb.append("\n\tCompression=");
sb.append(compression);
sb.append("\n\tPhotometricInterpretation=");
sb.append(photoInterp);
sb.append("\n\tStripOffsets=");
sb.append(stripOffsets[0]);
for (int i=1; i<stripOffsets.length; i++) {
sb.append(",");
sb.append(stripOffsets[i]);
}
sb.append("\n\tRowsPerStrip=");
sb.append(rowsPerStripArray[0]);
for (int i=1; i<rowsPerStripArray.length; i++) {
sb.append(",");
sb.append(rowsPerStripArray[i]);
}
sb.append("\n\tStripByteCounts=");
sb.append(stripByteCounts[0]);
for (int i=1; i<stripByteCounts.length; i++) {
sb.append(",");
sb.append(stripByteCounts[i]);
}
sb.append("\n\tXResolution=");
sb.append(xResolution);
sb.append("\n\tYResolution=");
sb.append(yResolution);
sb.append("\n\tPlanarConfiguration=");
sb.append(planarConfig);
sb.append("\n\tResolutionUnit=");
sb.append(resolutionUnit);
sb.append("\n\tColorMap=");
if (colorMap == null) sb.append("null");
else {
sb.append(colorMap[0]);
for (int i=1; i<colorMap.length; i++) {
sb.append(",");
sb.append(colorMap[i]);
}
}
sb.append("\n\tPredictor=");
sb.append(predictor);
debug(sb.toString());
}
for (int i=0; i<samplesPerPixel; i++) {
if (bitsPerSample[i] < 1) {
throw new FormatException("Illegal BitsPerSample (" +
bitsPerSample[i] + ")");
}
// don't support odd numbers of bits (except for 1)
else if (bitsPerSample[i] % 2 != 0 && bitsPerSample[i] != 1) {
throw new FormatException("Sorry, unsupported BitsPerSample (" +
bitsPerSample[i] + ")");
}
}
if (bitsPerSample.length < samplesPerPixel) {
throw new FormatException("BitsPerSample length (" +
bitsPerSample.length + ") does not match SamplesPerPixel (" +
samplesPerPixel + ")");
}
else if (photoInterp == TRANSPARENCY_MASK) {
throw new FormatException(
"Sorry, Transparency Mask PhotometricInterpretation is not supported");
}
else if (photoInterp == Y_CB_CR) {
throw new FormatException(
"Sorry, YCbCr PhotometricInterpretation is not supported");
}
else if (photoInterp == CIE_LAB) {
throw new FormatException(
"Sorry, CIELAB PhotometricInterpretation is not supported");
}
else if (photoInterp != WHITE_IS_ZERO &&
photoInterp != BLACK_IS_ZERO && photoInterp != RGB &&
photoInterp != RGB_PALETTE && photoInterp != CMYK &&
photoInterp != Y_CB_CR && photoInterp != CFA_ARRAY)
{
throw new FormatException("Unknown PhotometricInterpretation (" +
photoInterp + ")");
}
long rowsPerStrip = rowsPerStripArray[0];
for (int i=1; i<rowsPerStripArray.length; i++) {
if (rowsPerStrip != rowsPerStripArray[i]) {
throw new FormatException(
"Sorry, non-uniform RowsPerStrip is not supported");
}
}
long numStrips = (imageLength + rowsPerStrip - 1) / rowsPerStrip;
if (isTiled) numStrips = stripOffsets.length;
if (planarConfig == 2) numStrips *= samplesPerPixel;
if (stripOffsets.length < numStrips) {
throw new FormatException("StripOffsets length (" +
stripOffsets.length + ") does not match expected " +
"number of strips (" + numStrips + ")");
}
if (stripByteCounts.length < numStrips) {
throw new FormatException("StripByteCounts length (" +
stripByteCounts.length + ") does not match expected " +
"number of strips (" + numStrips + ")");
}
if (imageWidth > Integer.MAX_VALUE || imageLength > Integer.MAX_VALUE ||
imageWidth * imageLength > Integer.MAX_VALUE)
{
throw new FormatException("Sorry, ImageWidth x ImageLength > " +
Integer.MAX_VALUE + " is not supported (" +
imageWidth + " x " + imageLength + ")");
}
int numSamples = (int) (imageWidth * imageLength);
if (planarConfig != 1 && planarConfig != 2) {
throw new FormatException(
"Unknown PlanarConfiguration (" + planarConfig + ")");
}
// read in image strips
if (DEBUG) {
debug("reading image data (samplesPerPixel=" +
samplesPerPixel + "; numSamples=" + numSamples + ")");
}
if (samplesPerPixel == 1 &&
(photoInterp == RGB_PALETTE || photoInterp == CFA_ARRAY))
{
samplesPerPixel = 3;
}
if (photoInterp == CFA_ARRAY) {
int[] tempMap = new int[colorMap.length + 2];
System.arraycopy(colorMap, 0, tempMap, 0, colorMap.length);
tempMap[tempMap.length - 2] = (int) imageWidth;
tempMap[tempMap.length - 1] = (int) imageLength;
colorMap = tempMap;
}
//if (planarConfig == 2) numSamples *= samplesPerPixel;
short[][] samples = new short[samplesPerPixel][numSamples];
byte[] altBytes = new byte[0];
if (bitsPerSample[0] == 16) littleEndian = !littleEndian;
if (isTiled) {
long tileWidth = getIFDLongValue(ifd, TILE_WIDTH, true, 0);
long tileLength = getIFDLongValue(ifd, TILE_LENGTH, true, 0);
byte[] data = new byte[(int) stripByteCounts[0] * stripOffsets.length];
int row = 0;
int col = 0;
int bytes = bitsPerSample[0] / 8;
for (int i=0; i<stripOffsets.length; i++) {
byte[] b = new byte[(int) stripByteCounts[i]];
in.seek(stripOffsets[i]);
in.read(b);
b = uncompress(b, compression);
int rowBytes = (int) (tileWidth *
(stripByteCounts[0] / (tileWidth*tileLength)));
for (int j=0; j<tileLength; j++) {
int len = rowBytes;
if (col*bytes + rowBytes > imageWidth*bytes) {
len = (int) (imageWidth*bytes - col*bytes);
}
System.arraycopy(b, j*rowBytes, data,
(int) ((row+j)*imageWidth*bytes + col*bytes), len);
}
// update row and column
col += (int) tileWidth;
if (col >= imageWidth) {
row += (int) tileLength;
col = 0;
}
}
undifference(data, bitsPerSample, imageWidth, planarConfig, predictor);
unpackBytes(samples, 0, data, bitsPerSample, photoInterp, colorMap,
littleEndian, maxValue, planarConfig, 0, 1, imageWidth);
}
else {
int overallOffset = 0;
for (int strip=0, row=0; strip<numStrips; strip++, row+=rowsPerStrip) {
try {
if (DEBUG) debug("reading image strip #" + strip);
in.seek((int) stripOffsets[strip]);
if (stripByteCounts[strip] > Integer.MAX_VALUE) {
throw new FormatException("Sorry, StripByteCounts > " +
Integer.MAX_VALUE + " is not supported");
}
byte[] bytes = new byte[(int) stripByteCounts[strip]];
in.read(bytes);
if (compression != PACK_BITS) {
bytes = uncompress(bytes, compression);
undifference(bytes, bitsPerSample,
imageWidth, planarConfig, predictor);
int offset = (int) (imageWidth * row);
if (planarConfig == 2) {
offset = overallOffset / samplesPerPixel;
}
unpackBytes(samples, offset, bytes, bitsPerSample,
photoInterp, colorMap, littleEndian, maxValue, planarConfig,
strip, (int) numStrips, imageWidth);
overallOffset += bytes.length / bitsPerSample.length;
}
else {
// concatenate contents of bytes to altBytes
byte[] tempPackBits = new byte[altBytes.length];
System.arraycopy(altBytes, 0, tempPackBits, 0, altBytes.length);
altBytes = new byte[altBytes.length + bytes.length];
System.arraycopy(tempPackBits, 0, altBytes, 0, tempPackBits.length);
System.arraycopy(bytes, 0, altBytes,
tempPackBits.length, bytes.length);
}
}
catch (Exception e) {
if (strip == 0) {
if (e instanceof FormatException) throw (FormatException) e;
else throw new FormatException(e);
}
byte[] bytes = new byte[samples[0].length];
undifference(bytes, bitsPerSample, imageWidth, planarConfig,
predictor);
int offset = (int) (imageWidth * row);
if (planarConfig == 2) offset = overallOffset / samplesPerPixel;
unpackBytes(samples, offset, bytes, bitsPerSample, photoInterp,
colorMap, littleEndian, maxValue, planarConfig,
strip, (int) numStrips, imageWidth);
overallOffset += bytes.length / bitsPerSample.length;
}
}
}
// only do this if the image uses PackBits compression
if (altBytes.length != 0) {
altBytes = uncompress(altBytes, compression);
undifference(altBytes, bitsPerSample,
imageWidth, planarConfig, predictor);
unpackBytes(samples, (int) imageWidth, altBytes, bitsPerSample,
photoInterp, colorMap, littleEndian, maxValue, planarConfig, 0, 1,
imageWidth);
}
// construct field
if (DEBUG) debug("constructing image");
// Since the lowest common denominator for all pixel operations is "byte"
// we're going to normalize everything to byte.
if (bitsPerSample[0] == 12) bitsPerSample[0] = 16;
if (photoInterp == CFA_ARRAY) {
samples =
ImageTools.demosaic(samples, (int) imageWidth, (int) imageLength);
}
if (bitsPerSample[0] == 16) {
int pt = 0;
for (int i = 0; i < samplesPerPixel; i++) {
for (int j = 0; j < numSamples; j++) {
buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8);
buf[pt++] = (byte) (samples[i][j] & 0xff);
}
}
}
else if (bitsPerSample[0] == 32) {
int pt = 0;
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<numSamples; j++) {
buf[pt++] = (byte) ((samples[i][j] & 0xff000000) >> 24);
buf[pt++] = (byte) ((samples[i][j] & 0xff0000) >> 16);
buf[pt++] = (byte) ((samples[i][j] & 0xff00) >> 8);
buf[pt++] = (byte) (samples[i][j] & 0xff);
}
}
}
else {
for (int i=0; i<samplesPerPixel; i++) {
for (int j=0; j<numSamples; j++) {
buf[j + i*numSamples] = (byte) samples[i][j];
}
}
}
return buf;
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java
index d5651c9b..cdbda0fb 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java
@@ -1,235 +1,244 @@
/*******************************************************************************
* Copyright (C) 2008, 2009 Robin Rosenberg <[email protected]>
*
* 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.egit.ui.internal.decorators;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;
import org.eclipse.core.resources.IResource;
import org.eclipse.egit.core.GitProvider;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.internal.CompareUtils;
import org.eclipse.egit.ui.internal.trace.GitTraceLocation;
import org.eclipse.jface.text.Document;
import org.eclipse.jgit.events.ListenerHandle;
import org.eclipse.jgit.events.RefsChangedEvent;
import org.eclipse.jgit.events.RefsChangedListener;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.osgi.util.NLS;
import org.eclipse.team.core.RepositoryProvider;
class GitDocument extends Document implements RefsChangedListener {
private final IResource resource;
private ObjectId lastCommit;
private ObjectId lastTree;
private ObjectId lastBlob;
private ListenerHandle myRefsChangedHandle;
static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>();
static GitDocument create(final IResource resource) throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) create: " + resource); //$NON-NLS-1$
GitDocument ret = null;
if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) {
ret = new GitDocument(resource);
ret.populate();
final Repository repository = ret.getRepository();
if (repository != null)
ret.myRefsChangedHandle = repository.getListenerList()
.addRefsChangedListener(ret);
}
return ret;
}
private GitDocument(IResource resource) {
this.resource = resource;
GitDocument.doc2repo.put(this, getRepository());
}
private void setResolved(final AnyObjectId commit, final AnyObjectId tree,
final AnyObjectId blob, final String value) {
lastCommit = commit != null ? commit.copy() : null;
lastTree = tree != null ? tree.copy() : null;
lastBlob = blob != null ? blob.copy() : null;
set(value);
if (blob != null)
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
else if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) unresolved " + resource); //$NON-NLS-1$
}
void populate() throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.QUICKDIFF.getLocation(), resource);
TreeWalk tw = null;
RevWalk rw = null;
try {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
if (mapping == null) {
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
final String gitPath = mapping.getRepoRelativePath(resource);
final Repository repository = mapping.getRepository();
String baseline = GitQuickDiffProvider.baseline.get(repository);
if (baseline == null)
baseline = Constants.HEAD;
ObjectId commitId = repository.resolve(baseline);
if (commitId != null) {
if (commitId.equals(lastCommit)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
} else {
String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff,
new Object[] { baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
rw = new RevWalk(repository);
RevCommit baselineCommit;
try {
baselineCommit = rw.parseCommit(commitId);
} catch (IOException err) {
String msg = NLS
.bind(UIText.GitDocument_errorLoadCommit, new Object[] {
commitId, baseline, resource, repository });
Activator.logError(msg, err);
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
RevTree treeId = baselineCommit.getTree();
if (treeId.equals(lastTree)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
tw = TreeWalk.forPath(repository, gitPath, treeId);
+ if (tw == null) {
+ setResolved(null, null, null, ""); //$NON-NLS-1$
+ String msg = NLS
+ .bind(UIText.GitDocument_errorLoadTree, new Object[] {
+ treeId, baseline, resource, repository });
+ Activator.logError(msg, new Throwable());
+ setResolved(null, null, null, ""); //$NON-NLS-1$
+ return;
+ }
ObjectId id = tw.getObjectId(0);
if (id.equals(ObjectId.zeroId())) {
setResolved(null, null, null, ""); //$NON-NLS-1$
String msg = NLS
.bind(UIText.GitDocument_errorLoadTree, new Object[] {
treeId, baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
if (!id.equals(lastBlob)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) compareTo: " + baseline); //$NON-NLS-1$
ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB);
byte[] bytes = loader.getBytes();
String charset;
charset = CompareUtils.getResourceEncoding(resource);
// Finally we could consider validating the content with respect
// to the content. We don't do that here.
String s = new String(bytes, charset);
setResolved(commitId, treeId, id, s);
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
}
} finally {
if (tw != null)
tw.release();
if (rw != null)
rw.release();
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.QUICKDIFF.getLocation());
}
}
void dispose() {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) dispose: " + resource); //$NON-NLS-1$
doc2repo.remove(this);
if (myRefsChangedHandle != null) {
myRefsChangedHandle.remove();
myRefsChangedHandle = null;
}
}
public void onRefsChanged(final RefsChangedEvent e) {
try {
populate();
} catch (IOException e1) {
Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1);
}
}
private Repository getRepository() {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
return (mapping != null) ? mapping.getRepository() : null;
}
/**
* A change occurred to a repository. Update any GitDocument instances
* referring to such repositories.
*
* @param repository
* Repository which changed
* @throws IOException
*/
static void refreshRelevant(final Repository repository) throws IOException {
for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) {
if (i.getValue() == repository) {
i.getKey().populate();
}
}
}
}
| true | true | void populate() throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.QUICKDIFF.getLocation(), resource);
TreeWalk tw = null;
RevWalk rw = null;
try {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
if (mapping == null) {
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
final String gitPath = mapping.getRepoRelativePath(resource);
final Repository repository = mapping.getRepository();
String baseline = GitQuickDiffProvider.baseline.get(repository);
if (baseline == null)
baseline = Constants.HEAD;
ObjectId commitId = repository.resolve(baseline);
if (commitId != null) {
if (commitId.equals(lastCommit)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
} else {
String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff,
new Object[] { baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
rw = new RevWalk(repository);
RevCommit baselineCommit;
try {
baselineCommit = rw.parseCommit(commitId);
} catch (IOException err) {
String msg = NLS
.bind(UIText.GitDocument_errorLoadCommit, new Object[] {
commitId, baseline, resource, repository });
Activator.logError(msg, err);
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
RevTree treeId = baselineCommit.getTree();
if (treeId.equals(lastTree)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
tw = TreeWalk.forPath(repository, gitPath, treeId);
ObjectId id = tw.getObjectId(0);
if (id.equals(ObjectId.zeroId())) {
setResolved(null, null, null, ""); //$NON-NLS-1$
String msg = NLS
.bind(UIText.GitDocument_errorLoadTree, new Object[] {
treeId, baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
if (!id.equals(lastBlob)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) compareTo: " + baseline); //$NON-NLS-1$
ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB);
byte[] bytes = loader.getBytes();
String charset;
charset = CompareUtils.getResourceEncoding(resource);
// Finally we could consider validating the content with respect
// to the content. We don't do that here.
String s = new String(bytes, charset);
setResolved(commitId, treeId, id, s);
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
}
} finally {
if (tw != null)
tw.release();
if (rw != null)
rw.release();
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.QUICKDIFF.getLocation());
}
}
| void populate() throws IOException {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceEntry(
GitTraceLocation.QUICKDIFF.getLocation(), resource);
TreeWalk tw = null;
RevWalk rw = null;
try {
RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
if (mapping == null) {
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
final String gitPath = mapping.getRepoRelativePath(resource);
final Repository repository = mapping.getRepository();
String baseline = GitQuickDiffProvider.baseline.get(repository);
if (baseline == null)
baseline = Constants.HEAD;
ObjectId commitId = repository.resolve(baseline);
if (commitId != null) {
if (commitId.equals(lastCommit)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
} else {
String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff,
new Object[] { baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
rw = new RevWalk(repository);
RevCommit baselineCommit;
try {
baselineCommit = rw.parseCommit(commitId);
} catch (IOException err) {
String msg = NLS
.bind(UIText.GitDocument_errorLoadCommit, new Object[] {
commitId, baseline, resource, repository });
Activator.logError(msg, err);
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
RevTree treeId = baselineCommit.getTree();
if (treeId.equals(lastTree)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
return;
}
tw = TreeWalk.forPath(repository, gitPath, treeId);
if (tw == null) {
setResolved(null, null, null, ""); //$NON-NLS-1$
String msg = NLS
.bind(UIText.GitDocument_errorLoadTree, new Object[] {
treeId, baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
ObjectId id = tw.getObjectId(0);
if (id.equals(ObjectId.zeroId())) {
setResolved(null, null, null, ""); //$NON-NLS-1$
String msg = NLS
.bind(UIText.GitDocument_errorLoadTree, new Object[] {
treeId, baseline, resource, repository });
Activator.logError(msg, new Throwable());
setResolved(null, null, null, ""); //$NON-NLS-1$
return;
}
if (!id.equals(lastBlob)) {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) compareTo: " + baseline); //$NON-NLS-1$
ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB);
byte[] bytes = loader.getBytes();
String charset;
charset = CompareUtils.getResourceEncoding(resource);
// Finally we could consider validating the content with respect
// to the content. We don't do that here.
String s = new String(bytes, charset);
setResolved(commitId, treeId, id, s);
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation
.getTrace()
.trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().trace(
GitTraceLocation.QUICKDIFF.getLocation(),
"(GitDocument) already resolved"); //$NON-NLS-1$
}
} finally {
if (tw != null)
tw.release();
if (rw != null)
rw.release();
if (GitTraceLocation.QUICKDIFF.isActive())
GitTraceLocation.getTrace().traceExit(
GitTraceLocation.QUICKDIFF.getLocation());
}
}
|
diff --git a/src/main/java/org/pircbotx/hooks/events/SetTopicProtectionEvent.java b/src/main/java/org/pircbotx/hooks/events/SetTopicProtectionEvent.java
index c78608c..1659b99 100644
--- a/src/main/java/org/pircbotx/hooks/events/SetTopicProtectionEvent.java
+++ b/src/main/java/org/pircbotx/hooks/events/SetTopicProtectionEvent.java
@@ -1,56 +1,56 @@
/**
* Copyright (C) 2010 Leon Blakey <lord.quackstar at gmail.com>
*
* This file is part of PircBotX.
*
* PircBotX 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.
*
* PircBotX 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 PircBotX. If not, see <http://www.gnu.org/licenses/>.
*/
package org.pircbotx.hooks.events;
import org.pircbotx.Channel;
import org.pircbotx.User;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.pircbotx.hooks.Event;
import org.pircbotx.PircBotX;
/**
* Called when topic protection is enabled for a channel. Topic protection
* means that only operators in a channel may change the topic.
* <p>
* This is a type of mode change and is also passed to the onMode
* method in the PircBotX class.
* <p>
* The implementation of this method in the PircBotX abstract class
* performs no actions and may be overridden as required.
* @author Leon Blakey <lord.quackstar at gmail.com>
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class SetTopicProtectionEvent extends Event {
protected final Channel channel;
protected final User user;
/**
* Default constructor to setup object. Timestamp is automatically set
* to current time as reported by {@link System#currentTimeMillis() }
* @param channel The channel in which the mode change took place.
* @param user The user that performed the mode change.
*/
public <T extends PircBotX> SetTopicProtectionEvent(T bot, Channel channel, User user) {
super(bot);
+ this.channel = channel;
this.user = user;
- this.source = source;
}
}
| false | true | public <T extends PircBotX> SetTopicProtectionEvent(T bot, Channel channel, User user) {
super(bot);
this.user = user;
this.source = source;
}
| public <T extends PircBotX> SetTopicProtectionEvent(T bot, Channel channel, User user) {
super(bot);
this.channel = channel;
this.user = user;
}
|
diff --git a/src/test/java/org/jproggy/snippetory/test/Page.java b/src/test/java/org/jproggy/snippetory/test/Page.java
index a003ebc..d0641bf 100644
--- a/src/test/java/org/jproggy/snippetory/test/Page.java
+++ b/src/test/java/org/jproggy/snippetory/test/Page.java
@@ -1,114 +1,115 @@
package org.jproggy.snippetory.test;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import org.jproggy.snippetory.Encodings;
import org.jproggy.snippetory.Repo;
import org.jproggy.snippetory.Template;
import org.jproggy.snippetory.spi.EncodedData;
public class Page implements EncodedData {
private final Template template;
private final Template page;
private final Map<String, String> errors;
private final ResourceBundle labels;
public Page(String title, String target, Map<String, String> errors, ResourceBundle labels) {
this.errors = errors;
this.labels = labels;
template = Repo.readResource("MetaRep.html")
.encoding(Encodings.html).locale(Locale.US).parse();
page = template.get("page");
page.set("title", title);
page.set("target", target);
}
public Section createSection(String title) {
return new Section(title);
}
public void render(PrintStream out) throws IOException {
page.render();
template.render(out);
}
public class Section implements EncodedData {
private Template section;
private Section(String title) {
section = page.get("section").set("title", title);
}
public Section addTextAttrib(String name, Object value) {
Template attrib = getAttrib(name);
Template control = section.get("controls", "text").set("name", name).set("value", value);
control.render(attrib, "control");
attrib.render();
return this;
}
private Template getAttrib(String name) {
Template attrib = section.get("attribute");
attrib.set("label", labels.getString(name));
if (errors.containsKey(name)) attrib.get("msg").set("error", errors.get(name)).render();
return attrib;
}
public Section addSelectionAttrib(String name, Collection<?> values, Object selected) {
Template attrib = getAttrib(name);
Template control = section.get("controls", "select");
+ control.set("name", name);
for (Object value : values) {
String type = value.equals(selected) ? "selected_option" : "option";
- Template option = control.get(type).set("name", name).set("value", value).set("label", labels.getString(value.toString()));
+ Template option = control.get(type).set("value", value).set("label", labels.getString(value.toString()));
option.render("option");
}
control.render(attrib, "control");
attrib.render();
return this;
}
public Section addMultiSelectionAttrib(String name, Collection<?> values, Collection<?> selected) {
Template attrib = getAttrib(name);
for (Object value : values) {
String type = selected.contains(value) ? "selected_checkbox" : "checkbox";
Template control = section.get("controls", type).set("name", name).set("value", value).set("label", labels.getString(value.toString()));
control.render(attrib, "control");
}
attrib.render();
return this;
}
public Section addDescription(Object desc) {
section.get("description").set("description", desc).render();
return this;
}
public void render() {
section.render();
}
@Override
public String getEncoding() {
return Encodings.html.name();
}
@Override
public CharSequence toCharSequence() {
return section.toCharSequence();
}
}
@Override
public String getEncoding() {
return Encodings.html.name();
}
@Override
public CharSequence toCharSequence() {
return template.toCharSequence();
}
}
| false | true | public Section addSelectionAttrib(String name, Collection<?> values, Object selected) {
Template attrib = getAttrib(name);
Template control = section.get("controls", "select");
for (Object value : values) {
String type = value.equals(selected) ? "selected_option" : "option";
Template option = control.get(type).set("name", name).set("value", value).set("label", labels.getString(value.toString()));
option.render("option");
}
control.render(attrib, "control");
attrib.render();
return this;
}
| public Section addSelectionAttrib(String name, Collection<?> values, Object selected) {
Template attrib = getAttrib(name);
Template control = section.get("controls", "select");
control.set("name", name);
for (Object value : values) {
String type = value.equals(selected) ? "selected_option" : "option";
Template option = control.get(type).set("value", value).set("label", labels.getString(value.toString()));
option.render("option");
}
control.render(attrib, "control");
attrib.render();
return this;
}
|
diff --git a/src/eu/bryants/anthony/plinth/compiler/passes/Resolver.java b/src/eu/bryants/anthony/plinth/compiler/passes/Resolver.java
index db1d5c3..2f7d8b2 100644
--- a/src/eu/bryants/anthony/plinth/compiler/passes/Resolver.java
+++ b/src/eu/bryants/anthony/plinth/compiler/passes/Resolver.java
@@ -1,2989 +1,2989 @@
package eu.bryants.anthony.plinth.compiler.passes;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import eu.bryants.anthony.plinth.ast.ClassDefinition;
import eu.bryants.anthony.plinth.ast.CompilationUnit;
import eu.bryants.anthony.plinth.ast.CompoundDefinition;
import eu.bryants.anthony.plinth.ast.InterfaceDefinition;
import eu.bryants.anthony.plinth.ast.LexicalPhrase;
import eu.bryants.anthony.plinth.ast.TypeDefinition;
import eu.bryants.anthony.plinth.ast.expression.ArithmeticExpression;
import eu.bryants.anthony.plinth.ast.expression.ArrayAccessExpression;
import eu.bryants.anthony.plinth.ast.expression.ArrayCreationExpression;
import eu.bryants.anthony.plinth.ast.expression.BitwiseNotExpression;
import eu.bryants.anthony.plinth.ast.expression.BooleanLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.BooleanNotExpression;
import eu.bryants.anthony.plinth.ast.expression.BracketedExpression;
import eu.bryants.anthony.plinth.ast.expression.CastExpression;
import eu.bryants.anthony.plinth.ast.expression.CreationExpression;
import eu.bryants.anthony.plinth.ast.expression.EqualityExpression;
import eu.bryants.anthony.plinth.ast.expression.Expression;
import eu.bryants.anthony.plinth.ast.expression.FieldAccessExpression;
import eu.bryants.anthony.plinth.ast.expression.FloatingLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.FunctionCallExpression;
import eu.bryants.anthony.plinth.ast.expression.InlineIfExpression;
import eu.bryants.anthony.plinth.ast.expression.InstanceOfExpression;
import eu.bryants.anthony.plinth.ast.expression.IntegerLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.LogicalExpression;
import eu.bryants.anthony.plinth.ast.expression.MinusExpression;
import eu.bryants.anthony.plinth.ast.expression.NullCoalescingExpression;
import eu.bryants.anthony.plinth.ast.expression.NullLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.ObjectCreationExpression;
import eu.bryants.anthony.plinth.ast.expression.RelationalExpression;
import eu.bryants.anthony.plinth.ast.expression.ShiftExpression;
import eu.bryants.anthony.plinth.ast.expression.StringLiteralExpression;
import eu.bryants.anthony.plinth.ast.expression.SuperVariableExpression;
import eu.bryants.anthony.plinth.ast.expression.ThisExpression;
import eu.bryants.anthony.plinth.ast.expression.TupleExpression;
import eu.bryants.anthony.plinth.ast.expression.TupleIndexExpression;
import eu.bryants.anthony.plinth.ast.expression.VariableExpression;
import eu.bryants.anthony.plinth.ast.member.Constructor;
import eu.bryants.anthony.plinth.ast.member.Field;
import eu.bryants.anthony.plinth.ast.member.Initialiser;
import eu.bryants.anthony.plinth.ast.member.Method;
import eu.bryants.anthony.plinth.ast.member.Property;
import eu.bryants.anthony.plinth.ast.metadata.ArrayLengthMemberReference;
import eu.bryants.anthony.plinth.ast.metadata.ConstructorReference;
import eu.bryants.anthony.plinth.ast.metadata.FieldInitialiser;
import eu.bryants.anthony.plinth.ast.metadata.FieldReference;
import eu.bryants.anthony.plinth.ast.metadata.GenericTypeSpecialiser;
import eu.bryants.anthony.plinth.ast.metadata.MemberReference;
import eu.bryants.anthony.plinth.ast.metadata.MethodReference;
import eu.bryants.anthony.plinth.ast.metadata.MethodReference.Disambiguator;
import eu.bryants.anthony.plinth.ast.metadata.PackageNode;
import eu.bryants.anthony.plinth.ast.metadata.PropertyInitialiser;
import eu.bryants.anthony.plinth.ast.metadata.PropertyReference;
import eu.bryants.anthony.plinth.ast.metadata.Variable;
import eu.bryants.anthony.plinth.ast.misc.ArrayElementAssignee;
import eu.bryants.anthony.plinth.ast.misc.Assignee;
import eu.bryants.anthony.plinth.ast.misc.BlankAssignee;
import eu.bryants.anthony.plinth.ast.misc.CatchClause;
import eu.bryants.anthony.plinth.ast.misc.FieldAssignee;
import eu.bryants.anthony.plinth.ast.misc.Import;
import eu.bryants.anthony.plinth.ast.misc.Parameter;
import eu.bryants.anthony.plinth.ast.misc.QName;
import eu.bryants.anthony.plinth.ast.misc.VariableAssignee;
import eu.bryants.anthony.plinth.ast.statement.AssignStatement;
import eu.bryants.anthony.plinth.ast.statement.Block;
import eu.bryants.anthony.plinth.ast.statement.BreakStatement;
import eu.bryants.anthony.plinth.ast.statement.ContinueStatement;
import eu.bryants.anthony.plinth.ast.statement.DelegateConstructorStatement;
import eu.bryants.anthony.plinth.ast.statement.ExpressionStatement;
import eu.bryants.anthony.plinth.ast.statement.ForStatement;
import eu.bryants.anthony.plinth.ast.statement.IfStatement;
import eu.bryants.anthony.plinth.ast.statement.PrefixIncDecStatement;
import eu.bryants.anthony.plinth.ast.statement.ReturnStatement;
import eu.bryants.anthony.plinth.ast.statement.ShorthandAssignStatement;
import eu.bryants.anthony.plinth.ast.statement.Statement;
import eu.bryants.anthony.plinth.ast.statement.ThrowStatement;
import eu.bryants.anthony.plinth.ast.statement.TryStatement;
import eu.bryants.anthony.plinth.ast.statement.WhileStatement;
import eu.bryants.anthony.plinth.ast.terminal.SinceSpecifier;
import eu.bryants.anthony.plinth.ast.type.ArrayType;
import eu.bryants.anthony.plinth.ast.type.FunctionType;
import eu.bryants.anthony.plinth.ast.type.NamedType;
import eu.bryants.anthony.plinth.ast.type.NullType;
import eu.bryants.anthony.plinth.ast.type.ObjectType;
import eu.bryants.anthony.plinth.ast.type.PrimitiveType;
import eu.bryants.anthony.plinth.ast.type.TupleType;
import eu.bryants.anthony.plinth.ast.type.Type;
import eu.bryants.anthony.plinth.ast.type.TypeParameter;
import eu.bryants.anthony.plinth.ast.type.VoidType;
import eu.bryants.anthony.plinth.ast.type.WildcardType;
import eu.bryants.anthony.plinth.compiler.CoalescedConceptualException;
import eu.bryants.anthony.plinth.compiler.ConceptualException;
import eu.bryants.anthony.plinth.compiler.NameNotResolvedException;
/*
* Created on 2 Apr 2012
*/
/**
* @author Anthony Bryant
*/
public class Resolver
{
private PackageNode rootPackage;
public Resolver(PackageNode rootPackage)
{
this.rootPackage = rootPackage;
}
/**
* Resolves the specified compilation unit's declared package, and the type definitions it makes to that package.
* @param compilationUnit - the compilation unit to resolve
* @throws ConceptualException - if there is a problem adding something to a package (e.g. a name conflict)
*/
public void resolvePackages(CompilationUnit compilationUnit) throws ConceptualException
{
// find the package for this compilation unit
PackageNode compilationUnitPackage = rootPackage;
if (compilationUnit.getDeclaredPackage() != null)
{
compilationUnitPackage = rootPackage.addPackageTree(compilationUnit.getDeclaredPackage());
}
compilationUnit.setResolvedPackage(compilationUnitPackage);
// add all of the type definitions in this compilation unit to the file's package
for (TypeDefinition typeDefinition : compilationUnit.getTypeDefinitions())
{
compilationUnitPackage.addTypeDefinition(typeDefinition);
}
}
/**
* Resolves the special types that are required for every program, such as string.
* @throws ConceptualException - if there is a conceptual problem while resolving the names
* @throws NameNotResolvedException - if a name could not be resolved
*/
public void resolveSpecialTypes() throws NameNotResolvedException, ConceptualException
{
resolve(SpecialTypeHandler.STRING_TYPE, null, null);
resolve(SpecialTypeHandler.THROWABLE_TYPE, null, null);
resolve(SpecialTypeHandler.CAST_ERROR_TYPE, null, null);
}
/**
* Resolves all of the imports in the specified CompilationUnit
* @param compilationUnit - the CompilationUnit to resolve the imports of
* @throws NameNotResolvedException - if a name could not be resolved
* @throws ConceptualException - if there is a conceptual problem while resolving the names
*/
public void resolveImports(CompilationUnit compilationUnit) throws NameNotResolvedException, ConceptualException
{
for (Import currentImport : compilationUnit.getImports())
{
QName qname = currentImport.getImported();
String[] names = qname.getNames();
PackageNode currentPackage = rootPackage;
TypeDefinition currentTypeDefinition = null;
// now resolve the rest of the names (or as many as possible until the current items are all null)
for (int i = 0; i < names.length; ++i)
{
if (currentPackage != null)
{
// at most one of these lookups can succeed
currentTypeDefinition = currentPackage.getTypeDefinition(names[i]);
// update currentPackage last (and only if we don't have a type definition)
currentPackage = currentTypeDefinition == null ? currentPackage.getSubPackage(names[i]) : null;
}
else if (currentTypeDefinition != null)
{
// TODO: if/when we add inner types, resolve the sub-type here
// for now, we cannot resolve the name on this definition, so fail by setting everything to null
currentTypeDefinition = null;
}
else
{
break;
}
}
if (currentTypeDefinition == null && currentPackage == null)
{
throw new NameNotResolvedException("Unable to resolve the import: " + qname, qname.getLexicalPhrase());
}
if (currentPackage != null && !currentImport.isWildcard())
{
throw new NameNotResolvedException("A non-wildcard import cannot resolve to a package", qname.getLexicalPhrase());
}
// only one of these calls will set the resolved object to a non-null value
currentImport.setResolvedPackage(currentPackage);
currentImport.setResolvedTypeDefinition(currentTypeDefinition);
}
}
/**
* Resolves the top level types in the specified type definition (e.g. function parameters and return types, field types),
* so that they can be used anywhere in statements and expressions later on.
* @param typeDefinition - the TypeDefinition to resolve the types of
* @param compilationUnit - the optional CompilationUnit to resolve the types in the context of
* @throws ConceptualException - if a conceptual problem is encountered during resolution, or a name could not be resolved
*/
public void resolveTypes(TypeDefinition typeDefinition, CompilationUnit compilationUnit) throws ConceptualException
{
CoalescedConceptualException coalescedException = null;
if (typeDefinition instanceof ClassDefinition)
{
ClassDefinition classDefinition = (ClassDefinition) typeDefinition;
for (TypeParameter typeParameter : classDefinition.getTypeParameters())
{
for (Type superType : typeParameter.getSuperTypes())
{
try
{
resolve(superType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (Type subType : typeParameter.getSubTypes())
{
try
{
resolve(subType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
NamedType superType = classDefinition.getSuperType();
if (superType != null)
{
try
{
resolve(superType, typeDefinition, compilationUnit);
// make sure the super-type has the right number of type arguments, and that none of them are wildcards, etc.
TypeChecker.checkSuperType(superType);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
NamedType[] superInterfaceTypes = classDefinition.getSuperInterfaceTypes();
if (superInterfaceTypes != null)
{
for (int i = 0; i < superInterfaceTypes.length; ++i)
{
try
{
resolve(superInterfaceTypes[i], typeDefinition, compilationUnit);
// make sure the super-type has the right number of type arguments, and that none of them are wildcards, etc.
TypeChecker.checkSuperType(superInterfaceTypes[i]);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
}
if (typeDefinition instanceof InterfaceDefinition)
{
InterfaceDefinition interfaceDefinition = (InterfaceDefinition) typeDefinition;
for (TypeParameter typeParameter : interfaceDefinition.getTypeParameters())
{
for (Type superType : typeParameter.getSuperTypes())
{
try
{
resolve(superType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (Type subType : typeParameter.getSubTypes())
{
try
{
resolve(subType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
NamedType[] superInterfaceTypes = interfaceDefinition.getSuperInterfaceTypes();
if (superInterfaceTypes != null)
{
for (int i = 0; i < superInterfaceTypes.length; ++i)
{
try
{
resolve(superInterfaceTypes[i], typeDefinition, compilationUnit);
// make sure the super-type has the right number of type arguments, and that none of them are wildcards, etc.
TypeChecker.checkSuperType(superInterfaceTypes[i]);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
}
if (typeDefinition instanceof CompoundDefinition)
{
CompoundDefinition compoundDefinition = (CompoundDefinition) typeDefinition;
for (TypeParameter typeParameter : compoundDefinition.getTypeParameters())
{
for (Type superType : typeParameter.getSuperTypes())
{
try
{
resolve(superType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (Type subType : typeParameter.getSubTypes())
{
try
{
resolve(subType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
}
for (Field field : typeDefinition.getFields())
{
// resolve the field's type
Type type = field.getType();
try
{
resolve(type, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
continue;
}
// make sure the field is not both mutable and final/immutable
if (field.isMutable())
{
// check whether the internals of the field can be altered
boolean isAlterable = (type instanceof ArrayType && !((ArrayType) type).isContextuallyImmutable()) ||
(type instanceof NamedType && !((NamedType) type).isContextuallyImmutable());
if (field.isFinal() && !isAlterable)
{
// the field is both final and not alterable (e.g. a final uint, or a final #Object), so it cannot be mutable
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("A final, immutably-typed field cannot be mutable", field.getLexicalPhrase()));
}
}
}
for (Property property : typeDefinition.getProperties())
{
// resolve the property's type
Type type = property.getType();
try
{
resolve(type, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (property.getGetterUncheckedThrownTypes() != null)
{
for (NamedType thrownType : property.getGetterUncheckedThrownTypes())
{
try
{
resolve(thrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (property.getSetterBlock() != null)
{
try
{
resolve(property.getSetterParameter().getType(), typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (property.getSetterUncheckedThrownTypes() != null)
{
for (NamedType thrownType : property.getSetterUncheckedThrownTypes())
{
try
{
resolve(thrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
}
if (property.getConstructorBlock() != null)
{
try
{
resolve(property.getConstructorParameter().getType(), typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (property.getConstructorUncheckedThrownTypes() != null)
{
for (NamedType thrownType : property.getConstructorUncheckedThrownTypes())
{
try
{
resolve(thrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
}
if (coalescedException != null)
{
continue;
}
if (property.getSetterBlock() != null)
{
property.getSetterBlock().addVariable(property.getSetterParameter().getVariable());
}
if (property.getConstructorBlock() != null)
{
property.getConstructorBlock().addVariable(property.getConstructorParameter().getVariable());
}
if (typeDefinition.isImmutable() && !property.isStatic() && !property.isFinal() && !property.isSetterImmutable())
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("An instance property in an immutable type must either have an immutable setter, or be marked as final (and thus have no setter)", property.getLexicalPhrase()));
}
}
Map<String, Constructor> allConstructors = new HashMap<String, Constructor>();
for (Constructor constructor : typeDefinition.getAllConstructors())
{
Block mainBlock = constructor.getBlock();
if (mainBlock == null)
{
// we are resolving a bitcode file with no blocks inside it, so create a temporary one so that we can check for duplicate parameters easily
mainBlock = new Block(null, null);
}
StringBuffer disambiguatorBuffer = new StringBuffer();
if (constructor.getSinceSpecifier() != null)
{
disambiguatorBuffer.append(constructor.getSinceSpecifier().getMangledName());
}
disambiguatorBuffer.append('_');
boolean parameterResolveFailed = false;
for (Parameter p : constructor.getParameters())
{
Variable oldVar = mainBlock.addVariable(p.getVariable());
if (oldVar != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Duplicate parameter: " + p.getName(), p.getLexicalPhrase()));
}
try
{
resolve(p.getType(), typeDefinition, compilationUnit);
disambiguatorBuffer.append(p.getType().getMangledName());
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
parameterResolveFailed = true;
}
}
if (!parameterResolveFailed)
{
String disambiguator = disambiguatorBuffer.toString();
Constructor existing = allConstructors.put(disambiguator, constructor);
if (existing != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Duplicate constructor", constructor.getLexicalPhrase()));
}
}
for (NamedType thrownType : constructor.getCheckedThrownTypes())
{
try
{
resolve(thrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (NamedType uncheckedThrownType : constructor.getUncheckedThrownTypes())
{
try
{
resolve(uncheckedThrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
// resolve all method return and parameter types, and check for duplicate methods
// however, we must allow duplicated static methods if their since specifiers differ, so our map must allow for multiple methods per disambiguator
Map<Disambiguator, Set<Method>> allMethods = new HashMap<Disambiguator, Set<Method>>();
for (Method method : typeDefinition.getAllMethods())
{
boolean typeResolveFailed = false;
try
{
resolve(method.getReturnType(), typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
typeResolveFailed = true;
}
Block mainBlock = method.getBlock();
if (mainBlock == null)
{
// we are resolving a method with no block, so create a temporary one so that we can check for duplicate parameters easily
mainBlock = new Block(null, null);
}
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; ++i)
{
Variable oldVar = mainBlock.addVariable(parameters[i].getVariable());
if (oldVar != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Duplicate parameter: " + parameters[i].getName(), parameters[i].getLexicalPhrase()));
}
try
{
resolve(parameters[i].getType(), typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
typeResolveFailed = true;
}
}
for (NamedType thrownType : method.getCheckedThrownTypes())
{
try
{
resolve(thrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
// this doesn't count as a failure to resolve the method's type, since it doesn't affect the disambiguator
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (NamedType uncheckedThrownType : method.getUncheckedThrownTypes())
{
try
{
resolve(uncheckedThrownType, typeDefinition, compilationUnit);
}
catch (ConceptualException e)
{
// this doesn't count as a failure to resolve the method's type, since it doesn't affect the disambiguator
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (!typeResolveFailed)
{
MethodReference methodReference = new MethodReference(method, GenericTypeSpecialiser.IDENTITY_SPECIALISER);
Set<Method> methodSet = allMethods.get(methodReference.getDisambiguator());
if (methodSet == null)
{
methodSet = new HashSet<Method>();
allMethods.put(methodReference.getDisambiguator(), methodSet);
}
if (methodSet.isEmpty())
{
methodSet.add(method);
}
else
{
// there is already a method with this disambiguator
if (!method.isStatic())
{
// disallow all duplicates for non-static methods (this works because Disambiguators take staticness into account)
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Duplicate non-static method: " + method.getName(), method.getLexicalPhrase()));
}
else
{
// for static methods, we only allow another method if it has a different since specifier from all of the existing ones
SinceSpecifier newSpecifier = method.getSinceSpecifier();
for (Method existing : methodSet)
{
SinceSpecifier currentSpecifier = existing.getSinceSpecifier();
if (newSpecifier == null ? currentSpecifier == null : newSpecifier.compareTo(currentSpecifier) == 0)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Duplicate static method: " + method.getName(), method.getLexicalPhrase()));
break;
}
}
// no methods exist with the same since specifier, so add the new one
methodSet.add(method);
}
}
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
/**
* Tries to resolve the specified QName to a TypeDefinition, from the context of the root package.
* @param qname - the QName to resolve
* @return the TypeDefinition resolved
* @throws NameNotResolvedException - if the QName cannot be resolved
* @throws ConceptualException - if a conceptual error occurs while resolving the TypeDefinition
*/
public TypeDefinition resolveTypeDefinition(QName qname) throws NameNotResolvedException, ConceptualException
{
NamedType namedType = new NamedType(false, false, qname, null, qname.getLexicalPhrase());
resolve(namedType, null, null);
return namedType.getResolvedTypeDefinition();
}
/**
* Resolves all of the method bodies, field assignments, etc. in the specified TypeDefinition.
* @param typeDefinition - the TypeDefinition to resolve
* @param compilationUnit - the CompilationUnit that the TypeDefinition was defined in
* @throws ConceptualException - if a conceptual error occurs while resolving the TypeDefinition, or a QName cannot be resolved
*/
public void resolve(TypeDefinition typeDefinition, CompilationUnit compilationUnit) throws ConceptualException
{
CoalescedConceptualException coalescedException = null;
// a non-static initialiser is an immutable context if there is at least one immutable constructor
// so we need to check whether there are any immutable constructors here
boolean hasImmutableConstructors = false;
for (Constructor constructor : typeDefinition.getAllConstructors())
{
if (constructor.isImmutable())
{
hasImmutableConstructors = true;
}
try
{
resolveTopLevelBlock(constructor.getBlock(), typeDefinition, compilationUnit, false, constructor.isImmutable(), false, null);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (Initialiser initialiser : typeDefinition.getInitialisers())
{
if (initialiser instanceof FieldInitialiser)
{
Field field = ((FieldInitialiser) initialiser).getField();
try
{
resolve(field.getInitialiserExpression(), initialiser.getBlock(), typeDefinition, compilationUnit, initialiser.isStatic(), !initialiser.isStatic() & hasImmutableConstructors, null);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
else if (initialiser instanceof PropertyInitialiser)
{
Property property = ((PropertyInitialiser) initialiser).getProperty();
try
{
resolve(property.getInitialiserExpression(), initialiser.getBlock(), typeDefinition, compilationUnit, initialiser.isStatic(), !initialiser.isStatic() & hasImmutableConstructors, null);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
else
{
try
{
resolveTopLevelBlock(initialiser.getBlock(), typeDefinition, compilationUnit, initialiser.isStatic(), !initialiser.isStatic() & hasImmutableConstructors, false, null);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
for (Property property : typeDefinition.getProperties())
{
if (property.getGetterBlock() != null)
{
try
{
// a getter can only return against contextual immutability if:
// 1. the property is not mutable (a mutable property never makes a result contextually immutable)
// 2. it is immutable itself (otherwise being able to do this would be pointless, as nothing would be contextually immutable anyway)
boolean canReturnAgainstContextualImmutability = !property.isMutable() && property.isGetterImmutable();
resolveTopLevelBlock(property.getGetterBlock(), typeDefinition, compilationUnit, property.isStatic(), property.isGetterImmutable(), canReturnAgainstContextualImmutability, property);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (property.getSetterBlock() != null)
{
try
{
resolveTopLevelBlock(property.getSetterBlock(), typeDefinition, compilationUnit, property.isStatic(), property.isSetterImmutable(), false, property);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (property.getConstructorBlock() != null)
{
try
{
resolveTopLevelBlock(property.getConstructorBlock(), typeDefinition, compilationUnit, property.isStatic(), property.isConstructorImmutable(), false, property);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
for (Method method : typeDefinition.getAllMethods())
{
if (method.getBlock() != null)
{
try
{
resolveTopLevelBlock(method.getBlock(), typeDefinition, compilationUnit, method.isStatic(), method.isImmutable(), false, null);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
private void resolve(Type type, TypeDefinition enclosingDefinition, CompilationUnit compilationUnit) throws NameNotResolvedException, ConceptualException
{
if (type instanceof ArrayType)
{
resolve(((ArrayType) type).getBaseType(), enclosingDefinition, compilationUnit);
}
else if (type instanceof FunctionType)
{
FunctionType functionType = (FunctionType) type;
resolve(functionType.getReturnType(), enclosingDefinition, compilationUnit);
for (Type parameterType : functionType.getParameterTypes())
{
resolve(parameterType, enclosingDefinition, compilationUnit);
}
for (Type thrownType : functionType.getThrownTypes())
{
resolve(thrownType, enclosingDefinition, compilationUnit);
}
}
else if (type instanceof NamedType)
{
NamedType namedType = (NamedType) type;
if (namedType.getResolvedTypeDefinition() != null || namedType.getResolvedTypeParameter() != null)
{
return;
}
String[] names = namedType.getQualifiedName().getNames();
// start by looking up the first name in the current type's TypeParameters
if (enclosingDefinition != null)
{
TypeParameter[] typeParameters = null;
if (enclosingDefinition instanceof ClassDefinition)
{
typeParameters = ((ClassDefinition) enclosingDefinition).getTypeParameters();
}
else if (enclosingDefinition instanceof InterfaceDefinition)
{
typeParameters = ((InterfaceDefinition) enclosingDefinition).getTypeParameters();
}
else if (enclosingDefinition instanceof CompoundDefinition)
{
typeParameters = ((CompoundDefinition) enclosingDefinition).getTypeParameters();
}
if (typeParameters != null)
{
for (TypeParameter typeParameter : typeParameters)
{
if (names[0].equals(typeParameter.getName()))
{
if (names.length > 1)
{
throw new NameNotResolvedException("Unable to resolve '" + names[1] + "': type parameters do not have sub-types", namedType.getLexicalPhrase());
}
namedType.setResolvedTypeParameter(typeParameter);
return;
}
}
}
}
// start by looking up the first name in the compilation unit
TypeDefinition currentDefinition = compilationUnit == null ? null : compilationUnit.getTypeDefinition(names[0]);
PackageNode currentPackage = null;
if (currentDefinition == null && compilationUnit != null)
{
// the lookup in the compilation unit failed, so try each of the imports in turn
for (Import currentImport : compilationUnit.getImports())
{
PackageNode importPackage = currentImport.getResolvedPackage();
TypeDefinition importDefinition = currentImport.getResolvedTypeDefinition();
if (currentImport.isWildcard())
{
if (importPackage != null)
{
// at most one of these lookups can succeed
currentDefinition = importPackage.getTypeDefinition(names[0]);
// update currentPackage last (and only if we don't have a type definition)
currentPackage = currentDefinition == null ? importPackage.getSubPackage(names[0]) : null;
}
else // if (importDefinition != null)
{
// TODO: if/when inner types are added, resolve the sub-type of importDefinition here
}
}
else if (currentImport.getName().equals(names[0]))
{
currentPackage = importPackage;
currentDefinition = importDefinition;
}
if (currentPackage != null || currentDefinition != null)
{
break;
}
}
}
if (currentPackage == null && currentDefinition == null && compilationUnit != null)
{
// the lookup from the imports failed, so try to look up the first name on the compilation unit's package instead
// (at most one of the following lookups can succeed)
currentDefinition = compilationUnit.getResolvedPackage().getTypeDefinition(names[0]);
// update currentPackage last (and only if we don't have a type definition)
if (currentDefinition == null)
{
currentPackage = compilationUnit.getResolvedPackage().getSubPackage(names[0]);
}
}
if (currentPackage == null && currentDefinition == null)
{
// all other lookups failed, so try to look up the first name on the root package
// (at most one of the following lookups can succeed)
currentDefinition = rootPackage.getTypeDefinition(names[0]);
// update currentPackage last (and only if we don't have a type definition)
if (currentDefinition == null)
{
currentPackage = rootPackage.getSubPackage(names[0]);
}
}
// now resolve the rest of the names (or as many as possible until the current items are all null)
for (int i = 1; i < names.length; ++i)
{
if (currentPackage != null)
{
// at most one of these lookups can succeed
currentDefinition = currentPackage.getTypeDefinition(names[i]);
// update currentPackage last (and only if we don't have a type definition)
currentPackage = currentDefinition == null ? currentPackage.getSubPackage(names[i]) : null;
}
else if (currentDefinition != null)
{
// TODO: if/when we add inner types, resolve the sub-type here
// for now, we cannot resolve the name on this definition, so fail by setting everything to null
currentDefinition = null;
}
else
{
break;
}
}
if (currentDefinition == null)
{
if (currentPackage != null)
{
throw new ConceptualException("A package cannot be used as a type", namedType.getLexicalPhrase());
}
throw new NameNotResolvedException("Unable to resolve: " + namedType.getQualifiedName(), namedType.getLexicalPhrase());
}
namedType.setResolvedTypeDefinition(currentDefinition);
if (namedType.getTypeArguments() != null)
{
CoalescedConceptualException coalescedException = null;
for (Type typeArgument : namedType.getTypeArguments())
{
try
{
resolve(typeArgument, enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
}
else if (type instanceof ObjectType)
{
// do nothing
}
else if (type instanceof PrimitiveType)
{
// do nothing
}
else if (type instanceof TupleType)
{
TupleType tupleType = (TupleType) type;
for (Type subType : tupleType.getSubTypes())
{
resolve(subType, enclosingDefinition, compilationUnit);
}
}
else if (type instanceof VoidType)
{
// do nothing
}
else if (type instanceof WildcardType)
{
WildcardType wildcardType = (WildcardType) type;
for (Type superType : wildcardType.getSuperTypes())
{
resolve(superType, enclosingDefinition, compilationUnit);
}
for (Type subType : wildcardType.getSubTypes())
{
resolve(subType, enclosingDefinition, compilationUnit);
}
}
else
{
throw new IllegalArgumentException("Unknown Type type: " + type);
}
}
private void resolveTopLevelBlock(Block block, TypeDefinition enclosingDefinition, CompilationUnit compilationUnit, boolean inStaticContext, boolean inImmutableContext, boolean canReturnAgainstContextualImmutability, Property enclosingProperty) throws ConceptualException
{
CoalescedConceptualException coalescedException = null;
for (Statement statement : block.getStatements())
{
try
{
resolve(statement, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
private void resolve(Statement statement, Block enclosingBlock, TypeDefinition enclosingDefinition, CompilationUnit compilationUnit, boolean inStaticContext, boolean inImmutableContext, boolean canReturnAgainstContextualImmutability, Property enclosingProperty) throws ConceptualException
{
if (statement instanceof AssignStatement)
{
AssignStatement assignStatement = (AssignStatement) statement;
Type type = assignStatement.getType();
if (type != null)
{
resolve(type, enclosingDefinition, compilationUnit);
}
CoalescedConceptualException coalescedException = null;
Assignee[] assignees = assignStatement.getAssignees();
boolean distributedTupleType = type != null && type instanceof TupleType && !type.canBeNullable() && ((TupleType) type).getSubTypes().length == assignees.length;
boolean madeVariableDeclaration = false;
List<VariableAssignee> alreadyDeclaredVariables = new LinkedList<VariableAssignee>();
for (int i = 0; i < assignees.length; i++)
{
if (assignees[i] instanceof VariableAssignee)
{
VariableAssignee variableAssignee = (VariableAssignee) assignees[i];
Variable variable = enclosingBlock.getVariable(variableAssignee.getVariableName());
if (variable != null)
{
alreadyDeclaredVariables.add(variableAssignee);
}
if (variable == null && type != null)
{
// we have a type, and the variable is not yet declared in this block, so declare the variable now
if (distributedTupleType)
{
Type subType = ((TupleType) type).getSubTypes()[i];
variable = new Variable(assignStatement.isFinal(), subType, variableAssignee.getVariableName());
}
else
{
variable = new Variable(assignStatement.isFinal(), type, variableAssignee.getVariableName());
}
enclosingBlock.addVariable(variable);
madeVariableDeclaration = true;
}
MemberReference<?> memberReference = null;
if (variable == null && enclosingDefinition != null)
{
// we haven't got a declared variable, so try to resolve it outside the block
Field field = null;
Property property = null;
for (final NamedType superType : enclosingDefinition.getInheritanceLinearisation())
{
TypeDefinition superTypeDefinition = superType.getResolvedTypeDefinition();
// note: this allows static fields from the superclass to be resolved, which is possible inside the class itself, but not by specifying an explicit type
field = superTypeDefinition.getField(variableAssignee.getVariableName());
property = superTypeDefinition.getProperty(variableAssignee.getVariableName());
if (field != null || property != null)
{
GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(superType);
if (field != null)
{
memberReference = new FieldReference(field, genericTypeSpecialiser);
}
else // property != null
{
memberReference = new PropertyReference(property, genericTypeSpecialiser);
}
break;
}
}
if (field != null)
{
if (field.isStatic())
{
variable = field.getGlobalVariable();
}
else
{
variable = field.getMemberVariable();
}
}
else if (property != null)
{
if (property == enclosingProperty)
{
if (property.isStatic())
{
variable = property.getBackingGlobalVariable();
}
else
{
variable = property.getBackingMemberVariable();
}
}
else
{
variable = property.getPseudoVariable();
}
}
}
if (variable == null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new NameNotResolvedException("Unable to resolve: " + variableAssignee.getVariableName(), variableAssignee.getLexicalPhrase()));
}
else
{
variableAssignee.setResolvedVariable(variable);
variableAssignee.setResolvedMemberReference(memberReference);
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
try
{
resolve(arrayElementAssignee.getArrayExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(arrayElementAssignee.getDimensionExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
fieldAssignee.getFieldAccessExpression().setIsAssignableHint(true);
// use the expression resolver to resolve the contained field access expression
try
{
resolve(fieldAssignee.getFieldAccessExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// do nothing, this assignee doesn't actually get assigned to
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
if (type != null && !madeVariableDeclaration)
{
// giving a type indicates a variable declaration, which is not allowed if all of the variables have already been declared
// if at least one of them is being declared, however, we allow the type to be present
if (alreadyDeclaredVariables.size() == 1)
{
VariableAssignee variableAssignee = alreadyDeclaredVariables.get(0);
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("'" + variableAssignee.getVariableName() + "' has already been declared, and cannot be redeclared", variableAssignee.getLexicalPhrase()));
}
else
{
StringBuffer buffer = new StringBuffer();
Iterator<VariableAssignee> it = alreadyDeclaredVariables.iterator();
while (it.hasNext())
{
buffer.append('\'');
buffer.append(it.next().getVariableName());
buffer.append('\'');
if (it.hasNext())
{
buffer.append(", ");
}
}
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("The variables " + buffer + " have all already been declared, and cannot be redeclared", assignStatement.getLexicalPhrase()));
}
}
if (assignStatement.getExpression() != null)
{
try
{
resolve(assignStatement.getExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (statement instanceof Block)
{
Block subBlock = (Block) statement;
for (Variable v : enclosingBlock.getVariables())
{
subBlock.addVariable(v);
}
CoalescedConceptualException coalescedException = null;
for (Statement s : subBlock.getStatements())
{
try
{
resolve(s, subBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (statement instanceof BreakStatement)
{
// do nothing
}
else if (statement instanceof ContinueStatement)
{
// do nothing
}
else if (statement instanceof DelegateConstructorStatement)
{
DelegateConstructorStatement delegateConstructorStatement = (DelegateConstructorStatement) statement;
CoalescedConceptualException coalescedException = null;
Expression[] arguments = delegateConstructorStatement.getArguments();
for (Expression argument : arguments)
{
try
{
resolve(argument, enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
NamedType constructorType;
if (delegateConstructorStatement.isSuperConstructor())
{
if (enclosingDefinition instanceof CompoundDefinition)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Cannot call a super(...) constructor from a compound type", delegateConstructorStatement.getLexicalPhrase()));
throw coalescedException;
}
else if (!(enclosingDefinition instanceof ClassDefinition))
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("A super(...) constructor can only be called from inside a class definition", delegateConstructorStatement.getLexicalPhrase()));
throw coalescedException;
}
constructorType = ((ClassDefinition) enclosingDefinition).getSuperType();
}
else
{
// create a NamedType from enclosingDefinition
TypeParameter[] typeParameters = enclosingDefinition.getTypeParameters();
Type[] typeArguments = null;
if (typeParameters != null)
{
typeArguments = new Type[typeParameters.length];
for (int i = 0; i < typeParameters.length; ++i)
{
typeArguments[i] = new NamedType(false, false, false, typeParameters[i]);
}
}
constructorType = new NamedType(false, false, enclosingDefinition, typeArguments);
}
if (coalescedException != null)
{
throw coalescedException;
}
if (constructorType == null)
{
// if the resolved type definition is null, it means that the object constructor should be called (which is a no-op, but runs the initialiser)
delegateConstructorStatement.setResolvedConstructorReference(null);
}
else
{
ConstructorReference resolvedConstructor = resolveConstructor(constructorType, arguments, delegateConstructorStatement.getLexicalPhrase(), enclosingDefinition, inStaticContext);
delegateConstructorStatement.setResolvedConstructorReference(resolvedConstructor);
}
// if there was no matching constructor, the resolved constructor call may not type check
// in this case, we should point out this error before we run the cycle checker, because the cycle checker could find that the constructor is recursive
// so run the type checker on this statement now
TypeChecker.checkTypes(delegateConstructorStatement, null, enclosingDefinition, inStaticContext); // give a null return type here, since the type checker will not need to use it
}
else if (statement instanceof ExpressionStatement)
{
resolve(((ExpressionStatement) statement).getExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (statement instanceof ForStatement)
{
ForStatement forStatement = (ForStatement) statement;
Statement init = forStatement.getInitStatement();
Expression condition = forStatement.getConditional();
Statement update = forStatement.getUpdateStatement();
Block block = forStatement.getBlock();
// process this block right here instead of recursing, since we need to process the init, condition, and update parts of the statement inside it after adding the variables, but before the rest of the resolution
for (Variable v : enclosingBlock.getVariables())
{
block.addVariable(v);
}
CoalescedConceptualException coalescedException = null;
if (init != null)
{
try
{
resolve(init, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (condition != null)
{
try
{
resolve(condition, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (update != null)
{
try
{
resolve(update, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
for (Statement s : block.getStatements())
{
try
{
resolve(s, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
CoalescedConceptualException coalescedException = null;
try
{
resolve(ifStatement.getExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(ifStatement.getThenClause(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (ifStatement.getElseClause() != null)
{
try
{
resolve(ifStatement.getElseClause(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (statement instanceof PrefixIncDecStatement)
{
PrefixIncDecStatement prefixIncDecStatement = (PrefixIncDecStatement) statement;
Assignee assignee = prefixIncDecStatement.getAssignee();
if (assignee instanceof VariableAssignee)
{
VariableAssignee variableAssignee = (VariableAssignee) assignee;
Variable variable = enclosingBlock.getVariable(variableAssignee.getVariableName());
MemberReference<?> memberReference = null;
if (variable == null && enclosingDefinition != null)
{
Field field = null;
Property property = null;
for (final NamedType superType : enclosingDefinition.getInheritanceLinearisation())
{
TypeDefinition superTypeDefinition = superType.getResolvedTypeDefinition();
// note: this allows static fields from the superclass to be resolved, which is possible inside the class itself, but not by specifying an explicit type
field = superTypeDefinition.getField(variableAssignee.getVariableName());
property = superTypeDefinition.getProperty(variableAssignee.getVariableName());
if (field != null || property != null)
{
GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(superType);
if (field != null)
{
memberReference = new FieldReference(field, genericTypeSpecialiser);
}
else // property != null
{
memberReference = new PropertyReference(property, genericTypeSpecialiser);
}
break;
}
}
if (field != null)
{
if (field.isStatic())
{
variable = field.getGlobalVariable();
}
else
{
variable = field.getMemberVariable();
}
}
else if (property != null)
{
if (property == enclosingProperty)
{
if (property.isStatic())
{
variable = property.getBackingGlobalVariable();
}
else
{
variable = property.getBackingMemberVariable();
}
}
else
{
variable = property.getPseudoVariable();
}
}
}
if (variable == null)
{
throw new NameNotResolvedException("Unable to resolve: " + variableAssignee.getVariableName(), variableAssignee.getLexicalPhrase());
}
variableAssignee.setResolvedVariable(variable);
variableAssignee.setResolvedMemberReference(memberReference);
}
else if (assignee instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee;
CoalescedConceptualException coalescedException = null;
try
{
resolve(arrayElementAssignee.getArrayExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(arrayElementAssignee.getDimensionExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (assignee instanceof BlankAssignee)
{
throw new ConceptualException("Cannot " + (prefixIncDecStatement.isIncrement() ? "inc" : "dec") + "rement a blank assignee", assignee.getLexicalPhrase());
}
else if (assignee instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignee;
// use the expression resolver to resolve the contained field access expression
resolve(fieldAssignee.getFieldAccessExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignee);
}
}
else if (statement instanceof ReturnStatement)
{
ReturnStatement returnStatement = (ReturnStatement) statement;
returnStatement.setCanReturnAgainstContextualImmutability(canReturnAgainstContextualImmutability);
Expression returnedExpression = returnStatement.getExpression();
if (returnedExpression != null)
{
resolve(returnedExpression, enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
}
else if (statement instanceof ShorthandAssignStatement)
{
ShorthandAssignStatement shorthandAssignStatement = (ShorthandAssignStatement) statement;
CoalescedConceptualException coalescedException = null;
for (Assignee assignee : shorthandAssignStatement.getAssignees())
{
if (assignee instanceof VariableAssignee)
{
VariableAssignee variableAssignee = (VariableAssignee) assignee;
Variable variable = enclosingBlock.getVariable(variableAssignee.getVariableName());
MemberReference<?> memberReference = null;
if (variable == null && enclosingDefinition != null)
{
Field field = null;
Property property = null;
for (final NamedType superType : enclosingDefinition.getInheritanceLinearisation())
{
TypeDefinition superTypeDefinition = superType.getResolvedTypeDefinition();
// note: this allows static fields from the superclass to be resolved, which is possible inside the class itself, but not by specifying an explicit type
field = superTypeDefinition.getField(variableAssignee.getVariableName());
property = superTypeDefinition.getProperty(variableAssignee.getVariableName());
if (field != null || property != null)
{
GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(superType);
if (field != null)
{
memberReference = new FieldReference(field, genericTypeSpecialiser);
}
else // property != null
{
memberReference = new PropertyReference(property, genericTypeSpecialiser);
}
break;
}
}
if (field != null)
{
if (field.isStatic())
{
variable = field.getGlobalVariable();
}
else
{
variable = field.getMemberVariable();
}
}
else if (property != null)
{
if (property == enclosingProperty)
{
if (property.isStatic())
{
variable = property.getBackingGlobalVariable();
}
else
{
variable = property.getBackingMemberVariable();
}
}
else
{
variable = property.getPseudoVariable();
}
}
}
if (variable == null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new NameNotResolvedException("Unable to resolve: " + variableAssignee.getVariableName(), variableAssignee.getLexicalPhrase()));
}
else
{
variableAssignee.setResolvedVariable(variable);
variableAssignee.setResolvedMemberReference(memberReference);
}
}
else if (assignee instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee;
try
{
resolve(arrayElementAssignee.getArrayExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(arrayElementAssignee.getDimensionExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
else if (assignee instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignee;
// use the expression resolver to resolve the contained field access expression
try
{
resolve(fieldAssignee.getFieldAccessExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
else if (assignee instanceof BlankAssignee)
{
// do nothing, this assignee doesn't actually get assigned to
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignee);
}
}
try
{
resolve(shorthandAssignStatement.getExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (statement instanceof ThrowStatement)
{
resolve(((ThrowStatement) statement).getThrownExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (statement instanceof TryStatement)
{
TryStatement tryStatement = (TryStatement) statement;
CoalescedConceptualException coalescedException = null;
try
{
resolve(tryStatement.getTryBlock(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
for (CatchClause catchClause : tryStatement.getCatchClauses())
{
CoalescedConceptualException subCoalescedException = null;
// process the block ourselves instead of recursing, as we need to add the exception variable ourselves
// resolve the type of the caught variable
for (Type t : catchClause.getCaughtTypes())
{
try
{
resolve(t, enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
subCoalescedException = CoalescedConceptualException.coalesce(subCoalescedException, e);
}
}
if (subCoalescedException != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, subCoalescedException);
continue;
}
Type variableType;
try
{
variableType = TypeChecker.checkCatchClauseTypes(catchClause.getCaughtTypes(), enclosingDefinition, inStaticContext);
}
catch (ConceptualException e)
{
subCoalescedException = CoalescedConceptualException.coalesce(subCoalescedException, e);
coalescedException = CoalescedConceptualException.coalesce(coalescedException, subCoalescedException);
continue;
}
// create the new variable, and set up the variables of the catch block
Variable variable = new Variable(catchClause.isVariableFinal(), variableType, catchClause.getVariableName());
catchClause.setResolvedExceptionVariable(variable);
Block catchBlock = catchClause.getBlock();
for (Variable v : enclosingBlock.getVariables())
{
catchBlock.addVariable(v);
}
Variable oldVar = catchBlock.addVariable(variable);
if (oldVar != null)
{
subCoalescedException = CoalescedConceptualException.coalesce(subCoalescedException, new ConceptualException("'" + variable.getName() + "' has already been declared, and cannot be redeclared", catchClause.getLexicalPhrase()));
coalescedException = CoalescedConceptualException.coalesce(coalescedException, subCoalescedException);
continue;
}
// resolve the contents of the catch block
for (Statement s : catchBlock.getStatements())
{
try
{
resolve(s, catchBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
subCoalescedException = CoalescedConceptualException.coalesce(subCoalescedException, e);
}
}
if (subCoalescedException != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, subCoalescedException);
continue;
}
}
if (tryStatement.getFinallyBlock() != null)
{
try
{
resolve(tryStatement.getFinallyBlock(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
CoalescedConceptualException coalescedException = null;
try
{
resolve(whileStatement.getExpression(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(whileStatement.getStatement(), enclosingBlock, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, canReturnAgainstContextualImmutability, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else
{
throw new IllegalArgumentException("Internal name resolution error: Unknown statement type: " + statement);
}
}
private void resolve(Expression expression, Block block, TypeDefinition enclosingDefinition, CompilationUnit compilationUnit, boolean inStaticContext, boolean inImmutableContext, Property enclosingProperty) throws ConceptualException
{
if (expression instanceof ArithmeticExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((ArithmeticExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((ArithmeticExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(arrayAccessExpression.getArrayExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(arrayAccessExpression.getDimensionExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression creationExpression = (ArrayCreationExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(creationExpression.getDeclaredType(), enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (creationExpression.getDimensionExpressions() != null)
{
for (Expression expr : creationExpression.getDimensionExpressions())
{
try
{
resolve(expr, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (creationExpression.getValueExpressions() != null)
{
for (Expression expr : creationExpression.getValueExpressions())
{
try
{
resolve(expr, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof BitwiseNotExpression)
{
resolve(((BitwiseNotExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof BooleanLiteralExpression)
{
// do nothing
}
else if (expression instanceof BooleanNotExpression)
{
resolve(((BooleanNotExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof BracketedExpression)
{
resolve(((BracketedExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof CastExpression)
{
CastExpression castExpression = (CastExpression) expression;
Type castType = expression.getType();
CoalescedConceptualException coalescedException = null;
try
{
resolve(castType, enclosingDefinition, compilationUnit);
// before resolving the casted expression, add hints for any FieldAccessExpressions or VariableExpressions that are directly inside it
Expression subExpression = castExpression.getExpression();
while (subExpression instanceof BracketedExpression)
{
subExpression = ((BracketedExpression) subExpression).getExpression();
}
if (subExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) subExpression).setTypeHint(castType);
}
if (subExpression instanceof VariableExpression)
{
((VariableExpression) subExpression).setTypeHint(castType);
}
if (subExpression instanceof FunctionCallExpression)
{
Expression baseExpression = ((FunctionCallExpression) subExpression).getFunctionExpression();
while (baseExpression instanceof BracketedExpression)
{
baseExpression = ((BracketedExpression) baseExpression).getExpression();
}
if (baseExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) baseExpression).setReturnTypeHint(castType);
}
if (baseExpression instanceof VariableExpression)
{
((VariableExpression) baseExpression).setReturnTypeHint(castType);
}
}
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(castExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof CreationExpression)
{
CreationExpression creationExpression = (CreationExpression) expression;
CoalescedConceptualException coalescedException = null;
NamedType type = creationExpression.getCreatedType();
try
{
resolve(type, enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
- if (type.getResolvedTypeDefinition() == null)
+ if (type.getResolvedTypeParameter() != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Cannot create an instance of a type parameter", type.getLexicalPhrase()));
}
Expression[] arguments = creationExpression.getArguments();
for (Expression argument : arguments)
{
try
{
resolve(argument, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
ConstructorReference resolvedConstructor = resolveConstructor(type, arguments, creationExpression.getLexicalPhrase(), enclosingDefinition, inStaticContext);
creationExpression.setResolvedConstructorReference(resolvedConstructor);
}
else if (expression instanceof EqualityExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((EqualityExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((EqualityExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
fieldAccessExpression.setResolvedContextImmutability(inImmutableContext);
String fieldName = fieldAccessExpression.getFieldName();
Type baseType;
boolean baseIsStatic;
if (fieldAccessExpression.getBaseExpression() != null)
{
resolve(fieldAccessExpression.getBaseExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
// find the type of the sub-expression, by calling the type checker
// this is fine as long as we resolve all of the sub-expression first
baseType = TypeChecker.checkTypes(fieldAccessExpression.getBaseExpression(), enclosingDefinition, inStaticContext);
baseIsStatic = false;
}
else if (fieldAccessExpression.getBaseType() != null)
{
baseType = fieldAccessExpression.getBaseType();
resolve(baseType, enclosingDefinition, compilationUnit);
TypeChecker.checkType(baseType, true, enclosingDefinition, inStaticContext);
baseIsStatic = true;
}
else
{
throw new IllegalStateException("Unknown base type for a field access: " + fieldAccessExpression);
}
Set<MemberReference<?>> memberSet = baseType.getMembers(fieldName);
Set<MemberReference<?>> staticFiltered = new HashSet<MemberReference<?>>();
for (MemberReference<?> member : memberSet)
{
if (member instanceof ArrayLengthMemberReference)
{
if (baseIsStatic)
{
throw new ConceptualException("Cannot access the array length member statically", fieldAccessExpression.getLexicalPhrase());
}
staticFiltered.add(member);
}
else if (member instanceof FieldReference)
{
if (((FieldReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else if (member instanceof PropertyReference)
{
if (((PropertyReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else if (member instanceof MethodReference)
{
if (((MethodReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else
{
throw new IllegalStateException("Unknown member type: " + member);
}
}
if (staticFiltered.isEmpty())
{
throw new NameNotResolvedException("No such " + (baseIsStatic ? "static" : "non-static") + " member \"" + fieldName + "\" for type " + baseType, fieldAccessExpression.getLexicalPhrase());
}
MemberReference<?> resolved = null;
if (staticFiltered.size() == 1)
{
resolved = staticFiltered.iterator().next();
}
else
{
Set<MemberReference<?>> hintFiltered = applyTypeHints(staticFiltered, fieldAccessExpression.getTypeHint(), fieldAccessExpression.getReturnTypeHint(), fieldAccessExpression.getIsFunctionHint(), fieldAccessExpression.getIsAssignableHint());
if (hintFiltered.size() == 1)
{
resolved = hintFiltered.iterator().next();
}
}
if (resolved == null)
{
throw new ConceptualException("Multiple " + (baseIsStatic ? "static" : "non-static") + " members have the name '" + fieldName + "'", fieldAccessExpression.getLexicalPhrase());
}
fieldAccessExpression.setResolvedMemberReference(resolved);
}
else if (expression instanceof FloatingLiteralExpression)
{
// do nothing
}
else if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression expr = (FunctionCallExpression) expression;
// resolve all of the sub-expressions
CoalescedConceptualException coalescedException = null;
for (Expression e : expr.getArguments())
{
try
{
resolve(e, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
TypeChecker.checkTypes(e, enclosingDefinition, inStaticContext);
}
catch (ConceptualException exception)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, exception);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
Expression functionExpression = expr.getFunctionExpression();
// before resolving the functionExpression, add hints for any FieldAccessExpressions or VariableExpressions that are directly inside it
Expression subExpression = functionExpression;
while (subExpression instanceof BracketedExpression)
{
subExpression = ((BracketedExpression) subExpression).getExpression();
}
if (subExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) subExpression).setIsFunctionHint(true);
}
if (subExpression instanceof VariableExpression)
{
((VariableExpression) subExpression).setIsFunctionHint(true);
}
Type expressionType = null;
Exception cachedException = null;
// first, try to resolve the function call as a normal expression
// this MUST be done first, so that local variables with function types are considered before outside methods
try
{
resolve(functionExpression, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
expressionType = TypeChecker.checkTypes(functionExpression, enclosingDefinition, inStaticContext);
}
catch (NameNotResolvedException e)
{
cachedException = e;
}
catch (ConceptualException e)
{
cachedException = e;
}
if (cachedException == null)
{
if (expressionType instanceof FunctionType)
{
// the sub-expressions all resolved properly, so we could just return here
// however, if this is just a normal method call, we can pull the resolved method into
// this FunctionCallExpression, so that we don't have to convert through FunctionType
Expression testExpression = functionExpression;
while (testExpression instanceof BracketedExpression)
{
testExpression = ((BracketedExpression) testExpression).getExpression();
}
if (testExpression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) testExpression;
if (variableExpression.getResolvedMemberReference() instanceof MethodReference) // "null instanceof Something" is always false
{
// the base resolved to a Method, so just resolve this FunctionCallExpression to the same Method
expr.setResolvedMethodReference((MethodReference) variableExpression.getResolvedMemberReference());
if (variableExpression instanceof SuperVariableExpression)
{
// this function call is of the form 'super.method()', so make it non-virtual
expr.setResolvedIsVirtual(false);
}
return;
}
}
else if (testExpression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) testExpression;
MemberReference<?> resolvedMemberReference = fieldAccessExpression.getResolvedMemberReference();
if (resolvedMemberReference instanceof MethodReference)
{
// the base resolved to a Method, so just resolve this FunctionCallExpression to the same Method
expr.setResolvedMethodReference((MethodReference) resolvedMemberReference);
expr.setResolvedBaseExpression(fieldAccessExpression.getBaseExpression()); // this will be null for static field accesses
expr.setResolvedNullTraversal(fieldAccessExpression.isNullTraversing());
return;
}
}
expr.setResolvedBaseExpression(functionExpression);
return;
}
- throw new ConceptualException("Cannot call a function on a non-function type", functionExpression.getLexicalPhrase());
+ throw new ConceptualException("Cannot call a non-function-typed value", functionExpression.getLexicalPhrase());
}
// we failed to resolve the sub-expression into something with a function type
// but the recursive resolver doesn't know which parameter types we're looking for here, so we may be able to consider some different options
// we can do this by checking if the function expression is actually a variable access or a field access expression, and checking them for other sources of method calls,
// such as constructor calls and method calls, each of which can be narrowed down by their parameter types
// first, go through any bracketed expressions, as we can ignore them
while (functionExpression instanceof BracketedExpression)
{
functionExpression = ((BracketedExpression) functionExpression).getExpression();
}
Map<Type[], MethodReference> paramTypeLists = new LinkedHashMap<Type[], MethodReference>();
Map<Type[], MethodReference> hintedParamLists = new LinkedHashMap<Type[], MethodReference>();
Map<MethodReference, Expression> methodBaseExpressions = new HashMap<MethodReference, Expression>();
boolean isSuperAccess = false;
if (functionExpression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) functionExpression;
isSuperAccess = variableExpression instanceof SuperVariableExpression;
String name = variableExpression.getName();
// the sub-expression didn't resolve to a variable or a field, or we would have got a valid type back in expressionType
if (enclosingDefinition != null)
{
Set<MemberReference<?>> memberSet = new NamedType(false, false, false, enclosingDefinition).getMembers(name, !isSuperAccess, isSuperAccess);
memberSet = memberSet != null ? memberSet : new HashSet<MemberReference<?>>();
Set<MemberReference<?>> hintedMemberSet = applyTypeHints(memberSet, variableExpression.getTypeHint(), variableExpression.getReturnTypeHint(), variableExpression.getIsFunctionHint(), variableExpression.getIsAssignableHint());
for (MemberReference<?> m : memberSet)
{
if (m instanceof MethodReference)
{
MethodReference methodReference = (MethodReference) m;
Type[] parameterTypes = methodReference.getParameterTypes();
paramTypeLists.put(parameterTypes, methodReference);
if (hintedMemberSet.contains(methodReference))
{
hintedParamLists.put(parameterTypes, methodReference);
}
// leave methodBaseExpressions with a null value for this method, as we have no base expression
}
}
}
}
else if (functionExpression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) functionExpression;
expr.setResolvedNullTraversal(fieldAccessExpression.isNullTraversing());
try
{
String name = fieldAccessExpression.getFieldName();
Expression baseExpression = fieldAccessExpression.getBaseExpression();
Type baseType;
boolean baseIsStatic;
if (baseExpression != null)
{
resolve(baseExpression, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
// find the type of the sub-expression, by calling the type checker
// this is fine as long as we resolve all of the sub-expression first
baseType = TypeChecker.checkTypes(baseExpression, enclosingDefinition, inStaticContext);
baseIsStatic = false;
}
else if (fieldAccessExpression.getBaseType() != null)
{
baseType = fieldAccessExpression.getBaseType();
resolve(baseType, enclosingDefinition, compilationUnit);
TypeChecker.checkType(baseType, true, enclosingDefinition, inStaticContext);
baseIsStatic = true;
}
else
{
throw new IllegalStateException("Unknown base type for a field access: " + fieldAccessExpression);
}
Set<MemberReference<?>> memberSet = baseType.getMembers(name);
memberSet = memberSet != null ? memberSet : new HashSet<MemberReference<?>>();
Set<MemberReference<?>> hintedMemberSet = applyTypeHints(memberSet, fieldAccessExpression.getTypeHint(), fieldAccessExpression.getReturnTypeHint(), fieldAccessExpression.getIsFunctionHint(), fieldAccessExpression.getIsAssignableHint());
for (MemberReference<?> member : memberSet)
{
// only allow access to this method if it is called in the right way, depending on whether or not it is static
if (member instanceof MethodReference && ((MethodReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
MethodReference methodReference = (MethodReference) member;
paramTypeLists.put(methodReference.getParameterTypes(), methodReference);
if (hintedMemberSet.contains(methodReference))
{
hintedParamLists.put(methodReference.getParameterTypes(), methodReference);
}
methodBaseExpressions.put(methodReference, baseExpression);
}
}
}
catch (NameNotResolvedException e)
{
// ignore this error, just assume it wasn't meant to resolve to a method call
}
catch (ConceptualException e)
{
// ignore this error, just assume it wasn't meant to resolve to a method call
}
}
// filter out parameter lists which are not assign-compatible with the arguments
filterParameterLists(hintedParamLists.entrySet(), expr.getArguments(), false, false);
// if there are multiple parameter lists, try to narrow it down to one that is equivalent to the argument list
if (hintedParamLists.size() > 1)
{
// first, try filtering for argument type equivalence, but ignoring nullability
Map<Type[], MethodReference> equivalenceFilteredHintedParamLists = new LinkedHashMap<Type[], MethodReference>(hintedParamLists);
filterParameterLists(equivalenceFilteredHintedParamLists.entrySet(), expr.getArguments(), true, true);
if (!equivalenceFilteredHintedParamLists.isEmpty())
{
hintedParamLists = equivalenceFilteredHintedParamLists;
if (hintedParamLists.size() > 1)
{
// the equivalence filter was not enough, so try a nullability filter as well
Map<Type[], MethodReference> nullabilityFilteredHintedParamLists = new LinkedHashMap<Type[], MethodReference>(hintedParamLists);
filterParameterLists(nullabilityFilteredHintedParamLists.entrySet(), expr.getArguments(), true, false);
if (!nullabilityFilteredHintedParamLists.isEmpty())
{
hintedParamLists = nullabilityFilteredHintedParamLists;
}
}
}
}
if (hintedParamLists.size() == 1)
{
paramTypeLists = hintedParamLists;
}
else
{
// try the same thing without using hintedParamLists
filterParameterLists(paramTypeLists.entrySet(), expr.getArguments(), false, false);
if (paramTypeLists.size() > 1)
{
Map<Type[], MethodReference> equivalenceFilteredParamTypeLists = new LinkedHashMap<Type[], MethodReference>(paramTypeLists);
filterParameterLists(equivalenceFilteredParamTypeLists.entrySet(), expr.getArguments(), true, true);
if (!equivalenceFilteredParamTypeLists.isEmpty())
{
paramTypeLists = equivalenceFilteredParamTypeLists;
if (paramTypeLists.size() > 1)
{
Map<Type[], MethodReference> nullabilityFilteredParamTypeLists = new LinkedHashMap<Type[], MethodReference>(paramTypeLists);
filterParameterLists(nullabilityFilteredParamTypeLists.entrySet(), expr.getArguments(), true, false);
if (!nullabilityFilteredParamTypeLists.isEmpty())
{
paramTypeLists = nullabilityFilteredParamTypeLists;
}
}
}
}
}
if (paramTypeLists.size() > 1)
{
throw new ConceptualException("Ambiguous method call, there are at least two applicable methods which take these arguments", expr.getLexicalPhrase());
}
if (paramTypeLists.isEmpty())
{
// we didn't find anything, so rethrow the exception from earlier
if (cachedException instanceof NameNotResolvedException)
{
throw (NameNotResolvedException) cachedException;
}
throw (ConceptualException) cachedException;
}
Entry<Type[], MethodReference> entry = paramTypeLists.entrySet().iterator().next();
expr.setResolvedMethodReference(entry.getValue());
// if the method call had no base expression, e.g. it was a VariableExpression being called, this will just set it to null
expr.setResolvedBaseExpression(methodBaseExpressions.get(entry.getValue()));
if (isSuperAccess)
{
// this function call is of the form 'super.method()', so make it non-virtual
expr.setResolvedIsVirtual(false);
}
}
else if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIfExpression = (InlineIfExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(inlineIfExpression.getCondition(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(inlineIfExpression.getThenExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(inlineIfExpression.getElseExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof InstanceOfExpression)
{
InstanceOfExpression instanceOfExpression = (InstanceOfExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(instanceOfExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(instanceOfExpression.getInstanceOfType(), enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof IntegerLiteralExpression)
{
// do nothing
}
else if (expression instanceof LogicalExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((LogicalExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((LogicalExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof MinusExpression)
{
resolve(((MinusExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof NullCoalescingExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((NullCoalescingExpression) expression).getNullableExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((NullCoalescingExpression) expression).getAlternativeExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof NullLiteralExpression)
{
// do nothing
}
else if (expression instanceof ObjectCreationExpression)
{
// do nothing
}
else if (expression instanceof RelationalExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((RelationalExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((RelationalExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ShiftExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((ShiftExpression) expression).getLeftExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((ShiftExpression) expression).getRightExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof StringLiteralExpression)
{
// resolve the type of the string literal here, so that we have access to it in the type checker
expression.setType(SpecialTypeHandler.STRING_TYPE);
}
else if (expression instanceof ThisExpression)
{
ThisExpression thisExpression = (ThisExpression) expression;
if (enclosingDefinition == null)
{
throw new ConceptualException("'this' does not refer to anything in this context", thisExpression.getLexicalPhrase());
}
thisExpression.setType(new NamedType(false, false, inImmutableContext, enclosingDefinition));
}
else if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
CoalescedConceptualException coalescedException = null;
Expression[] subExpressions = tupleExpression.getSubExpressions();
for (int i = 0; i < subExpressions.length; i++)
{
try
{
resolve(subExpressions[i], block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression indexExpression = (TupleIndexExpression) expression;
resolve(indexExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof VariableExpression)
{
VariableExpression expr = (VariableExpression) expression;
boolean isSuperAccess = expr instanceof SuperVariableExpression;
expr.setResolvedContextImmutability(inImmutableContext);
Variable var = block.getVariable(expr.getName());
if (var != null & !isSuperAccess)
{
expr.setResolvedVariable(var);
return;
}
if (enclosingDefinition != null)
{
Set<MemberReference<?>> members = new NamedType(false, false, enclosingDefinition, null).getMembers(expr.getName(), !isSuperAccess, isSuperAccess);
members = members != null ? members : new HashSet<MemberReference<?>>();
MemberReference<?> resolved = null;
if (members.size() == 1)
{
resolved = members.iterator().next();
}
else
{
Set<MemberReference<?>> filteredMembers = applyTypeHints(members, expr.getTypeHint(), expr.getReturnTypeHint(), expr.getIsFunctionHint(), expr.getIsAssignableHint());
if (filteredMembers.size() == 1)
{
resolved = filteredMembers.iterator().next();
}
else if (members.size() > 1)
{
throw new ConceptualException("Multiple members have the name '" + expr.getName() + "'", expr.getLexicalPhrase());
}
}
if (resolved != null)
{
if (resolved instanceof FieldReference)
{
FieldReference fieldReference = (FieldReference) resolved;
if (fieldReference.getReferencedMember().isStatic())
{
var = fieldReference.getReferencedMember().getGlobalVariable();
}
else
{
var = fieldReference.getReferencedMember().getMemberVariable();
}
expr.setResolvedVariable(var);
expr.setResolvedMemberReference(fieldReference);
return;
}
else if (resolved instanceof PropertyReference)
{
PropertyReference propertyReference = (PropertyReference) resolved;
Property property = propertyReference.getReferencedMember();
if (property == enclosingProperty)
{
if (property.isStatic())
{
var = property.getBackingGlobalVariable();
}
else
{
var = property.getBackingMemberVariable();
}
}
else
{
var = property.getPseudoVariable();
}
expr.setResolvedVariable(var);
expr.setResolvedMemberReference(propertyReference);
return;
}
else if (resolved instanceof MethodReference)
{
expr.setResolvedMemberReference(resolved);
return;
}
throw new IllegalStateException("Unknown member type: " + resolved);
}
}
throw new NameNotResolvedException("Unable to resolve \"" + (isSuperAccess ? "super." : "") + expr.getName() + "\"", expr.getLexicalPhrase());
}
else
{
throw new ConceptualException("Internal name resolution error: Unknown expression type", expression.getLexicalPhrase());
}
}
/**
* Applies the specified type hints to the given member set, and returns the resulting set. The original set is not modified.
* @param members - the set of members to filter
* @param typeHint - a hint about the type of the member, or null for no hint
* @param returnTypeHint - a hint about the return type of the member (which only applies if isFunctionHint == true), or null for no hint
* @param isFunctionHint - true to hint that the result should have a function type, false to not hint anything
* @param isAssignableHint - true to hint that the result should be an assignable member, false to not hint anything
* @return a set of only the Members which match the given hints
*/
private Set<MemberReference<?>> applyTypeHints(Set<MemberReference<?>> members, Type typeHint, Type returnTypeHint, boolean isFunctionHint, boolean isAssignableHint)
{
// TODO: allow members which only match the typeHints and returnTypeHints if the result is being casted (i.e. check canAssign() in reverse, but perform the same checks as the TypeChecker)
// (this works, since typeHints and returnTypeHints are only added by casting)
Set<MemberReference<?>> filtered = new HashSet<MemberReference<?>>(members);
Iterator<MemberReference<?>> it = filtered.iterator();
while (it.hasNext())
{
MemberReference<?> member = it.next();
if (isAssignableHint && member instanceof MethodReference)
{
it.remove();
continue;
}
if (isFunctionHint)
{
if (member instanceof FieldReference && !(((FieldReference) member).getType() instanceof FunctionType))
{
it.remove();
continue;
}
if (member instanceof PropertyReference && !(((PropertyReference) member).getType() instanceof FunctionType))
{
it.remove();
continue;
}
if (returnTypeHint != null && member instanceof MethodReference && !returnTypeHint.canAssign(((MethodReference) member).getReturnType()))
{
it.remove();
continue;
}
}
if (typeHint != null)
{
if (member instanceof FieldReference && !typeHint.canAssign(((FieldReference) member).getType()))
{
it.remove();
continue;
}
if (member instanceof PropertyReference && !typeHint.canAssign(((PropertyReference) member).getType()))
{
it.remove();
continue;
}
if (member instanceof MethodReference)
{
MethodReference methodReference = (MethodReference) member;
FunctionType functionType = new FunctionType(false, methodReference.getReferencedMember().isImmutable(), methodReference.getReturnType(), methodReference.getParameterTypes(), methodReference.getCheckedThrownTypes(), null);
if (!typeHint.canAssign(functionType))
{
it.remove();
continue;
}
}
}
}
return filtered;
}
/**
* Filters a set of parameter type lists based on which lists can be assigned from the specified arguments.
* If ensureEquivalent is true, then this method will also remove all parameter type lists which are not equivalent to the argument types.
* If allowNullable is true, then the equivalency check ignores the nullability of the parameter types.
* @param paramTypeLists - the set of parameter type lists to filter
* @param arguments - the arguments to filter the parameter type lists based on
* @param ensureEquivalent - true to filter out parameter type lists which do not have equivalent types to the arguments, false to just check whether they are assign-compatible
* @param allowNullable - true to ignore the nullability of the parameter types in the equivalence check, false to check for strict equivalence
* @param M - the Member type for the set of entries (this is never actually used)
*/
private <M extends MemberReference<?>> void filterParameterLists(Set<Entry<Type[], M>> paramTypeLists, Expression[] arguments, boolean ensureEquivalent, boolean allowNullable)
{
Iterator<Entry<Type[], M>> it = paramTypeLists.iterator();
while (it.hasNext())
{
Entry<Type[], M> entry = it.next();
Type[] parameterTypes = entry.getKey();
boolean typesMatch = parameterTypes.length == arguments.length;
if (typesMatch)
{
for (int i = 0; i < parameterTypes.length; i++)
{
Type parameterType = parameterTypes[i];
Type argumentType = arguments[i].getType();
if (!parameterType.canAssign(argumentType))
{
typesMatch = false;
break;
}
if (ensureEquivalent && !(parameterType.isEquivalent(argumentType) ||
(argumentType instanceof NullType && parameterType.isNullable()) ||
(allowNullable && parameterType.isEquivalent(Type.findTypeWithNullability(argumentType, true)))))
{
typesMatch = false;
break;
}
}
}
if (!typesMatch)
{
it.remove();
}
}
}
/**
* Resolves a constructor call from the specified target type and argument list.
* This method runs the type checker on each of the arguments in order to determine their types, so it needs to know the enclosing TypeDefinition and whether or not we are in a static context.
* @param creationType - the type which contains the constructor being called
* @param arguments - the arguments being passed to the constructor
* @param callerLexicalPhrase - the LexicalPhrase of the caller, to be used in any errors generated
* @param enclosingDefinition - the TypeDefinition which encloses the call to the constructor
* @param inStaticContext - true if the constructor call is in a static context, false otherwise
* @return the ConstructorReference resolved
* @throws ConceptualException - if there was a conceptual problem resolving the Constructor
*/
private ConstructorReference resolveConstructor(final NamedType creationType, Expression[] arguments, LexicalPhrase callerLexicalPhrase, TypeDefinition enclosingDefinition, boolean inStaticContext) throws ConceptualException
{
Type[] argumentTypes = new Type[arguments.length];
for (int i = 0; i < arguments.length; ++i)
{
argumentTypes[i] = TypeChecker.checkTypes(arguments[i], enclosingDefinition, inStaticContext);
}
GenericTypeSpecialiser genericTypeSpecialiser = new GenericTypeSpecialiser(creationType);
// resolve the constructor being called
TypeDefinition typeDefinition = creationType.getResolvedTypeDefinition();
Collection<Constructor> constructors = typeDefinition.getUniqueConstructors();
ConstructorReference[] constructorReferences = new ConstructorReference[constructors.size()];
Map<Type[], ConstructorReference> parameterTypeLists = new LinkedHashMap<Type[], ConstructorReference>();
int index = 0;
for (Constructor constructor : constructors)
{
constructorReferences[index] = new ConstructorReference(constructor, genericTypeSpecialiser);
parameterTypeLists.put(constructorReferences[index].getParameterTypes(), constructorReferences[index]);
index++;
}
filterParameterLists(parameterTypeLists.entrySet(), arguments, false, false);
// if there are multiple parameter lists, try to narrow it down to one that is equivalent to the argument list
if (parameterTypeLists.size() > 1)
{
// first, try filtering for argument type equivalence, but ignoring nullability
Map<Type[], ConstructorReference> equivalenceFiltered = new LinkedHashMap<Type[], ConstructorReference>(parameterTypeLists);
filterParameterLists(equivalenceFiltered.entrySet(), arguments, true, true);
if (!equivalenceFiltered.isEmpty())
{
parameterTypeLists = equivalenceFiltered;
if (parameterTypeLists.size() > 1)
{
// the equivalence filter was not enough, so try a nullability filter as well
Map<Type[], ConstructorReference> nullabilityEquivalenceFiltered = new LinkedHashMap<Type[], ConstructorReference>(parameterTypeLists);
filterParameterLists(nullabilityEquivalenceFiltered.entrySet(), arguments, true, false);
if (!nullabilityEquivalenceFiltered.isEmpty())
{
parameterTypeLists = nullabilityEquivalenceFiltered;
}
}
}
}
if (parameterTypeLists.size() > 1)
{
throw new ConceptualException("Ambiguous constructor call, there are at least two applicable constructors which take these arguments", callerLexicalPhrase);
}
if (!parameterTypeLists.isEmpty())
{
return parameterTypeLists.entrySet().iterator().next().getValue();
}
// since we failed to resolve the constructor, pick the most relevant one so that the type checker can point out exactly why it failed to match
ConstructorReference mostRelevantConstructorReference = null;
int mostRelevantArgCount = -1;
for (ConstructorReference constructorReference : constructorReferences)
{
// try to maximise the index of the first parameter that doesn't match
Type[] parameterTypes = constructorReference.getParameterTypes();
if (parameterTypes.length == arguments.length)
{
for (int i = 0; i < parameterTypes.length; ++i)
{
if (!parameterTypes[i].canAssign(argumentTypes[i]))
{
if (i + 1 > mostRelevantArgCount)
{
mostRelevantConstructorReference = constructorReference;
mostRelevantArgCount = i + 1;
}
break;
}
}
}
}
if (mostRelevantConstructorReference != null)
{
return mostRelevantConstructorReference;
}
if (constructorReferences.length >= 1)
{
return constructorReferences[0];
}
throw new ConceptualException("Cannot create '" + typeDefinition.getQualifiedName() + "' - it has no constructors", callerLexicalPhrase);
}
/**
* Finds all of the nested variables of a block.
* Before calling this, resolve() must have been called on the compilation unit containing the block.
* @param block - the block to get all the nested variables of
* @return a set containing all of the variables defined in this block, including in nested blocks
*/
public static Set<Variable> getAllNestedVariables(Block block)
{
Set<Variable> result = new HashSet<Variable>();
Deque<Statement> stack = new LinkedList<Statement>();
stack.push(block);
while (!stack.isEmpty())
{
Statement statement = stack.pop();
if (statement instanceof Block)
{
// add all variables from this block to the result set
result.addAll(((Block) statement).getVariables());
for (Statement s : ((Block) statement).getStatements())
{
stack.push(s);
}
}
else if (statement instanceof ForStatement)
{
ForStatement forStatement = (ForStatement) statement;
if (forStatement.getInitStatement() != null)
{
stack.push(forStatement.getInitStatement());
}
if (forStatement.getUpdateStatement() != null)
{
stack.push(forStatement.getUpdateStatement());
}
stack.push(forStatement.getBlock());
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
stack.push(ifStatement.getThenClause());
if (ifStatement.getElseClause() != null)
{
stack.push(ifStatement.getElseClause());
}
}
else if (statement instanceof TryStatement)
{
TryStatement tryStatement = (TryStatement) statement;
stack.push(tryStatement.getTryBlock());
for (CatchClause catchClause : tryStatement.getCatchClauses())
{
stack.push(catchClause.getBlock());
}
if (tryStatement.getFinallyBlock() != null)
{
stack.push(tryStatement.getFinallyBlock());
}
}
else if (statement instanceof WhileStatement)
{
stack.push(((WhileStatement) statement).getStatement());
}
}
return result;
}
}
| false | true | private void resolve(Expression expression, Block block, TypeDefinition enclosingDefinition, CompilationUnit compilationUnit, boolean inStaticContext, boolean inImmutableContext, Property enclosingProperty) throws ConceptualException
{
if (expression instanceof ArithmeticExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((ArithmeticExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((ArithmeticExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(arrayAccessExpression.getArrayExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(arrayAccessExpression.getDimensionExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression creationExpression = (ArrayCreationExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(creationExpression.getDeclaredType(), enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (creationExpression.getDimensionExpressions() != null)
{
for (Expression expr : creationExpression.getDimensionExpressions())
{
try
{
resolve(expr, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (creationExpression.getValueExpressions() != null)
{
for (Expression expr : creationExpression.getValueExpressions())
{
try
{
resolve(expr, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof BitwiseNotExpression)
{
resolve(((BitwiseNotExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof BooleanLiteralExpression)
{
// do nothing
}
else if (expression instanceof BooleanNotExpression)
{
resolve(((BooleanNotExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof BracketedExpression)
{
resolve(((BracketedExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof CastExpression)
{
CastExpression castExpression = (CastExpression) expression;
Type castType = expression.getType();
CoalescedConceptualException coalescedException = null;
try
{
resolve(castType, enclosingDefinition, compilationUnit);
// before resolving the casted expression, add hints for any FieldAccessExpressions or VariableExpressions that are directly inside it
Expression subExpression = castExpression.getExpression();
while (subExpression instanceof BracketedExpression)
{
subExpression = ((BracketedExpression) subExpression).getExpression();
}
if (subExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) subExpression).setTypeHint(castType);
}
if (subExpression instanceof VariableExpression)
{
((VariableExpression) subExpression).setTypeHint(castType);
}
if (subExpression instanceof FunctionCallExpression)
{
Expression baseExpression = ((FunctionCallExpression) subExpression).getFunctionExpression();
while (baseExpression instanceof BracketedExpression)
{
baseExpression = ((BracketedExpression) baseExpression).getExpression();
}
if (baseExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) baseExpression).setReturnTypeHint(castType);
}
if (baseExpression instanceof VariableExpression)
{
((VariableExpression) baseExpression).setReturnTypeHint(castType);
}
}
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(castExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof CreationExpression)
{
CreationExpression creationExpression = (CreationExpression) expression;
CoalescedConceptualException coalescedException = null;
NamedType type = creationExpression.getCreatedType();
try
{
resolve(type, enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (type.getResolvedTypeDefinition() == null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Cannot create an instance of a type parameter", type.getLexicalPhrase()));
}
Expression[] arguments = creationExpression.getArguments();
for (Expression argument : arguments)
{
try
{
resolve(argument, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
ConstructorReference resolvedConstructor = resolveConstructor(type, arguments, creationExpression.getLexicalPhrase(), enclosingDefinition, inStaticContext);
creationExpression.setResolvedConstructorReference(resolvedConstructor);
}
else if (expression instanceof EqualityExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((EqualityExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((EqualityExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
fieldAccessExpression.setResolvedContextImmutability(inImmutableContext);
String fieldName = fieldAccessExpression.getFieldName();
Type baseType;
boolean baseIsStatic;
if (fieldAccessExpression.getBaseExpression() != null)
{
resolve(fieldAccessExpression.getBaseExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
// find the type of the sub-expression, by calling the type checker
// this is fine as long as we resolve all of the sub-expression first
baseType = TypeChecker.checkTypes(fieldAccessExpression.getBaseExpression(), enclosingDefinition, inStaticContext);
baseIsStatic = false;
}
else if (fieldAccessExpression.getBaseType() != null)
{
baseType = fieldAccessExpression.getBaseType();
resolve(baseType, enclosingDefinition, compilationUnit);
TypeChecker.checkType(baseType, true, enclosingDefinition, inStaticContext);
baseIsStatic = true;
}
else
{
throw new IllegalStateException("Unknown base type for a field access: " + fieldAccessExpression);
}
Set<MemberReference<?>> memberSet = baseType.getMembers(fieldName);
Set<MemberReference<?>> staticFiltered = new HashSet<MemberReference<?>>();
for (MemberReference<?> member : memberSet)
{
if (member instanceof ArrayLengthMemberReference)
{
if (baseIsStatic)
{
throw new ConceptualException("Cannot access the array length member statically", fieldAccessExpression.getLexicalPhrase());
}
staticFiltered.add(member);
}
else if (member instanceof FieldReference)
{
if (((FieldReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else if (member instanceof PropertyReference)
{
if (((PropertyReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else if (member instanceof MethodReference)
{
if (((MethodReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else
{
throw new IllegalStateException("Unknown member type: " + member);
}
}
if (staticFiltered.isEmpty())
{
throw new NameNotResolvedException("No such " + (baseIsStatic ? "static" : "non-static") + " member \"" + fieldName + "\" for type " + baseType, fieldAccessExpression.getLexicalPhrase());
}
MemberReference<?> resolved = null;
if (staticFiltered.size() == 1)
{
resolved = staticFiltered.iterator().next();
}
else
{
Set<MemberReference<?>> hintFiltered = applyTypeHints(staticFiltered, fieldAccessExpression.getTypeHint(), fieldAccessExpression.getReturnTypeHint(), fieldAccessExpression.getIsFunctionHint(), fieldAccessExpression.getIsAssignableHint());
if (hintFiltered.size() == 1)
{
resolved = hintFiltered.iterator().next();
}
}
if (resolved == null)
{
throw new ConceptualException("Multiple " + (baseIsStatic ? "static" : "non-static") + " members have the name '" + fieldName + "'", fieldAccessExpression.getLexicalPhrase());
}
fieldAccessExpression.setResolvedMemberReference(resolved);
}
else if (expression instanceof FloatingLiteralExpression)
{
// do nothing
}
else if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression expr = (FunctionCallExpression) expression;
// resolve all of the sub-expressions
CoalescedConceptualException coalescedException = null;
for (Expression e : expr.getArguments())
{
try
{
resolve(e, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
TypeChecker.checkTypes(e, enclosingDefinition, inStaticContext);
}
catch (ConceptualException exception)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, exception);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
Expression functionExpression = expr.getFunctionExpression();
// before resolving the functionExpression, add hints for any FieldAccessExpressions or VariableExpressions that are directly inside it
Expression subExpression = functionExpression;
while (subExpression instanceof BracketedExpression)
{
subExpression = ((BracketedExpression) subExpression).getExpression();
}
if (subExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) subExpression).setIsFunctionHint(true);
}
if (subExpression instanceof VariableExpression)
{
((VariableExpression) subExpression).setIsFunctionHint(true);
}
Type expressionType = null;
Exception cachedException = null;
// first, try to resolve the function call as a normal expression
// this MUST be done first, so that local variables with function types are considered before outside methods
try
{
resolve(functionExpression, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
expressionType = TypeChecker.checkTypes(functionExpression, enclosingDefinition, inStaticContext);
}
catch (NameNotResolvedException e)
{
cachedException = e;
}
catch (ConceptualException e)
{
cachedException = e;
}
if (cachedException == null)
{
if (expressionType instanceof FunctionType)
{
// the sub-expressions all resolved properly, so we could just return here
// however, if this is just a normal method call, we can pull the resolved method into
// this FunctionCallExpression, so that we don't have to convert through FunctionType
Expression testExpression = functionExpression;
while (testExpression instanceof BracketedExpression)
{
testExpression = ((BracketedExpression) testExpression).getExpression();
}
if (testExpression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) testExpression;
if (variableExpression.getResolvedMemberReference() instanceof MethodReference) // "null instanceof Something" is always false
{
// the base resolved to a Method, so just resolve this FunctionCallExpression to the same Method
expr.setResolvedMethodReference((MethodReference) variableExpression.getResolvedMemberReference());
if (variableExpression instanceof SuperVariableExpression)
{
// this function call is of the form 'super.method()', so make it non-virtual
expr.setResolvedIsVirtual(false);
}
return;
}
}
else if (testExpression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) testExpression;
MemberReference<?> resolvedMemberReference = fieldAccessExpression.getResolvedMemberReference();
if (resolvedMemberReference instanceof MethodReference)
{
// the base resolved to a Method, so just resolve this FunctionCallExpression to the same Method
expr.setResolvedMethodReference((MethodReference) resolvedMemberReference);
expr.setResolvedBaseExpression(fieldAccessExpression.getBaseExpression()); // this will be null for static field accesses
expr.setResolvedNullTraversal(fieldAccessExpression.isNullTraversing());
return;
}
}
expr.setResolvedBaseExpression(functionExpression);
return;
}
throw new ConceptualException("Cannot call a function on a non-function type", functionExpression.getLexicalPhrase());
}
// we failed to resolve the sub-expression into something with a function type
// but the recursive resolver doesn't know which parameter types we're looking for here, so we may be able to consider some different options
// we can do this by checking if the function expression is actually a variable access or a field access expression, and checking them for other sources of method calls,
// such as constructor calls and method calls, each of which can be narrowed down by their parameter types
// first, go through any bracketed expressions, as we can ignore them
while (functionExpression instanceof BracketedExpression)
{
functionExpression = ((BracketedExpression) functionExpression).getExpression();
}
Map<Type[], MethodReference> paramTypeLists = new LinkedHashMap<Type[], MethodReference>();
Map<Type[], MethodReference> hintedParamLists = new LinkedHashMap<Type[], MethodReference>();
Map<MethodReference, Expression> methodBaseExpressions = new HashMap<MethodReference, Expression>();
boolean isSuperAccess = false;
if (functionExpression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) functionExpression;
isSuperAccess = variableExpression instanceof SuperVariableExpression;
String name = variableExpression.getName();
// the sub-expression didn't resolve to a variable or a field, or we would have got a valid type back in expressionType
if (enclosingDefinition != null)
{
Set<MemberReference<?>> memberSet = new NamedType(false, false, false, enclosingDefinition).getMembers(name, !isSuperAccess, isSuperAccess);
memberSet = memberSet != null ? memberSet : new HashSet<MemberReference<?>>();
Set<MemberReference<?>> hintedMemberSet = applyTypeHints(memberSet, variableExpression.getTypeHint(), variableExpression.getReturnTypeHint(), variableExpression.getIsFunctionHint(), variableExpression.getIsAssignableHint());
for (MemberReference<?> m : memberSet)
{
if (m instanceof MethodReference)
{
MethodReference methodReference = (MethodReference) m;
Type[] parameterTypes = methodReference.getParameterTypes();
paramTypeLists.put(parameterTypes, methodReference);
if (hintedMemberSet.contains(methodReference))
{
hintedParamLists.put(parameterTypes, methodReference);
}
// leave methodBaseExpressions with a null value for this method, as we have no base expression
}
}
}
}
else if (functionExpression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) functionExpression;
expr.setResolvedNullTraversal(fieldAccessExpression.isNullTraversing());
try
{
String name = fieldAccessExpression.getFieldName();
Expression baseExpression = fieldAccessExpression.getBaseExpression();
Type baseType;
boolean baseIsStatic;
if (baseExpression != null)
{
resolve(baseExpression, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
// find the type of the sub-expression, by calling the type checker
// this is fine as long as we resolve all of the sub-expression first
baseType = TypeChecker.checkTypes(baseExpression, enclosingDefinition, inStaticContext);
baseIsStatic = false;
}
else if (fieldAccessExpression.getBaseType() != null)
{
baseType = fieldAccessExpression.getBaseType();
resolve(baseType, enclosingDefinition, compilationUnit);
TypeChecker.checkType(baseType, true, enclosingDefinition, inStaticContext);
baseIsStatic = true;
}
else
{
throw new IllegalStateException("Unknown base type for a field access: " + fieldAccessExpression);
}
Set<MemberReference<?>> memberSet = baseType.getMembers(name);
memberSet = memberSet != null ? memberSet : new HashSet<MemberReference<?>>();
Set<MemberReference<?>> hintedMemberSet = applyTypeHints(memberSet, fieldAccessExpression.getTypeHint(), fieldAccessExpression.getReturnTypeHint(), fieldAccessExpression.getIsFunctionHint(), fieldAccessExpression.getIsAssignableHint());
for (MemberReference<?> member : memberSet)
{
// only allow access to this method if it is called in the right way, depending on whether or not it is static
if (member instanceof MethodReference && ((MethodReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
MethodReference methodReference = (MethodReference) member;
paramTypeLists.put(methodReference.getParameterTypes(), methodReference);
if (hintedMemberSet.contains(methodReference))
{
hintedParamLists.put(methodReference.getParameterTypes(), methodReference);
}
methodBaseExpressions.put(methodReference, baseExpression);
}
}
}
catch (NameNotResolvedException e)
{
// ignore this error, just assume it wasn't meant to resolve to a method call
}
catch (ConceptualException e)
{
// ignore this error, just assume it wasn't meant to resolve to a method call
}
}
// filter out parameter lists which are not assign-compatible with the arguments
filterParameterLists(hintedParamLists.entrySet(), expr.getArguments(), false, false);
// if there are multiple parameter lists, try to narrow it down to one that is equivalent to the argument list
if (hintedParamLists.size() > 1)
{
// first, try filtering for argument type equivalence, but ignoring nullability
Map<Type[], MethodReference> equivalenceFilteredHintedParamLists = new LinkedHashMap<Type[], MethodReference>(hintedParamLists);
filterParameterLists(equivalenceFilteredHintedParamLists.entrySet(), expr.getArguments(), true, true);
if (!equivalenceFilteredHintedParamLists.isEmpty())
{
hintedParamLists = equivalenceFilteredHintedParamLists;
if (hintedParamLists.size() > 1)
{
// the equivalence filter was not enough, so try a nullability filter as well
Map<Type[], MethodReference> nullabilityFilteredHintedParamLists = new LinkedHashMap<Type[], MethodReference>(hintedParamLists);
filterParameterLists(nullabilityFilteredHintedParamLists.entrySet(), expr.getArguments(), true, false);
if (!nullabilityFilteredHintedParamLists.isEmpty())
{
hintedParamLists = nullabilityFilteredHintedParamLists;
}
}
}
}
if (hintedParamLists.size() == 1)
{
paramTypeLists = hintedParamLists;
}
else
{
// try the same thing without using hintedParamLists
filterParameterLists(paramTypeLists.entrySet(), expr.getArguments(), false, false);
if (paramTypeLists.size() > 1)
{
Map<Type[], MethodReference> equivalenceFilteredParamTypeLists = new LinkedHashMap<Type[], MethodReference>(paramTypeLists);
filterParameterLists(equivalenceFilteredParamTypeLists.entrySet(), expr.getArguments(), true, true);
if (!equivalenceFilteredParamTypeLists.isEmpty())
{
paramTypeLists = equivalenceFilteredParamTypeLists;
if (paramTypeLists.size() > 1)
{
Map<Type[], MethodReference> nullabilityFilteredParamTypeLists = new LinkedHashMap<Type[], MethodReference>(paramTypeLists);
filterParameterLists(nullabilityFilteredParamTypeLists.entrySet(), expr.getArguments(), true, false);
if (!nullabilityFilteredParamTypeLists.isEmpty())
{
paramTypeLists = nullabilityFilteredParamTypeLists;
}
}
}
}
}
if (paramTypeLists.size() > 1)
{
throw new ConceptualException("Ambiguous method call, there are at least two applicable methods which take these arguments", expr.getLexicalPhrase());
}
if (paramTypeLists.isEmpty())
{
// we didn't find anything, so rethrow the exception from earlier
if (cachedException instanceof NameNotResolvedException)
{
throw (NameNotResolvedException) cachedException;
}
throw (ConceptualException) cachedException;
}
Entry<Type[], MethodReference> entry = paramTypeLists.entrySet().iterator().next();
expr.setResolvedMethodReference(entry.getValue());
// if the method call had no base expression, e.g. it was a VariableExpression being called, this will just set it to null
expr.setResolvedBaseExpression(methodBaseExpressions.get(entry.getValue()));
if (isSuperAccess)
{
// this function call is of the form 'super.method()', so make it non-virtual
expr.setResolvedIsVirtual(false);
}
}
else if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIfExpression = (InlineIfExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(inlineIfExpression.getCondition(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(inlineIfExpression.getThenExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(inlineIfExpression.getElseExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof InstanceOfExpression)
{
InstanceOfExpression instanceOfExpression = (InstanceOfExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(instanceOfExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(instanceOfExpression.getInstanceOfType(), enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof IntegerLiteralExpression)
{
// do nothing
}
else if (expression instanceof LogicalExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((LogicalExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((LogicalExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof MinusExpression)
{
resolve(((MinusExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof NullCoalescingExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((NullCoalescingExpression) expression).getNullableExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((NullCoalescingExpression) expression).getAlternativeExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof NullLiteralExpression)
{
// do nothing
}
else if (expression instanceof ObjectCreationExpression)
{
// do nothing
}
else if (expression instanceof RelationalExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((RelationalExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((RelationalExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ShiftExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((ShiftExpression) expression).getLeftExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((ShiftExpression) expression).getRightExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof StringLiteralExpression)
{
// resolve the type of the string literal here, so that we have access to it in the type checker
expression.setType(SpecialTypeHandler.STRING_TYPE);
}
else if (expression instanceof ThisExpression)
{
ThisExpression thisExpression = (ThisExpression) expression;
if (enclosingDefinition == null)
{
throw new ConceptualException("'this' does not refer to anything in this context", thisExpression.getLexicalPhrase());
}
thisExpression.setType(new NamedType(false, false, inImmutableContext, enclosingDefinition));
}
else if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
CoalescedConceptualException coalescedException = null;
Expression[] subExpressions = tupleExpression.getSubExpressions();
for (int i = 0; i < subExpressions.length; i++)
{
try
{
resolve(subExpressions[i], block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression indexExpression = (TupleIndexExpression) expression;
resolve(indexExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof VariableExpression)
{
VariableExpression expr = (VariableExpression) expression;
boolean isSuperAccess = expr instanceof SuperVariableExpression;
expr.setResolvedContextImmutability(inImmutableContext);
Variable var = block.getVariable(expr.getName());
if (var != null & !isSuperAccess)
{
expr.setResolvedVariable(var);
return;
}
if (enclosingDefinition != null)
{
Set<MemberReference<?>> members = new NamedType(false, false, enclosingDefinition, null).getMembers(expr.getName(), !isSuperAccess, isSuperAccess);
members = members != null ? members : new HashSet<MemberReference<?>>();
MemberReference<?> resolved = null;
if (members.size() == 1)
{
resolved = members.iterator().next();
}
else
{
Set<MemberReference<?>> filteredMembers = applyTypeHints(members, expr.getTypeHint(), expr.getReturnTypeHint(), expr.getIsFunctionHint(), expr.getIsAssignableHint());
if (filteredMembers.size() == 1)
{
resolved = filteredMembers.iterator().next();
}
else if (members.size() > 1)
{
throw new ConceptualException("Multiple members have the name '" + expr.getName() + "'", expr.getLexicalPhrase());
}
}
if (resolved != null)
{
if (resolved instanceof FieldReference)
{
FieldReference fieldReference = (FieldReference) resolved;
if (fieldReference.getReferencedMember().isStatic())
{
var = fieldReference.getReferencedMember().getGlobalVariable();
}
else
{
var = fieldReference.getReferencedMember().getMemberVariable();
}
expr.setResolvedVariable(var);
expr.setResolvedMemberReference(fieldReference);
return;
}
else if (resolved instanceof PropertyReference)
{
PropertyReference propertyReference = (PropertyReference) resolved;
Property property = propertyReference.getReferencedMember();
if (property == enclosingProperty)
{
if (property.isStatic())
{
var = property.getBackingGlobalVariable();
}
else
{
var = property.getBackingMemberVariable();
}
}
else
{
var = property.getPseudoVariable();
}
expr.setResolvedVariable(var);
expr.setResolvedMemberReference(propertyReference);
return;
}
else if (resolved instanceof MethodReference)
{
expr.setResolvedMemberReference(resolved);
return;
}
throw new IllegalStateException("Unknown member type: " + resolved);
}
}
throw new NameNotResolvedException("Unable to resolve \"" + (isSuperAccess ? "super." : "") + expr.getName() + "\"", expr.getLexicalPhrase());
}
else
{
throw new ConceptualException("Internal name resolution error: Unknown expression type", expression.getLexicalPhrase());
}
}
| private void resolve(Expression expression, Block block, TypeDefinition enclosingDefinition, CompilationUnit compilationUnit, boolean inStaticContext, boolean inImmutableContext, Property enclosingProperty) throws ConceptualException
{
if (expression instanceof ArithmeticExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((ArithmeticExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((ArithmeticExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(arrayAccessExpression.getArrayExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(arrayAccessExpression.getDimensionExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression creationExpression = (ArrayCreationExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(creationExpression.getDeclaredType(), enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (creationExpression.getDimensionExpressions() != null)
{
for (Expression expr : creationExpression.getDimensionExpressions())
{
try
{
resolve(expr, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (creationExpression.getValueExpressions() != null)
{
for (Expression expr : creationExpression.getValueExpressions())
{
try
{
resolve(expr, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof BitwiseNotExpression)
{
resolve(((BitwiseNotExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof BooleanLiteralExpression)
{
// do nothing
}
else if (expression instanceof BooleanNotExpression)
{
resolve(((BooleanNotExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof BracketedExpression)
{
resolve(((BracketedExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof CastExpression)
{
CastExpression castExpression = (CastExpression) expression;
Type castType = expression.getType();
CoalescedConceptualException coalescedException = null;
try
{
resolve(castType, enclosingDefinition, compilationUnit);
// before resolving the casted expression, add hints for any FieldAccessExpressions or VariableExpressions that are directly inside it
Expression subExpression = castExpression.getExpression();
while (subExpression instanceof BracketedExpression)
{
subExpression = ((BracketedExpression) subExpression).getExpression();
}
if (subExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) subExpression).setTypeHint(castType);
}
if (subExpression instanceof VariableExpression)
{
((VariableExpression) subExpression).setTypeHint(castType);
}
if (subExpression instanceof FunctionCallExpression)
{
Expression baseExpression = ((FunctionCallExpression) subExpression).getFunctionExpression();
while (baseExpression instanceof BracketedExpression)
{
baseExpression = ((BracketedExpression) baseExpression).getExpression();
}
if (baseExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) baseExpression).setReturnTypeHint(castType);
}
if (baseExpression instanceof VariableExpression)
{
((VariableExpression) baseExpression).setReturnTypeHint(castType);
}
}
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(castExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof CreationExpression)
{
CreationExpression creationExpression = (CreationExpression) expression;
CoalescedConceptualException coalescedException = null;
NamedType type = creationExpression.getCreatedType();
try
{
resolve(type, enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (type.getResolvedTypeParameter() != null)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, new ConceptualException("Cannot create an instance of a type parameter", type.getLexicalPhrase()));
}
Expression[] arguments = creationExpression.getArguments();
for (Expression argument : arguments)
{
try
{
resolve(argument, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
ConstructorReference resolvedConstructor = resolveConstructor(type, arguments, creationExpression.getLexicalPhrase(), enclosingDefinition, inStaticContext);
creationExpression.setResolvedConstructorReference(resolvedConstructor);
}
else if (expression instanceof EqualityExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((EqualityExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((EqualityExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
fieldAccessExpression.setResolvedContextImmutability(inImmutableContext);
String fieldName = fieldAccessExpression.getFieldName();
Type baseType;
boolean baseIsStatic;
if (fieldAccessExpression.getBaseExpression() != null)
{
resolve(fieldAccessExpression.getBaseExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
// find the type of the sub-expression, by calling the type checker
// this is fine as long as we resolve all of the sub-expression first
baseType = TypeChecker.checkTypes(fieldAccessExpression.getBaseExpression(), enclosingDefinition, inStaticContext);
baseIsStatic = false;
}
else if (fieldAccessExpression.getBaseType() != null)
{
baseType = fieldAccessExpression.getBaseType();
resolve(baseType, enclosingDefinition, compilationUnit);
TypeChecker.checkType(baseType, true, enclosingDefinition, inStaticContext);
baseIsStatic = true;
}
else
{
throw new IllegalStateException("Unknown base type for a field access: " + fieldAccessExpression);
}
Set<MemberReference<?>> memberSet = baseType.getMembers(fieldName);
Set<MemberReference<?>> staticFiltered = new HashSet<MemberReference<?>>();
for (MemberReference<?> member : memberSet)
{
if (member instanceof ArrayLengthMemberReference)
{
if (baseIsStatic)
{
throw new ConceptualException("Cannot access the array length member statically", fieldAccessExpression.getLexicalPhrase());
}
staticFiltered.add(member);
}
else if (member instanceof FieldReference)
{
if (((FieldReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else if (member instanceof PropertyReference)
{
if (((PropertyReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else if (member instanceof MethodReference)
{
if (((MethodReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
staticFiltered.add(member);
}
}
else
{
throw new IllegalStateException("Unknown member type: " + member);
}
}
if (staticFiltered.isEmpty())
{
throw new NameNotResolvedException("No such " + (baseIsStatic ? "static" : "non-static") + " member \"" + fieldName + "\" for type " + baseType, fieldAccessExpression.getLexicalPhrase());
}
MemberReference<?> resolved = null;
if (staticFiltered.size() == 1)
{
resolved = staticFiltered.iterator().next();
}
else
{
Set<MemberReference<?>> hintFiltered = applyTypeHints(staticFiltered, fieldAccessExpression.getTypeHint(), fieldAccessExpression.getReturnTypeHint(), fieldAccessExpression.getIsFunctionHint(), fieldAccessExpression.getIsAssignableHint());
if (hintFiltered.size() == 1)
{
resolved = hintFiltered.iterator().next();
}
}
if (resolved == null)
{
throw new ConceptualException("Multiple " + (baseIsStatic ? "static" : "non-static") + " members have the name '" + fieldName + "'", fieldAccessExpression.getLexicalPhrase());
}
fieldAccessExpression.setResolvedMemberReference(resolved);
}
else if (expression instanceof FloatingLiteralExpression)
{
// do nothing
}
else if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression expr = (FunctionCallExpression) expression;
// resolve all of the sub-expressions
CoalescedConceptualException coalescedException = null;
for (Expression e : expr.getArguments())
{
try
{
resolve(e, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
TypeChecker.checkTypes(e, enclosingDefinition, inStaticContext);
}
catch (ConceptualException exception)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, exception);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
Expression functionExpression = expr.getFunctionExpression();
// before resolving the functionExpression, add hints for any FieldAccessExpressions or VariableExpressions that are directly inside it
Expression subExpression = functionExpression;
while (subExpression instanceof BracketedExpression)
{
subExpression = ((BracketedExpression) subExpression).getExpression();
}
if (subExpression instanceof FieldAccessExpression)
{
((FieldAccessExpression) subExpression).setIsFunctionHint(true);
}
if (subExpression instanceof VariableExpression)
{
((VariableExpression) subExpression).setIsFunctionHint(true);
}
Type expressionType = null;
Exception cachedException = null;
// first, try to resolve the function call as a normal expression
// this MUST be done first, so that local variables with function types are considered before outside methods
try
{
resolve(functionExpression, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
expressionType = TypeChecker.checkTypes(functionExpression, enclosingDefinition, inStaticContext);
}
catch (NameNotResolvedException e)
{
cachedException = e;
}
catch (ConceptualException e)
{
cachedException = e;
}
if (cachedException == null)
{
if (expressionType instanceof FunctionType)
{
// the sub-expressions all resolved properly, so we could just return here
// however, if this is just a normal method call, we can pull the resolved method into
// this FunctionCallExpression, so that we don't have to convert through FunctionType
Expression testExpression = functionExpression;
while (testExpression instanceof BracketedExpression)
{
testExpression = ((BracketedExpression) testExpression).getExpression();
}
if (testExpression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) testExpression;
if (variableExpression.getResolvedMemberReference() instanceof MethodReference) // "null instanceof Something" is always false
{
// the base resolved to a Method, so just resolve this FunctionCallExpression to the same Method
expr.setResolvedMethodReference((MethodReference) variableExpression.getResolvedMemberReference());
if (variableExpression instanceof SuperVariableExpression)
{
// this function call is of the form 'super.method()', so make it non-virtual
expr.setResolvedIsVirtual(false);
}
return;
}
}
else if (testExpression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) testExpression;
MemberReference<?> resolvedMemberReference = fieldAccessExpression.getResolvedMemberReference();
if (resolvedMemberReference instanceof MethodReference)
{
// the base resolved to a Method, so just resolve this FunctionCallExpression to the same Method
expr.setResolvedMethodReference((MethodReference) resolvedMemberReference);
expr.setResolvedBaseExpression(fieldAccessExpression.getBaseExpression()); // this will be null for static field accesses
expr.setResolvedNullTraversal(fieldAccessExpression.isNullTraversing());
return;
}
}
expr.setResolvedBaseExpression(functionExpression);
return;
}
throw new ConceptualException("Cannot call a non-function-typed value", functionExpression.getLexicalPhrase());
}
// we failed to resolve the sub-expression into something with a function type
// but the recursive resolver doesn't know which parameter types we're looking for here, so we may be able to consider some different options
// we can do this by checking if the function expression is actually a variable access or a field access expression, and checking them for other sources of method calls,
// such as constructor calls and method calls, each of which can be narrowed down by their parameter types
// first, go through any bracketed expressions, as we can ignore them
while (functionExpression instanceof BracketedExpression)
{
functionExpression = ((BracketedExpression) functionExpression).getExpression();
}
Map<Type[], MethodReference> paramTypeLists = new LinkedHashMap<Type[], MethodReference>();
Map<Type[], MethodReference> hintedParamLists = new LinkedHashMap<Type[], MethodReference>();
Map<MethodReference, Expression> methodBaseExpressions = new HashMap<MethodReference, Expression>();
boolean isSuperAccess = false;
if (functionExpression instanceof VariableExpression)
{
VariableExpression variableExpression = (VariableExpression) functionExpression;
isSuperAccess = variableExpression instanceof SuperVariableExpression;
String name = variableExpression.getName();
// the sub-expression didn't resolve to a variable or a field, or we would have got a valid type back in expressionType
if (enclosingDefinition != null)
{
Set<MemberReference<?>> memberSet = new NamedType(false, false, false, enclosingDefinition).getMembers(name, !isSuperAccess, isSuperAccess);
memberSet = memberSet != null ? memberSet : new HashSet<MemberReference<?>>();
Set<MemberReference<?>> hintedMemberSet = applyTypeHints(memberSet, variableExpression.getTypeHint(), variableExpression.getReturnTypeHint(), variableExpression.getIsFunctionHint(), variableExpression.getIsAssignableHint());
for (MemberReference<?> m : memberSet)
{
if (m instanceof MethodReference)
{
MethodReference methodReference = (MethodReference) m;
Type[] parameterTypes = methodReference.getParameterTypes();
paramTypeLists.put(parameterTypes, methodReference);
if (hintedMemberSet.contains(methodReference))
{
hintedParamLists.put(parameterTypes, methodReference);
}
// leave methodBaseExpressions with a null value for this method, as we have no base expression
}
}
}
}
else if (functionExpression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) functionExpression;
expr.setResolvedNullTraversal(fieldAccessExpression.isNullTraversing());
try
{
String name = fieldAccessExpression.getFieldName();
Expression baseExpression = fieldAccessExpression.getBaseExpression();
Type baseType;
boolean baseIsStatic;
if (baseExpression != null)
{
resolve(baseExpression, block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
// find the type of the sub-expression, by calling the type checker
// this is fine as long as we resolve all of the sub-expression first
baseType = TypeChecker.checkTypes(baseExpression, enclosingDefinition, inStaticContext);
baseIsStatic = false;
}
else if (fieldAccessExpression.getBaseType() != null)
{
baseType = fieldAccessExpression.getBaseType();
resolve(baseType, enclosingDefinition, compilationUnit);
TypeChecker.checkType(baseType, true, enclosingDefinition, inStaticContext);
baseIsStatic = true;
}
else
{
throw new IllegalStateException("Unknown base type for a field access: " + fieldAccessExpression);
}
Set<MemberReference<?>> memberSet = baseType.getMembers(name);
memberSet = memberSet != null ? memberSet : new HashSet<MemberReference<?>>();
Set<MemberReference<?>> hintedMemberSet = applyTypeHints(memberSet, fieldAccessExpression.getTypeHint(), fieldAccessExpression.getReturnTypeHint(), fieldAccessExpression.getIsFunctionHint(), fieldAccessExpression.getIsAssignableHint());
for (MemberReference<?> member : memberSet)
{
// only allow access to this method if it is called in the right way, depending on whether or not it is static
if (member instanceof MethodReference && ((MethodReference) member).getReferencedMember().isStatic() == baseIsStatic)
{
MethodReference methodReference = (MethodReference) member;
paramTypeLists.put(methodReference.getParameterTypes(), methodReference);
if (hintedMemberSet.contains(methodReference))
{
hintedParamLists.put(methodReference.getParameterTypes(), methodReference);
}
methodBaseExpressions.put(methodReference, baseExpression);
}
}
}
catch (NameNotResolvedException e)
{
// ignore this error, just assume it wasn't meant to resolve to a method call
}
catch (ConceptualException e)
{
// ignore this error, just assume it wasn't meant to resolve to a method call
}
}
// filter out parameter lists which are not assign-compatible with the arguments
filterParameterLists(hintedParamLists.entrySet(), expr.getArguments(), false, false);
// if there are multiple parameter lists, try to narrow it down to one that is equivalent to the argument list
if (hintedParamLists.size() > 1)
{
// first, try filtering for argument type equivalence, but ignoring nullability
Map<Type[], MethodReference> equivalenceFilteredHintedParamLists = new LinkedHashMap<Type[], MethodReference>(hintedParamLists);
filterParameterLists(equivalenceFilteredHintedParamLists.entrySet(), expr.getArguments(), true, true);
if (!equivalenceFilteredHintedParamLists.isEmpty())
{
hintedParamLists = equivalenceFilteredHintedParamLists;
if (hintedParamLists.size() > 1)
{
// the equivalence filter was not enough, so try a nullability filter as well
Map<Type[], MethodReference> nullabilityFilteredHintedParamLists = new LinkedHashMap<Type[], MethodReference>(hintedParamLists);
filterParameterLists(nullabilityFilteredHintedParamLists.entrySet(), expr.getArguments(), true, false);
if (!nullabilityFilteredHintedParamLists.isEmpty())
{
hintedParamLists = nullabilityFilteredHintedParamLists;
}
}
}
}
if (hintedParamLists.size() == 1)
{
paramTypeLists = hintedParamLists;
}
else
{
// try the same thing without using hintedParamLists
filterParameterLists(paramTypeLists.entrySet(), expr.getArguments(), false, false);
if (paramTypeLists.size() > 1)
{
Map<Type[], MethodReference> equivalenceFilteredParamTypeLists = new LinkedHashMap<Type[], MethodReference>(paramTypeLists);
filterParameterLists(equivalenceFilteredParamTypeLists.entrySet(), expr.getArguments(), true, true);
if (!equivalenceFilteredParamTypeLists.isEmpty())
{
paramTypeLists = equivalenceFilteredParamTypeLists;
if (paramTypeLists.size() > 1)
{
Map<Type[], MethodReference> nullabilityFilteredParamTypeLists = new LinkedHashMap<Type[], MethodReference>(paramTypeLists);
filterParameterLists(nullabilityFilteredParamTypeLists.entrySet(), expr.getArguments(), true, false);
if (!nullabilityFilteredParamTypeLists.isEmpty())
{
paramTypeLists = nullabilityFilteredParamTypeLists;
}
}
}
}
}
if (paramTypeLists.size() > 1)
{
throw new ConceptualException("Ambiguous method call, there are at least two applicable methods which take these arguments", expr.getLexicalPhrase());
}
if (paramTypeLists.isEmpty())
{
// we didn't find anything, so rethrow the exception from earlier
if (cachedException instanceof NameNotResolvedException)
{
throw (NameNotResolvedException) cachedException;
}
throw (ConceptualException) cachedException;
}
Entry<Type[], MethodReference> entry = paramTypeLists.entrySet().iterator().next();
expr.setResolvedMethodReference(entry.getValue());
// if the method call had no base expression, e.g. it was a VariableExpression being called, this will just set it to null
expr.setResolvedBaseExpression(methodBaseExpressions.get(entry.getValue()));
if (isSuperAccess)
{
// this function call is of the form 'super.method()', so make it non-virtual
expr.setResolvedIsVirtual(false);
}
}
else if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIfExpression = (InlineIfExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(inlineIfExpression.getCondition(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(inlineIfExpression.getThenExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(inlineIfExpression.getElseExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof InstanceOfExpression)
{
InstanceOfExpression instanceOfExpression = (InstanceOfExpression) expression;
CoalescedConceptualException coalescedException = null;
try
{
resolve(instanceOfExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(instanceOfExpression.getInstanceOfType(), enclosingDefinition, compilationUnit);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof IntegerLiteralExpression)
{
// do nothing
}
else if (expression instanceof LogicalExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((LogicalExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((LogicalExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof MinusExpression)
{
resolve(((MinusExpression) expression).getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof NullCoalescingExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((NullCoalescingExpression) expression).getNullableExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((NullCoalescingExpression) expression).getAlternativeExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof NullLiteralExpression)
{
// do nothing
}
else if (expression instanceof ObjectCreationExpression)
{
// do nothing
}
else if (expression instanceof RelationalExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((RelationalExpression) expression).getLeftSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((RelationalExpression) expression).getRightSubExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof ShiftExpression)
{
CoalescedConceptualException coalescedException = null;
try
{
resolve(((ShiftExpression) expression).getLeftExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
try
{
resolve(((ShiftExpression) expression).getRightExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof StringLiteralExpression)
{
// resolve the type of the string literal here, so that we have access to it in the type checker
expression.setType(SpecialTypeHandler.STRING_TYPE);
}
else if (expression instanceof ThisExpression)
{
ThisExpression thisExpression = (ThisExpression) expression;
if (enclosingDefinition == null)
{
throw new ConceptualException("'this' does not refer to anything in this context", thisExpression.getLexicalPhrase());
}
thisExpression.setType(new NamedType(false, false, inImmutableContext, enclosingDefinition));
}
else if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
CoalescedConceptualException coalescedException = null;
Expression[] subExpressions = tupleExpression.getSubExpressions();
for (int i = 0; i < subExpressions.length; i++)
{
try
{
resolve(subExpressions[i], block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
catch (ConceptualException e)
{
coalescedException = CoalescedConceptualException.coalesce(coalescedException, e);
}
}
if (coalescedException != null)
{
throw coalescedException;
}
}
else if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression indexExpression = (TupleIndexExpression) expression;
resolve(indexExpression.getExpression(), block, enclosingDefinition, compilationUnit, inStaticContext, inImmutableContext, enclosingProperty);
}
else if (expression instanceof VariableExpression)
{
VariableExpression expr = (VariableExpression) expression;
boolean isSuperAccess = expr instanceof SuperVariableExpression;
expr.setResolvedContextImmutability(inImmutableContext);
Variable var = block.getVariable(expr.getName());
if (var != null & !isSuperAccess)
{
expr.setResolvedVariable(var);
return;
}
if (enclosingDefinition != null)
{
Set<MemberReference<?>> members = new NamedType(false, false, enclosingDefinition, null).getMembers(expr.getName(), !isSuperAccess, isSuperAccess);
members = members != null ? members : new HashSet<MemberReference<?>>();
MemberReference<?> resolved = null;
if (members.size() == 1)
{
resolved = members.iterator().next();
}
else
{
Set<MemberReference<?>> filteredMembers = applyTypeHints(members, expr.getTypeHint(), expr.getReturnTypeHint(), expr.getIsFunctionHint(), expr.getIsAssignableHint());
if (filteredMembers.size() == 1)
{
resolved = filteredMembers.iterator().next();
}
else if (members.size() > 1)
{
throw new ConceptualException("Multiple members have the name '" + expr.getName() + "'", expr.getLexicalPhrase());
}
}
if (resolved != null)
{
if (resolved instanceof FieldReference)
{
FieldReference fieldReference = (FieldReference) resolved;
if (fieldReference.getReferencedMember().isStatic())
{
var = fieldReference.getReferencedMember().getGlobalVariable();
}
else
{
var = fieldReference.getReferencedMember().getMemberVariable();
}
expr.setResolvedVariable(var);
expr.setResolvedMemberReference(fieldReference);
return;
}
else if (resolved instanceof PropertyReference)
{
PropertyReference propertyReference = (PropertyReference) resolved;
Property property = propertyReference.getReferencedMember();
if (property == enclosingProperty)
{
if (property.isStatic())
{
var = property.getBackingGlobalVariable();
}
else
{
var = property.getBackingMemberVariable();
}
}
else
{
var = property.getPseudoVariable();
}
expr.setResolvedVariable(var);
expr.setResolvedMemberReference(propertyReference);
return;
}
else if (resolved instanceof MethodReference)
{
expr.setResolvedMemberReference(resolved);
return;
}
throw new IllegalStateException("Unknown member type: " + resolved);
}
}
throw new NameNotResolvedException("Unable to resolve \"" + (isSuperAccess ? "super." : "") + expr.getName() + "\"", expr.getLexicalPhrase());
}
else
{
throw new ConceptualException("Internal name resolution error: Unknown expression type", expression.getLexicalPhrase());
}
}
|
diff --git a/src/main/java/com/oschrenk/humangeo/cs/Vectors.java b/src/main/java/com/oschrenk/humangeo/cs/Vectors.java
index d848a72..12159c0 100644
--- a/src/main/java/com/oschrenk/humangeo/cs/Vectors.java
+++ b/src/main/java/com/oschrenk/humangeo/cs/Vectors.java
@@ -1,116 +1,116 @@
package com.oschrenk.humangeo.cs;
import com.oschrenk.humangeo.core.Cartesian2dCoordinate;
import com.oschrenk.humangeo.core.Cartesian3dCoordinate;
/**
*
* @author Oliver Schrenk <[email protected]>
*/
public class Vectors {
/**
* Length of vector
*
* @param cartesianCoordinate
* the cartesian coordinate
* @return the length of the vector
*/
public static final double length(
final Cartesian2dCoordinate cartesianCoordinate) {
return Math.sqrt(cartesianCoordinate.getX()
* cartesianCoordinate.getX() + cartesianCoordinate.getY()
* cartesianCoordinate.getY());
}
/**
* Length of vector
*
* @param cartesianCoordinate
* the cartesian coordinate
* @return length of the vector
*/
public static final double length(
final Cartesian3dCoordinate cartesianCoordinate) {
return Math.sqrt(cartesianCoordinate.getX()
* cartesianCoordinate.getX() + cartesianCoordinate.getY()
* cartesianCoordinate.getY() + cartesianCoordinate.getZ()
- + cartesianCoordinate.getZ());
+ * cartesianCoordinate.getZ());
}
/**
* Length of vector with arbitrary dimensions
*
* @param v
* the vector v
* @return the length of the vector
*/
public static final double length(final double[] v) {
double distanceSquared = 0;
for (final double element : v) {
distanceSquared += element * element;
}
return Math.sqrt(distanceSquared);
}
/**
* a dot b
*
* @param a
* the vector a
* @param b
* the vector a
* @return dot product
*/
public static final double dot(final Cartesian3dCoordinate a,
final Cartesian3dCoordinate b) {
return a.getX() * b.getX() + a.getY() * b.getY() + a.getZ() * b.getZ();
}
/**
* a cross b.
*
* @param a
* the vector a
* @param b
* the vector b
* @return the cross product of a and b
*/
public static final Cartesian3dCoordinate cross(
final Cartesian3dCoordinate a, final Cartesian3dCoordinate b) {
return new Cartesian3dCoordinate(a.getY() * b.getZ() - a.getZ()
* b.getY(), a.getZ() * b.getX() - a.getX() * b.getZ(), a.getX()
* b.getY() - a.getY() * b.getX());
}
/**
* c * v.
*
* @param c
* the constant c
* @param v
* the vector v
* @return the cartesian3d coordinate
*/
public static final Cartesian3dCoordinate mult(final double c,
final Cartesian3dCoordinate v) {
return new Cartesian3dCoordinate(c * v.getX(), c * v.getY(), c
* v.getZ());
}
/**
* v-w
*
* @param v
* the v
* @param w
* the w
* @return the double[]
*/
public static final Cartesian3dCoordinate minus(
final Cartesian3dCoordinate v, final Cartesian3dCoordinate w) {
return new Cartesian3dCoordinate(v.getX() - w.getX(), v.getY()
- w.getY(), v.getZ() - w.getZ());
}
}
| true | true | public static final double length(
final Cartesian3dCoordinate cartesianCoordinate) {
return Math.sqrt(cartesianCoordinate.getX()
* cartesianCoordinate.getX() + cartesianCoordinate.getY()
* cartesianCoordinate.getY() + cartesianCoordinate.getZ()
+ cartesianCoordinate.getZ());
}
| public static final double length(
final Cartesian3dCoordinate cartesianCoordinate) {
return Math.sqrt(cartesianCoordinate.getX()
* cartesianCoordinate.getX() + cartesianCoordinate.getY()
* cartesianCoordinate.getY() + cartesianCoordinate.getZ()
* cartesianCoordinate.getZ());
}
|
diff --git a/workspace/enwida/src/main/java/de/enwida/web/service/implementation/UserServiceImpl.java b/workspace/enwida/src/main/java/de/enwida/web/service/implementation/UserServiceImpl.java
index b7b27bc4..21c7fa26 100644
--- a/workspace/enwida/src/main/java/de/enwida/web/service/implementation/UserServiceImpl.java
+++ b/workspace/enwida/src/main/java/de/enwida/web/service/implementation/UserServiceImpl.java
@@ -1,694 +1,695 @@
package de.enwida.web.service.implementation;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.sql.Date;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import de.enwida.web.dao.interfaces.IGroupDao;
import de.enwida.web.dao.interfaces.IRightDao;
import de.enwida.web.dao.interfaces.IRoleDao;
import de.enwida.web.dao.interfaces.IUserDao;
import de.enwida.web.model.Group;
import de.enwida.web.model.Right;
import de.enwida.web.model.Role;
import de.enwida.web.model.User;
import de.enwida.web.service.interfaces.IUserService;
import de.enwida.web.utils.Constants;
import de.enwida.web.utils.EnwidaUtils;
@Service("userService")
@TransactionConfiguration(transactionManager = "jpaTransactionManager", defaultRollback = true)
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements IUserService {
//This variable is used for tests
static String lastActivationLink="";
/**
* User Data Access Object
*/
@Autowired
private IUserDao userDao;
/**
* Group Data Access Object
*/
@Autowired
private IGroupDao groupDao;
/**
* Role Data Access Object
*/
@Autowired
private IRoleDao roleDao;
/**
* Rights Data Access Object
*/
@Autowired
private IRightDao rightDao;
@Autowired
private MessageSource messageSource;
/**
* Mailing Service to send activation link or password
*/
@Autowired
private MailServiceImpl mailService;
/**
* Log4j static class
*/
private Logger logger = Logger.getLogger(getClass());
/**
* Gets the User from UserID
*
* @throws Exception
*/
@Override
public User fetchUser(Long id) {
return userDao.fetchById(id);
}
/**
* Gets the Group from Group Name
*
* @throws Exception
*/
@Override
public Group findGroup(Group group) {
return groupDao.fetchByName(group.getGroupName());
}
/**
* Gets the role from Role Name
*
* @throws Exception
*/
@Override
public Role findRole(Role role) {
return roleDao.fetchByName(role.getRoleName());
}
/**
* Gets the role from Role Name
*
* @throws Exception
*/
@Override
public Right findRight(Right right) {
return rightDao.fetchById(right.getRightID());
}
/**
* Gets all the user from database
* @throws Exception
*/
@Override
public List<User> fetchAllUsers() throws Exception {
return userDao.fetchAll();
}
/**
* Saves user into Database
* @throws Exception
*/
@Override
public boolean saveUser(User user, String activationHost, Locale locale,boolean sendEmail) throws Exception
{
// FIXME: what is the return value?
Date date = new Date(Calendar.getInstance().getTimeInMillis());
user.setJoiningDate(date);
user.setEnabled(false);
// Generating activation Id for User
EnwidaUtils activationIdGenerator = new EnwidaUtils();
user.setActivationKey(activationIdGenerator.getActivationId());
// Password Encryption
user.setPassword(EnwidaUtils.md5(user.getPassword()));
// Saving user in the user table
long userId;
try {
//check if we dont have this user
if(userDao.fetchByName(user.getUsername())==null)
{
userDao.create(user);
userId=user.getUserId();
}else{
throw new Exception("This user is already in database");
}
} catch (Exception e) {
logger.info(e.getMessage());
return false;
}
if(userId != -1)
{
// Getting domain name from email
String domain = this.getDomainFromEmail(user.getEmail());
// Fetching the same group and assigning that group to user
Group group = this.fetchGroupByDomainName(domain);
if(group != null && group.isAutoPass())
{
Group newGroup = groupDao.fetchById(group.getGroupID());
this.assignGroupToUser(userId, newGroup.getGroupID());
}
// saving in default group (Anonymous)
Group anonymousGroup = groupDao.fetchByName(Constants.ANONYMOUS_GROUP);
if(anonymousGroup == null)
{
anonymousGroup = new Group();
anonymousGroup.setGroupName(Constants.ANONYMOUS_GROUP);
anonymousGroup.setAutoPass(true);
}
anonymousGroup = groupDao.addGroup(anonymousGroup);
this.assignGroupToUser(userId, anonymousGroup.getGroupID());
//creating individual group to see uploaded data for the user
Group userGroup = new Group(Constants.USER_UPLOAD_PREFIX+user.getUserName());
userGroup=groupDao.addGroup(userGroup);
//assign user to this group
this.assignGroupToUser(userId, userGroup.getGroupID());
//saving individual role for the group
Role userRole = new Role(Constants.USER_UPLOAD_PREFIX+user.getUserName());
userRole=roleDao.addRole(userRole);
//assign group to this role
this.assignRoleToGroup(userRole.getRoleID(),userGroup.getGroupID());
if(sendEmail){
sendUserActivationEmail(user, locale);
}
return true;
}
else
{
return false;
- } }
+ }
+ }
/**
* Gets user Password from the mail
*/
@Override
public String getPassword(String email)throws Exception {
return userDao.fetchByName(email).getPassword();
}
/**
* Gets all the groups
*/
@Override
public List<Group> fetchAllGroups() {
return groupDao.fetchAll();
}
/**
* Adds new group
*
* @throws Exception
*/
@Override
public Group saveGroup(Group newGroup) throws Exception {
return groupDao.addGroup(newGroup);
}
/**
* Adds new role to the DB
*/
@Override
public void saveRole(Role role) throws Exception {
roleDao.addRole(role);
}
@Override
public void saveRight(Right right) throws Exception {
rightDao.addRight(right);
}
/**
* Gets all Roles
*/
@Override
public List<Role> fetchAllRoles()throws Exception {
return roleDao.fetchAll();
}
@Override
public List<Right> fetchAllRights() throws Exception {
return rightDao.fetchAll();
}
/**
* Updates the user
*/
@Override
public void updateUser(User user) throws Exception {
userDao.update(user, true);
}
/**
* Gets the user based on userName
*/
@Override
public User fetchUser(String userName) {
return userDao.fetchByName(userName);
}
/**
* Resets user Password and send an email link
*/
@Override
public void resetPassword(long userID,Locale locale)throws Exception {
SecureRandom random = new SecureRandom();
String newPassword=new BigInteger(30, random).toString(32);
User user=userDao.fetchById(userID);
try {
mailService.SendEmail(user.getEmail(),messageSource.getMessage("de.enwida.userManagement.error.newPassword", null, locale),messageSource.getMessage("de.enwida.userManagement.error.newPassword", null, locale)+":"+newPassword);
user.setPassword(newPassword);
userDao.update(user);
} catch (Exception e) {
throw new Exception("Invalid Email.Please contact [email protected]");
}
}
/**
* Deletes the user
*/
@Override
public void deleteUser(User user) throws Exception {
userDao.deleteById(user.getUserId());
}
@Override
public void deleteUser(long userId) throws Exception {
userDao.deleteById(userId);
}
/**
* Caution: user and group parameters should be persisted and in clean state!
* Dirty attributes might be applied (i.e. committed to database, eventually).
* @return the updated and managed group object
* @throws Exception
*/
@Override
public Group assignGroupToUser(User user, Group group) throws Exception {
if (user.getUserId() == null) {
throw new IllegalArgumentException("user object is not persisted");
}
if (group.getGroupID() == null) {
throw new IllegalArgumentException("group object is not persisted");
}
// Temporarily remove assigned users
// This is necessary to avoid having stale user objects in the group's object tree
final Set<User> assignedUsers = group.getAssignedUsers();
group.setAssignedUsers(null);
// Modify user's set of groups
final Set<Group> groups = new HashSet<Group>(user.getGroups());
groups.add(group);
user.setGroups(groups);
userDao.update(user, true); // with flush
// Reassign users
group.setAssignedUsers(assignedUsers);
// Refresh the group in order to reflect the changes
final Group result = fetchGroupById(group.getGroupID());
groupDao.refresh(result);
return result;
}
@Override
public void assignGroupToUser(long userId, Long groupID) throws Exception {
User user = userDao.fetchById(userId);
Group group = groupDao.fetchById(groupID);
assignGroupToUser(user, group);
}
/**
* Caution: user and group parameters should be persisted and in clean state!
* Dirty attributes might be applied (i.e. committed to database, eventually).
* @return the updated and managed group object
* @throws Exception
*/
@Override
public Group revokeUserFromGroup(User user, Group group) throws Exception {
if (user.getUserId() == null) {
throw new IllegalArgumentException("user object is not persisted");
}
if (group.getGroupID() == null) {
throw new IllegalArgumentException("group object is not persisted");
}
// Modify user's set of groups
final Set<Group> groups = new HashSet<Group>(user.getGroups());
groups.remove(group);
user.setGroups(groups);
userDao.update(user, true); // with flush
// Refresh the group in order to reflect the changes
final Group result = fetchGroupById(group.getGroupID());
groupDao.refresh(result);
return result;
}
@Override
public void assignRoleToGroup(long roleID, long groupID) throws Exception {
final Group group = groupDao.fetchById(groupID);
final Role role = roleDao.fetchById(roleID);
assignRoleToGroup(role, group);
}
/**
* Caution: group and role parameters should be persisted and in clean state!
* Dirty attributes might be applied (i.e. committed to database, eventually).
* @return the updated and managed role object
* @throws Exception
*/
@Override
@Transactional
public Role assignRoleToGroup(Role role, Group group) throws Exception {
if (group.getGroupID() == null) {
throw new IllegalArgumentException("group object is not persisted");
}
if (role.getRoleID() == null) {
throw new IllegalArgumentException("role object is not persisted");
}
// Temporarily remove assigned groups
// This is necessary to avoid having stale group objects in the role's object tree
final Set<Group> assignedGroups = role.getAssignedGroups();
group.setAssignedUsers(null);
// Modify group's set of roles
final Set<Role> roles = new HashSet<Role>(group.getAssignedRoles());
roles.add(role);
group.setAssignedRoles(roles);
groupDao.update(group, true); // with flush
// Reassign groups
role.setAssignedGroups(assignedGroups);
// Refresh the role in order to reflect the changes
final Role result = fetchRoleById(role.getRoleID());
roleDao.refresh(result);
return result;
}
@Override
public void revokeRoleFromGroup(long roleID, long groupID) throws Exception{
final Group group = groupDao.fetchById(groupID);
final Role role = roleDao.fetchById(roleID);
revokeRoleFromGroup(role, group);
}
/**
* Caution: group and role parameters should be persisted and in clean state!
* Dirty attributes might be applied (i.e. committed to database, eventually).
* @return the updated and managed role object
* @throws Exception
*/
@Override
public Role revokeRoleFromGroup(Role role, Group group) throws Exception {
if (group.getGroupID() == null) {
throw new IllegalArgumentException("group object is not persisted");
}
if (role.getRoleID() == null) {
throw new IllegalArgumentException("role object is not persisted");
}
// Modify group's set of roles
final Set<Role> roles = new HashSet<Role>(group.getAssignedRoles());
roles.remove(role);
group.setAssignedRoles(roles);
groupDao.update(group, true); // with flush
// Refresh the role in order to reflect the changes
final Role result = fetchRoleById(role.getRoleID());
roleDao.refresh(result);
return result;
}
@Override
public void revokeUserFromGroup(long userID, long groupID) {
User user=userDao.fetchById(userID);
Group group=groupDao.fetchById(groupID);
if (group.getAssignedUsers().contains(user)){
group.getAssignedUsers().remove(user);
}
if(group!=null || user!=null)
try {
groupDao.save(group);
} catch (Exception e) {
logger.error("Unable to save group", e);
}
}
/**
* Enables or Disables the user
*/
@Override
public void enableDisableUser(int userID, boolean enabled)throws Exception {
userDao.enableDisableUser(userID,enabled);
}
/**
* Removes the group
*/
@Override
public void deleteGroup(long groupID) throws Exception {
groupDao.deleteById(groupID);
}
@Override
public void deleteRole(long roleID) throws Exception {
roleDao.deleteById(roleID);
}
@Override
public void deleteRight(long rightID) throws Exception {
rightDao.deleteById(rightID);
}
/**
* Checks usernameAvailability
*/
@Override
public boolean userNameAvailability(String username) throws Exception {
return userDao.usernameAvailablility(username);
}
/**
* Enables or disables the aspect based on rightID
*/
@Override
public void enableDisableAspect(int rightID, boolean enabled)throws Exception {
rightDao.enableDisableAspect(rightID,enabled);
}
/**
* Activates the user
*/
@Override
public boolean activateUser(String username, String activationCode) throws Exception
{
if(userDao.checkUserActivationId(username, activationCode))
{
userDao.activateUser(username);
return true;
}
return false;
}
@Override
public Long getNextSequence(String schema, String sequenceName) {
Long value = null;
try {
value = userDao.getNextSequence(schema, sequenceName);
} catch (Exception e) {
logger.error("Do nothing");
}
return value;
}
/**
* Gets the current User
*/
@Override
public User getCurrentUser() throws Exception {
String userName = SecurityContextHolder.getContext().getAuthentication().getName();
User user=this.fetchUser(userName);
//If user is not found return anonymous user;
if (user==null){
user = fetchUser(Constants.ANONYMOUS_USER);
if (user == null) {
user = new User("[email protected]", Constants.ANONYMOUS_USER, "secret", "Anonymous", "User", true);
user.setCompanyName("enwida.de");
saveUser(user,false);
final Group anonymousGroup = fetchGroup(Constants.ANONYMOUS_GROUP);
assignGroupToUser(user, anonymousGroup);
}
}
return user;
}
/**
* Saves the user
* @throws Exception
*/
@Override
public boolean saveUser(User user,boolean sendEmail) throws Exception {
return saveUser(user,null, null,sendEmail);
}
@Override
public Group fetchGroup(String groupName) throws Exception {
return groupDao.fetchByName(groupName);
}
@Override
public Role fetchRole(String roleName) {
return roleDao.fetchByName(roleName);
}
@Override
public Right fetchRight(Long rightId) {
return rightDao.fetchById(rightId);
}
@Override
public Group fetchGroupByCompanyName(final String companyName)
{
for (Group group : groupDao.fetchAll()) {
for (User user : group.getAssignedUsers()) {
if(user.getCompanyName().equals(companyName))
return group;
}
}
return null;
}
@Override
public User syncUser(User user) throws Exception {
user = fetchUser(user.getUsername());
userDao.refresh(user);
return user;
}
@Override
public boolean emailAvailability(String email) throws Exception {
for (User user : userDao.fetchAll()) {
if(email.equalsIgnoreCase(user.getEmail())){
return true;
}
}
return false;
}
@Override
public Group fetchGroupById(long groupId) {
return groupDao.fetchById(groupId);
}
@Override
public Role fetchRoleById(long roleId) {
return roleDao.fetchById(roleId);
}
private void sendUserActivationEmail(User user, Locale locale) throws Exception {
try{
String activationLink = Constants.ACTIVATION_URL+"username=" + user.getUserName() + "&actId=" + user.getActivationKey();
String emailText = messageSource.getMessage("de.enwida.activation.email.message", null, locale) +
activationLink +" \n"+ messageSource.getMessage("de.enwida.activation.email.signature", null, locale);
mailService.SendEmail(user.getEmail(), messageSource.getMessage("de.enwida.activation.email.subject", null, locale), emailText );
}catch(Exception ex){
logger.error(ex);
throw new Exception("Mailing Error occured");
}
}
@Override
public void enableDisableAutoPass(Long groupID, boolean enabled) throws Exception {
Group group=groupDao.fetchById(groupID);
group.setAutoPass(enabled);
groupDao.save(group);
}
@Override
public Long getNextSequence(String schema, String sequenceName,
boolean reset) {
Long value = null;
try {
value = userDao.getNextSequence(schema, sequenceName, reset);
} catch (Exception e) {
logger.error("Do nothing");
}
return value;
}
public String getLastActivationLink() {
return lastActivationLink;
}
private String getDomainFromEmail(String email){
String company = email.substring(email.indexOf('@') + 1, email.length());
return company;
}
@Override
public Group fetchGroupByDomainName(String domainName) {
for (Group group : groupDao.fetchAll()) {
if (group.getDomainAutoPass() != null
&& group.getDomainAutoPass().equalsIgnoreCase(domainName))
return group;
}
return null;
}
@Override
public void updateDomainAutoPass(Long groupID, String domainAutoPass) throws Exception {
Group group=groupDao.fetchById(groupID);
group.setDomainAutoPass(domainAutoPass);
groupDao.save(group);
}
@Override
@Transactional
public Role enableDisableAspectForRole(Right right, Role role,boolean enabled) throws Exception {
if (role.getRoleID() == null) {
throw new IllegalArgumentException("role object is not persisted");
}
if (right.getRightID() == null) {
throw new IllegalArgumentException("right object is not persisted");
}
final Set<Right> rights=new HashSet<Right>(role.getRights());
if(enabled)
rights.add(right);
else
rights.remove(right);
role.setRights(rights);
roleDao.update(role, true);
final Right result =rightDao.fetchById(right.getRightID());
rightDao.refresh(result);
return role;
}
}
| true | true | public boolean saveUser(User user, String activationHost, Locale locale,boolean sendEmail) throws Exception
{
// FIXME: what is the return value?
Date date = new Date(Calendar.getInstance().getTimeInMillis());
user.setJoiningDate(date);
user.setEnabled(false);
// Generating activation Id for User
EnwidaUtils activationIdGenerator = new EnwidaUtils();
user.setActivationKey(activationIdGenerator.getActivationId());
// Password Encryption
user.setPassword(EnwidaUtils.md5(user.getPassword()));
// Saving user in the user table
long userId;
try {
//check if we dont have this user
if(userDao.fetchByName(user.getUsername())==null)
{
userDao.create(user);
userId=user.getUserId();
}else{
throw new Exception("This user is already in database");
}
} catch (Exception e) {
logger.info(e.getMessage());
return false;
}
if(userId != -1)
{
// Getting domain name from email
String domain = this.getDomainFromEmail(user.getEmail());
// Fetching the same group and assigning that group to user
Group group = this.fetchGroupByDomainName(domain);
if(group != null && group.isAutoPass())
{
Group newGroup = groupDao.fetchById(group.getGroupID());
this.assignGroupToUser(userId, newGroup.getGroupID());
}
// saving in default group (Anonymous)
Group anonymousGroup = groupDao.fetchByName(Constants.ANONYMOUS_GROUP);
if(anonymousGroup == null)
{
anonymousGroup = new Group();
anonymousGroup.setGroupName(Constants.ANONYMOUS_GROUP);
anonymousGroup.setAutoPass(true);
}
anonymousGroup = groupDao.addGroup(anonymousGroup);
this.assignGroupToUser(userId, anonymousGroup.getGroupID());
//creating individual group to see uploaded data for the user
Group userGroup = new Group(Constants.USER_UPLOAD_PREFIX+user.getUserName());
userGroup=groupDao.addGroup(userGroup);
//assign user to this group
this.assignGroupToUser(userId, userGroup.getGroupID());
//saving individual role for the group
Role userRole = new Role(Constants.USER_UPLOAD_PREFIX+user.getUserName());
userRole=roleDao.addRole(userRole);
//assign group to this role
this.assignRoleToGroup(userRole.getRoleID(),userGroup.getGroupID());
if(sendEmail){
sendUserActivationEmail(user, locale);
}
return true;
}
else
{
return false;
} }
| public boolean saveUser(User user, String activationHost, Locale locale,boolean sendEmail) throws Exception
{
// FIXME: what is the return value?
Date date = new Date(Calendar.getInstance().getTimeInMillis());
user.setJoiningDate(date);
user.setEnabled(false);
// Generating activation Id for User
EnwidaUtils activationIdGenerator = new EnwidaUtils();
user.setActivationKey(activationIdGenerator.getActivationId());
// Password Encryption
user.setPassword(EnwidaUtils.md5(user.getPassword()));
// Saving user in the user table
long userId;
try {
//check if we dont have this user
if(userDao.fetchByName(user.getUsername())==null)
{
userDao.create(user);
userId=user.getUserId();
}else{
throw new Exception("This user is already in database");
}
} catch (Exception e) {
logger.info(e.getMessage());
return false;
}
if(userId != -1)
{
// Getting domain name from email
String domain = this.getDomainFromEmail(user.getEmail());
// Fetching the same group and assigning that group to user
Group group = this.fetchGroupByDomainName(domain);
if(group != null && group.isAutoPass())
{
Group newGroup = groupDao.fetchById(group.getGroupID());
this.assignGroupToUser(userId, newGroup.getGroupID());
}
// saving in default group (Anonymous)
Group anonymousGroup = groupDao.fetchByName(Constants.ANONYMOUS_GROUP);
if(anonymousGroup == null)
{
anonymousGroup = new Group();
anonymousGroup.setGroupName(Constants.ANONYMOUS_GROUP);
anonymousGroup.setAutoPass(true);
}
anonymousGroup = groupDao.addGroup(anonymousGroup);
this.assignGroupToUser(userId, anonymousGroup.getGroupID());
//creating individual group to see uploaded data for the user
Group userGroup = new Group(Constants.USER_UPLOAD_PREFIX+user.getUserName());
userGroup=groupDao.addGroup(userGroup);
//assign user to this group
this.assignGroupToUser(userId, userGroup.getGroupID());
//saving individual role for the group
Role userRole = new Role(Constants.USER_UPLOAD_PREFIX+user.getUserName());
userRole=roleDao.addRole(userRole);
//assign group to this role
this.assignRoleToGroup(userRole.getRoleID(),userGroup.getGroupID());
if(sendEmail){
sendUserActivationEmail(user, locale);
}
return true;
}
else
{
return false;
}
}
|
diff --git a/ass1/src/com/kkirch/symbols/SymbolContext.java b/ass1/src/com/kkirch/symbols/SymbolContext.java
index 313fb1d..64bdfcc 100644
--- a/ass1/src/com/kkirch/symbols/SymbolContext.java
+++ b/ass1/src/com/kkirch/symbols/SymbolContext.java
@@ -1,42 +1,42 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.kkirch.symbols;
import com.kkirch.ir.Id;
import com.kkirch.lexer.Token;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author kkirch
*/
public class SymbolContext {
private Map<Token, Id> symbolTable = new HashMap<Token, Id>();
protected SymbolContext parentContext;
public SymbolContext(SymbolContext parentContext) {
this.parentContext = parentContext;
}
public void put(Token t, Id i) {
symbolTable.put(t, i);
}
public Id get(Token t) {
Id foundId = null;
SymbolContext currentContext = this;
while (currentContext != null) {
- foundId = symbolTable.get(t);
+ foundId = currentContext.symbolTable.get(t);
if (foundId == null) {
currentContext = currentContext.parentContext;
} else {
break;
}
}
return foundId;
}
}
| true | true | public Id get(Token t) {
Id foundId = null;
SymbolContext currentContext = this;
while (currentContext != null) {
foundId = symbolTable.get(t);
if (foundId == null) {
currentContext = currentContext.parentContext;
} else {
break;
}
}
return foundId;
}
| public Id get(Token t) {
Id foundId = null;
SymbolContext currentContext = this;
while (currentContext != null) {
foundId = currentContext.symbolTable.get(t);
if (foundId == null) {
currentContext = currentContext.parentContext;
} else {
break;
}
}
return foundId;
}
|
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java
index 657504e..2ef617a 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/deployer/BpmnDeployer.java
@@ -1,343 +1,338 @@
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.impl.bpmn.deployer;
import java.awt.GraphicsEnvironment;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.impl.bpmn.diagram.ProcessDiagramGenerator;
import org.activiti.engine.impl.bpmn.parser.BpmnParse;
import org.activiti.engine.impl.bpmn.parser.BpmnParser;
import org.activiti.engine.impl.bpmn.parser.MessageEventDefinition;
import org.activiti.engine.impl.cfg.IdGenerator;
import org.activiti.engine.impl.cmd.DeleteJobsCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.db.DbSqlSession;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.event.MessageEventHandler;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.jobexecutor.TimerDeclarationImpl;
import org.activiti.engine.impl.jobexecutor.TimerStartEventJobHandler;
import org.activiti.engine.impl.persistence.deploy.Deployer;
import org.activiti.engine.impl.persistence.deploy.DeploymentCache;
import org.activiti.engine.impl.persistence.entity.DeploymentEntity;
import org.activiti.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.activiti.engine.impl.persistence.entity.MessageEventSubscriptionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionManager;
import org.activiti.engine.impl.persistence.entity.ResourceEntity;
import org.activiti.engine.impl.persistence.entity.TimerEntity;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.runtime.Job;
/**
* @author Tom Baeyens
* @author Joram Barrez
*/
public class BpmnDeployer implements Deployer {
private static final Logger LOG = Logger.getLogger(BpmnDeployer.class.getName());;
public static final String[] BPMN_RESOURCE_SUFFIXES = new String[] { "bpmn20.xml", "bpmn" };
public static final String[] DIAGRAM_SUFFIXES = new String[]{"png", "jpg", "gif", "svg"};
protected ExpressionManager expressionManager;
protected BpmnParser bpmnParser;
protected IdGenerator idGenerator;
public void deploy(DeploymentEntity deployment) {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource " + resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
if (!deployment.isValidatingSchema()) {
bpmnParse.setSchemaResource(null);
}
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if (diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
- GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
- if(!ge.isHeadlessInstance()) {
- byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
- diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
- createResource(diagramResourceName, diagramBytes, deployment);
- } else {
- LOG.log(Level.WARNING, "Cannot generate process diagram while running in AWT headless-mode");
- }
+ byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
+ diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
+ createResource(diagramResourceName, diagramBytes, deployment);
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable).
LOG.log(Level.WARNING, "Error while generating process diagram, image will not be stored in repository", t);
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 charcaters
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
deploymentCache.addProcessDefinition(processDefinition);
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
deploymentCache.addProcessDefinition(processDefinition);
}
Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.addProcessDefinition(processDefinition);
}
}
@SuppressWarnings("unchecked")
private void addTimerDeclarations(ProcessDefinitionEntity processDefinition) {
List<TimerDeclarationImpl> timerDeclarations = (List<TimerDeclarationImpl>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_START_TIMER);
if (timerDeclarations!=null) {
for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
TimerEntity timer = timerDeclaration.prepareTimerEntity(null);
Context
.getCommandContext()
.getJobManager()
.schedule(timer);
}
}
}
private void removeObsoleteTimers(ProcessDefinitionEntity processDefinition) {
List<Job> jobsToDelete = Context
.getCommandContext()
.getJobManager()
.findJobsByConfiguration(TimerStartEventJobHandler.TYPE, processDefinition.getKey());
for (Job job :jobsToDelete) {
new DeleteJobsCmd(job.getId()).execute(Context.getCommandContext());
}
}
protected void removeObsoleteMessageEventSubscriptions(ProcessDefinitionEntity processDefinition, ProcessDefinitionEntity latestProcessDefinition) {
// remove all subscriptions for the previous version
if(latestProcessDefinition != null) {
CommandContext commandContext = Context.getCommandContext();
List<EventSubscriptionEntity> subscriptionsToDelete = commandContext
.getEventSubscriptionManager()
.findEventSubscriptionsByConfiguration(MessageEventHandler.TYPE, latestProcessDefinition.getId());
for (EventSubscriptionEntity eventSubscriptionEntity : subscriptionsToDelete) {
eventSubscriptionEntity.delete();
}
}
}
@SuppressWarnings("unchecked")
protected void addMessageEventSubscriptions(ProcessDefinitionEntity processDefinition) {
CommandContext commandContext = Context.getCommandContext();
List<MessageEventDefinition> messageEventDefinitions = (List<MessageEventDefinition>) processDefinition.getProperty(BpmnParse.PROPERTYNAME_MESSAGE_EVENT_DEFINITIONS);
if(messageEventDefinitions != null) {
for (MessageEventDefinition messageEventDefinition : messageEventDefinitions) {
if(messageEventDefinition.isStartEvent()) {
// look for subscriptions for the same name in db:
List<EventSubscriptionEntity> subscriptionsForSameMessageName = commandContext
.getEventSubscriptionManager()
.findEventSubscriptionByName(MessageEventHandler.TYPE, messageEventDefinition.getName());
// also look for subscriptions created in the session:
List<MessageEventSubscriptionEntity> cachedSubscriptions = commandContext
.getDbSqlSession()
.findInCache(MessageEventSubscriptionEntity.class);
for (MessageEventSubscriptionEntity cachedSubscription : cachedSubscriptions) {
if(messageEventDefinition.getName().equals(cachedSubscription.getEventName())
&& !subscriptionsForSameMessageName.contains(cachedSubscription)) {
subscriptionsForSameMessageName.add(cachedSubscription);
}
}
// remove subscriptions deleted in the same command
subscriptionsForSameMessageName = commandContext
.getDbSqlSession()
.pruneDeletedEntities(subscriptionsForSameMessageName);
if(!subscriptionsForSameMessageName.isEmpty()) {
throw new ActivitiException("Cannot deploy process definition '" + processDefinition.getResourceName()
+ "': there already is a message event subscription for the message with name '" + messageEventDefinition.getName() + "'.");
}
MessageEventSubscriptionEntity newSubscription = new MessageEventSubscriptionEntity();
newSubscription.setEventName(messageEventDefinition.getName());
newSubscription.setActivityId(messageEventDefinition.getActivityId());
newSubscription.setConfiguration(processDefinition.getId());
newSubscription.insert();
}
}
}
}
/**
* Returns the default name of the image resource for a certain process.
*
* It will first look for an image resource which matches the process
* specifically, before resorting to an image resource which matches the BPMN
* 2.0 xml file resource.
*
* Example: if the deployment contains a BPMN 2.0 xml resource called
* 'abc.bpmn20.xml' containing only one process with key 'myProcess', then
* this method will look for an image resources called 'abc.myProcess.png'
* (or .jpg, or .gif, etc.) or 'abc.png' if the previous one wasn't found.
*
* Example 2: if the deployment contains a BPMN 2.0 xml resource called
* 'abc.bpmn20.xml' containing three processes (with keys a, b and c),
* then this method will first look for an image resource called 'abc.a.png'
* before looking for 'abc.png' (likewise for b and c).
* Note that if abc.a.png, abc.b.png and abc.c.png don't exist, all
* processes will have the same image: abc.png.
*
* @return null if no matching image resource is found.
*/
protected String getDiagramResourceForProcess(String bpmnFileResource, String processKey, Map<String, ResourceEntity> resources) {
for (String diagramSuffix: DIAGRAM_SUFFIXES) {
String diagramForBpmnFileResource = getBpmnFileImageResourceName(bpmnFileResource, diagramSuffix);
String processDiagramResource = getProcessImageResourceName(bpmnFileResource, processKey, diagramSuffix);
if (resources.containsKey(processDiagramResource)) {
return processDiagramResource;
} else if (resources.containsKey(diagramForBpmnFileResource)) {
return diagramForBpmnFileResource;
}
}
return null;
}
protected String getBpmnFileImageResourceName(String bpmnFileResource, String diagramSuffix) {
String bpmnFileResourceBase = bpmnFileResource.substring(0, bpmnFileResource.length()-10); // minus 10 to remove 'bpmn20.xml'
return bpmnFileResourceBase + diagramSuffix;
}
protected String getProcessImageResourceName(String bpmnFileResource, String processKey, String diagramSuffix) {
String bpmnFileResourceBase = bpmnFileResource.substring(0, bpmnFileResource.length()-10); // minus 10 to remove 'bpmn20.xml'
return bpmnFileResourceBase + processKey + "." + diagramSuffix;
}
protected void createResource(String name, byte[] bytes, DeploymentEntity deploymentEntity) {
ResourceEntity resource = new ResourceEntity();
resource.setName(name);
resource.setBytes(bytes);
resource.setDeploymentId(deploymentEntity.getId());
// Mark the resource as 'generated'
resource.setGenerated(true);
Context
.getCommandContext()
.getDbSqlSession()
.insert(resource);
}
protected boolean isBpmnResource(String resourceName) {
for (String suffix : BPMN_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public BpmnParser getBpmnParser() {
return bpmnParser;
}
public void setBpmnParser(BpmnParser bpmnParser) {
this.bpmnParser = bpmnParser;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
}
| true | true | public void deploy(DeploymentEntity deployment) {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource " + resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
if (!deployment.isValidatingSchema()) {
bpmnParse.setSchemaResource(null);
}
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if (diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
if(!ge.isHeadlessInstance()) {
byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
createResource(diagramResourceName, diagramBytes, deployment);
} else {
LOG.log(Level.WARNING, "Cannot generate process diagram while running in AWT headless-mode");
}
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable).
LOG.log(Level.WARNING, "Error while generating process diagram, image will not be stored in repository", t);
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 charcaters
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
deploymentCache.addProcessDefinition(processDefinition);
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
deploymentCache.addProcessDefinition(processDefinition);
}
Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.addProcessDefinition(processDefinition);
}
}
| public void deploy(DeploymentEntity deployment) {
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
Map<String, ResourceEntity> resources = deployment.getResources();
for (String resourceName : resources.keySet()) {
LOG.info("Processing resource " + resourceName);
if (isBpmnResource(resourceName)) {
ResourceEntity resource = resources.get(resourceName);
byte[] bytes = resource.getBytes();
ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
BpmnParse bpmnParse = bpmnParser
.createParse()
.sourceInputStream(inputStream)
.deployment(deployment)
.name(resourceName);
if (!deployment.isValidatingSchema()) {
bpmnParse.setSchemaResource(null);
}
bpmnParse.execute();
for (ProcessDefinitionEntity processDefinition: bpmnParse.getProcessDefinitions()) {
processDefinition.setResourceName(resourceName);
String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
if (diagramResourceName==null && processDefinition.isGraphicalNotationDefined()) {
try {
byte[] diagramBytes = IoUtil.readInputStream(ProcessDiagramGenerator.generatePngDiagram(processDefinition), null);
diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
createResource(diagramResourceName, diagramBytes, deployment);
} catch (Throwable t) { // if anything goes wrong, we don't store the image (the process will still be executable).
LOG.log(Level.WARNING, "Error while generating process diagram, image will not be stored in repository", t);
}
}
processDefinition.setDiagramResourceName(diagramResourceName);
processDefinitions.add(processDefinition);
}
}
}
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionManager processDefinitionManager = commandContext.getProcessDefinitionManager();
DeploymentCache deploymentCache = Context.getProcessEngineConfiguration().getDeploymentCache();
DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
if (deployment.isNew()) {
int processDefinitionVersion;
ProcessDefinitionEntity latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
if (latestProcessDefinition != null) {
processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
} else {
processDefinitionVersion = 1;
}
processDefinition.setVersion(processDefinitionVersion);
processDefinition.setDeploymentId(deployment.getId());
String nextId = idGenerator.getNextId();
String processDefinitionId = processDefinition.getKey()
+ ":" + processDefinition.getVersion()
+ ":" + nextId; // ACT-505
// ACT-115: maximum id length is 64 charcaters
if (processDefinitionId.length() > 64) {
processDefinitionId = nextId;
}
processDefinition.setId(processDefinitionId);
removeObsoleteTimers(processDefinition);
addTimerDeclarations(processDefinition);
removeObsoleteMessageEventSubscriptions(processDefinition, latestProcessDefinition);
addMessageEventSubscriptions(processDefinition);
dbSqlSession.insert(processDefinition);
deploymentCache.addProcessDefinition(processDefinition);
} else {
String deploymentId = deployment.getId();
processDefinition.setDeploymentId(deploymentId);
ProcessDefinitionEntity persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
processDefinition.setId(persistedProcessDefinition.getId());
processDefinition.setVersion(persistedProcessDefinition.getVersion());
deploymentCache.addProcessDefinition(processDefinition);
}
Context
.getProcessEngineConfiguration()
.getDeploymentCache()
.addProcessDefinition(processDefinition);
}
}
|
diff --git a/at.owlsoft.owl/src/at/owlsoft/owl/usecases/ExtensionController.java b/at.owlsoft.owl/src/at/owlsoft/owl/usecases/ExtensionController.java
index 7639bd3..d3f552f 100644
--- a/at.owlsoft.owl/src/at/owlsoft/owl/usecases/ExtensionController.java
+++ b/at.owlsoft.owl/src/at/owlsoft/owl/usecases/ExtensionController.java
@@ -1,172 +1,173 @@
package at.owlsoft.owl.usecases;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import at.owlsoft.owl.business.ControllerBase;
import at.owlsoft.owl.business.OwlApplicationContext;
import at.owlsoft.owl.dao.DaoManager;
import at.owlsoft.owl.model.IDefaultRoles;
import at.owlsoft.owl.model.NoPermissionException;
import at.owlsoft.owl.model.SearchField;
import at.owlsoft.owl.model.SearchFieldType;
import at.owlsoft.owl.model.accounting.Activity;
import at.owlsoft.owl.model.accounting.ActivityStatus;
import at.owlsoft.owl.model.accounting.FilingExtension;
import at.owlsoft.owl.model.accounting.Rental;
import at.owlsoft.owl.model.accounting.Reservation;
import at.owlsoft.owl.model.media.MediumExemplar;
import at.owlsoft.owl.model.media.MediumExemplarStatus;
import at.owlsoft.owl.model.user.SystemUserStatus;
import at.owlsoft.owl.validation.ValidationMessage;
import at.owlsoft.owl.validation.ValidationMessageStatus;
public class ExtensionController extends ControllerBase
{
private static final int DEFAULT_MAX_EXTENSIONS = 3;
private static final int DEFAULT_EXTENSION_DURATION = 7;
public ExtensionController(OwlApplicationContext context)
{
super(context);
}
private List<ValidationMessage> _messages;
public List<ValidationMessage> extend(MediumExemplar copy)
throws NoPermissionException
{
getContext().getAuthenticationController().checkAccess(
IDefaultRoles.RENTAL_EXTEND);
Rental rental = copy.getLastRental();
if (validate(rental))
{
FilingExtension fex = new FilingExtension();
fex.setCreationDate(new Date());
Date endDate = new Date(rental.getEndDate().getTime()
+ getExtensionPeriode(rental.getMediumExemplar()));
fex.setNewEndDate(endDate);
fex.setRental(rental);
rental.addFilingExtension(fex);
DaoManager.getInstance().getRentalDao().store(rental);
}
return _messages;
}
private long getExtensionPeriode(MediumExemplar copy)
{
// TODO Read extension periode from config.
Class<?> c = copy.getClass();
String name = c.getName().concat("extensionDuration");
return getContext().getConfigurationController().getInt(name,
DEFAULT_EXTENSION_DURATION)
* 24 * 60 * 60 * 1000;
}
private boolean validate(Rental rental)
{
boolean hasNoError = true;
_messages = new ArrayList<ValidationMessage>();
// TODO Read from config maximum FilingExtension number
Class<?> c = rental.getMediumExemplar().getClass();
String name = c.getName().concat("maxExtensions");
int maxExtensions = getContext().getConfigurationController().getInt(
name, DEFAULT_MAX_EXTENSIONS);
if (rental.getFilingExtensionCount() >= maxExtensions)
{
_messages.add(new ValidationMessage("Maximum extensions reached.",
ValidationMessageStatus.Error));
hasNoError = false;
}
if (rental.getCustomer().getLastSystemUserStatusEntry()
.getSystemUserStatus() != SystemUserStatus.Active)
{
_messages.add(new ValidationMessage("Customer not active.",
ValidationMessageStatus.Warning));
}
// check for open reservations
List<Activity> activities = rental.getMedium().getActivities();
int reservationCount = 0;
int rentableCopies = 0;
for (Activity activity : activities)
{
if (activity instanceof Reservation)
{
Reservation reservation = (Reservation) activity;
if (reservation.getCurrentStatus().equals(ActivityStatus.Open))
{
reservationCount++;
}
}
}
// count rentable copies
List<MediumExemplar> copies = rental.getMedium().getMediumExemplars();
for (MediumExemplar copy : copies)
{
if (copy.getCurrentState().equals(MediumExemplarStatus.Rentable))
{
rentableCopies++;
}
}
- if (reservationCount > rentableCopies)
+ // check wether there are more reservations than rentable copies
+ if (reservationCount >= rentableCopies)
{
_messages.add(new ValidationMessage(
"Not enough rentable copies for reservations.",
ValidationMessageStatus.Warning));
}
return hasNoError;
}
public List<ValidationMessage> extend(UUID uuid)
throws NoPermissionException
{
getContext().getAuthenticationController().checkAccess(
IDefaultRoles.RENTAL_EXTEND);
List<ValidationMessage> temp = new ArrayList<ValidationMessage>();
List<SearchField> searchFields = new ArrayList<SearchField>();
searchFields.add(new SearchField("_UUID", uuid.toString(),
SearchFieldType.Equals));
List<Rental> rentals = getContext().getRentalSearchController().search(
searchFields);
if (rentals == null || rentals.isEmpty())
{
temp.add(new ValidationMessage("No rental found.",
ValidationMessageStatus.Error));
}
else if (rentals.size() > 1)
{
temp.add(new ValidationMessage("To many rentals found.",
ValidationMessageStatus.Error));
}
else
{
temp = extend(rentals.get(0).getMediumExemplar());
}
return temp;
}
}
| true | true | private boolean validate(Rental rental)
{
boolean hasNoError = true;
_messages = new ArrayList<ValidationMessage>();
// TODO Read from config maximum FilingExtension number
Class<?> c = rental.getMediumExemplar().getClass();
String name = c.getName().concat("maxExtensions");
int maxExtensions = getContext().getConfigurationController().getInt(
name, DEFAULT_MAX_EXTENSIONS);
if (rental.getFilingExtensionCount() >= maxExtensions)
{
_messages.add(new ValidationMessage("Maximum extensions reached.",
ValidationMessageStatus.Error));
hasNoError = false;
}
if (rental.getCustomer().getLastSystemUserStatusEntry()
.getSystemUserStatus() != SystemUserStatus.Active)
{
_messages.add(new ValidationMessage("Customer not active.",
ValidationMessageStatus.Warning));
}
// check for open reservations
List<Activity> activities = rental.getMedium().getActivities();
int reservationCount = 0;
int rentableCopies = 0;
for (Activity activity : activities)
{
if (activity instanceof Reservation)
{
Reservation reservation = (Reservation) activity;
if (reservation.getCurrentStatus().equals(ActivityStatus.Open))
{
reservationCount++;
}
}
}
// count rentable copies
List<MediumExemplar> copies = rental.getMedium().getMediumExemplars();
for (MediumExemplar copy : copies)
{
if (copy.getCurrentState().equals(MediumExemplarStatus.Rentable))
{
rentableCopies++;
}
}
if (reservationCount > rentableCopies)
{
_messages.add(new ValidationMessage(
"Not enough rentable copies for reservations.",
ValidationMessageStatus.Warning));
}
return hasNoError;
}
| private boolean validate(Rental rental)
{
boolean hasNoError = true;
_messages = new ArrayList<ValidationMessage>();
// TODO Read from config maximum FilingExtension number
Class<?> c = rental.getMediumExemplar().getClass();
String name = c.getName().concat("maxExtensions");
int maxExtensions = getContext().getConfigurationController().getInt(
name, DEFAULT_MAX_EXTENSIONS);
if (rental.getFilingExtensionCount() >= maxExtensions)
{
_messages.add(new ValidationMessage("Maximum extensions reached.",
ValidationMessageStatus.Error));
hasNoError = false;
}
if (rental.getCustomer().getLastSystemUserStatusEntry()
.getSystemUserStatus() != SystemUserStatus.Active)
{
_messages.add(new ValidationMessage("Customer not active.",
ValidationMessageStatus.Warning));
}
// check for open reservations
List<Activity> activities = rental.getMedium().getActivities();
int reservationCount = 0;
int rentableCopies = 0;
for (Activity activity : activities)
{
if (activity instanceof Reservation)
{
Reservation reservation = (Reservation) activity;
if (reservation.getCurrentStatus().equals(ActivityStatus.Open))
{
reservationCount++;
}
}
}
// count rentable copies
List<MediumExemplar> copies = rental.getMedium().getMediumExemplars();
for (MediumExemplar copy : copies)
{
if (copy.getCurrentState().equals(MediumExemplarStatus.Rentable))
{
rentableCopies++;
}
}
// check wether there are more reservations than rentable copies
if (reservationCount >= rentableCopies)
{
_messages.add(new ValidationMessage(
"Not enough rentable copies for reservations.",
ValidationMessageStatus.Warning));
}
return hasNoError;
}
|
diff --git a/loci/visbio/ClassManager.java b/loci/visbio/ClassManager.java
index 4edb4035a..84dfbb990 100644
--- a/loci/visbio/ClassManager.java
+++ b/loci/visbio/ClassManager.java
@@ -1,101 +1,101 @@
//
// ClassManager.java
//
/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2004 Curtis Rueden.
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
*/
package loci.visbio;
import java.io.*;
import java.util.Vector;
/**
* ClassManager is the manager for preloading classes
* to speed VisBio response time later on.
*/
public class ClassManager extends LogicManager {
// -- Fields --
/** List of classes to preload. */
protected Vector preloadClasses;
// -- Constructor --
/** Constructs a class manager. */
public ClassManager(VisBioFrame bio) {
super(bio);
// extract classes to preload from data file
preloadClasses = new Vector();
try {
BufferedReader fin = new BufferedReader(new FileReader("classes.txt"));
while (true) {
String line = fin.readLine();
if (line == null) break; // eof
preloadClasses.add(line);
}
fin.close();
}
catch (IOException exc) { } // ignore data file I/O errors
}
// -- LogicManager API methods --
/** Called to notify the logic manager of a VisBio event. */
public void doEvent(VisBioEvent evt) {
int eventType = evt.getEventType();
if (eventType == VisBioEvent.LOGIC_ADDED) {
LogicManager lm = (LogicManager) evt.getSource();
if (lm == this) doGUI();
}
}
/** Gets the number of tasks required to initialize this logic manager. */
public int getTasks() { return preloadClasses.size(); }
// -- Helper methods --
/** Adds system-related GUI components to VisBio. */
private void doGUI() {
// preload a bunch of classes
int size = preloadClasses.size();
String pkg = "";
for (int i=0; i<size; i++) {
String className = (String) preloadClasses.elementAt(i);
int dot = className.lastIndexOf(".");
String prefix = className.substring(0, dot);
if (!prefix.equals(pkg)) {
pkg = prefix;
bio.setSplashStatus("Loading " + pkg);
}
else bio.setSplashStatus(null);
// preload class, ignoring errors
try { Class.forName(className); }
- catch (ClassNotFoundException exc) { }
+ catch (Exception exc) { }
}
if (VisBioFrame.DEBUG) System.out.println("DONE PRELOADING CLASSES");
}
}
| true | true | private void doGUI() {
// preload a bunch of classes
int size = preloadClasses.size();
String pkg = "";
for (int i=0; i<size; i++) {
String className = (String) preloadClasses.elementAt(i);
int dot = className.lastIndexOf(".");
String prefix = className.substring(0, dot);
if (!prefix.equals(pkg)) {
pkg = prefix;
bio.setSplashStatus("Loading " + pkg);
}
else bio.setSplashStatus(null);
// preload class, ignoring errors
try { Class.forName(className); }
catch (ClassNotFoundException exc) { }
}
if (VisBioFrame.DEBUG) System.out.println("DONE PRELOADING CLASSES");
}
| private void doGUI() {
// preload a bunch of classes
int size = preloadClasses.size();
String pkg = "";
for (int i=0; i<size; i++) {
String className = (String) preloadClasses.elementAt(i);
int dot = className.lastIndexOf(".");
String prefix = className.substring(0, dot);
if (!prefix.equals(pkg)) {
pkg = prefix;
bio.setSplashStatus("Loading " + pkg);
}
else bio.setSplashStatus(null);
// preload class, ignoring errors
try { Class.forName(className); }
catch (Exception exc) { }
}
if (VisBioFrame.DEBUG) System.out.println("DONE PRELOADING CLASSES");
}
|
diff --git a/cyklotron-core/src/main/java/net/cyklotron/cms/accesslimits/ProtectedItem.java b/cyklotron-core/src/main/java/net/cyklotron/cms/accesslimits/ProtectedItem.java
index 7e9e642e1..22ced4fc0 100644
--- a/cyklotron-core/src/main/java/net/cyklotron/cms/accesslimits/ProtectedItem.java
+++ b/cyklotron-core/src/main/java/net/cyklotron/cms/accesslimits/ProtectedItem.java
@@ -1,110 +1,110 @@
package net.cyklotron.cms.accesslimits;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.jcontainer.dna.Logger;
import org.objectledge.coral.entity.EntityDoesNotExistException;
import org.objectledge.coral.event.ResourceChangeListener;
import org.objectledge.coral.event.ResourceCreationListener;
import org.objectledge.coral.event.ResourceDeletionListener;
import org.objectledge.coral.security.Subject;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.store.Resource;
import org.objectledge.web.ratelimit.impl.RequestInfo;
import org.objectledge.web.ratelimit.impl.Rule;
import org.objectledge.web.ratelimit.impl.RuleFactory;
import org.objectledge.web.ratelimit.rules.ParseException;
public class ProtectedItem
implements ResourceChangeListener, ResourceCreationListener, ResourceDeletionListener
{
private final ProtectedItemResource res;
private final Logger log;
private volatile Pattern urlPattern;
private volatile List<Rule> rules;
public ProtectedItem(ProtectedItemResource res, CoralSession coralSession, Logger log)
throws EntityDoesNotExistException
{
this.res = res;
this.log = log;
initialize(res);
coralSession.getEvent().addResourceChangeListener(this, res);
coralSession.getEvent().addResourceChangeListener(this,
coralSession.getSchema().getResourceClass(RuleResource.CLASS_NAME));
}
@Override
public void resourceChanged(Resource resource, Subject subject)
{
if(resource instanceof ProtectedItemResource || resource instanceof RuleResource
&& resource.getParent().equals(res))
{
initialize(res);
}
}
@Override
public void resourceCreated(Resource resource)
{
if(resource instanceof RuleResource && resource.getParent().equals(res))
{
initialize(res);
}
}
@Override
public void resourceDeleted(Resource resource)
throws Exception
{
if(resource instanceof RuleResource && resource.getParent().equals(res))
{
initialize(res);
}
}
private void initialize(ProtectedItemResource res)
{
try
{
urlPattern = Pattern.compile(res.getUrlPattern());
Resource[] children = res.getChildren();
List<RuleResource> ruleDefs = new ArrayList<>();
for(Resource child : children)
{
if(child instanceof RuleResource)
{
ruleDefs.add((RuleResource)child);
}
}
Collections.sort(ruleDefs, RuleResource.BY_PRIORITY);
List<Rule> newRules = new ArrayList<>(ruleDefs.size());
for(RuleResource def : ruleDefs)
{
- rules.add(RuleFactory.getInstance().newRule(def.getId(), def.getRuleDefinition()));
+ newRules.add(RuleFactory.getInstance().newRule(def.getId(), def.getRuleDefinition()));
}
rules = Collections.unmodifiableList(newRules);
}
catch(ParseException | PatternSyntaxException e)
{
log.error("invalid protected item definition #" + res.getId(), e);
}
}
public boolean matches(RequestInfo request)
{
return urlPattern.matcher(request.getPath()).matches();
}
public List<Rule> getRules()
{
return rules;
}
}
| true | true | private void initialize(ProtectedItemResource res)
{
try
{
urlPattern = Pattern.compile(res.getUrlPattern());
Resource[] children = res.getChildren();
List<RuleResource> ruleDefs = new ArrayList<>();
for(Resource child : children)
{
if(child instanceof RuleResource)
{
ruleDefs.add((RuleResource)child);
}
}
Collections.sort(ruleDefs, RuleResource.BY_PRIORITY);
List<Rule> newRules = new ArrayList<>(ruleDefs.size());
for(RuleResource def : ruleDefs)
{
rules.add(RuleFactory.getInstance().newRule(def.getId(), def.getRuleDefinition()));
}
rules = Collections.unmodifiableList(newRules);
}
catch(ParseException | PatternSyntaxException e)
{
log.error("invalid protected item definition #" + res.getId(), e);
}
}
| private void initialize(ProtectedItemResource res)
{
try
{
urlPattern = Pattern.compile(res.getUrlPattern());
Resource[] children = res.getChildren();
List<RuleResource> ruleDefs = new ArrayList<>();
for(Resource child : children)
{
if(child instanceof RuleResource)
{
ruleDefs.add((RuleResource)child);
}
}
Collections.sort(ruleDefs, RuleResource.BY_PRIORITY);
List<Rule> newRules = new ArrayList<>(ruleDefs.size());
for(RuleResource def : ruleDefs)
{
newRules.add(RuleFactory.getInstance().newRule(def.getId(), def.getRuleDefinition()));
}
rules = Collections.unmodifiableList(newRules);
}
catch(ParseException | PatternSyntaxException e)
{
log.error("invalid protected item definition #" + res.getId(), e);
}
}
|
diff --git a/src/org/odk/collect/android/tasks/FormLoaderTask.java b/src/org/odk/collect/android/tasks/FormLoaderTask.java
index b4ff37f..9b900be 100644
--- a/src/org/odk/collect/android/tasks/FormLoaderTask.java
+++ b/src/org/odk/collect/android/tasks/FormLoaderTask.java
@@ -1,393 +1,399 @@
/*
* Copyright (C) 2009 University of Washington
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.odk.collect.android.tasks;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.services.PrototypeManager;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.form.api.FormEntryController;
import org.javarosa.form.api.FormEntryModel;
import org.javarosa.xform.parse.XFormParseException;
import org.javarosa.xform.parse.XFormParser;
import org.javarosa.xform.util.XFormUtils;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.database.FileDbAdapter;
import org.odk.collect.android.listeners.FormLoaderListener;
import org.odk.collect.android.utilities.FileUtils;
import android.database.Cursor;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
/**
* Background task for loading a form.
*
* @author Carl Hartung ([email protected])
* @author Yaw Anokwa ([email protected])
*/
public class FormLoaderTask extends AsyncTask<String, String, FormLoaderTask.FECWrapper> {
private final static String t = "FormLoaderTask";
/**
* Classes needed to serialize objects. Need to put anything from JR in here.
*/
public final static String[] SERIALIABLE_CLASSES = {
"org.javarosa.core.model.FormDef", "org.javarosa.core.model.GroupDef",
"org.javarosa.core.model.QuestionDef", "org.javarosa.core.model.data.DateData",
"org.javarosa.core.model.data.DateTimeData",
"org.javarosa.core.model.data.DecimalData",
"org.javarosa.core.model.data.GeoPointData",
"org.javarosa.core.model.data.helper.BasicDataPointer",
"org.javarosa.core.model.data.IntegerData",
"org.javarosa.core.model.data.MultiPointerAnswerData",
"org.javarosa.core.model.data.PointerAnswerData",
"org.javarosa.core.model.data.SelectMultiData",
"org.javarosa.core.model.data.SelectOneData",
"org.javarosa.core.model.data.StringData", "org.javarosa.core.model.data.TimeData",
"org.javarosa.core.services.locale.TableLocaleSource",
"org.javarosa.xpath.expr.XPathArithExpr", "org.javarosa.xpath.expr.XPathBoolExpr",
"org.javarosa.xpath.expr.XPathCmpExpr", "org.javarosa.xpath.expr.XPathEqExpr",
"org.javarosa.xpath.expr.XPathFilterExpr", "org.javarosa.xpath.expr.XPathFuncExpr",
"org.javarosa.xpath.expr.XPathNumericLiteral",
"org.javarosa.xpath.expr.XPathNumNegExpr", "org.javarosa.xpath.expr.XPathPathExpr",
"org.javarosa.xpath.expr.XPathStringLiteral", "org.javarosa.xpath.expr.XPathUnionExpr",
"org.javarosa.xpath.expr.XPathVariableReference"
};
FormLoaderListener mStateListener;
String mErrorMsg;
protected class FECWrapper {
FormEntryController controller;
protected FECWrapper(FormEntryController controller) {
this.controller = controller;
}
protected FormEntryController getController() {
return controller;
}
protected void free() {
controller = null;
}
}
FECWrapper data;
/**
* Initialize {@link FormEntryController} with {@link FormDef} from binary or from XML. If given
* an instance, it will be used to fill the {@link FormDef}.
*/
@Override
protected FECWrapper doInBackground(String... path) {
FormEntryController fec = null;
FormDef fd = null;
FileInputStream fis = null;
String formPath = path[0];
String instancePath = path[1];
+ if ( formPath == null && instancePath != null ) {
+ String instanceName = (new File(instancePath)).getName();
+ this.publishProgress(Collect.getInstance().getString(R.string.load_error_no_form,
+ instanceName ));
+ return null;
+ }
File formXml = new File(formPath);
String formHash = FileUtils.getMd5Hash(formXml);
File formBin = new File(FileUtils.CACHE_PATH + formHash + ".formdef");
if (formBin.exists()) {
// if we have binary, deserialize binary
try {
Log.i(
t,
"Attempting to load " + formXml.getName() + " from cached file: "
+ formBin.getAbsolutePath());
fd = deserializeFormDef(formBin);
} catch ( Exception e ) {
// didn't load --
// the common case here is that the javarosa library that
// serialized the binary is incompatible with the javarosa
// library that is now attempting to deserialize it.
}
if (fd == null) {
// some error occured with deserialization. Remove the file, and make a new .formdef
// from xml
Log.w(t,
"Deserialization FAILED! Deleting cache file: " + formBin.getAbsolutePath());
formBin.delete();
}
}
if (fd == null) {
// no binary, read from xml
try {
Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
fis = new FileInputStream(formXml);
fd = XFormUtils.getFormFromInputStream(fis);
if (fd == null) {
mErrorMsg = "Error reading XForm file";
} else {
serializeFormDef(fd, formPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
mErrorMsg = e.getMessage();
} catch (XFormParseException e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} catch (Exception e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} finally {
if (fd == null) {
// remove cache reference from file db if it exists
FileDbAdapter fda = new FileDbAdapter();
fda.open();
if (fda.deleteFile(null, formHash)) {
Log.i(t, "Cached file: " + formBin.getAbsolutePath()
+ " removed from database");
} else {
Log.i(t, "Failed to remove cached file: " + formBin.getAbsolutePath()
+ " from database (might not have existed...)");
}
fda.close();
return null;
} else {
// add to file db if it doesn't already exist.
// MainMenu will add files that don't exist, but intents can load
// FormEntryActivity directly.
FileDbAdapter fda = new FileDbAdapter();
fda.open();
Cursor c = fda.fetchFilesByPath(null, formHash);
if (c.getCount() == 0) {
fda.createFile(formXml.getAbsolutePath(), FileDbAdapter.TYPE_FORM,
FileDbAdapter.STATUS_AVAILABLE);
}
if (c != null)
c.close();
fda.close();
}
}
}
// new evaluation context for function handlers
EvaluationContext ec = new EvaluationContext();
fd.setEvaluationContext(ec);
// create FormEntryController from formdef
FormEntryModel fem = new FormEntryModel(fd);
fec = new FormEntryController(fem);
try {
// import existing data into formdef
if (instancePath != null) {
// This order is important. Import data, then initialize.
importData(instancePath, fec);
fd.initialize(false);
} else {
fd.initialize(true);
}
} catch (Exception e) {
e.printStackTrace();
this.publishProgress(Collect.getInstance().getString(R.string.load_error,
formXml.getName()) + " : " + e.getMessage());
return null;
}
// set paths to FORMS_PATH + formfilename-media/
// This is a singleton, how do we ensure that we're not doing this
// multiple times?
String mediaPath = FileUtils.getFormMediaPath(formXml.getName());
Collect.getInstance().registerMediaPath(mediaPath);
// clean up vars
fis = null;
fd = null;
formBin = null;
formXml = null;
formPath = null;
instancePath = null;
data = new FECWrapper(fec);
return data;
}
public boolean importData(String filePath, FormEntryController fec) {
// convert files into a byte array
byte[] fileBytes = FileUtils.getFileAsBytes(new File(filePath));
// get the root of the saved and template instances
TreeElement savedRoot = XFormParser.restoreDataModel(fileBytes, null).getRoot();
TreeElement templateRoot = fec.getModel().getForm().getInstance().getRoot().deepCopy(true);
// weak check for matching forms
if (!savedRoot.getName().equals(templateRoot.getName()) || savedRoot.getMult() != 0) {
Log.e(t, "Saved form instance does not match template form definition");
return false;
} else {
// populate the data model
TreeReference tr = TreeReference.rootRef();
tr.add(templateRoot.getName(), TreeReference.INDEX_UNBOUND);
templateRoot.populate(savedRoot, fec.getModel().getForm());
// populated model to current form
fec.getModel().getForm().getInstance().setRoot(templateRoot);
// fix any language issues
// : http://bitbucket.org/javarosa/main/issue/5/itext-n-appearing-in-restored-instances
if (fec.getModel().getLanguages() != null) {
fec.getModel()
.getForm()
.localeChanged(fec.getModel().getLanguage(),
fec.getModel().getForm().getLocalizer());
}
return true;
}
}
/**
* Read serialized {@link FormDef} from file and recreate as object.
*
* @param formDef serialized FormDef file
* @return {@link FormDef} object
*/
public FormDef deserializeFormDef(File formDef) {
// TODO: any way to remove reliance on jrsp?
Log.i(t, "Attempting read of " + formDef.getAbsolutePath());
// need a list of classes that formdef uses
PrototypeManager.registerPrototypes(SERIALIABLE_CLASSES);
FileInputStream fis = null;
FormDef fd = null;
DataInputStream dis = null;
try {
// create new form def
fd = new FormDef();
fis = new FileInputStream(formDef);
dis = new DataInputStream(fis);
// read serialized formdef into new formdef
fd.readExternal(dis, ExtUtil.defaultPrototypes());
} catch (FileNotFoundException e) {
e.printStackTrace();
fd = null;
} catch (IOException e) {
e.printStackTrace();
fd = null;
} catch (DeserializationException e) {
e.printStackTrace();
fd = null;
} finally {
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
// ignore...
}
}
}
return fd;
}
/**
* Write the FormDef to the file system as a binary blog.
*
* @param filepath path to the form file
*/
public void serializeFormDef(FormDef fd, String filepath) {
// if cache folder is missing, create it.
if (FileUtils.createFolder(FileUtils.CACHE_PATH)) {
// calculate unique md5 identifier
String hash = FileUtils.getMd5Hash(new File(filepath));
File formDef = new File(FileUtils.CACHE_PATH + hash + ".formdef");
// formdef does not exist, create one.
if (!formDef.exists()) {
FileOutputStream fos;
try {
fos = new FileOutputStream(formDef);
DataOutputStream dos = new DataOutputStream(fos);
fd.writeExternal(dos);
dos.flush();
dos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onProgressUpdate(String... values) {
Toast.makeText(Collect.getInstance().getApplicationContext(),
values[0], Toast.LENGTH_LONG).show();
}
@Override
protected void onPostExecute(FECWrapper wrapper) {
synchronized (this) {
if (mStateListener != null) {
if (wrapper == null) {
mStateListener.loadingError(mErrorMsg);
} else {
mStateListener.loadingComplete(wrapper.getController());
}
}
}
}
public void setFormLoaderListener(FormLoaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
public void destroy() {
if (data != null) {
data.free();
data = null;
}
}
}
| true | true | protected FECWrapper doInBackground(String... path) {
FormEntryController fec = null;
FormDef fd = null;
FileInputStream fis = null;
String formPath = path[0];
String instancePath = path[1];
File formXml = new File(formPath);
String formHash = FileUtils.getMd5Hash(formXml);
File formBin = new File(FileUtils.CACHE_PATH + formHash + ".formdef");
if (formBin.exists()) {
// if we have binary, deserialize binary
try {
Log.i(
t,
"Attempting to load " + formXml.getName() + " from cached file: "
+ formBin.getAbsolutePath());
fd = deserializeFormDef(formBin);
} catch ( Exception e ) {
// didn't load --
// the common case here is that the javarosa library that
// serialized the binary is incompatible with the javarosa
// library that is now attempting to deserialize it.
}
if (fd == null) {
// some error occured with deserialization. Remove the file, and make a new .formdef
// from xml
Log.w(t,
"Deserialization FAILED! Deleting cache file: " + formBin.getAbsolutePath());
formBin.delete();
}
}
if (fd == null) {
// no binary, read from xml
try {
Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
fis = new FileInputStream(formXml);
fd = XFormUtils.getFormFromInputStream(fis);
if (fd == null) {
mErrorMsg = "Error reading XForm file";
} else {
serializeFormDef(fd, formPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
mErrorMsg = e.getMessage();
} catch (XFormParseException e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} catch (Exception e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} finally {
if (fd == null) {
// remove cache reference from file db if it exists
FileDbAdapter fda = new FileDbAdapter();
fda.open();
if (fda.deleteFile(null, formHash)) {
Log.i(t, "Cached file: " + formBin.getAbsolutePath()
+ " removed from database");
} else {
Log.i(t, "Failed to remove cached file: " + formBin.getAbsolutePath()
+ " from database (might not have existed...)");
}
fda.close();
return null;
} else {
// add to file db if it doesn't already exist.
// MainMenu will add files that don't exist, but intents can load
// FormEntryActivity directly.
FileDbAdapter fda = new FileDbAdapter();
fda.open();
Cursor c = fda.fetchFilesByPath(null, formHash);
if (c.getCount() == 0) {
fda.createFile(formXml.getAbsolutePath(), FileDbAdapter.TYPE_FORM,
FileDbAdapter.STATUS_AVAILABLE);
}
if (c != null)
c.close();
fda.close();
}
}
}
// new evaluation context for function handlers
EvaluationContext ec = new EvaluationContext();
fd.setEvaluationContext(ec);
// create FormEntryController from formdef
FormEntryModel fem = new FormEntryModel(fd);
fec = new FormEntryController(fem);
try {
// import existing data into formdef
if (instancePath != null) {
// This order is important. Import data, then initialize.
importData(instancePath, fec);
fd.initialize(false);
} else {
fd.initialize(true);
}
} catch (Exception e) {
e.printStackTrace();
this.publishProgress(Collect.getInstance().getString(R.string.load_error,
formXml.getName()) + " : " + e.getMessage());
return null;
}
// set paths to FORMS_PATH + formfilename-media/
// This is a singleton, how do we ensure that we're not doing this
// multiple times?
String mediaPath = FileUtils.getFormMediaPath(formXml.getName());
Collect.getInstance().registerMediaPath(mediaPath);
// clean up vars
fis = null;
fd = null;
formBin = null;
formXml = null;
formPath = null;
instancePath = null;
data = new FECWrapper(fec);
return data;
}
| protected FECWrapper doInBackground(String... path) {
FormEntryController fec = null;
FormDef fd = null;
FileInputStream fis = null;
String formPath = path[0];
String instancePath = path[1];
if ( formPath == null && instancePath != null ) {
String instanceName = (new File(instancePath)).getName();
this.publishProgress(Collect.getInstance().getString(R.string.load_error_no_form,
instanceName ));
return null;
}
File formXml = new File(formPath);
String formHash = FileUtils.getMd5Hash(formXml);
File formBin = new File(FileUtils.CACHE_PATH + formHash + ".formdef");
if (formBin.exists()) {
// if we have binary, deserialize binary
try {
Log.i(
t,
"Attempting to load " + formXml.getName() + " from cached file: "
+ formBin.getAbsolutePath());
fd = deserializeFormDef(formBin);
} catch ( Exception e ) {
// didn't load --
// the common case here is that the javarosa library that
// serialized the binary is incompatible with the javarosa
// library that is now attempting to deserialize it.
}
if (fd == null) {
// some error occured with deserialization. Remove the file, and make a new .formdef
// from xml
Log.w(t,
"Deserialization FAILED! Deleting cache file: " + formBin.getAbsolutePath());
formBin.delete();
}
}
if (fd == null) {
// no binary, read from xml
try {
Log.i(t, "Attempting to load from: " + formXml.getAbsolutePath());
fis = new FileInputStream(formXml);
fd = XFormUtils.getFormFromInputStream(fis);
if (fd == null) {
mErrorMsg = "Error reading XForm file";
} else {
serializeFormDef(fd, formPath);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
mErrorMsg = e.getMessage();
} catch (XFormParseException e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} catch (Exception e) {
mErrorMsg = e.getMessage();
e.printStackTrace();
} finally {
if (fd == null) {
// remove cache reference from file db if it exists
FileDbAdapter fda = new FileDbAdapter();
fda.open();
if (fda.deleteFile(null, formHash)) {
Log.i(t, "Cached file: " + formBin.getAbsolutePath()
+ " removed from database");
} else {
Log.i(t, "Failed to remove cached file: " + formBin.getAbsolutePath()
+ " from database (might not have existed...)");
}
fda.close();
return null;
} else {
// add to file db if it doesn't already exist.
// MainMenu will add files that don't exist, but intents can load
// FormEntryActivity directly.
FileDbAdapter fda = new FileDbAdapter();
fda.open();
Cursor c = fda.fetchFilesByPath(null, formHash);
if (c.getCount() == 0) {
fda.createFile(formXml.getAbsolutePath(), FileDbAdapter.TYPE_FORM,
FileDbAdapter.STATUS_AVAILABLE);
}
if (c != null)
c.close();
fda.close();
}
}
}
// new evaluation context for function handlers
EvaluationContext ec = new EvaluationContext();
fd.setEvaluationContext(ec);
// create FormEntryController from formdef
FormEntryModel fem = new FormEntryModel(fd);
fec = new FormEntryController(fem);
try {
// import existing data into formdef
if (instancePath != null) {
// This order is important. Import data, then initialize.
importData(instancePath, fec);
fd.initialize(false);
} else {
fd.initialize(true);
}
} catch (Exception e) {
e.printStackTrace();
this.publishProgress(Collect.getInstance().getString(R.string.load_error,
formXml.getName()) + " : " + e.getMessage());
return null;
}
// set paths to FORMS_PATH + formfilename-media/
// This is a singleton, how do we ensure that we're not doing this
// multiple times?
String mediaPath = FileUtils.getFormMediaPath(formXml.getName());
Collect.getInstance().registerMediaPath(mediaPath);
// clean up vars
fis = null;
fd = null;
formBin = null;
formXml = null;
formPath = null;
instancePath = null;
data = new FECWrapper(fec);
return data;
}
|
diff --git a/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java b/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java
index 455a38dd1..9e34fa160 100644
--- a/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java
+++ b/core/src/main/java/hudson/maven/reporters/MavenArtifactArchiver.java
@@ -1,151 +1,151 @@
package hudson.maven.reporters;
import hudson.maven.MavenBuildProxy;
import hudson.maven.MavenModule;
import hudson.maven.MavenReporter;
import hudson.maven.MavenReporterDescriptor;
import hudson.maven.MojoInfo;
import hudson.maven.MavenBuild;
import hudson.model.BuildListener;
import hudson.util.InvocationInterceptor;
import hudson.FilePath;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.installer.ArtifactInstallationException;
import org.apache.maven.project.MavenProject;
import java.io.IOException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.lang.reflect.Proxy;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;
/**
* 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 {
/**
* Accumulates {@link File}s that are created from assembly plugins.
* Note that some of them might be attached.
*/
private transient List<File> assemblies;
@Override
public boolean preBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException {
// System.out.println("Zeroing out at "+MavenArtifactArchiver.this);
assemblies = new ArrayList<File>();
return true;
}
@Override
public boolean preExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException {
if(mojo.is("org.apache.maven.plugins","maven-assembly-plugin","assembly")) {
try {
// watch out for AssemblyArchiver.createArchive that returns a File object, pointing to the archives created by the assembly plugin.
mojo.intercept("assemblyArchiver",new InvocationInterceptor() {
public Object invoke(Object proxy, Method method, Object[] args, InvocationHandler delegate) throws Throwable {
Object ret = delegate.invoke(proxy, method, args);
if(method.getName().equals("createArchive") && method.getReturnType()==File.class) {
// System.out.println("Discovered "+ret+" at "+MavenArtifactArchiver.this);
assemblies.add((File)ret);
}
return ret;
}
});
} catch (NoSuchFieldException e) {
listener.getLogger().println("[HUDSON] Failed to monitor the execution of the assembly plugin: "+e.getMessage());
}
}
return true;
}
public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException {
// artifacts that are known to Maven.
Set<File> mavenArtifacts = new HashSet<File>();
if(pom.getFile()!=null) {// goals like 'clean' runs without loading POM, apparently.
// record POM
final MavenArtifact pomArtifact = new MavenArtifact(
pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), null, "pom", pom.getFile().getName());
mavenArtifacts.add(pom.getFile());
pomArtifact.archive(build,pom.getFile(),listener);
// record main artifact (if packaging is POM, this doesn't exist)
final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact());
if(mainArtifact!=null) {
File f = pom.getArtifact().getFile();
mavenArtifacts.add(f);
mainArtifact.archive(build, f,listener);
}
// record attached artifacts
final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>();
for( Artifact a : (List<Artifact>)pom.getAttachedArtifacts() ) {
MavenArtifact ma = MavenArtifact.create(a);
if(ma!=null) {
mavenArtifacts.add(a.getFile());
ma.archive(build,a.getFile(),listener);
attachedArtifacts.add(ma);
}
}
// record the action
build.executeAsync(new MavenBuildProxy.BuildCallable<Void,IOException>() {
public Void call(MavenBuild build) throws IOException, InterruptedException {
MavenArtifactRecord mar = new MavenArtifactRecord(build,pomArtifact,mainArtifact,attachedArtifacts);
build.addAction(mar);
mar.recordFingerprints();
return null;
}
});
}
// do we have any assembly artifacts?
// System.out.println("Considering "+assemblies+" at "+MavenArtifactArchiver.this);
- new Exception().fillInStackTrace().printStackTrace();
+// new Exception().fillInStackTrace().printStackTrace();
for (File assembly : assemblies) {
if(mavenArtifacts.contains(assembly))
continue; // looks like this is already archived
FilePath target = build.getArtifactsDir().child(assembly.getName());
listener.getLogger().println("[HUDSON] Archiving "+ assembly+" to "+target);
new FilePath(assembly).copyTo(target);
// TODO: fingerprint
}
return true;
}
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 Messages.MavenArtifactArchiver_DisplayName();
}
public MavenReporter newAutoInstance(MavenModule module) {
return new MavenArtifactArchiver();
}
}
private static final long serialVersionUID = 1L;
}
| true | true | public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException {
// artifacts that are known to Maven.
Set<File> mavenArtifacts = new HashSet<File>();
if(pom.getFile()!=null) {// goals like 'clean' runs without loading POM, apparently.
// record POM
final MavenArtifact pomArtifact = new MavenArtifact(
pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), null, "pom", pom.getFile().getName());
mavenArtifacts.add(pom.getFile());
pomArtifact.archive(build,pom.getFile(),listener);
// record main artifact (if packaging is POM, this doesn't exist)
final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact());
if(mainArtifact!=null) {
File f = pom.getArtifact().getFile();
mavenArtifacts.add(f);
mainArtifact.archive(build, f,listener);
}
// record attached artifacts
final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>();
for( Artifact a : (List<Artifact>)pom.getAttachedArtifacts() ) {
MavenArtifact ma = MavenArtifact.create(a);
if(ma!=null) {
mavenArtifacts.add(a.getFile());
ma.archive(build,a.getFile(),listener);
attachedArtifacts.add(ma);
}
}
// record the action
build.executeAsync(new MavenBuildProxy.BuildCallable<Void,IOException>() {
public Void call(MavenBuild build) throws IOException, InterruptedException {
MavenArtifactRecord mar = new MavenArtifactRecord(build,pomArtifact,mainArtifact,attachedArtifacts);
build.addAction(mar);
mar.recordFingerprints();
return null;
}
});
}
// do we have any assembly artifacts?
// System.out.println("Considering "+assemblies+" at "+MavenArtifactArchiver.this);
new Exception().fillInStackTrace().printStackTrace();
for (File assembly : assemblies) {
if(mavenArtifacts.contains(assembly))
continue; // looks like this is already archived
FilePath target = build.getArtifactsDir().child(assembly.getName());
listener.getLogger().println("[HUDSON] Archiving "+ assembly+" to "+target);
new FilePath(assembly).copyTo(target);
// TODO: fingerprint
}
return true;
}
| public boolean postBuild(MavenBuildProxy build, MavenProject pom, final BuildListener listener) throws InterruptedException, IOException {
// artifacts that are known to Maven.
Set<File> mavenArtifacts = new HashSet<File>();
if(pom.getFile()!=null) {// goals like 'clean' runs without loading POM, apparently.
// record POM
final MavenArtifact pomArtifact = new MavenArtifact(
pom.getGroupId(), pom.getArtifactId(), pom.getVersion(), null, "pom", pom.getFile().getName());
mavenArtifacts.add(pom.getFile());
pomArtifact.archive(build,pom.getFile(),listener);
// record main artifact (if packaging is POM, this doesn't exist)
final MavenArtifact mainArtifact = MavenArtifact.create(pom.getArtifact());
if(mainArtifact!=null) {
File f = pom.getArtifact().getFile();
mavenArtifacts.add(f);
mainArtifact.archive(build, f,listener);
}
// record attached artifacts
final List<MavenArtifact> attachedArtifacts = new ArrayList<MavenArtifact>();
for( Artifact a : (List<Artifact>)pom.getAttachedArtifacts() ) {
MavenArtifact ma = MavenArtifact.create(a);
if(ma!=null) {
mavenArtifacts.add(a.getFile());
ma.archive(build,a.getFile(),listener);
attachedArtifacts.add(ma);
}
}
// record the action
build.executeAsync(new MavenBuildProxy.BuildCallable<Void,IOException>() {
public Void call(MavenBuild build) throws IOException, InterruptedException {
MavenArtifactRecord mar = new MavenArtifactRecord(build,pomArtifact,mainArtifact,attachedArtifacts);
build.addAction(mar);
mar.recordFingerprints();
return null;
}
});
}
// do we have any assembly artifacts?
// System.out.println("Considering "+assemblies+" at "+MavenArtifactArchiver.this);
// new Exception().fillInStackTrace().printStackTrace();
for (File assembly : assemblies) {
if(mavenArtifacts.contains(assembly))
continue; // looks like this is already archived
FilePath target = build.getArtifactsDir().child(assembly.getName());
listener.getLogger().println("[HUDSON] Archiving "+ assembly+" to "+target);
new FilePath(assembly).copyTo(target);
// TODO: fingerprint
}
return true;
}
|
diff --git a/src/test/java/sstTest/ShipTests.java b/src/test/java/sstTest/ShipTests.java
index afa17be..e529060 100644
--- a/src/test/java/sstTest/ShipTests.java
+++ b/src/test/java/sstTest/ShipTests.java
@@ -1,172 +1,172 @@
package sstTest;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import sst.ShieldControl;
import sst.Ship;
import sst.SubSystem;
public class ShipTests {
HashMap<String, SubSystem> mapOfSubSystems;
@Before
public void initializeSubSystems() {
mapOfSubSystems = new HashMap<String, SubSystem>();
mapOfSubSystems.put("Weapons", new SubSystem(2000, 200));
mapOfSubSystems.put("Engine", new SubSystem(1500, 100));
mapOfSubSystems.put("LifeSupport", new SubSystem(1000, 100));
mapOfSubSystems.put("ShieldControl", new ShieldControl(0));
}
@Test
public void ShipConstruction() {
String registration = "NCC-1701";
Ship ship = new Ship(registration, mapOfSubSystems);
Assert.assertEquals(registration, ship.getRegistration());
}
@Test
public void ShieldsAtStart() {
Ship ship = new Ship("NCC-1701", mapOfSubSystems);
Assert.assertEquals(0, ship.getShieldLevel());
}
@Test
public void TransferEnergyToShields() {
Ship ship = new Ship("NCC-1701", mapOfSubSystems);
ship.transferEnergyToShields(1000);
Assert.assertEquals(1000, ship.getShieldLevel());
}
@Test
public void ShipEnergyAtStart() {
Ship ship = new Ship("NCC-1701", mapOfSubSystems);
Assert.assertEquals(50000, ship.getEnergyLevel());
}
@Test
public void TransferEnergyFromShipToShields() {
Ship ship = new Ship("NCC-1701", 10000, mapOfSubSystems);
ship.transferEnergyToShields(1000);
Assert.assertEquals(1000, ship.getShieldLevel());
Assert.assertEquals(9000, ship.getEnergyLevel());
}
@Test
public void TransferMoreEnergyThanShieldsCanTake() {
Ship ship = new Ship("NCC-1701", 20000, mapOfSubSystems);
ship.transferEnergyToShields(9500);
ship.transferEnergyToShields(1000);
Assert.assertEquals(10000, ship.getShieldLevel());
Assert.assertEquals(10000, ship.getEnergyLevel());
}
@Test
public void TakeDamage() {
Ship ship = new Ship("NCC-1701", mapOfSubSystems);
ship.transferEnergyToShields(10000);
int damage = 1000;
ship.takeDamage(damage);
Assert.assertEquals(9000, ship.getShieldLevel());
}
@Test
public void TransferEnergyYouDoNotHave() {
Ship ship = new Ship("NCC-1701", 1000, mapOfSubSystems);
int deficitEnergy = ship.transferEnergyToShields(2000);
Assert.assertEquals(1000, ship.getShieldLevel());
Assert.assertEquals(-1000, deficitEnergy);
}
@Test
public void TransferExtraEnergy() {
Ship ship = new Ship("NCC-1701", 20000, mapOfSubSystems);
int extraEnergy = ship.transferEnergyToShields(20000);
Assert.assertEquals(10000, ship.getShieldLevel());
Assert.assertEquals(10000, extraEnergy);
}
@Test
public void CreateShipWithInitialEnergy() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
int shipEnergy = ship.getEnergyLevel();
Assert.assertEquals(2000, shipEnergy);
}
@Test
public void pickRandomSubSystemWithOneSubSystem() {
HashMap<String, SubSystem> mapOfSubSystems = new HashMap<String, SubSystem>();
SubSystem engine = new SubSystem(1500, 100);
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
mapOfSubSystems.put("Engine", engine);
Assert.assertSame("Engine should be returned", engine, ship.pickRandomSubSystem());
}
public void pickRandomSubSystemWithMultipleSubSystems() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
SubSystem engine = mapOfSubSystems.get("Engine");
Ship.generator = new MockRandom();
Assert.assertSame("Engine should be returned", engine, ship.pickRandomSubSystem());
}
@Test
public void DamageSubSystem() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
ship.takeDamage(200);
boolean subSystemIsDamaged = ship.isSubSystemDamaged();
Assert.assertEquals(true, subSystemIsDamaged);
}
@Test
public void RestShipToRepairCompletely() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
ship.takeDamage(1000);
ship.rest(50);
Assert.assertEquals(false, ship.isSubSystemDamaged());
}
@Test
public void RestShipToRepairPartially() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
ship.takeDamage(10000);
ship.rest(10);
Assert.assertEquals(true, ship.isSubSystemDamaged());
}
@Test
public void DockingWithNoStarbaseNearby() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
boolean docked = ship.dock(false);
Assert.assertEquals(false, docked);
}
@Test
public void DockingWithStarbase() {
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
boolean docked = ship.dock(true);
Assert.assertEquals(true, docked);
}
@Test
public void RepairWhileDocked() {
mapOfSubSystems = new HashMap<String, SubSystem>();
- mapOfSubSystems.put("Weapons", new SubSystem(1000, 200));
+ mapOfSubSystems.put("ShieldControl", new ShieldControl(0));
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
- ship.takeDamage(2000);
+ ship.takeDamage(1000);
ship.dock(true);
- ship.rest(10);
+ ship.rest(20);
Assert.assertEquals(false, ship.isSubSystemDamaged());
}
}
| false | true | public void RepairWhileDocked() {
mapOfSubSystems = new HashMap<String, SubSystem>();
mapOfSubSystems.put("Weapons", new SubSystem(1000, 200));
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
ship.takeDamage(2000);
ship.dock(true);
ship.rest(10);
Assert.assertEquals(false, ship.isSubSystemDamaged());
}
| public void RepairWhileDocked() {
mapOfSubSystems = new HashMap<String, SubSystem>();
mapOfSubSystems.put("ShieldControl", new ShieldControl(0));
Ship ship = new Ship("NCC-1701", 2000, mapOfSubSystems);
ship.takeDamage(1000);
ship.dock(true);
ship.rest(20);
Assert.assertEquals(false, ship.isSubSystemDamaged());
}
|
diff --git a/src/main/java/org/apache/maven/archiva/meeper/Synchronizer.java b/src/main/java/org/apache/maven/archiva/meeper/Synchronizer.java
index 860f28f..c439924 100644
--- a/src/main/java/org/apache/maven/archiva/meeper/Synchronizer.java
+++ b/src/main/java/org/apache/maven/archiva/meeper/Synchronizer.java
@@ -1,290 +1,291 @@
package org.apache.maven.archiva.meeper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
/**
* exclusions=$HOME/bin/synchronize/syncopate/exclusions.txt BASEDIR=$HOME/repository-staging/to-ibiblio/maven2
* CHANGED_LOG=/tmp/sync-changed.log
*/
public class Synchronizer
{
private static final String RSYNC = "rsync";
private static final String SVN = "svn";
private static final String DRY_RUN = "-n";
private SynchronizerOptions options;
private List failedRepositories = new ArrayList();
public Synchronizer( SynchronizerOptions options )
{
this.options = options;
}
public void sync( List repositories )
{
int i = 1;
Iterator it = repositories.iterator();
while ( it.hasNext() )
{
SyncedRepository repo = (SyncedRepository) it.next();
try
{
System.out.println( "[" + ( i++ ) + " of " + repositories.size() + "] Synchronizing " +
repo.getGroupId() + " " + repo.getLocation() );
sync( repo );
}
catch ( RuntimeException e )
{
System.out.println( "Error synchronizing repository " + repo.getGroupId() + ". " + e.getMessage() );
failedRepositories.add( repo );
Throwable cause = e;
while ( cause != null )
{
repo.getErr().append( cause.getMessage() );
cause = cause.getCause();
}
}
}
}
public void sync( SyncedRepository repo )
{
/* update from svn if necessary */
if ( SyncedRepository.PROTOCOL_SVN.equals( repo.getProtocol() ) )
{
Commandline cl = new Commandline();
cl.setExecutable( SVN );
cl.createArg().setValue( "update" );
cl.createArg().setValue( appendGroupFolder( repo, repo.getLocation() ) );
int exitCode = executeCommandLine( cl, repo );
if ( exitCode != 0 )
{
throw new RuntimeException( "Error updating from SVN. Exit code: " + exitCode );
}
}
int exitCode = syncMetadata( repo );
if ( exitCode != 0 )
{
throw new RuntimeException( "Error synchronizing metadata. Exit code: " + exitCode );
}
exitCode = syncArtifacts( repo );
if ( exitCode != 0 )
{
throw new RuntimeException( "Error synchronizing artifacts. Exit code: " + exitCode );
}
}
private int syncMetadata( SyncedRepository repo )
{
Commandline cl = new Commandline();
cl.setExecutable( RSYNC );
cl.createArg().setValue( "--include=*/" );
cl.createArg().setValue( "--include=**/maven-metadata.xml*" );
cl.createArg().setValue( "--exclude=*" );
cl.createArg().setValue( "--exclude-from=" + options.getExclusionsFile() );
addCommonArguments( cl, repo );
return executeCommandLine( cl, repo );
}
private int syncArtifacts( SyncedRepository repo )
{
Commandline cl = new Commandline();
cl.setExecutable( RSYNC );
cl.createArg().setValue( "--exclude-from=" + options.getExclusionsFile() );
cl.createArg().setValue( "--ignore-existing" );
addCommonArguments( cl, repo );
return executeCommandLine( cl, repo );
}
private void addCommonArguments( Commandline cl, SyncedRepository repo )
{
if ( options.isDryRun() )
{
cl.createArg().setValue( DRY_RUN );
}
// cl.createArg().setValue("$RSYNC_OPTS");
cl.createArg().setValue( "-Lrtivz" );
if ( SyncedRepository.PROTOCOL_SSH.equals( repo.getProtocol() ) )
{
String s = repo.getSshOptions() == null ? "" : repo.getSshOptions();
cl.createArg().setValue( "--rsh=ssh " + s );
}
cl.createArg().setValue( appendGroupFolder( repo, repo.getLocation() ) );
String destinationFolder = appendGroupFolder( repo, options.getBasedir() );
( new File( destinationFolder ) ).mkdirs();
cl.createArg().setValue( destinationFolder );
}
private String appendGroupFolder( SyncedRepository repo, String location )
{
String groupDir = "";
if ( repo.getGroupId() != null )
{
groupDir = repo.getGroupId().replaceAll( "\\.", "\\/" ) + "/";
}
return location + "/" + groupDir;
}
private int executeCommandLine( Commandline cl, SyncedRepository repo )
{
CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();
CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
// System.out.println( "About to execute " + cl );
repo.setCommandline(cl);
int exitCode;
try
{
exitCode = CommandLineUtils.executeCommandLine( cl, out, err, options.getTimeout() * 60 );
}
catch ( CommandLineException e )
{
throw new RuntimeException( e );
}
repo.getOut().append( out.getOutput() );
String serr = err.getOutput();
if ( ( serr != null ) && serr.length() > 0 )
{
repo.getErr().append( serr );
}
return exitCode;
}
public static void main( String[] args )
{
if ( ( args.length != 2 ) && ( args.length != 3 ) )
{
System.out.println( "Arguments required: CONFIG_PROPERTIES_FILE REPOSITORIES_FILE [go]" );
return;
}
int i = 0;
SynchronizerOptions options = SynchronizerOptions.parse( new File( args[i++] ) );
Synchronizer synchronizer = new Synchronizer( options );
FileInputStream is = null;
try
{
is = new FileInputStream( new File( args[i++] ) );
}
catch ( FileNotFoundException e )
{
System.err.println( "Repositories file " + args[i - 1] + " is not present" );
}
List repositories;
try
{
repositories = new CsvReader().parse( is );
}
catch ( IOException e )
{
+ synchronizer.sendEmail( synchronizer.failedRepositories, "ERROR", e.getMessage() );
throw new RuntimeException( e );
}
finally
{
IOUtil.close( is );
}
if ( args.length == 3 )
{
String go = args[i++];
if ( ( go != null ) && ( "go".equals( go ) ) )
{
options.setDryRun( false );
}
}
synchronizer.sync( repositories );
if ( synchronizer.failedRepositories.isEmpty() )
{
synchronizer.sendEmail( Collections.EMPTY_LIST, "SUCCESS",
"--- All repositories synchronized successfully ---" );
}
else
{
StringBuffer sb = new StringBuffer();
sb.append( "--- Some repositories were not synchronized ---" );
sb.append( "\n" );
Iterator it = synchronizer.failedRepositories.iterator();
while ( it.hasNext() )
{
SyncedRepository repo = (SyncedRepository) it.next();
sb.append( "groupId: " );
sb.append( repo.getGroupId() );
sb.append( "\nError:\n" );
sb.append( repo.getErr() );
sb.append( "\n" );
sb.append( "Command line executed: " );
sb.append( repo.getCommandline() );
sb.append( "\n" );
sb.append( "\n" );
}
synchronizer.sendEmail( synchronizer.failedRepositories, "FAILURE", sb.toString() );
}
}
/**
* send email out
*/
private void sendEmail( List failedRepos, String subject, String text )
{
SimpleEmail email = new SimpleEmail();
email.setHostName( options.getMailHostname() );
try
{
email.addTo( options.getMailTo() );
Iterator it = failedRepos.iterator();
while ( it.hasNext() )
{
SyncedRepository repo = (SyncedRepository) it.next();
if ( repo.getContactMail() != null )
{
email.addTo( repo.getContactMail(), repo.getContactName() );
}
}
email.setFrom( options.getMailFrom() );
email.setSubject( options.getMailSubject() + " " + subject );
email.setMsg( text + options.getMailFooter() );
email.send();
}
catch ( EmailException e )
{
throw new RuntimeException( e );
}
}
}
| true | true | public static void main( String[] args )
{
if ( ( args.length != 2 ) && ( args.length != 3 ) )
{
System.out.println( "Arguments required: CONFIG_PROPERTIES_FILE REPOSITORIES_FILE [go]" );
return;
}
int i = 0;
SynchronizerOptions options = SynchronizerOptions.parse( new File( args[i++] ) );
Synchronizer synchronizer = new Synchronizer( options );
FileInputStream is = null;
try
{
is = new FileInputStream( new File( args[i++] ) );
}
catch ( FileNotFoundException e )
{
System.err.println( "Repositories file " + args[i - 1] + " is not present" );
}
List repositories;
try
{
repositories = new CsvReader().parse( is );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
IOUtil.close( is );
}
if ( args.length == 3 )
{
String go = args[i++];
if ( ( go != null ) && ( "go".equals( go ) ) )
{
options.setDryRun( false );
}
}
synchronizer.sync( repositories );
if ( synchronizer.failedRepositories.isEmpty() )
{
synchronizer.sendEmail( Collections.EMPTY_LIST, "SUCCESS",
"--- All repositories synchronized successfully ---" );
}
else
{
StringBuffer sb = new StringBuffer();
sb.append( "--- Some repositories were not synchronized ---" );
sb.append( "\n" );
Iterator it = synchronizer.failedRepositories.iterator();
while ( it.hasNext() )
{
SyncedRepository repo = (SyncedRepository) it.next();
sb.append( "groupId: " );
sb.append( repo.getGroupId() );
sb.append( "\nError:\n" );
sb.append( repo.getErr() );
sb.append( "\n" );
sb.append( "Command line executed: " );
sb.append( repo.getCommandline() );
sb.append( "\n" );
sb.append( "\n" );
}
synchronizer.sendEmail( synchronizer.failedRepositories, "FAILURE", sb.toString() );
}
}
| public static void main( String[] args )
{
if ( ( args.length != 2 ) && ( args.length != 3 ) )
{
System.out.println( "Arguments required: CONFIG_PROPERTIES_FILE REPOSITORIES_FILE [go]" );
return;
}
int i = 0;
SynchronizerOptions options = SynchronizerOptions.parse( new File( args[i++] ) );
Synchronizer synchronizer = new Synchronizer( options );
FileInputStream is = null;
try
{
is = new FileInputStream( new File( args[i++] ) );
}
catch ( FileNotFoundException e )
{
System.err.println( "Repositories file " + args[i - 1] + " is not present" );
}
List repositories;
try
{
repositories = new CsvReader().parse( is );
}
catch ( IOException e )
{
synchronizer.sendEmail( synchronizer.failedRepositories, "ERROR", e.getMessage() );
throw new RuntimeException( e );
}
finally
{
IOUtil.close( is );
}
if ( args.length == 3 )
{
String go = args[i++];
if ( ( go != null ) && ( "go".equals( go ) ) )
{
options.setDryRun( false );
}
}
synchronizer.sync( repositories );
if ( synchronizer.failedRepositories.isEmpty() )
{
synchronizer.sendEmail( Collections.EMPTY_LIST, "SUCCESS",
"--- All repositories synchronized successfully ---" );
}
else
{
StringBuffer sb = new StringBuffer();
sb.append( "--- Some repositories were not synchronized ---" );
sb.append( "\n" );
Iterator it = synchronizer.failedRepositories.iterator();
while ( it.hasNext() )
{
SyncedRepository repo = (SyncedRepository) it.next();
sb.append( "groupId: " );
sb.append( repo.getGroupId() );
sb.append( "\nError:\n" );
sb.append( repo.getErr() );
sb.append( "\n" );
sb.append( "Command line executed: " );
sb.append( repo.getCommandline() );
sb.append( "\n" );
sb.append( "\n" );
}
synchronizer.sendEmail( synchronizer.failedRepositories, "FAILURE", sb.toString() );
}
}
|
diff --git a/src/me/libraryaddict/Hungergames/Commands/Me.java b/src/me/libraryaddict/Hungergames/Commands/Me.java
index bc8422e..fcbb345 100644
--- a/src/me/libraryaddict/Hungergames/Commands/Me.java
+++ b/src/me/libraryaddict/Hungergames/Commands/Me.java
@@ -1,31 +1,35 @@
package me.libraryaddict.Hungergames.Commands;
import me.libraryaddict.Hungergames.Configs.TranslationConfig;
import me.libraryaddict.Hungergames.Managers.ConfigManager;
import me.libraryaddict.Hungergames.Managers.PlayerManager;
import me.libraryaddict.Hungergames.Types.HungergamesApi;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Me implements CommandExecutor {
private ConfigManager config = HungergamesApi.getConfigManager();
public String description = "Act out a message";
private PlayerManager pm = HungergamesApi.getPlayerManager();
private TranslationConfig tm = HungergamesApi.getConfigManager().getTranslationsConfig();
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (config.getMainConfig().isSpectatorsChatHidden() && pm.getGamer((Player) sender).isSpectator()) {
sender.sendMessage(tm.getCommandMeSpectating());
return true;
}
- Bukkit.broadcastMessage("* " + ((Player) sender).getDisplayName() + ChatColor.RESET + " " + StringUtils.join(args, " "));
- return true;
+ if (args.length == 0) {
+ return false;
+ } else {
+ Bukkit.broadcastMessage("* " + ((Player) sender).getDisplayName() + ChatColor.RESET + " " + StringUtils.join(args, " "));
+ return true;
+ }
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (config.getMainConfig().isSpectatorsChatHidden() && pm.getGamer((Player) sender).isSpectator()) {
sender.sendMessage(tm.getCommandMeSpectating());
return true;
}
Bukkit.broadcastMessage("* " + ((Player) sender).getDisplayName() + ChatColor.RESET + " " + StringUtils.join(args, " "));
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (config.getMainConfig().isSpectatorsChatHidden() && pm.getGamer((Player) sender).isSpectator()) {
sender.sendMessage(tm.getCommandMeSpectating());
return true;
}
if (args.length == 0) {
return false;
} else {
Bukkit.broadcastMessage("* " + ((Player) sender).getDisplayName() + ChatColor.RESET + " " + StringUtils.join(args, " "));
return true;
}
}
|
diff --git a/Aufgabe02/src/main_Aufgabe02.java b/Aufgabe02/src/main_Aufgabe02.java
index dd88226..a671db6 100644
--- a/Aufgabe02/src/main_Aufgabe02.java
+++ b/Aufgabe02/src/main_Aufgabe02.java
@@ -1,101 +1,100 @@
import java.io.*;
import java.util.regex.*;
public class main_Aufgabe02 {
/**
* Wiederholen bis input negative Zahl {
* input prozent
* |
* + wenn < 10000 -> 0%
* + wenn 10000 bis 39999 -> 2%
* + wenn 40000 bis 99999 -> 5%
* + wenn >= 100000 -> 8%
*
* resultat = input * prozent / 100
* }
*/
public static void main(String[] args) {
System.out.println("Aufgabe 02");
double dblIncome = -1;
double dblResult = 0;
String strInput = "";
boolean quit = false;
do {
System.out.println("\nBitte Einkommen eingeben: ");
strInput = readInput();
if (Pattern.matches("[0-9]+[.]{0,1}[0-9]*", strInput)) {
try { // convert String to double
dblIncome = Double.valueOf(strInput);
} catch (NumberFormatException e) {
} // error handling
int intPercent = taxPercent(dblIncome);
System.out.println("Steuernsatz: " + intPercent + "%");
// calculate the tax according to the percentage
if (intPercent > 0) {
dblResult = dblIncome * intPercent / 100;
System.out.println("Steuern zu zahlen: " + dblResult);
} else {
System.out.println("Keine Steuern zu zahlen");
}
} else {
dblResult = 0;
if (Pattern.matches("[-q]+[0-9]*", strInput)) {
quit = true;
} else {
System.out.println("Bitte eine positive Zahl eingeben.");
- System.out
- .println("Negative Zahl oder 'q' um Programm zu beenden.");
+ System.out.println("Negative Zahl oder 'q' eingeben, um Programm zu beenden.");
}
}
} while (!quit);
System.out.println("Auf wiedersehen.");
}
// Gets the percentage of the tax
private static int taxPercent(double dblIncome) {
int intPercent = 0;
if (dblIncome >= 0 && dblIncome < 10000) {
intPercent = 0;
} else if (dblIncome >= 10000 && dblIncome < 40000) {
intPercent = 2;
} else if (dblIncome >= 40000 && dblIncome < 100000) {
intPercent = 5;
} else if (dblIncome >= 100000) {
intPercent = 8;
} else {
intPercent = -1;
}
return intPercent;
}
// Reads from standard Input.
private static String readInput() {
String strInput;
// Creating a BufferReader from standard input.
BufferedReader buffRead = new BufferedReader(new InputStreamReader(
System.in));
// Read input
try {
strInput = buffRead.readLine();
} catch (IOException e) {
strInput = "";
}
return strInput;
}
}
| true | true | public static void main(String[] args) {
System.out.println("Aufgabe 02");
double dblIncome = -1;
double dblResult = 0;
String strInput = "";
boolean quit = false;
do {
System.out.println("\nBitte Einkommen eingeben: ");
strInput = readInput();
if (Pattern.matches("[0-9]+[.]{0,1}[0-9]*", strInput)) {
try { // convert String to double
dblIncome = Double.valueOf(strInput);
} catch (NumberFormatException e) {
} // error handling
int intPercent = taxPercent(dblIncome);
System.out.println("Steuernsatz: " + intPercent + "%");
// calculate the tax according to the percentage
if (intPercent > 0) {
dblResult = dblIncome * intPercent / 100;
System.out.println("Steuern zu zahlen: " + dblResult);
} else {
System.out.println("Keine Steuern zu zahlen");
}
} else {
dblResult = 0;
if (Pattern.matches("[-q]+[0-9]*", strInput)) {
quit = true;
} else {
System.out.println("Bitte eine positive Zahl eingeben.");
System.out
.println("Negative Zahl oder 'q' um Programm zu beenden.");
}
}
} while (!quit);
System.out.println("Auf wiedersehen.");
}
| public static void main(String[] args) {
System.out.println("Aufgabe 02");
double dblIncome = -1;
double dblResult = 0;
String strInput = "";
boolean quit = false;
do {
System.out.println("\nBitte Einkommen eingeben: ");
strInput = readInput();
if (Pattern.matches("[0-9]+[.]{0,1}[0-9]*", strInput)) {
try { // convert String to double
dblIncome = Double.valueOf(strInput);
} catch (NumberFormatException e) {
} // error handling
int intPercent = taxPercent(dblIncome);
System.out.println("Steuernsatz: " + intPercent + "%");
// calculate the tax according to the percentage
if (intPercent > 0) {
dblResult = dblIncome * intPercent / 100;
System.out.println("Steuern zu zahlen: " + dblResult);
} else {
System.out.println("Keine Steuern zu zahlen");
}
} else {
dblResult = 0;
if (Pattern.matches("[-q]+[0-9]*", strInput)) {
quit = true;
} else {
System.out.println("Bitte eine positive Zahl eingeben.");
System.out.println("Negative Zahl oder 'q' eingeben, um Programm zu beenden.");
}
}
} while (!quit);
System.out.println("Auf wiedersehen.");
}
|
diff --git a/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/TypeImpl.java b/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/TypeImpl.java
index 1f6f7c137..fb71fd08f 100644
--- a/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/TypeImpl.java
+++ b/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/TypeImpl.java
@@ -1,381 +1,379 @@
package org.eclipse.jdi.internal;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import com.sun.jdi.*;
import com.sun.jdi.connect.*;
import com.sun.jdi.event.*;
import com.sun.jdi.request.*;
import org.eclipse.jdi.internal.connect.*;
import org.eclipse.jdi.internal.request.*;
import org.eclipse.jdi.internal.event.*;
import org.eclipse.jdi.internal.jdwp.*;
import org.eclipse.jdi.internal.spy.*;
import java.util.*;
import java.io.*;
/**
* this class implements the corresponding interfaces
* declared by the JDI specification. See the com.sun.jdi package
* for more information.
*
*/
public abstract class TypeImpl extends AccessibleImpl implements Type {
/** Text representation of this type. */
protected String fName = null;
/** JNI-style signature for this type. */
protected String fSignature = null;
/**
* Creates new instance, used for REFERENCE types.
*/
protected TypeImpl(String description, VirtualMachineImpl vmImpl) {
super(description, vmImpl);
}
/**
* Creates new instance, used for PRIMITIVE types or VOID.
*/
protected TypeImpl(String description, VirtualMachineImpl vmImpl, String name, String signature) {
super(description, vmImpl);
setName(name);
setSignature(signature);
}
/**
* @return Returns new instance based on signature and (if it is a ReferenceType) classLoader.
* @throws ClassNotLoadedException when type is a ReferenceType and it has not been loaded
* by the specified class loader.
*/
public static TypeImpl create(VirtualMachineImpl vmImpl, String signature, ClassLoaderReference classLoader) throws ClassNotLoadedException {
// For void values, a VoidType is always returned.
if (TypeImpl.isVoidSignature(signature))
return new VoidTypeImpl(vmImpl);
// For primitive variables, an appropriate PrimitiveType is always returned.
if (TypeImpl.isPrimitiveSignature(signature))
return PrimitiveTypeImpl.create(vmImpl, signature);
// For object variables, the appropriate ReferenceType is returned if it has
// been loaded through the enclosing type's class loader.
return ReferenceTypeImpl.create(vmImpl, signature, classLoader);
}
/**
* Assigns name.
*/
public void setName(String name) {
fName = name;
}
/**
* Assigns signature.
*/
public void setSignature(String signature) {
fSignature = signature;
}
/**
* @return Returns description of Mirror object.
*/
public String toString() {
try {
return name();
} catch (ClassNotPreparedException e) {
return "(Unloaded Type)";
} catch (Exception e) {
return fDescription;
}
}
/**
* @return Create a null value instance of the type.
*/
public abstract Value createNullValue();
/**
* @return Returns text representation of this type.
*/
public abstract String name();
/**
* @return JNI-style signature for this type.
*/
public abstract String signature();
/**
* @return Returns modifier bits.
*/
public abstract int modifiers();
/**
* @returns Returns true if signature is a class signature.
*/
public static boolean isClassSignature(String signature) {
return signature.charAt(0) == 'L';
}
/**
* @returns Returns true if signature is an array signature.
*/
public static boolean isArraySignature(String signature) {
return signature.charAt(0) == '[';
}
/**
* @returns Returns true if signature is an primitive signature.
*/
public static boolean isPrimitiveSignature(String signature) {
switch (signature.charAt(0)) {
case 'Z':
case 'B':
case 'C':
case 'S':
case 'I':
case 'J':
case 'F':
case 'D':
return true;
}
return false;
}
/**
* @returns Returns true if signature is void signature.
*/
public static boolean isVoidSignature(String signature) {
return (signature.charAt(0) == 'V');
}
/**
* Converts a class name to a JNI signature.
*/
public static String classNameToSignature(String qualifiedName) {
// L<classname>; : fully-qualified-class
/* JNI signature examples:
* int[][] -> [[I
* long[] -> [J
* java.lang.String -> Ljava/lang/String;
* java.lang.String[] -> [Ljava/lang/String;
*/
StringBuffer signature= new StringBuffer();
int firstBrace= qualifiedName.indexOf('[');
if (firstBrace < 0) {
// Not an array type. Must be class type.
signature.append('L');
signature.append(qualifiedName.replace('.','/'));
signature.append(';');
return signature.toString();
}
int index= 0;
while ((index= (qualifiedName.indexOf('[', index) + 1)) > 0) {
signature.append('[');
}
String name= qualifiedName.substring(0, firstBrace);
switch (name.charAt(0)) {
// Check for primitive array type
case 'b':
if (name.equals("byte")) {
signature.append('B');
return signature.toString();
} else if (name.equals("boolean")) {
signature.append('Z');
return signature.toString();
}
break;
case 'i':
if (name.equals("int")) {
signature.append('I');
return signature.toString();
}
break;
case 'd':
if (name.equals("double")) {
signature.append('D');
return signature.toString();
}
break;
case 's':
if (name.equals("short")) {
signature.append('S');
return signature.toString();
}
break;
case 'c':
if (name.equals("char")) {
signature.append('C');
return signature.toString();
}
break;
case 'l':
if (name.equals("long")) {
signature.append('J');
return signature.toString();
}
break;
- /*
case 'f':
if (name.equals("float")) {
signature.append('F');
return signature.toString();
}
break;
- */
}
// Class type array
signature.append('L');
signature.append(name.replace('.','/'));
signature.append(';');
return signature.toString();
}
/**
* Converts a JNI class signature to a name.
*/
public static String classSignatureToName(String signature) {
// L<classname>; : fully-qualified-class
return signature.substring(1, signature.length() - 1).replace('/','.');
}
/**
* Converts a JNI array signature to a name.
*/
public static String arraySignatureToName(String signature) {
// [<type> : array of type <type>
if (signature.indexOf('[') < 0) {
return signature;
}
StringBuffer name= new StringBuffer();
String type= signature.substring(signature.lastIndexOf('[') + 1);
if (type.length() == 1 && isPrimitiveSignature(type)) {
name.append(getPrimitiveSignatureToName(type.charAt(0)));
} else {
name.append(classSignatureToName(type));
}
int index= 0;
while ((index= (signature.indexOf('[', index) + 1)) > 0) {
name.append('[').append(']');
}
return signatureToName(signature.substring(1)) + "[]";
}
/**
* @returns Returns Type Name, converted from a JNI signature.
*/
public static String signatureToName(String signature) {
// See JNI 1.1 Specification, Table 3-2 Java VM Type Signatures.
String primitive= getPrimitiveSignatureToName(signature.charAt(0));
if (primitive != null) {
return primitive;
}
switch (signature.charAt(0)) {
case 'V':
return "void";
case 'L':
return classSignatureToName(signature);
case '[':
return arraySignatureToName(signature);
case '(':
throw new InternalError("Can't covert method signature to name.");
}
throw new InternalError("Invalid signature: \"" + signature + "\"");
}
private static String getPrimitiveSignatureToName(char signature) {
switch (signature) {
case 'Z':
return "boolean";
case 'B':
return "byte";
case 'C':
return "char";
case 'S':
return "short";
case 'I':
return "int";
case 'J':
return "long";
case 'F':
return "float";
case 'D':
return "double";
default:
return null;
}
}
/**
* @returns Returns length of the Class type-string in the signature at the given index.
*/
private static int signatureClassTypeStringLength(String signature, int index) {
int endPos = signature.indexOf(';', index + 1);
if (endPos < 0)
throw new InternalError("Invalid Class Type signature.");
return endPos - index + 1;
}
/**
* @returns Returns length of the first type-string in the signature at the given index.
*/
public static int signatureTypeStringLength(String signature, int index) {
switch (signature.charAt(index)) {
case 'Z':
case 'B':
case 'C':
case 'S':
case 'I':
case 'J':
case 'F':
case 'D':
case 'V':
return 1;
case 'L':
return signatureClassTypeStringLength(signature, index);
case '[':
return 1 + signatureTypeStringLength(signature, index + 1);
case '(':
throw new InternalError("Can't covert method signature to name.");
}
throw new InternalError("Invalid signature: \"" + signature + "\"");
}
/**
* @returns Returns Jdwp Tag, converted from a JNI signature.
*/
public static byte signatureToTag(String signature) {
switch (signature.charAt(0)) {
case 'Z':
return BooleanValueImpl.tag;
case 'B':
return ByteValueImpl.tag;
case 'C':
return CharValueImpl.tag;
case 'S':
return ShortValueImpl.tag;
case 'I':
return IntegerValueImpl.tag;
case 'J':
return LongValueImpl.tag;
case 'F':
return FloatValueImpl.tag;
case 'D':
return DoubleValueImpl.tag;
case 'V':
return VoidValueImpl.tag;
case 'L':
return ObjectReferenceImpl.tag;
case '[':
return ArrayReferenceImpl.tag;
case '(':
throw new InternalError("Can't covert method signature to tag.");
}
throw new InternalError("Invalid signature: \"" + signature + "\"");
}
}
| false | true | public static String classNameToSignature(String qualifiedName) {
// L<classname>; : fully-qualified-class
/* JNI signature examples:
* int[][] -> [[I
* long[] -> [J
* java.lang.String -> Ljava/lang/String;
* java.lang.String[] -> [Ljava/lang/String;
*/
StringBuffer signature= new StringBuffer();
int firstBrace= qualifiedName.indexOf('[');
if (firstBrace < 0) {
// Not an array type. Must be class type.
signature.append('L');
signature.append(qualifiedName.replace('.','/'));
signature.append(';');
return signature.toString();
}
int index= 0;
while ((index= (qualifiedName.indexOf('[', index) + 1)) > 0) {
signature.append('[');
}
String name= qualifiedName.substring(0, firstBrace);
switch (name.charAt(0)) {
// Check for primitive array type
case 'b':
if (name.equals("byte")) {
signature.append('B');
return signature.toString();
} else if (name.equals("boolean")) {
signature.append('Z');
return signature.toString();
}
break;
case 'i':
if (name.equals("int")) {
signature.append('I');
return signature.toString();
}
break;
case 'd':
if (name.equals("double")) {
signature.append('D');
return signature.toString();
}
break;
case 's':
if (name.equals("short")) {
signature.append('S');
return signature.toString();
}
break;
case 'c':
if (name.equals("char")) {
signature.append('C');
return signature.toString();
}
break;
case 'l':
if (name.equals("long")) {
signature.append('J');
return signature.toString();
}
break;
/*
case 'f':
if (name.equals("float")) {
signature.append('F');
return signature.toString();
}
break;
*/
}
// Class type array
signature.append('L');
signature.append(name.replace('.','/'));
signature.append(';');
return signature.toString();
}
| public static String classNameToSignature(String qualifiedName) {
// L<classname>; : fully-qualified-class
/* JNI signature examples:
* int[][] -> [[I
* long[] -> [J
* java.lang.String -> Ljava/lang/String;
* java.lang.String[] -> [Ljava/lang/String;
*/
StringBuffer signature= new StringBuffer();
int firstBrace= qualifiedName.indexOf('[');
if (firstBrace < 0) {
// Not an array type. Must be class type.
signature.append('L');
signature.append(qualifiedName.replace('.','/'));
signature.append(';');
return signature.toString();
}
int index= 0;
while ((index= (qualifiedName.indexOf('[', index) + 1)) > 0) {
signature.append('[');
}
String name= qualifiedName.substring(0, firstBrace);
switch (name.charAt(0)) {
// Check for primitive array type
case 'b':
if (name.equals("byte")) {
signature.append('B');
return signature.toString();
} else if (name.equals("boolean")) {
signature.append('Z');
return signature.toString();
}
break;
case 'i':
if (name.equals("int")) {
signature.append('I');
return signature.toString();
}
break;
case 'd':
if (name.equals("double")) {
signature.append('D');
return signature.toString();
}
break;
case 's':
if (name.equals("short")) {
signature.append('S');
return signature.toString();
}
break;
case 'c':
if (name.equals("char")) {
signature.append('C');
return signature.toString();
}
break;
case 'l':
if (name.equals("long")) {
signature.append('J');
return signature.toString();
}
break;
case 'f':
if (name.equals("float")) {
signature.append('F');
return signature.toString();
}
break;
}
// Class type array
signature.append('L');
signature.append(name.replace('.','/'));
signature.append(';');
return signature.toString();
}
|
diff --git a/impl/src/main/java/org/richfaces/application/push/impl/SessionManagerImpl.java b/impl/src/main/java/org/richfaces/application/push/impl/SessionManagerImpl.java
index d67bc6001..f53357303 100644
--- a/impl/src/main/java/org/richfaces/application/push/impl/SessionManagerImpl.java
+++ b/impl/src/main/java/org/richfaces/application/push/impl/SessionManagerImpl.java
@@ -1,107 +1,106 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.richfaces.application.push.impl;
import java.util.Iterator;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ThreadFactory;
import org.richfaces.application.push.Session;
import org.richfaces.application.push.SessionManager;
import org.richfaces.log.Logger;
import org.richfaces.log.RichfacesLogger;
import com.google.common.collect.MapMaker;
/**
* @author Nick Belaevski
*
*/
public class SessionManagerImpl implements SessionManager {
private static final Logger LOGGER = RichfacesLogger.APPLICATION.getLogger();
private final class SessionsExpirationRunnable implements Runnable {
public void run() {
while (true) {
try {
Session session = sessionQueue.take();
sessionMap.remove(session.getId());
session.destroy();
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
private ConcurrentMap<String, Session> sessionMap = new MapMaker().makeMap();
private SessionQueue sessionQueue = new SessionQueue();
public SessionManagerImpl(ThreadFactory threadFactory) {
threadFactory.newThread(new SessionsExpirationRunnable()).start();
}
public Session getPushSession(String id) {
return sessionMap.get(id);
}
public void removePushSession(Session session) {
// XXX - possible null pointer exception
if (session != null) {
sessionMap.remove(session.getId());
sessionQueue.remove(session);
}
}
public void destroy() {
//TODO notify all session
- // TODO - synchronize clear/remove/clear. Other thread can insert new value during destroy.
sessionQueue.clear();
while (!sessionMap.isEmpty()) {
for (Iterator<Session> sessionsItr = sessionMap.values().iterator(); sessionsItr.hasNext(); ) {
Session session = sessionsItr.next();
sessionsItr.remove();
session.destroy();
}
}
sessionMap.clear();
}
public void putPushSession(Session session) throws IllegalStateException {
Session existingSession = sessionMap.putIfAbsent(session.getId(), session);
if (existingSession != null) {
throw new IllegalStateException();
}
requeue(session);
}
public void requeue(Session session) {
sessionQueue.requeue(session);
}
}
| true | true | public void destroy() {
//TODO notify all session
// TODO - synchronize clear/remove/clear. Other thread can insert new value during destroy.
sessionQueue.clear();
while (!sessionMap.isEmpty()) {
for (Iterator<Session> sessionsItr = sessionMap.values().iterator(); sessionsItr.hasNext(); ) {
Session session = sessionsItr.next();
sessionsItr.remove();
session.destroy();
}
}
sessionMap.clear();
}
| public void destroy() {
//TODO notify all session
sessionQueue.clear();
while (!sessionMap.isEmpty()) {
for (Iterator<Session> sessionsItr = sessionMap.values().iterator(); sessionsItr.hasNext(); ) {
Session session = sessionsItr.next();
sessionsItr.remove();
session.destroy();
}
}
sessionMap.clear();
}
|
diff --git a/src/main/java/iTests/framework/testng/report/mail/HtmlMailReporter.java b/src/main/java/iTests/framework/testng/report/mail/HtmlMailReporter.java
index 2c1d237..a7d6ec9 100644
--- a/src/main/java/iTests/framework/testng/report/mail/HtmlMailReporter.java
+++ b/src/main/java/iTests/framework/testng/report/mail/HtmlMailReporter.java
@@ -1,140 +1,140 @@
package iTests.framework.testng.report.mail;
import com.gigaspaces.dashboard.DashboardDBReporter;
import iTests.framework.testng.report.wiki.WikiUtils;
import iTests.framework.testng.report.xml.SummaryReport;
import iTests.framework.tools.SGTestHelper;
import iTests.framework.tools.SimpleMail;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
public class HtmlMailReporter {
protected static final String CREDENTIALS_FOLDER = System.getProperty("iTests.credentialsFolder",
SGTestHelper.getSGTestRootDir() + "/src/main/resources/credentials");
private static final String MAIL_REPORTER_PROPERTIES = CREDENTIALS_FOLDER + "/mailreporter.properties";
public HtmlMailReporter() {
}
public void sendHtmlMailReport(SummaryReport summaryReport, String wikiPageUrl, Properties extProperties) {
String buildNumber = extProperties.getProperty("buildVersion");
String majorVersion = extProperties.getProperty("majorVersion");
String minorVersion = extProperties.getProperty("minorVersion");
String buildLogUrl = extProperties.getProperty("buildLogUrl");
String suiteName = summaryReport.getSuiteName();
List<String> mailRecipients = null;
if(buildNumber == null)
return;
Properties props = new Properties();
try {
props.load(new FileInputStream(MAIL_REPORTER_PROPERTIES));
} catch (IOException e) {
throw new RuntimeException("failed to read " + MAIL_REPORTER_PROPERTIES + " file - " + e, e);
}
System.out.println("mailreporter.properties: " + props);
MailReporterProperties mailProperties = new MailReporterProperties(props);
String link = "<a href=" + wikiPageUrl + ">"
+ buildNumber + " " + majorVersion + " " + minorVersion + " </a>";
StringBuilder sb = new StringBuilder();
sb.append("<html>").append("\n");
String type;
System.out.println("project name: " + extProperties.getProperty("suiteType"));
if(extProperties.getProperty("suiteType").contains("XAP")){
sb.append("<h1>SGTest XAP Results </h1></br></br></br>").append("\n");
type = "iTests-XAP";
}
else{
sb.append("<h1>Cloudify-iTests Results </h1></br></br></br>").append("\n");
type = "iTests-Cloudify";
}
sb.append("<h2>Suite Name: " + summaryReport.getSuiteName() + " </h2></br>").append("\n");
sb.append("<h4>Duration: " + WikiUtils.formatDuration(summaryReport.getDuration()) + " </h4></br>").append("\n");
sb.append("<h4>Full Suite Report: " + link + " </h4></br>").append("\n");
- if(buildLogUrl != null)
+ if(buildLogUrl != null|| !buildLogUrl.equals(""))
sb.append("<h4>Full build log: <a href=" + getFullBuildLog(buildLogUrl) + ">" + getFullBuildLog(buildLogUrl) + "</a> </h4></br>").append("\n");
sb.append("<h4 style=\"color:blue\">Total run: " + summaryReport.getTotalTestsRun() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:red\">Failed Tests: " + summaryReport.getFailed() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:green\">Passed Tests: " + summaryReport.getSuccess() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:orange\">Skipped: " + summaryReport.getSkipped() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:coral\">Suspected: " + summaryReport.getSuspected() + " </h4></br>").append("\n");
sb.append("</html>");
try {
mailRecipients = mailProperties.getRecipients();
if (suiteName.contains("webui")) mailRecipients = mailProperties.getWebUIRecipients();
if (suiteName.equals("ServiceGrid")) mailRecipients = mailProperties.getSGRecipients();
if (suiteName.equals("WAN")) mailRecipients = mailProperties.getWanRecipients();
if (suiteName.equals("SECURITY")) mailRecipients = mailProperties.getSecurityRecipients();
if (suiteName.equals("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
if (suiteName.equals("ESM")) mailRecipients = mailProperties.getESMRecipients();
if (suiteName.equals("DISCONNECT")) mailRecipients = mailProperties.getDisconnectRecipients();
if (suiteName.equals("CPP_Linux-amd64")) mailRecipients = mailProperties.getCPP_Linux_amd64Recipients();
if (suiteName.equals("CPP_Linux32")) mailRecipients = mailProperties.getCPP_Linux32();
if (suiteName.contains("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
System.out.println("sending mail to recipients: " + mailRecipients);
SimpleMail.send(mailProperties.getMailHost(), mailProperties.getUsername(), mailProperties.getPassword(),
"SGTest Suite " + summaryReport.getSuiteName() + " results " + buildNumber + " " + majorVersion
+ " " + minorVersion, sb.toString(), mailRecipients);
} catch (Exception e) {
throw new RuntimeException("failed to send mail - " + e, e);
}
String[] buildeNumberSplit = buildNumber.split("_");
String buildNumberForDB;
if(buildeNumberSplit.length >= 2)
buildNumberForDB = buildeNumberSplit[1];
else
buildNumberForDB = buildNumber;
DashboardDBReporter.writeToDB(summaryReport.getSuiteName(), buildNumberForDB, majorVersion, minorVersion,
summaryReport.getDuration(), buildLogUrl, summaryReport.getTotalTestsRun(), summaryReport.getFailed(),
summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), 0/*orphans*/, wikiPageUrl, "", type);
}
static String getFullBuildLog(String buildLog) {
StringTokenizer tokenizer = new StringTokenizer(buildLog, "/");
List<String> tokens = new ArrayList<String>();
while (tokenizer.hasMoreTokens()) {
tokens.add(tokenizer.nextToken());
}
return tokens.get(0) + "//" + tokens.get(1) + "/download/" + tokens.get(3) + "/" + tokens.get(2);
}
// /*
// * Test this!
// */
// public static void main(String[] args) {
//
// System.setProperty("iTests.buildNumber", "1234-123");
// System.setProperty("iTests.suiteName", "ServiceGrid");
// System.setProperty("sgtest.majorVersion", "9.0.0");
// System.setProperty("sgtest.minorVersion", "m1");
//
// HtmlMailReporter mailReporter = new HtmlMailReporter();
// TestsReport testsReport = TestsReport.newEmptyReport();
// testsReport.setSuiteName("ServiceGrid");
// TestReport report = new TestReport("test");
// report.setDuration(10L);
// testsReport.getReports().add(report);
// SummaryReport summaryReport = new SummaryReport(testsReport);
// mailReporter.sendHtmlMailReport(summaryReport, "some-url");
// }
}
| true | true | public void sendHtmlMailReport(SummaryReport summaryReport, String wikiPageUrl, Properties extProperties) {
String buildNumber = extProperties.getProperty("buildVersion");
String majorVersion = extProperties.getProperty("majorVersion");
String minorVersion = extProperties.getProperty("minorVersion");
String buildLogUrl = extProperties.getProperty("buildLogUrl");
String suiteName = summaryReport.getSuiteName();
List<String> mailRecipients = null;
if(buildNumber == null)
return;
Properties props = new Properties();
try {
props.load(new FileInputStream(MAIL_REPORTER_PROPERTIES));
} catch (IOException e) {
throw new RuntimeException("failed to read " + MAIL_REPORTER_PROPERTIES + " file - " + e, e);
}
System.out.println("mailreporter.properties: " + props);
MailReporterProperties mailProperties = new MailReporterProperties(props);
String link = "<a href=" + wikiPageUrl + ">"
+ buildNumber + " " + majorVersion + " " + minorVersion + " </a>";
StringBuilder sb = new StringBuilder();
sb.append("<html>").append("\n");
String type;
System.out.println("project name: " + extProperties.getProperty("suiteType"));
if(extProperties.getProperty("suiteType").contains("XAP")){
sb.append("<h1>SGTest XAP Results </h1></br></br></br>").append("\n");
type = "iTests-XAP";
}
else{
sb.append("<h1>Cloudify-iTests Results </h1></br></br></br>").append("\n");
type = "iTests-Cloudify";
}
sb.append("<h2>Suite Name: " + summaryReport.getSuiteName() + " </h2></br>").append("\n");
sb.append("<h4>Duration: " + WikiUtils.formatDuration(summaryReport.getDuration()) + " </h4></br>").append("\n");
sb.append("<h4>Full Suite Report: " + link + " </h4></br>").append("\n");
if(buildLogUrl != null)
sb.append("<h4>Full build log: <a href=" + getFullBuildLog(buildLogUrl) + ">" + getFullBuildLog(buildLogUrl) + "</a> </h4></br>").append("\n");
sb.append("<h4 style=\"color:blue\">Total run: " + summaryReport.getTotalTestsRun() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:red\">Failed Tests: " + summaryReport.getFailed() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:green\">Passed Tests: " + summaryReport.getSuccess() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:orange\">Skipped: " + summaryReport.getSkipped() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:coral\">Suspected: " + summaryReport.getSuspected() + " </h4></br>").append("\n");
sb.append("</html>");
try {
mailRecipients = mailProperties.getRecipients();
if (suiteName.contains("webui")) mailRecipients = mailProperties.getWebUIRecipients();
if (suiteName.equals("ServiceGrid")) mailRecipients = mailProperties.getSGRecipients();
if (suiteName.equals("WAN")) mailRecipients = mailProperties.getWanRecipients();
if (suiteName.equals("SECURITY")) mailRecipients = mailProperties.getSecurityRecipients();
if (suiteName.equals("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
if (suiteName.equals("ESM")) mailRecipients = mailProperties.getESMRecipients();
if (suiteName.equals("DISCONNECT")) mailRecipients = mailProperties.getDisconnectRecipients();
if (suiteName.equals("CPP_Linux-amd64")) mailRecipients = mailProperties.getCPP_Linux_amd64Recipients();
if (suiteName.equals("CPP_Linux32")) mailRecipients = mailProperties.getCPP_Linux32();
if (suiteName.contains("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
System.out.println("sending mail to recipients: " + mailRecipients);
SimpleMail.send(mailProperties.getMailHost(), mailProperties.getUsername(), mailProperties.getPassword(),
"SGTest Suite " + summaryReport.getSuiteName() + " results " + buildNumber + " " + majorVersion
+ " " + minorVersion, sb.toString(), mailRecipients);
} catch (Exception e) {
throw new RuntimeException("failed to send mail - " + e, e);
}
String[] buildeNumberSplit = buildNumber.split("_");
String buildNumberForDB;
if(buildeNumberSplit.length >= 2)
buildNumberForDB = buildeNumberSplit[1];
else
buildNumberForDB = buildNumber;
DashboardDBReporter.writeToDB(summaryReport.getSuiteName(), buildNumberForDB, majorVersion, minorVersion,
summaryReport.getDuration(), buildLogUrl, summaryReport.getTotalTestsRun(), summaryReport.getFailed(),
summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), 0/*orphans*/, wikiPageUrl, "", type);
}
| public void sendHtmlMailReport(SummaryReport summaryReport, String wikiPageUrl, Properties extProperties) {
String buildNumber = extProperties.getProperty("buildVersion");
String majorVersion = extProperties.getProperty("majorVersion");
String minorVersion = extProperties.getProperty("minorVersion");
String buildLogUrl = extProperties.getProperty("buildLogUrl");
String suiteName = summaryReport.getSuiteName();
List<String> mailRecipients = null;
if(buildNumber == null)
return;
Properties props = new Properties();
try {
props.load(new FileInputStream(MAIL_REPORTER_PROPERTIES));
} catch (IOException e) {
throw new RuntimeException("failed to read " + MAIL_REPORTER_PROPERTIES + " file - " + e, e);
}
System.out.println("mailreporter.properties: " + props);
MailReporterProperties mailProperties = new MailReporterProperties(props);
String link = "<a href=" + wikiPageUrl + ">"
+ buildNumber + " " + majorVersion + " " + minorVersion + " </a>";
StringBuilder sb = new StringBuilder();
sb.append("<html>").append("\n");
String type;
System.out.println("project name: " + extProperties.getProperty("suiteType"));
if(extProperties.getProperty("suiteType").contains("XAP")){
sb.append("<h1>SGTest XAP Results </h1></br></br></br>").append("\n");
type = "iTests-XAP";
}
else{
sb.append("<h1>Cloudify-iTests Results </h1></br></br></br>").append("\n");
type = "iTests-Cloudify";
}
sb.append("<h2>Suite Name: " + summaryReport.getSuiteName() + " </h2></br>").append("\n");
sb.append("<h4>Duration: " + WikiUtils.formatDuration(summaryReport.getDuration()) + " </h4></br>").append("\n");
sb.append("<h4>Full Suite Report: " + link + " </h4></br>").append("\n");
if(buildLogUrl != null|| !buildLogUrl.equals(""))
sb.append("<h4>Full build log: <a href=" + getFullBuildLog(buildLogUrl) + ">" + getFullBuildLog(buildLogUrl) + "</a> </h4></br>").append("\n");
sb.append("<h4 style=\"color:blue\">Total run: " + summaryReport.getTotalTestsRun() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:red\">Failed Tests: " + summaryReport.getFailed() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:green\">Passed Tests: " + summaryReport.getSuccess() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:orange\">Skipped: " + summaryReport.getSkipped() + " </h4></br>").append("\n");
sb.append("<h4 style=\"color:coral\">Suspected: " + summaryReport.getSuspected() + " </h4></br>").append("\n");
sb.append("</html>");
try {
mailRecipients = mailProperties.getRecipients();
if (suiteName.contains("webui")) mailRecipients = mailProperties.getWebUIRecipients();
if (suiteName.equals("ServiceGrid")) mailRecipients = mailProperties.getSGRecipients();
if (suiteName.equals("WAN")) mailRecipients = mailProperties.getWanRecipients();
if (suiteName.equals("SECURITY")) mailRecipients = mailProperties.getSecurityRecipients();
if (suiteName.equals("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
if (suiteName.equals("ESM")) mailRecipients = mailProperties.getESMRecipients();
if (suiteName.equals("DISCONNECT")) mailRecipients = mailProperties.getDisconnectRecipients();
if (suiteName.equals("CPP_Linux-amd64")) mailRecipients = mailProperties.getCPP_Linux_amd64Recipients();
if (suiteName.equals("CPP_Linux32")) mailRecipients = mailProperties.getCPP_Linux32();
if (suiteName.contains("CLOUDIFY")) mailRecipients = mailProperties.getCloudifyRecipients();
System.out.println("sending mail to recipients: " + mailRecipients);
SimpleMail.send(mailProperties.getMailHost(), mailProperties.getUsername(), mailProperties.getPassword(),
"SGTest Suite " + summaryReport.getSuiteName() + " results " + buildNumber + " " + majorVersion
+ " " + minorVersion, sb.toString(), mailRecipients);
} catch (Exception e) {
throw new RuntimeException("failed to send mail - " + e, e);
}
String[] buildeNumberSplit = buildNumber.split("_");
String buildNumberForDB;
if(buildeNumberSplit.length >= 2)
buildNumberForDB = buildeNumberSplit[1];
else
buildNumberForDB = buildNumber;
DashboardDBReporter.writeToDB(summaryReport.getSuiteName(), buildNumberForDB, majorVersion, minorVersion,
summaryReport.getDuration(), buildLogUrl, summaryReport.getTotalTestsRun(), summaryReport.getFailed(),
summaryReport.getSuccess(), summaryReport.getSkipped(), summaryReport.getSuspected(), 0/*orphans*/, wikiPageUrl, "", type);
}
|
diff --git a/src/jpcsp/graphics/VertexInfo.java b/src/jpcsp/graphics/VertexInfo.java
index 2b462958..9b501606 100644
--- a/src/jpcsp/graphics/VertexInfo.java
+++ b/src/jpcsp/graphics/VertexInfo.java
@@ -1,374 +1,381 @@
/*
This file is part of jpcsp.
Jpcsp 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.
Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.graphics;
import jpcsp.Memory;
// Based on soywiz/pspemulator
public class VertexInfo {
// vtype
private int transform2D; // for logging purposes (got moved into VideoEngine.java)
public int skinningWeightCount;
public int morphingVertexCount;
public int texture;
public int color;
public int normal;
public int position;
public int weight;
public int index;
// vaddr, iaddr
public int ptr_vertex;
public int ptr_index;
// other data
public int vertexSize;
private static int[] size_mapping = new int[] { 0, 1, 2, 4 };
private static int[] size_padding = new int[] { 0, 0, 1, 3 };
private static String[] texture_info = new String[] {
null, "GU_TEXTURE_8BIT", "GU_TEXTURE_16BIT", "GU_TEXTURE_32BITF"
};
private static String[] color_info = new String[] {
null, "GU_COLOR_UNK2", "GU_COLOR_UNK3", "GU_COLOR_UNK4",
"GU_COLOR_5650", "GU_COLOR_5551", "GU_COLOR_4444", "GU_COLOR_8888"
};
private static String[] normal_info = new String[] {
null, "GU_NORMAL_8BIT", "GU_NORMAL_16BIT", "GU_NORMAL_32BITF"
};
private static String[] vertex_info = new String[] {
null, "GU_VERTEX_8BIT", "GU_VERTEX_16BIT", "GU_VERTEX_32BITF"
};
private static String[] weight_info = new String[] {
null, "GU_WEIGHT_8BIT", "GU_WEIGHT_16BIT", "GU_WEIGHT_32BITF"
};
private static String[] index_info = new String[] {
null, "GU_INDEX_8BIT", "GU_INDEX_16BIT", "GU_INDEX_UNK3"
};
private static String[] transform_info = new String[] {
"GU_TRANSFORM_3D", "GU_TRANSFORM_2D"
};
public void processType(int param) {
texture = (param >> 0) & 0x3;
color = (param >> 2) & 0x7;
normal = (param >> 5) & 0x3;
position = (param >> 7) & 0x3;
weight = (param >> 9) & 0x3;
index = (param >> 11) & 0x3;
skinningWeightCount = ((param >> 14) & 0x7) + 1;
morphingVertexCount = ((param >> 18) & 0x7) + 1;
transform2D = (param >> 23) & 0x1;
vertexSize = 0;
vertexSize += size_mapping[weight] * skinningWeightCount;
vertexSize = (vertexSize + ((color != 0) ? ((color == 7) ? 3 : 1) : 0)) & ~((color != 0) ? ((color == 7) ? 3 : 1) : 0);
vertexSize += (color != 0) ? ((color == 7) ? 4 : 2) : 0;
vertexSize = (vertexSize + size_padding[texture]) & ~size_padding[texture];
vertexSize += size_mapping[texture] * 2;
vertexSize = (vertexSize + size_padding[position]) & ~size_padding[position];
vertexSize += size_mapping[position] * 3;
vertexSize = (vertexSize + size_padding[normal]) & ~size_padding[normal];
vertexSize += size_mapping[normal] * 3;
int maxsize = Math.max(size_mapping[weight],
Math.max((color != 0) ? ((color == 7) ? 4 : 2) : 0,
Math.max(size_padding[normal],
Math.max(size_padding[texture],
size_padding[position]))));
vertexSize = (vertexSize + maxsize - 1) & ~(maxsize - 1);
}
public int getAddress(Memory mem, int i) {
if (ptr_index != 0) {
int addr = ptr_index + i * index;
switch(index) {
case 1: i = mem.read8(addr); break;
case 2: i = mem.read16(addr); break;
case 4: i = mem.read32(addr); break;
}
}
return ptr_vertex + i * vertexSize;
}
public VertexState lastVertex = new VertexState();
public VertexState readVertex(Memory mem, int addr) {
VertexState v = new VertexState();
// testing
if (false) {
int u0 = mem.read8(addr);
int u1 = mem.read8(addr + 1);
int u2 = mem.read8(addr + 2);
int u3 = mem.read8(addr + 3);
int u4 = mem.read8(addr + 4);
int u5 = mem.read8(addr + 5);
int u6 = mem.read8(addr + 6);
int u7 = mem.read8(addr + 7);
int u8 = mem.read8(addr + 8);
int u9 = mem.read8(addr + 9);
int u10 = mem.read8(addr + 10);
int u11 = mem.read8(addr + 11);
int u12 = mem.read8(addr + 12);
VideoEngine.log.debug("vertex "
+ String.format("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x ",
u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12));
}
//VideoEngine.log.debug("skinning " + String.format("0x%08x", addr));
if (weight != 0) {
for (int i = 0; i < skinningWeightCount; ++i) {
switch (weight) {
case 1:
// Unsigned 8 bit, mapped to [0..2]
v.boneWeights[i] = mem.read8(addr); addr += 1;
v.boneWeights[i] /= 0x80;
break;
case 2:
addr = (addr + 1) & ~1;
// Unsigned 16 bit, mapped to [0..2]
v.boneWeights[i] = mem.read16(addr); addr += 2;
v.boneWeights[i] /= 0x8000;
break;
case 3:
addr = (addr + 3) & ~3;
v.boneWeights[i] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
break;
}
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace(String.format("Weight(%d) %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f", skinningWeightCount, v.boneWeights[0], v.boneWeights[1], v.boneWeights[2], v.boneWeights[3], v.boneWeights[4], v.boneWeights[5], v.boneWeights[6], v.boneWeights[7]));
}
}
//VideoEngine.log.debug("texture " + String.format("0x%08x", addr));
switch(texture) {
case 1:
// Unsigned 8 bit
v.t[0] = mem.read8(addr) & 0xFF; addr += 1;
v.t[1] = mem.read8(addr) & 0xFF; addr += 1;
if (transform2D == 0) {
// To be mapped to [0..2] for 3D
v.t[0] /= 0x80;
v.t[1] /= 0x80;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 1 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
// Unsigned 16 bit
v.t[0] = mem.read16(addr) & 0xFFFF; addr += 2;
v.t[1] = mem.read16(addr) & 0xFFFF; addr += 2;
if (transform2D == 0) {
// To be mapped to [0..2] for 3D
v.t[0] /= 0x8000;
v.t[1] /= 0x8000;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 2 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
case 3:
addr = (addr + 3) & ~3;
v.t[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.t[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 3 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
}
//VideoEngine.log.debug("color " + String.format("0x%08x", addr));
switch(color) {
case 1: case 2: case 3:
VideoEngine.log.warn("unimplemented color type " + color);
addr += 1;
break;
case 4: { // GU_COLOR_5650
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0x1f) / 31.0f;
v.c[1] = ((packed >> 5) & 0x3f) / 63.0f;
v.c[2] = ((packed >> 11) & 0x1f) / 31.0f;
v.c[3] = 0.0f; // 1.0f
// Alpha needs confirming, other components have been checked (fiveofhearts)
VideoEngine.log.debug("color type " + color + " untested");
break;
}
case 5: { // GU_COLOR_5551
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0x1f) / 31.0f;
v.c[1] = ((packed >> 5) & 0x1f) / 31.0f;
v.c[2] = ((packed >> 10) & 0x1f) / 31.0f;
v.c[3] = ((packed >> 15) & 0x1) / 1.0f;
break;
}
case 6: { // GU_COLOR_4444
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0xf) / 15.0f;
v.c[1] = ((packed >> 4) & 0xf) / 15.0f;
v.c[2] = ((packed >> 8) & 0xf) / 15.0f;
v.c[3] = ((packed >> 12) & 0xf) / 15.0f;
+ if (VideoEngine.log.isTraceEnabled()) {
+ VideoEngine.log.trace("color type 6 " + String.format("r=%.1f g=%.1f b=%.1f a=%.1f (%04X)", v.c[0], v.c[1], v.c[2], v.c[3], packed));
+ }
break;
}
case 7: { // GU_COLOR_8888
// 32-bit align here instead of on vertexSize, from actarus/sam
addr = (addr + 3) & ~3;
int packed = mem.read32(addr); addr += 4;
v.c[0] = ((packed ) & 0xff) / 255.0f;
v.c[1] = ((packed >> 8) & 0xff) / 255.0f;
v.c[2] = ((packed >> 16) & 0xff) / 255.0f;
v.c[3] = ((packed >> 24) & 0xff) / 255.0f;
- //VideoEngine.log.debug("color type 7 " + String.format("r=%.1f g=%.1f b=%.1f (%08X)", v.r, v.g, v.b, packed));
+ if (VideoEngine.log.isTraceEnabled()) {
+ VideoEngine.log.trace("color type 7 " + String.format("r=%.1f g=%.1f b=%.1f a=%.1f (%08X)", v.c[0], v.c[1], v.c[2], v.c[3], packed));
+ }
break;
}
}
//VideoEngine.log.debug("normal " + String.format("0x%08x", addr));
switch(normal) {
case 1:
// TODO Check if this value is signed like position or unsigned like texture
// Signed 8 bit
v.n[0] = (byte)mem.read8(addr); addr += 1;
v.n[1] = (byte)mem.read8(addr); addr += 1;
v.n[2] = (byte)mem.read8(addr); addr += 1;
if (transform2D == 0) {
// To be mapped to [-1..1] for 3D
v.n[0] /= 0x7f;
v.n[1] /= 0x7f;
v.n[2] /= 0x7f;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("normal type 1 " + v.n[0] + ", " + v.n[1] + ", " + v.n[2] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
// TODO Check if this value is signed like position or unsigned like texture
// Signed 16 bit
v.n[0] = (short)mem.read16(addr); addr += 2;
v.n[1] = (short)mem.read16(addr); addr += 2;
v.n[2] = (short)mem.read16(addr); addr += 2;
if (transform2D == 0) {
// To be mapped to [-1..1] for 3D
v.n[0] /= 0x7fff;
v.n[1] /= 0x7fff;
v.n[2] /= 0x7fff;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("normal type 2 " + v.n[0] + ", " + v.n[1] + ", " + v.n[2] + " transform2D=" + transform2D);
}
break;
case 3:
addr = (addr + 3) & ~3;
v.n[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.n[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.n[2] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
break;
}
//VideoEngine.log.debug("position " + String.format("0x%08x", addr));
switch (position) {
case 1:
if (transform2D == 1) {
// X and Y are signed 8 bit, Z is unsigned 8 bit
v.p[0] = (byte) mem.read8(addr); addr += 1;
v.p[1] = (byte) mem.read8(addr); addr += 1;
v.p[2] = mem.read8(addr); addr += 1;
} else {
// Signed 8 bit, to be mapped to [-1..1] for 3D
v.p[0] = ((byte)mem.read8(addr)) / 127f; addr += 1;
v.p[1] = ((byte)mem.read8(addr)) / 127f; addr += 1;
v.p[2] = ((byte)mem.read8(addr)) / 127f; addr += 1;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 1 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
if (transform2D == 1) {
// X and Y are signed 16 bit, Z is unsigned 16 bit
v.p[0] = (short)mem.read16(addr); addr += 2;
v.p[1] = (short)mem.read16(addr); addr += 2;
v.p[2] = mem.read16(addr); addr += 2;
} else {
// Signed 16 bit, to be mapped to [-1..1] for 3D
v.p[0] = ((short)mem.read16(addr)) / 32767f; addr += 2;
v.p[1] = ((short)mem.read16(addr)) / 32767f; addr += 2;
v.p[2] = ((short)mem.read16(addr)) / 32767f; addr += 2;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 2 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D + ", addr=0x" + Integer.toHexString(addr - 6));
}
break;
case 3: // GU_VERTEX_32BITF
addr = (addr + 3) & ~3;
v.p[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.p[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.p[2] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
if (transform2D == 1) {
// Negative Z are interpreted as 0
if (v.p[2] < 0) {
v.p[2] = 0;
+ } else {
+ v.p[2] = (int) v.p[2]; // 2D positions are always integer values
}
}
if (VideoEngine.log.isTraceEnabled()) {
- VideoEngine.log.trace("vertex type 3 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D);
+ VideoEngine.log.trace("vertex type 3 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D + ", addr=0x" + Integer.toHexString(addr - 12));
}
break;
}
//VideoEngine.log.debug("end " + String.format("0x%08x", addr) + " size=" + vertexSize);
lastVertex = v;
return v;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
if (texture_info[texture] != null)
sb.append(texture_info[texture] + "|");
if (color_info[color] != null)
sb.append(color_info[color] + "|");
if (normal_info[normal] != null)
sb.append(normal_info[normal] + "|");
if (vertex_info[position] != null)
sb.append(vertex_info[position] + "|");
if (weight_info[weight] != null)
sb.append(weight_info[weight] + "|");
if (index_info[index] != null)
sb.append(index_info[index] + "|");
if (transform_info[transform2D] != null)
sb.append(transform_info[transform2D]);
sb.append(" size=" + vertexSize);
return sb.toString();
}
}
| false | true | public VertexState readVertex(Memory mem, int addr) {
VertexState v = new VertexState();
// testing
if (false) {
int u0 = mem.read8(addr);
int u1 = mem.read8(addr + 1);
int u2 = mem.read8(addr + 2);
int u3 = mem.read8(addr + 3);
int u4 = mem.read8(addr + 4);
int u5 = mem.read8(addr + 5);
int u6 = mem.read8(addr + 6);
int u7 = mem.read8(addr + 7);
int u8 = mem.read8(addr + 8);
int u9 = mem.read8(addr + 9);
int u10 = mem.read8(addr + 10);
int u11 = mem.read8(addr + 11);
int u12 = mem.read8(addr + 12);
VideoEngine.log.debug("vertex "
+ String.format("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x ",
u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12));
}
//VideoEngine.log.debug("skinning " + String.format("0x%08x", addr));
if (weight != 0) {
for (int i = 0; i < skinningWeightCount; ++i) {
switch (weight) {
case 1:
// Unsigned 8 bit, mapped to [0..2]
v.boneWeights[i] = mem.read8(addr); addr += 1;
v.boneWeights[i] /= 0x80;
break;
case 2:
addr = (addr + 1) & ~1;
// Unsigned 16 bit, mapped to [0..2]
v.boneWeights[i] = mem.read16(addr); addr += 2;
v.boneWeights[i] /= 0x8000;
break;
case 3:
addr = (addr + 3) & ~3;
v.boneWeights[i] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
break;
}
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace(String.format("Weight(%d) %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f", skinningWeightCount, v.boneWeights[0], v.boneWeights[1], v.boneWeights[2], v.boneWeights[3], v.boneWeights[4], v.boneWeights[5], v.boneWeights[6], v.boneWeights[7]));
}
}
//VideoEngine.log.debug("texture " + String.format("0x%08x", addr));
switch(texture) {
case 1:
// Unsigned 8 bit
v.t[0] = mem.read8(addr) & 0xFF; addr += 1;
v.t[1] = mem.read8(addr) & 0xFF; addr += 1;
if (transform2D == 0) {
// To be mapped to [0..2] for 3D
v.t[0] /= 0x80;
v.t[1] /= 0x80;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 1 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
// Unsigned 16 bit
v.t[0] = mem.read16(addr) & 0xFFFF; addr += 2;
v.t[1] = mem.read16(addr) & 0xFFFF; addr += 2;
if (transform2D == 0) {
// To be mapped to [0..2] for 3D
v.t[0] /= 0x8000;
v.t[1] /= 0x8000;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 2 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
case 3:
addr = (addr + 3) & ~3;
v.t[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.t[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 3 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
}
//VideoEngine.log.debug("color " + String.format("0x%08x", addr));
switch(color) {
case 1: case 2: case 3:
VideoEngine.log.warn("unimplemented color type " + color);
addr += 1;
break;
case 4: { // GU_COLOR_5650
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0x1f) / 31.0f;
v.c[1] = ((packed >> 5) & 0x3f) / 63.0f;
v.c[2] = ((packed >> 11) & 0x1f) / 31.0f;
v.c[3] = 0.0f; // 1.0f
// Alpha needs confirming, other components have been checked (fiveofhearts)
VideoEngine.log.debug("color type " + color + " untested");
break;
}
case 5: { // GU_COLOR_5551
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0x1f) / 31.0f;
v.c[1] = ((packed >> 5) & 0x1f) / 31.0f;
v.c[2] = ((packed >> 10) & 0x1f) / 31.0f;
v.c[3] = ((packed >> 15) & 0x1) / 1.0f;
break;
}
case 6: { // GU_COLOR_4444
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0xf) / 15.0f;
v.c[1] = ((packed >> 4) & 0xf) / 15.0f;
v.c[2] = ((packed >> 8) & 0xf) / 15.0f;
v.c[3] = ((packed >> 12) & 0xf) / 15.0f;
break;
}
case 7: { // GU_COLOR_8888
// 32-bit align here instead of on vertexSize, from actarus/sam
addr = (addr + 3) & ~3;
int packed = mem.read32(addr); addr += 4;
v.c[0] = ((packed ) & 0xff) / 255.0f;
v.c[1] = ((packed >> 8) & 0xff) / 255.0f;
v.c[2] = ((packed >> 16) & 0xff) / 255.0f;
v.c[3] = ((packed >> 24) & 0xff) / 255.0f;
//VideoEngine.log.debug("color type 7 " + String.format("r=%.1f g=%.1f b=%.1f (%08X)", v.r, v.g, v.b, packed));
break;
}
}
//VideoEngine.log.debug("normal " + String.format("0x%08x", addr));
switch(normal) {
case 1:
// TODO Check if this value is signed like position or unsigned like texture
// Signed 8 bit
v.n[0] = (byte)mem.read8(addr); addr += 1;
v.n[1] = (byte)mem.read8(addr); addr += 1;
v.n[2] = (byte)mem.read8(addr); addr += 1;
if (transform2D == 0) {
// To be mapped to [-1..1] for 3D
v.n[0] /= 0x7f;
v.n[1] /= 0x7f;
v.n[2] /= 0x7f;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("normal type 1 " + v.n[0] + ", " + v.n[1] + ", " + v.n[2] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
// TODO Check if this value is signed like position or unsigned like texture
// Signed 16 bit
v.n[0] = (short)mem.read16(addr); addr += 2;
v.n[1] = (short)mem.read16(addr); addr += 2;
v.n[2] = (short)mem.read16(addr); addr += 2;
if (transform2D == 0) {
// To be mapped to [-1..1] for 3D
v.n[0] /= 0x7fff;
v.n[1] /= 0x7fff;
v.n[2] /= 0x7fff;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("normal type 2 " + v.n[0] + ", " + v.n[1] + ", " + v.n[2] + " transform2D=" + transform2D);
}
break;
case 3:
addr = (addr + 3) & ~3;
v.n[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.n[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.n[2] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
break;
}
//VideoEngine.log.debug("position " + String.format("0x%08x", addr));
switch (position) {
case 1:
if (transform2D == 1) {
// X and Y are signed 8 bit, Z is unsigned 8 bit
v.p[0] = (byte) mem.read8(addr); addr += 1;
v.p[1] = (byte) mem.read8(addr); addr += 1;
v.p[2] = mem.read8(addr); addr += 1;
} else {
// Signed 8 bit, to be mapped to [-1..1] for 3D
v.p[0] = ((byte)mem.read8(addr)) / 127f; addr += 1;
v.p[1] = ((byte)mem.read8(addr)) / 127f; addr += 1;
v.p[2] = ((byte)mem.read8(addr)) / 127f; addr += 1;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 1 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
if (transform2D == 1) {
// X and Y are signed 16 bit, Z is unsigned 16 bit
v.p[0] = (short)mem.read16(addr); addr += 2;
v.p[1] = (short)mem.read16(addr); addr += 2;
v.p[2] = mem.read16(addr); addr += 2;
} else {
// Signed 16 bit, to be mapped to [-1..1] for 3D
v.p[0] = ((short)mem.read16(addr)) / 32767f; addr += 2;
v.p[1] = ((short)mem.read16(addr)) / 32767f; addr += 2;
v.p[2] = ((short)mem.read16(addr)) / 32767f; addr += 2;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 2 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D + ", addr=0x" + Integer.toHexString(addr - 6));
}
break;
case 3: // GU_VERTEX_32BITF
addr = (addr + 3) & ~3;
v.p[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.p[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.p[2] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
if (transform2D == 1) {
// Negative Z are interpreted as 0
if (v.p[2] < 0) {
v.p[2] = 0;
}
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 3 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D);
}
break;
}
//VideoEngine.log.debug("end " + String.format("0x%08x", addr) + " size=" + vertexSize);
lastVertex = v;
return v;
}
| public VertexState readVertex(Memory mem, int addr) {
VertexState v = new VertexState();
// testing
if (false) {
int u0 = mem.read8(addr);
int u1 = mem.read8(addr + 1);
int u2 = mem.read8(addr + 2);
int u3 = mem.read8(addr + 3);
int u4 = mem.read8(addr + 4);
int u5 = mem.read8(addr + 5);
int u6 = mem.read8(addr + 6);
int u7 = mem.read8(addr + 7);
int u8 = mem.read8(addr + 8);
int u9 = mem.read8(addr + 9);
int u10 = mem.read8(addr + 10);
int u11 = mem.read8(addr + 11);
int u12 = mem.read8(addr + 12);
VideoEngine.log.debug("vertex "
+ String.format("%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x ",
u0, u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, u12));
}
//VideoEngine.log.debug("skinning " + String.format("0x%08x", addr));
if (weight != 0) {
for (int i = 0; i < skinningWeightCount; ++i) {
switch (weight) {
case 1:
// Unsigned 8 bit, mapped to [0..2]
v.boneWeights[i] = mem.read8(addr); addr += 1;
v.boneWeights[i] /= 0x80;
break;
case 2:
addr = (addr + 1) & ~1;
// Unsigned 16 bit, mapped to [0..2]
v.boneWeights[i] = mem.read16(addr); addr += 2;
v.boneWeights[i] /= 0x8000;
break;
case 3:
addr = (addr + 3) & ~3;
v.boneWeights[i] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
break;
}
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace(String.format("Weight(%d) %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f", skinningWeightCount, v.boneWeights[0], v.boneWeights[1], v.boneWeights[2], v.boneWeights[3], v.boneWeights[4], v.boneWeights[5], v.boneWeights[6], v.boneWeights[7]));
}
}
//VideoEngine.log.debug("texture " + String.format("0x%08x", addr));
switch(texture) {
case 1:
// Unsigned 8 bit
v.t[0] = mem.read8(addr) & 0xFF; addr += 1;
v.t[1] = mem.read8(addr) & 0xFF; addr += 1;
if (transform2D == 0) {
// To be mapped to [0..2] for 3D
v.t[0] /= 0x80;
v.t[1] /= 0x80;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 1 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
// Unsigned 16 bit
v.t[0] = mem.read16(addr) & 0xFFFF; addr += 2;
v.t[1] = mem.read16(addr) & 0xFFFF; addr += 2;
if (transform2D == 0) {
// To be mapped to [0..2] for 3D
v.t[0] /= 0x8000;
v.t[1] /= 0x8000;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 2 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
case 3:
addr = (addr + 3) & ~3;
v.t[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.t[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("texture type 3 " + v.t[0] + ", " + v.t[1] + " transform2D=" + transform2D);
}
break;
}
//VideoEngine.log.debug("color " + String.format("0x%08x", addr));
switch(color) {
case 1: case 2: case 3:
VideoEngine.log.warn("unimplemented color type " + color);
addr += 1;
break;
case 4: { // GU_COLOR_5650
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0x1f) / 31.0f;
v.c[1] = ((packed >> 5) & 0x3f) / 63.0f;
v.c[2] = ((packed >> 11) & 0x1f) / 31.0f;
v.c[3] = 0.0f; // 1.0f
// Alpha needs confirming, other components have been checked (fiveofhearts)
VideoEngine.log.debug("color type " + color + " untested");
break;
}
case 5: { // GU_COLOR_5551
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0x1f) / 31.0f;
v.c[1] = ((packed >> 5) & 0x1f) / 31.0f;
v.c[2] = ((packed >> 10) & 0x1f) / 31.0f;
v.c[3] = ((packed >> 15) & 0x1) / 1.0f;
break;
}
case 6: { // GU_COLOR_4444
addr = (addr + 1) & ~1;
int packed = mem.read16(addr); addr += 2;
v.c[0] = ((packed ) & 0xf) / 15.0f;
v.c[1] = ((packed >> 4) & 0xf) / 15.0f;
v.c[2] = ((packed >> 8) & 0xf) / 15.0f;
v.c[3] = ((packed >> 12) & 0xf) / 15.0f;
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("color type 6 " + String.format("r=%.1f g=%.1f b=%.1f a=%.1f (%04X)", v.c[0], v.c[1], v.c[2], v.c[3], packed));
}
break;
}
case 7: { // GU_COLOR_8888
// 32-bit align here instead of on vertexSize, from actarus/sam
addr = (addr + 3) & ~3;
int packed = mem.read32(addr); addr += 4;
v.c[0] = ((packed ) & 0xff) / 255.0f;
v.c[1] = ((packed >> 8) & 0xff) / 255.0f;
v.c[2] = ((packed >> 16) & 0xff) / 255.0f;
v.c[3] = ((packed >> 24) & 0xff) / 255.0f;
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("color type 7 " + String.format("r=%.1f g=%.1f b=%.1f a=%.1f (%08X)", v.c[0], v.c[1], v.c[2], v.c[3], packed));
}
break;
}
}
//VideoEngine.log.debug("normal " + String.format("0x%08x", addr));
switch(normal) {
case 1:
// TODO Check if this value is signed like position or unsigned like texture
// Signed 8 bit
v.n[0] = (byte)mem.read8(addr); addr += 1;
v.n[1] = (byte)mem.read8(addr); addr += 1;
v.n[2] = (byte)mem.read8(addr); addr += 1;
if (transform2D == 0) {
// To be mapped to [-1..1] for 3D
v.n[0] /= 0x7f;
v.n[1] /= 0x7f;
v.n[2] /= 0x7f;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("normal type 1 " + v.n[0] + ", " + v.n[1] + ", " + v.n[2] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
// TODO Check if this value is signed like position or unsigned like texture
// Signed 16 bit
v.n[0] = (short)mem.read16(addr); addr += 2;
v.n[1] = (short)mem.read16(addr); addr += 2;
v.n[2] = (short)mem.read16(addr); addr += 2;
if (transform2D == 0) {
// To be mapped to [-1..1] for 3D
v.n[0] /= 0x7fff;
v.n[1] /= 0x7fff;
v.n[2] /= 0x7fff;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("normal type 2 " + v.n[0] + ", " + v.n[1] + ", " + v.n[2] + " transform2D=" + transform2D);
}
break;
case 3:
addr = (addr + 3) & ~3;
v.n[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.n[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.n[2] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
break;
}
//VideoEngine.log.debug("position " + String.format("0x%08x", addr));
switch (position) {
case 1:
if (transform2D == 1) {
// X and Y are signed 8 bit, Z is unsigned 8 bit
v.p[0] = (byte) mem.read8(addr); addr += 1;
v.p[1] = (byte) mem.read8(addr); addr += 1;
v.p[2] = mem.read8(addr); addr += 1;
} else {
// Signed 8 bit, to be mapped to [-1..1] for 3D
v.p[0] = ((byte)mem.read8(addr)) / 127f; addr += 1;
v.p[1] = ((byte)mem.read8(addr)) / 127f; addr += 1;
v.p[2] = ((byte)mem.read8(addr)) / 127f; addr += 1;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 1 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D);
}
break;
case 2:
addr = (addr + 1) & ~1;
if (transform2D == 1) {
// X and Y are signed 16 bit, Z is unsigned 16 bit
v.p[0] = (short)mem.read16(addr); addr += 2;
v.p[1] = (short)mem.read16(addr); addr += 2;
v.p[2] = mem.read16(addr); addr += 2;
} else {
// Signed 16 bit, to be mapped to [-1..1] for 3D
v.p[0] = ((short)mem.read16(addr)) / 32767f; addr += 2;
v.p[1] = ((short)mem.read16(addr)) / 32767f; addr += 2;
v.p[2] = ((short)mem.read16(addr)) / 32767f; addr += 2;
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 2 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D + ", addr=0x" + Integer.toHexString(addr - 6));
}
break;
case 3: // GU_VERTEX_32BITF
addr = (addr + 3) & ~3;
v.p[0] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.p[1] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
v.p[2] = Float.intBitsToFloat(mem.read32(addr)); addr += 4;
if (transform2D == 1) {
// Negative Z are interpreted as 0
if (v.p[2] < 0) {
v.p[2] = 0;
} else {
v.p[2] = (int) v.p[2]; // 2D positions are always integer values
}
}
if (VideoEngine.log.isTraceEnabled()) {
VideoEngine.log.trace("vertex type 3 " + v.p[0] + ", " + v.p[1] + ", " + v.p[2] + " transform2D=" + transform2D + ", addr=0x" + Integer.toHexString(addr - 12));
}
break;
}
//VideoEngine.log.debug("end " + String.format("0x%08x", addr) + " size=" + vertexSize);
lastVertex = v;
return v;
}
|
diff --git a/blueprint-sdk/src/blueprint/sdk/util/jdbc/H2Queue.java b/blueprint-sdk/src/blueprint/sdk/util/jdbc/H2Queue.java
index 477dce6..c4531bf 100644
--- a/blueprint-sdk/src/blueprint/sdk/util/jdbc/H2Queue.java
+++ b/blueprint-sdk/src/blueprint/sdk/util/jdbc/H2Queue.java
@@ -1,162 +1,163 @@
/*
License:
blueprint-sdk is licensed under the terms of Eclipse Public License(EPL) v1.0
(http://www.eclipse.org/legal/epl-v10.html)
Distribution:
Repository - https://github.com/lempel/blueprint-sdk.git
Blog - http://lempel.egloos.com
*/
package blueprint.sdk.util.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
/**
* H2 based AbstractJdbcQueue implementation (example).
*
* @author Simon Lee
* @since 2013. 8. 27.
*/
public class H2Queue extends AbstractJdbcQueue {
/** H2 Connection */
protected Connection con = null;
/** schema for queue */
protected String schema = "BLUEPRINT";
/** table for queue */
protected String table = "QUEUE";
/**
* Constructor
*
* @param datasrc
* DataSource for persistence
*/
public H2Queue(DataSource datasrc) {
super(datasrc);
}
/**
* Check connection to H2
*
* @throws SQLException
*/
protected void checkConnection() throws SQLException {
synchronized (this) {
if (con == null || con.isClosed()) {
con = datasrc.getConnection();
}
}
}
@Override
protected void createTable() throws SQLException {
checkConnection();
Statement stmt = con.createStatement();
try {
stmt.executeUpdate("CREATE SCHEMA " + schema);
} catch (SQLException e) {
if (e.getErrorCode() != 90078) {
throw e;
}
}
try {
stmt.executeUpdate("CREATE TABLE " + schema + "." + table + " ( UUID CHAR(36) NOT NULL, CONTENT VARCHAR)");
- stmt.executeUpdate("ALTER TABLE " + schema + "." + table + " ADD CONSTRAINT QUEUE_IDX_01 UNIQUE (UUID)");
+ stmt.executeUpdate("ALTER TABLE " + schema + "." + table + " ADD CONSTRAINT " + table
+ + "_IDX_01 UNIQUE (UUID)");
} catch (SQLException e) {
if (e.getErrorCode() != 42101) {
throw e;
}
} finally {
CloseHelper.close(stmt);
}
}
@Override
protected void load() throws SQLException {
checkConnection();
Statement stmt = null;
ResultSet rset = null;
try {
stmt = con.createStatement();
rset = stmt.executeQuery("SELECT UUID, CONTENT FROM " + schema + "." + table + "");
while (rset.next()) {
Element item = new Element();
item.uuid = rset.getString(1);
item.content = rset.getString(2);
queue.add(item);
}
} finally {
CloseHelper.close(stmt, rset);
}
}
@Override
protected void insert(Element element) throws SQLException {
checkConnection();
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO " + schema + "." + table + " (UUID, CONTENT) VALUES ('" + element.uuid
+ "', '" + element.content + "')");
} finally {
CloseHelper.close(stmt);
}
}
@Override
protected void delete(Element element) throws SQLException {
checkConnection();
Statement stmt = null;
try {
stmt = con.createStatement();
stmt.executeUpdate("DELETE FROM " + schema + "." + table + " WHERE UUID = '" + element.uuid + "'");
} finally {
CloseHelper.close(stmt);
}
}
/**
* @return the schema
*/
public String getSchema() {
return schema;
}
/**
* @param schema
* the schema to set
*/
public void setSchema(String schema) {
this.schema = schema;
}
/**
* @return the table
*/
public String getTable() {
return table;
}
/**
* @param table
* the table to set
*/
public void setTable(String table) {
this.table = table;
}
}
| true | true | protected void createTable() throws SQLException {
checkConnection();
Statement stmt = con.createStatement();
try {
stmt.executeUpdate("CREATE SCHEMA " + schema);
} catch (SQLException e) {
if (e.getErrorCode() != 90078) {
throw e;
}
}
try {
stmt.executeUpdate("CREATE TABLE " + schema + "." + table + " ( UUID CHAR(36) NOT NULL, CONTENT VARCHAR)");
stmt.executeUpdate("ALTER TABLE " + schema + "." + table + " ADD CONSTRAINT QUEUE_IDX_01 UNIQUE (UUID)");
} catch (SQLException e) {
if (e.getErrorCode() != 42101) {
throw e;
}
} finally {
CloseHelper.close(stmt);
}
}
| protected void createTable() throws SQLException {
checkConnection();
Statement stmt = con.createStatement();
try {
stmt.executeUpdate("CREATE SCHEMA " + schema);
} catch (SQLException e) {
if (e.getErrorCode() != 90078) {
throw e;
}
}
try {
stmt.executeUpdate("CREATE TABLE " + schema + "." + table + " ( UUID CHAR(36) NOT NULL, CONTENT VARCHAR)");
stmt.executeUpdate("ALTER TABLE " + schema + "." + table + " ADD CONSTRAINT " + table
+ "_IDX_01 UNIQUE (UUID)");
} catch (SQLException e) {
if (e.getErrorCode() != 42101) {
throw e;
}
} finally {
CloseHelper.close(stmt);
}
}
|
diff --git a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/servlet/TermsOfUseFilter.java b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/servlet/TermsOfUseFilter.java
index 88d1a07e1..076ffff0b 100644
--- a/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/servlet/TermsOfUseFilter.java
+++ b/dvn-app/trunk/src/DVN-web/src/edu/harvard/iq/dvn/core/web/servlet/TermsOfUseFilter.java
@@ -1,526 +1,527 @@
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
/*
* TermsOfUseFilter.java
*
* Created on December 13, 2006, 2:07 PM
*/
package edu.harvard.iq.dvn.core.web.servlet;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.study.DataTable;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyFile;
import edu.harvard.iq.dvn.core.study.StudyFileServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.study.VariableServiceLocal;
import edu.harvard.iq.dvn.core.vdc.*;
import edu.harvard.iq.dvn.core.web.common.VDCSessionBean;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
import javax.ejb.EJB;
import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author gdurand
* @version
*/
public class TermsOfUseFilter implements Filter {
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;
public static String TOU_DOWNLOAD="download";
public static String TOU_DEPOSIT="deposit";
public TermsOfUseFilter() {
}
@EJB
VDCServiceLocal vdcService;
@EJB
StudyServiceLocal studyService;
@EJB
VariableServiceLocal variableService;
@EJB
VDCNetworkServiceLocal vdcNetworkService;
@EJB
StudyFileServiceLocal studyFileService;
@EJB private GuestBookResponseServiceBean guestBookResponseServiceBean;
@Inject VDCSessionBean vdcSession;
public static boolean isDownloadDataverseTermsRequired(Study study, Map termsOfUseMap) {
boolean vdcTermsRequired = study.getOwner().isDownloadTermsOfUseEnabled();
if (vdcTermsRequired) {
return termsOfUseMap.get("vdc_download_" + study.getOwner().getId()) == null;
}
return false;
}
public static boolean isGuestbookRequired(Study study, Map termsOfUseMap) {
boolean vdcTermsRequired = false;
if (study.getOwner().getGuestBookQuestionnaire() != null){
vdcTermsRequired = study.getOwner().getGuestBookQuestionnaire().isEnabled();
}
if (vdcTermsRequired) {
return termsOfUseMap.get("study_guestbook_" + study.getId()) == null;
}
return false;
}
public static boolean isGuestbookBypassed(Study study, Map termsOfUseMap) {
boolean vdcTermsRequired = false;
if (study.getOwner().getGuestBookQuestionnaire() != null){
vdcTermsRequired = study.getOwner().getGuestBookQuestionnaire().isEnabled();
}
if (vdcTermsRequired) {
return termsOfUseMap.get("study_guestbook_logged_in_" + study.getId()) == null;
}
return false;
}
private void addGuestbookRecords(Study study, String fileId ) {
if (vdcSession.getLoginBean() == null){
return;
}
boolean vdcTermsRequired = false;
if (study.getOwner().getGuestBookQuestionnaire() != null){
vdcTermsRequired = study.getOwner().getGuestBookQuestionnaire().isEnabled();
}
if (vdcTermsRequired && !fileId.trim().isEmpty()) {
StringTokenizer st = new StringTokenizer(fileId, ",");
while (st.hasMoreTokens()) {
StudyFile file = studyFileService.getStudyFile(new Long(st.nextToken()));
if (study == null) {
study = file.getStudy();
}
guestBookResponseServiceBean.addGuestBookRecord(study, vdcSession.getLoginBean().getUser() ,file);
}
}
}
public static boolean isDepositDataverseTermsRequired(VDC currentVDC,
Map termsOfUseMap) {
boolean vdcTermsRequired = currentVDC.isDepositTermsOfUseEnabled();
if (vdcTermsRequired) {
return termsOfUseMap.get("vdc_deposit_" + currentVDC.getId()) == null;
}
return false;
}
public static boolean isDownloadStudyTermsRequired(Study study, Map termsOfUseMap) {
boolean studyTermsRequired = study.getReleasedVersion().getMetadata().isTermsOfUseEnabled();
if (studyTermsRequired) {
return termsOfUseMap.get("study_download_" + study.getId()) == null;
}
return false;
}
public static boolean isDownloadDvnTermsRequired(VDCNetwork vdcNetwork, Map termsOfUseMap) {
boolean dvnTermsRequired = vdcNetwork.isDownloadTermsOfUseEnabled();
if (dvnTermsRequired) {
return termsOfUseMap.get("dvn_download") == null;
}
return false;
}
public static boolean isDepositDvnTermsRequired(VDCNetwork vdcNetwork, Map termsOfUseMap) {
boolean dvnTermsRequired = vdcNetwork.isDepositTermsOfUseEnabled();
if (dvnTermsRequired) {
return termsOfUseMap.get("dvn_deposit") == null;
}
return false;
}
private Map getTermsOfUseMap() {
if (vdcSession.getLoginBean() != null) {
return vdcSession.getLoginBean().getTermsfUseMap();
} else {
return vdcSession.getTermsfUseMap();
}
}
/**
*
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
log("TermsOfUseFilter:doFilter()");
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
boolean redirected = false;
if (req.getServletPath().equals("/FileDownload") || (req.getServletPath().equals("/faces")
&& req.getPathInfo().startsWith("/subsetting/SubsettingPage"))
|| req.getServletPath().equals("/faces") && (req.getPathInfo().startsWith("/viz/ExploreDataPage"))) {
redirected = checkDownloadTermsOfUse(req, res);
} else if (req.getServletPath().equals("/faces") && (req.getPathInfo().startsWith("/study/EditStudyPage") || req.getPathInfo().startsWith("/study/AddFilesPage") ) ) {
redirected = checkDepositTermsOfUse(req, res);
}
if (!redirected) {
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
//
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
//
problem = t;
t.printStackTrace();
}
//
// If there was a problem, we want to rethrow it if it is
// a known type, otherwise log it.
//
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
}
/**
* Return the filter configuration object for this filter.
*/
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
/**
* Set the filter configuration object for this filter.
*
* @param filterConfig The filter configuration object
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Destroy method for this filter
*
*/
public void destroy() {
}
/**
* Init method for this filter
*
*/
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (debug) {
log("TermsOfUseFilter:Initializing filter");
}
}
}
/**
* Return a String representation of this object.
*/
public String toString() {
if (filterConfig == null) {
return ("TermsOfUseFilter()");
}
StringBuffer sb = new StringBuffer("TermsOfUseFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private boolean checkDepositTermsOfUse(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
Map termsOfUseMap = getTermsOfUseMap();
String studyId = req.getParameter("studyId");
VDC currentVDC = vdcService.getVDCFromRequest(req);
VDC depositVDC = null;
if (studyId!=null) {
depositVDC = studyService.getStudy(Long.parseLong(studyId)).getOwner();
} else {
depositVDC = currentVDC;
}
if (isDepositDvnTermsRequired(vdcNetworkService.find(), termsOfUseMap) ||(depositVDC!=null && isDepositDataverseTermsRequired(depositVDC,termsOfUseMap))) {
String params = "?tou="+TOU_DEPOSIT;
params += "&studyId=" + studyId;
params += "&redirectPage=" + URLEncoder.encode(req.getServletPath() + req.getPathInfo() + "?" + req.getQueryString(), "UTF-8");
if (currentVDC != null) {
params += "&vdcId=" + currentVDC.getId();
}
res.sendRedirect(req.getContextPath() + "/faces/study/TermsOfUsePage.xhtml" + params);
return true; // don't continue with chain since we are redirecting'
}
return false;
}
private boolean checkDownloadTermsOfUse(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
String fileId = req.getParameter("fileId");
String catId = req.getParameter("catId");
String studyId = req.getParameter("studyId");
String versionNumber = req.getParameter("versionNumber");
String requestPath = req.getPathInfo();
String imageThumb = req.getParameter("imageThumb");
Study study = null;
if (req.getServletPath().equals("/FileDownload")) {
if (fileId != null) {
try {
// a user can now download a comma delimited list of files; so we have to check the study of each of these
// and if any are from a different study, go to error page
StringTokenizer st = new StringTokenizer(fileId,",");
while (st.hasMoreTokens()) {
StudyFile file = studyFileService.getStudyFile(new Long(st.nextToken()));
if (study == null) {
study = file.getStudy();
} else if ( !study.equals(file.getStudy()) ) {
res.sendRedirect(req.getContextPath() + "/ExceptionHandler?You may not download multiple files from different studies.");
//res.sendRedirect(req.getContextPath() + "/faces/ErrorPage.xhtml");
return true; // don't continue with chain since we are redirecting'
}
}
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// do nothing.
// if the file does not exist, there sure
// isn't a license/terms of use for it!
} else {
ex.printStackTrace();
return false;
}
}
} else if (studyId != null) {
try {
study = studyService.getStudy(new Long(studyId));
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// do nothing.
// if the study does not exist, there sure
// isn't a license/terms of use for it!
} else {
ex.printStackTrace();
return false;
}
}
}
} else if (req.getServletPath().equals("/faces")) {
if (requestPath.startsWith("/subsetting/SubsettingPage")) {
String dtId = req.getParameter("dtId");
if (dtId != null) {
DataTable dt = variableService.getDataTable(new Long(dtId));
study = dt.getStudyFile().getStudy();
+ fileId = dt.getStudyFile().getId().toString();
}
}
if (requestPath.startsWith("/viz/ExploreDataPage")) {
String vFileId = req.getParameter("fileId");
StudyFile file = studyFileService.getStudyFile(new Long(vFileId));
if (study == null) {
study = file.getStudy();
}
}
}
// if we've populate the study, then check the TermsOfUse'
// We only need to display the terms if the study is Released.
if (study.getReleasedVersion() != null) {
// the code below is for determining if the request is from
// our registered DSB host; (then no agreement form should be
// displayed!)
// this logic is essentially cut-and-pasted from
// FileDownloadServlet.java, where I added it earlie this year.
String dsbHost = System.getProperty("vdc.dsb.host");
if (dsbHost == null) {
dsbHost = System.getProperty("vdc.dsb.url");
}
String localHostByName = "localhost";
String localHostNumeric = "127.0.0.1";
boolean NOTaDSBrequest = true;
if ( dsbHost.equals(req.getRemoteHost()) ||
localHostByName.equals(req.getRemoteHost()) ||
localHostNumeric.equals(req.getRemoteHost()) ) {
NOTaDSBrequest = false;
} else {
try {
String dsbHostIPAddress = InetAddress.getByName(dsbHost).getHostAddress();
if (dsbHostIPAddress.equals(req.getRemoteHost())) {
NOTaDSBrequest = false;
}
} catch (UnknownHostException ex) {
// do nothing;
// the "vdc.dsb.host" setting is clearly misconfigured,
// so we just keep assuming this is NOT a DSB call
}
}
if ( imageThumb != null ) {
NOTaDSBrequest = false;
}
if (NOTaDSBrequest) {
Map termsOfUseMap = getTermsOfUseMap();
if (!isGuestbookBypassed(study, termsOfUseMap)){
addGuestbookRecords(study, fileId);
}
if (isDownloadDvnTermsRequired(vdcNetworkService.find(), termsOfUseMap)
|| isDownloadDataverseTermsRequired(study, termsOfUseMap)
|| isDownloadStudyTermsRequired(study, termsOfUseMap)
|| isGuestbookRequired(study, termsOfUseMap)) {
VDC currentVDC = vdcService.getVDCFromRequest(req);
String params = "?studyId=" + study.getId();
if ( versionNumber != null ) {
params += "&versionNumber=" + versionNumber;
}
if ( fileId != null && !fileId.trim().isEmpty() ) {
params += "&fileId=" + fileId;
}
params += "&redirectPage=" + URLEncoder.encode(req.getServletPath() + req.getPathInfo() + "?" + req.getQueryString(), "UTF-8");
params += "&tou="+TOU_DOWNLOAD;
if (currentVDC != null) {
params += "&vdcId=" + currentVDC.getId();
}
res.sendRedirect(req.getContextPath() + "/faces/study/TermsOfUsePage.xhtml" + params);
return true; // don't continue with chain since we are redirecting'
}
}
}
return false;
}
private void sendProcessingError(Throwable t, ServletResponse response) {
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
PrintStream ps = new PrintStream(response.getOutputStream());
PrintWriter pw = new PrintWriter(ps);
pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
// PENDING! Localize this for next official release
pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
pw.print(stackTrace);
pw.print("</pre></body>\n</html>"); //NOI18N
pw.close();
ps.close();
response.getOutputStream().close();
;
} catch (Exception ex) {
}
} else {
try {
PrintStream ps = new PrintStream(response.getOutputStream());
t.printStackTrace(ps);
ps.close();
response.getOutputStream().close();
;
} catch (Exception ex) {
}
}
}
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}
public void log(String msg) {
filterConfig.getServletContext().log(msg);
}
private static final boolean debug = true;
}
| true | true | private boolean checkDownloadTermsOfUse(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
String fileId = req.getParameter("fileId");
String catId = req.getParameter("catId");
String studyId = req.getParameter("studyId");
String versionNumber = req.getParameter("versionNumber");
String requestPath = req.getPathInfo();
String imageThumb = req.getParameter("imageThumb");
Study study = null;
if (req.getServletPath().equals("/FileDownload")) {
if (fileId != null) {
try {
// a user can now download a comma delimited list of files; so we have to check the study of each of these
// and if any are from a different study, go to error page
StringTokenizer st = new StringTokenizer(fileId,",");
while (st.hasMoreTokens()) {
StudyFile file = studyFileService.getStudyFile(new Long(st.nextToken()));
if (study == null) {
study = file.getStudy();
} else if ( !study.equals(file.getStudy()) ) {
res.sendRedirect(req.getContextPath() + "/ExceptionHandler?You may not download multiple files from different studies.");
//res.sendRedirect(req.getContextPath() + "/faces/ErrorPage.xhtml");
return true; // don't continue with chain since we are redirecting'
}
}
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// do nothing.
// if the file does not exist, there sure
// isn't a license/terms of use for it!
} else {
ex.printStackTrace();
return false;
}
}
} else if (studyId != null) {
try {
study = studyService.getStudy(new Long(studyId));
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// do nothing.
// if the study does not exist, there sure
// isn't a license/terms of use for it!
} else {
ex.printStackTrace();
return false;
}
}
}
} else if (req.getServletPath().equals("/faces")) {
if (requestPath.startsWith("/subsetting/SubsettingPage")) {
String dtId = req.getParameter("dtId");
if (dtId != null) {
DataTable dt = variableService.getDataTable(new Long(dtId));
study = dt.getStudyFile().getStudy();
}
}
if (requestPath.startsWith("/viz/ExploreDataPage")) {
String vFileId = req.getParameter("fileId");
StudyFile file = studyFileService.getStudyFile(new Long(vFileId));
if (study == null) {
study = file.getStudy();
}
}
}
// if we've populate the study, then check the TermsOfUse'
// We only need to display the terms if the study is Released.
if (study.getReleasedVersion() != null) {
// the code below is for determining if the request is from
// our registered DSB host; (then no agreement form should be
// displayed!)
// this logic is essentially cut-and-pasted from
// FileDownloadServlet.java, where I added it earlie this year.
String dsbHost = System.getProperty("vdc.dsb.host");
if (dsbHost == null) {
dsbHost = System.getProperty("vdc.dsb.url");
}
String localHostByName = "localhost";
String localHostNumeric = "127.0.0.1";
boolean NOTaDSBrequest = true;
if ( dsbHost.equals(req.getRemoteHost()) ||
localHostByName.equals(req.getRemoteHost()) ||
localHostNumeric.equals(req.getRemoteHost()) ) {
NOTaDSBrequest = false;
} else {
try {
String dsbHostIPAddress = InetAddress.getByName(dsbHost).getHostAddress();
if (dsbHostIPAddress.equals(req.getRemoteHost())) {
NOTaDSBrequest = false;
}
} catch (UnknownHostException ex) {
// do nothing;
// the "vdc.dsb.host" setting is clearly misconfigured,
// so we just keep assuming this is NOT a DSB call
}
}
if ( imageThumb != null ) {
NOTaDSBrequest = false;
}
if (NOTaDSBrequest) {
Map termsOfUseMap = getTermsOfUseMap();
if (!isGuestbookBypassed(study, termsOfUseMap)){
addGuestbookRecords(study, fileId);
}
if (isDownloadDvnTermsRequired(vdcNetworkService.find(), termsOfUseMap)
|| isDownloadDataverseTermsRequired(study, termsOfUseMap)
|| isDownloadStudyTermsRequired(study, termsOfUseMap)
|| isGuestbookRequired(study, termsOfUseMap)) {
VDC currentVDC = vdcService.getVDCFromRequest(req);
String params = "?studyId=" + study.getId();
if ( versionNumber != null ) {
params += "&versionNumber=" + versionNumber;
}
if ( fileId != null && !fileId.trim().isEmpty() ) {
params += "&fileId=" + fileId;
}
params += "&redirectPage=" + URLEncoder.encode(req.getServletPath() + req.getPathInfo() + "?" + req.getQueryString(), "UTF-8");
params += "&tou="+TOU_DOWNLOAD;
if (currentVDC != null) {
params += "&vdcId=" + currentVDC.getId();
}
res.sendRedirect(req.getContextPath() + "/faces/study/TermsOfUsePage.xhtml" + params);
return true; // don't continue with chain since we are redirecting'
}
}
}
return false;
}
| private boolean checkDownloadTermsOfUse(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
String fileId = req.getParameter("fileId");
String catId = req.getParameter("catId");
String studyId = req.getParameter("studyId");
String versionNumber = req.getParameter("versionNumber");
String requestPath = req.getPathInfo();
String imageThumb = req.getParameter("imageThumb");
Study study = null;
if (req.getServletPath().equals("/FileDownload")) {
if (fileId != null) {
try {
// a user can now download a comma delimited list of files; so we have to check the study of each of these
// and if any are from a different study, go to error page
StringTokenizer st = new StringTokenizer(fileId,",");
while (st.hasMoreTokens()) {
StudyFile file = studyFileService.getStudyFile(new Long(st.nextToken()));
if (study == null) {
study = file.getStudy();
} else if ( !study.equals(file.getStudy()) ) {
res.sendRedirect(req.getContextPath() + "/ExceptionHandler?You may not download multiple files from different studies.");
//res.sendRedirect(req.getContextPath() + "/faces/ErrorPage.xhtml");
return true; // don't continue with chain since we are redirecting'
}
}
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// do nothing.
// if the file does not exist, there sure
// isn't a license/terms of use for it!
} else {
ex.printStackTrace();
return false;
}
}
} else if (studyId != null) {
try {
study = studyService.getStudy(new Long(studyId));
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalArgumentException) {
// do nothing.
// if the study does not exist, there sure
// isn't a license/terms of use for it!
} else {
ex.printStackTrace();
return false;
}
}
}
} else if (req.getServletPath().equals("/faces")) {
if (requestPath.startsWith("/subsetting/SubsettingPage")) {
String dtId = req.getParameter("dtId");
if (dtId != null) {
DataTable dt = variableService.getDataTable(new Long(dtId));
study = dt.getStudyFile().getStudy();
fileId = dt.getStudyFile().getId().toString();
}
}
if (requestPath.startsWith("/viz/ExploreDataPage")) {
String vFileId = req.getParameter("fileId");
StudyFile file = studyFileService.getStudyFile(new Long(vFileId));
if (study == null) {
study = file.getStudy();
}
}
}
// if we've populate the study, then check the TermsOfUse'
// We only need to display the terms if the study is Released.
if (study.getReleasedVersion() != null) {
// the code below is for determining if the request is from
// our registered DSB host; (then no agreement form should be
// displayed!)
// this logic is essentially cut-and-pasted from
// FileDownloadServlet.java, where I added it earlie this year.
String dsbHost = System.getProperty("vdc.dsb.host");
if (dsbHost == null) {
dsbHost = System.getProperty("vdc.dsb.url");
}
String localHostByName = "localhost";
String localHostNumeric = "127.0.0.1";
boolean NOTaDSBrequest = true;
if ( dsbHost.equals(req.getRemoteHost()) ||
localHostByName.equals(req.getRemoteHost()) ||
localHostNumeric.equals(req.getRemoteHost()) ) {
NOTaDSBrequest = false;
} else {
try {
String dsbHostIPAddress = InetAddress.getByName(dsbHost).getHostAddress();
if (dsbHostIPAddress.equals(req.getRemoteHost())) {
NOTaDSBrequest = false;
}
} catch (UnknownHostException ex) {
// do nothing;
// the "vdc.dsb.host" setting is clearly misconfigured,
// so we just keep assuming this is NOT a DSB call
}
}
if ( imageThumb != null ) {
NOTaDSBrequest = false;
}
if (NOTaDSBrequest) {
Map termsOfUseMap = getTermsOfUseMap();
if (!isGuestbookBypassed(study, termsOfUseMap)){
addGuestbookRecords(study, fileId);
}
if (isDownloadDvnTermsRequired(vdcNetworkService.find(), termsOfUseMap)
|| isDownloadDataverseTermsRequired(study, termsOfUseMap)
|| isDownloadStudyTermsRequired(study, termsOfUseMap)
|| isGuestbookRequired(study, termsOfUseMap)) {
VDC currentVDC = vdcService.getVDCFromRequest(req);
String params = "?studyId=" + study.getId();
if ( versionNumber != null ) {
params += "&versionNumber=" + versionNumber;
}
if ( fileId != null && !fileId.trim().isEmpty() ) {
params += "&fileId=" + fileId;
}
params += "&redirectPage=" + URLEncoder.encode(req.getServletPath() + req.getPathInfo() + "?" + req.getQueryString(), "UTF-8");
params += "&tou="+TOU_DOWNLOAD;
if (currentVDC != null) {
params += "&vdcId=" + currentVDC.getId();
}
res.sendRedirect(req.getContextPath() + "/faces/study/TermsOfUsePage.xhtml" + params);
return true; // don't continue with chain since we are redirecting'
}
}
}
return false;
}
|
diff --git a/src/play/modules/log4play/Log4PlayEvent.java b/src/play/modules/log4play/Log4PlayEvent.java
index 9d88af4..64c02a1 100644
--- a/src/play/modules/log4play/Log4PlayEvent.java
+++ b/src/play/modules/log4play/Log4PlayEvent.java
@@ -1,81 +1,82 @@
/**
* Copyright 2011 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.
*
* @author Felipe Oliveira (http://mashup.fm)
*
*/
package play.modules.log4play;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
/**
* The Class Log4PlayEvent.
*/
public class Log4PlayEvent {
/** The level. */
public String level;
/** The category. */
public String category;
/** The thread. */
public String thread;
/** The message. */
public String message;
/** The date. */
public String date;
/**
* Instantiates a new log4 play event.
*
* @param event
* the event
*/
public Log4PlayEvent(LoggingEvent event) {
// Define Date Format
DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
// Set Data Fields
this.category = event.categoryName;
this.thread = event.getThreadName();
this.date = dateFormat.format(new Date(event.getTimeStamp()));
this.message = event.getRenderedMessage();
+ this.message = this.message.replaceAll("\u003c", "<").replaceAll("\u003e", ">");
// Set Log Level
if (event.getLevel().toInt() == Level.TRACE_INT) {
this.level = "TRACE";
}
if (event.getLevel().toInt() == Level.DEBUG_INT) {
this.level = "DEBUG";
}
if (event.getLevel().toInt() == Level.INFO_INT) {
this.level = "INFO";
}
if (event.getLevel().toInt() == Level.WARN_INT) {
this.level = "WARN";
}
if (event.getLevel().toInt() == Level.ERROR_INT) {
this.level = "ERROR";
}
}
}
| true | true | public Log4PlayEvent(LoggingEvent event) {
// Define Date Format
DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
// Set Data Fields
this.category = event.categoryName;
this.thread = event.getThreadName();
this.date = dateFormat.format(new Date(event.getTimeStamp()));
this.message = event.getRenderedMessage();
// Set Log Level
if (event.getLevel().toInt() == Level.TRACE_INT) {
this.level = "TRACE";
}
if (event.getLevel().toInt() == Level.DEBUG_INT) {
this.level = "DEBUG";
}
if (event.getLevel().toInt() == Level.INFO_INT) {
this.level = "INFO";
}
if (event.getLevel().toInt() == Level.WARN_INT) {
this.level = "WARN";
}
if (event.getLevel().toInt() == Level.ERROR_INT) {
this.level = "ERROR";
}
}
| public Log4PlayEvent(LoggingEvent event) {
// Define Date Format
DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
// Set Data Fields
this.category = event.categoryName;
this.thread = event.getThreadName();
this.date = dateFormat.format(new Date(event.getTimeStamp()));
this.message = event.getRenderedMessage();
this.message = this.message.replaceAll("\u003c", "<").replaceAll("\u003e", ">");
// Set Log Level
if (event.getLevel().toInt() == Level.TRACE_INT) {
this.level = "TRACE";
}
if (event.getLevel().toInt() == Level.DEBUG_INT) {
this.level = "DEBUG";
}
if (event.getLevel().toInt() == Level.INFO_INT) {
this.level = "INFO";
}
if (event.getLevel().toInt() == Level.WARN_INT) {
this.level = "WARN";
}
if (event.getLevel().toInt() == Level.ERROR_INT) {
this.level = "ERROR";
}
}
|
diff --git a/htroot/WatchCrawler_p.java b/htroot/WatchCrawler_p.java
index 1d4582ec3..55420564f 100644
--- a/htroot/WatchCrawler_p.java
+++ b/htroot/WatchCrawler_p.java
@@ -1,392 +1,392 @@
// WatchCrawler_p.java
// (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
// first published 18.12.2006 on http://www.anomic.de
// this file was created using the an implementation from IndexCreate_p.java, published 02.12.2004
//
// This is a part of YaCy, a peer-to-peer based web search engine
//
// $LastChangedDate: 2006-04-02 22:40:07 +0200 (So, 02 Apr 2006) $
// $LastChangedRevision: 1986 $
// $LastChangedBy: orbiter $
//
// LICENSE
//
// 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
import java.io.File;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import de.anomic.htmlFilter.htmlFilterContentScraper;
import de.anomic.htmlFilter.htmlFilterWriter;
import de.anomic.http.httpHeader;
import de.anomic.net.URL;
import de.anomic.plasma.plasmaCrawlProfile;
import de.anomic.plasma.plasmaCrawlZURL;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaURL;
import de.anomic.plasma.dbImport.dbImporter;
import de.anomic.server.serverFileUtils;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.yacyNewsRecord;
public class WatchCrawler_p {
public static final String CRAWLING_MODE_URL = "url";
public static final String CRAWLING_MODE_FILE = "file";
public static final String CRAWLING_MODE_SITEMAP = "sitemap";
// this servlet does NOT create the WatchCrawler page content!
// this servlet starts a web crawl. The interface for entering the web crawl parameters is in IndexCreate_p.html
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
// not a crawl start, only monitoring
prop.put("info", 0);
} else {
prop.put("info", 0);
if (post.containsKey("continue")) {
// continue queue
String queue = post.get("continue", "");
if (queue.equals("localcrawler")) {
switchboard.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
switchboard.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_GLOBAL_CRAWL_TRIGGER);
}
}
if (post.containsKey("pause")) {
// pause queue
String queue = post.get("pause", "");
if (queue.equals("localcrawler")) {
switchboard.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
switchboard.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_GLOBAL_CRAWL_TRIGGER);
}
}
if (post.containsKey("crawlingstart")) {
// init crawl
if (yacyCore.seedDB == null) {
prop.put("info", 3);
} else {
// set new properties
String newcrawlingfilter = post.get("crawlingFilter", ".*");
env.setConfig("crawlingFilter", newcrawlingfilter);
int newcrawlingdepth = Integer.parseInt(post.get("crawlingDepth", "0"));
env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth));
boolean crawlingIfOlderCheck = post.get("crawlingIfOlderCheck", "off").equals("on");
int crawlingIfOlderNumber = Integer.parseInt(post.get("crawlingIfOlderNumber", "-1"));
String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year");
int crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
env.setConfig("crawlingIfOlder", crawlingIfOlder);
boolean crawlingDomFilterCheck = post.get("crawlingDomFilterCheck", "off").equals("on");
int crawlingDomFilterDepth = (crawlingDomFilterCheck) ? Integer.parseInt(post.get("crawlingDomFilterDepth", "-1")) : -1;
env.setConfig("crawlingDomFilterDepth", Integer.toString(crawlingDomFilterDepth));
boolean crawlingDomMaxCheck = post.get("crawlingDomMaxCheck", "off").equals("on");
int crawlingDomMaxPages = (crawlingDomMaxCheck) ? Integer.parseInt(post.get("crawlingDomMaxPages", "-1")) : -1;
env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages));
boolean crawlingQ = post.get("crawlingQ", "off").equals("on");
env.setConfig("crawlingQ", (crawlingQ) ? "true" : "false");
boolean indexText = post.get("indexText", "off").equals("on");
env.setConfig("indexText", (indexText) ? "true" : "false");
boolean indexMedia = post.get("indexMedia", "off").equals("on");
env.setConfig("indexMedia", (indexMedia) ? "true" : "false");
boolean storeHTCache = post.get("storeHTCache", "off").equals("on");
env.setConfig("storeHTCache", (storeHTCache) ? "true" : "false");
boolean crawlOrder = post.get("crawlOrder", "off").equals("on");
env.setConfig("crawlOrder", (crawlOrder) ? "true" : "false");
boolean xsstopw = post.get("xsstopw", "off").equals("on");
env.setConfig("xsstopw", (xsstopw) ? "true" : "false");
boolean xdstopw = post.get("xdstopw", "off").equals("on");
env.setConfig("xdstopw", (xdstopw) ? "true" : "false");
boolean xpstopw = post.get("xpstopw", "off").equals("on");
env.setConfig("xpstopw", (xpstopw) ? "true" : "false");
String crawlingMode = post.get("crawlingMode","url");
if (crawlingMode.equals(CRAWLING_MODE_URL)) {
// getting the crawljob start url
String crawlingStart = post.get("crawlingURL","");
crawlingStart = crawlingStart.trim();
// adding the prefix http:// if necessary
int pos = crawlingStart.indexOf("://");
if (pos == -1) crawlingStart = "http://" + crawlingStart;
// normalizing URL
try {crawlingStart = new URL(crawlingStart).toNormalform();} catch (MalformedURLException e1) {}
// check if url is proper
URL crawlingStartURL = null;
try {
crawlingStartURL = new URL(crawlingStart);
} catch (MalformedURLException e) {
crawlingStartURL = null;
}
// check if pattern matches
if ((crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) {
// print error message
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_crawlingStart", crawlingStart);
} else try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// stack request
// first delete old entry, if exists
String urlhash = plasmaURL.urlHash(crawlingStart);
switchboard.wordIndex.loadedURL.remove(urlhash);
switchboard.noticeURL.remove(urlhash);
switchboard.errorURL.remove(urlhash);
// stack url
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(
crawlingStartURL.getHost(), crawlingStart, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
String reasonString = switchboard.sbStackCrawlThread.stackCrawl(crawlingStart, null, yacyCore.seedDB.mySeed.hash, "CRAWLING-ROOT", new Date(), 0, pe);
if (reasonString == null) {
// liftoff!
prop.put("info", 8);//start msg
prop.put("info_crawlingURL", ((String) post.get("crawlingURL")));
// generate a YaCyNews if the global flag was set
if (crawlOrder) {
Map m = new HashMap(pe.map()); // must be cloned
m.remove("specificDepth");
m.remove("indexText");
m.remove("indexMedia");
m.remove("remoteIndexing");
m.remove("xsstopw");
m.remove("xpstopw");
m.remove("xdstopw");
m.remove("storeTXCache");
m.remove("storeHTCache");
m.remove("generalFilter");
m.remove("specificFilter");
m.put("intention", post.get("intention", "").replace(',', '/'));
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_CRAWL_START, m));
}
} else {
prop.put("info", 5); //Crawling failed
prop.put("info_crawlingURL", ((String) post.get("crawlingURL")));
prop.put("info_reasonString", reasonString);
plasmaCrawlZURL.Entry ee = switchboard.errorURL.newEntry(crawlingStartURL, reasonString);
ee.store();
switchboard.errorURL.stackPushEntry(ee);
}
} catch (PatternSyntaxException e) {
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_error", e.getMessage());
} catch (Exception e) {
// mist
prop.put("info", 6);//Error with url
prop.put("info_crawlingStart", crawlingStart);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
} else if (crawlingMode.equals(CRAWLING_MODE_FILE)) {
if (post.containsKey("crawlingFile")) {
// getting the name of the uploaded file
String fileName = (String) post.get("crawlingFile");
try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// loading the file content
File file = new File(fileName);
// getting the content of the bookmark file
byte[] fileContent = (byte[]) post.get("crawlingFile$file");
// TODO: determine the real charset here ....
String fileString = new String(fileContent,"UTF-8");
// parsing the bookmark file and fetching the headline and contained links
htmlFilterContentScraper scraper = new htmlFilterContentScraper(new URL(file));
//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
serverFileUtils.write(fileString,writer);
writer.close();
//String headline = scraper.getHeadline();
HashMap hyperlinks = (HashMap) scraper.getAnchors();
// creating a crawler profile
plasmaCrawlProfile.entry profile = switchboard.profiles.newEntry(fileName, "file://" + file.toString(), newcrawlingfilter, newcrawlingfilter, newcrawlingdepth, newcrawlingdepth, crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// loop through the contained links
Iterator interator = hyperlinks.entrySet().iterator();
int c = 0;
while (interator.hasNext()) {
Map.Entry e = (Map.Entry) interator.next();
String nexturlstring = (String) e.getKey();
if (nexturlstring == null) continue;
nexturlstring = nexturlstring.trim();
// normalizing URL
nexturlstring = new URL(nexturlstring).toNormalform();
// generating an url object
URL nexturlURL = null;
try {
nexturlURL = new URL(nexturlstring);
} catch (MalformedURLException ex) {
nexturlURL = null;
c++;
continue;
}
// enqueuing the url for crawling
String rejectReason = switchboard.sbStackCrawlThread.stackCrawl(nexturlstring, null, yacyCore.seedDB.mySeed.hash, (String)e.getValue(), new Date(), 1, profile);
// if something failed add the url into the errorURL list
if (rejectReason == null) {
c++;
} else {
plasmaCrawlZURL.Entry ee = switchboard.errorURL.newEntry(nexturlURL, rejectReason);
ee.store();
switchboard.errorURL.stackPushEntry(ee);
}
}
} catch (PatternSyntaxException e) {
// print error message
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_error", e.getMessage());
} catch (Exception e) {
// mist
prop.put("info", 7);//Error with file
prop.put("info_crawlingStart", fileName);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
}
} else if (crawlingMode.equals(CRAWLING_MODE_SITEMAP)) {
String sitemapURLStr = null;
try {
// getting the sitemap URL
sitemapURLStr = post.get("sitemapURL","");
// create a new profile
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(
sitemapURLStr, sitemapURLStr, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// create a new sitemap importer
dbImporter importerThread = switchboard.dbImportManager.getNewImporter("sitemap");
if (importerThread != null) {
HashMap initParams = new HashMap();
initParams.put("sitemapURL",sitemapURLStr);
initParams.put("crawlingProfile",pe.handle());
importerThread.init(initParams);
importerThread.startIt();
}
} catch (Exception e) {
// mist
prop.put("info", 6);//Error with url
prop.put("info_crawlingStart", sitemapURLStr);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
}
}
}
if (post.containsKey("crawlingPerformance")) {
setPerformance(switchboard, post);
}
}
// performance settings
long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
- int LCppm = (int) (60000L / LCbusySleep);
+ int LCppm = (int) (60000L / Math.max(1,LCbusySleep));
prop.put("crawlingSpeedMaxChecked", (LCppm >= 1000) ? 1 : 0);
prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 1000)) ? 1 : 0);
prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? 1 : 0);
prop.put("customPPMdefault", ((LCppm > 10) && (LCppm < 1000)) ? Integer.toString(LCppm) : "");
// return rewrite properties
return prop;
}
private static int recrawlIfOlderC(boolean recrawlIfOlderCheck, int recrawlIfOlderNumber, String crawlingIfOlderUnit) {
if (!recrawlIfOlderCheck) return -1;
if (crawlingIfOlderUnit.equals("year")) return recrawlIfOlderNumber * 60 * 24 * 365;
if (crawlingIfOlderUnit.equals("month")) return recrawlIfOlderNumber * 60 * 24 * 30;
if (crawlingIfOlderUnit.equals("day")) return recrawlIfOlderNumber * 60 * 24;
if (crawlingIfOlderUnit.equals("hour")) return recrawlIfOlderNumber * 60;
if (crawlingIfOlderUnit.equals("minute")) return recrawlIfOlderNumber;
return -1;
}
private static void setPerformance(plasmaSwitchboard sb, serverObjects post) {
String crawlingPerformance = post.get("crawlingPerformance","custom");
long LCbusySleep = Integer.parseInt(sb.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
int wantedPPM = (int) (60000L / LCbusySleep);
try {
wantedPPM = Integer.parseInt(post.get("customPPM",Integer.toString(wantedPPM)));
} catch (NumberFormatException e) {}
if (crawlingPerformance.equals("minimum")) wantedPPM = 10;
if (crawlingPerformance.equals("maximum")) wantedPPM = 1000;
sb.setPerformance(wantedPPM);
}
}
| true | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
// not a crawl start, only monitoring
prop.put("info", 0);
} else {
prop.put("info", 0);
if (post.containsKey("continue")) {
// continue queue
String queue = post.get("continue", "");
if (queue.equals("localcrawler")) {
switchboard.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
switchboard.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_GLOBAL_CRAWL_TRIGGER);
}
}
if (post.containsKey("pause")) {
// pause queue
String queue = post.get("pause", "");
if (queue.equals("localcrawler")) {
switchboard.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
switchboard.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_GLOBAL_CRAWL_TRIGGER);
}
}
if (post.containsKey("crawlingstart")) {
// init crawl
if (yacyCore.seedDB == null) {
prop.put("info", 3);
} else {
// set new properties
String newcrawlingfilter = post.get("crawlingFilter", ".*");
env.setConfig("crawlingFilter", newcrawlingfilter);
int newcrawlingdepth = Integer.parseInt(post.get("crawlingDepth", "0"));
env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth));
boolean crawlingIfOlderCheck = post.get("crawlingIfOlderCheck", "off").equals("on");
int crawlingIfOlderNumber = Integer.parseInt(post.get("crawlingIfOlderNumber", "-1"));
String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year");
int crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
env.setConfig("crawlingIfOlder", crawlingIfOlder);
boolean crawlingDomFilterCheck = post.get("crawlingDomFilterCheck", "off").equals("on");
int crawlingDomFilterDepth = (crawlingDomFilterCheck) ? Integer.parseInt(post.get("crawlingDomFilterDepth", "-1")) : -1;
env.setConfig("crawlingDomFilterDepth", Integer.toString(crawlingDomFilterDepth));
boolean crawlingDomMaxCheck = post.get("crawlingDomMaxCheck", "off").equals("on");
int crawlingDomMaxPages = (crawlingDomMaxCheck) ? Integer.parseInt(post.get("crawlingDomMaxPages", "-1")) : -1;
env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages));
boolean crawlingQ = post.get("crawlingQ", "off").equals("on");
env.setConfig("crawlingQ", (crawlingQ) ? "true" : "false");
boolean indexText = post.get("indexText", "off").equals("on");
env.setConfig("indexText", (indexText) ? "true" : "false");
boolean indexMedia = post.get("indexMedia", "off").equals("on");
env.setConfig("indexMedia", (indexMedia) ? "true" : "false");
boolean storeHTCache = post.get("storeHTCache", "off").equals("on");
env.setConfig("storeHTCache", (storeHTCache) ? "true" : "false");
boolean crawlOrder = post.get("crawlOrder", "off").equals("on");
env.setConfig("crawlOrder", (crawlOrder) ? "true" : "false");
boolean xsstopw = post.get("xsstopw", "off").equals("on");
env.setConfig("xsstopw", (xsstopw) ? "true" : "false");
boolean xdstopw = post.get("xdstopw", "off").equals("on");
env.setConfig("xdstopw", (xdstopw) ? "true" : "false");
boolean xpstopw = post.get("xpstopw", "off").equals("on");
env.setConfig("xpstopw", (xpstopw) ? "true" : "false");
String crawlingMode = post.get("crawlingMode","url");
if (crawlingMode.equals(CRAWLING_MODE_URL)) {
// getting the crawljob start url
String crawlingStart = post.get("crawlingURL","");
crawlingStart = crawlingStart.trim();
// adding the prefix http:// if necessary
int pos = crawlingStart.indexOf("://");
if (pos == -1) crawlingStart = "http://" + crawlingStart;
// normalizing URL
try {crawlingStart = new URL(crawlingStart).toNormalform();} catch (MalformedURLException e1) {}
// check if url is proper
URL crawlingStartURL = null;
try {
crawlingStartURL = new URL(crawlingStart);
} catch (MalformedURLException e) {
crawlingStartURL = null;
}
// check if pattern matches
if ((crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) {
// print error message
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_crawlingStart", crawlingStart);
} else try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// stack request
// first delete old entry, if exists
String urlhash = plasmaURL.urlHash(crawlingStart);
switchboard.wordIndex.loadedURL.remove(urlhash);
switchboard.noticeURL.remove(urlhash);
switchboard.errorURL.remove(urlhash);
// stack url
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(
crawlingStartURL.getHost(), crawlingStart, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
String reasonString = switchboard.sbStackCrawlThread.stackCrawl(crawlingStart, null, yacyCore.seedDB.mySeed.hash, "CRAWLING-ROOT", new Date(), 0, pe);
if (reasonString == null) {
// liftoff!
prop.put("info", 8);//start msg
prop.put("info_crawlingURL", ((String) post.get("crawlingURL")));
// generate a YaCyNews if the global flag was set
if (crawlOrder) {
Map m = new HashMap(pe.map()); // must be cloned
m.remove("specificDepth");
m.remove("indexText");
m.remove("indexMedia");
m.remove("remoteIndexing");
m.remove("xsstopw");
m.remove("xpstopw");
m.remove("xdstopw");
m.remove("storeTXCache");
m.remove("storeHTCache");
m.remove("generalFilter");
m.remove("specificFilter");
m.put("intention", post.get("intention", "").replace(',', '/'));
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_CRAWL_START, m));
}
} else {
prop.put("info", 5); //Crawling failed
prop.put("info_crawlingURL", ((String) post.get("crawlingURL")));
prop.put("info_reasonString", reasonString);
plasmaCrawlZURL.Entry ee = switchboard.errorURL.newEntry(crawlingStartURL, reasonString);
ee.store();
switchboard.errorURL.stackPushEntry(ee);
}
} catch (PatternSyntaxException e) {
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_error", e.getMessage());
} catch (Exception e) {
// mist
prop.put("info", 6);//Error with url
prop.put("info_crawlingStart", crawlingStart);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
} else if (crawlingMode.equals(CRAWLING_MODE_FILE)) {
if (post.containsKey("crawlingFile")) {
// getting the name of the uploaded file
String fileName = (String) post.get("crawlingFile");
try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// loading the file content
File file = new File(fileName);
// getting the content of the bookmark file
byte[] fileContent = (byte[]) post.get("crawlingFile$file");
// TODO: determine the real charset here ....
String fileString = new String(fileContent,"UTF-8");
// parsing the bookmark file and fetching the headline and contained links
htmlFilterContentScraper scraper = new htmlFilterContentScraper(new URL(file));
//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
serverFileUtils.write(fileString,writer);
writer.close();
//String headline = scraper.getHeadline();
HashMap hyperlinks = (HashMap) scraper.getAnchors();
// creating a crawler profile
plasmaCrawlProfile.entry profile = switchboard.profiles.newEntry(fileName, "file://" + file.toString(), newcrawlingfilter, newcrawlingfilter, newcrawlingdepth, newcrawlingdepth, crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// loop through the contained links
Iterator interator = hyperlinks.entrySet().iterator();
int c = 0;
while (interator.hasNext()) {
Map.Entry e = (Map.Entry) interator.next();
String nexturlstring = (String) e.getKey();
if (nexturlstring == null) continue;
nexturlstring = nexturlstring.trim();
// normalizing URL
nexturlstring = new URL(nexturlstring).toNormalform();
// generating an url object
URL nexturlURL = null;
try {
nexturlURL = new URL(nexturlstring);
} catch (MalformedURLException ex) {
nexturlURL = null;
c++;
continue;
}
// enqueuing the url for crawling
String rejectReason = switchboard.sbStackCrawlThread.stackCrawl(nexturlstring, null, yacyCore.seedDB.mySeed.hash, (String)e.getValue(), new Date(), 1, profile);
// if something failed add the url into the errorURL list
if (rejectReason == null) {
c++;
} else {
plasmaCrawlZURL.Entry ee = switchboard.errorURL.newEntry(nexturlURL, rejectReason);
ee.store();
switchboard.errorURL.stackPushEntry(ee);
}
}
} catch (PatternSyntaxException e) {
// print error message
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_error", e.getMessage());
} catch (Exception e) {
// mist
prop.put("info", 7);//Error with file
prop.put("info_crawlingStart", fileName);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
}
} else if (crawlingMode.equals(CRAWLING_MODE_SITEMAP)) {
String sitemapURLStr = null;
try {
// getting the sitemap URL
sitemapURLStr = post.get("sitemapURL","");
// create a new profile
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(
sitemapURLStr, sitemapURLStr, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// create a new sitemap importer
dbImporter importerThread = switchboard.dbImportManager.getNewImporter("sitemap");
if (importerThread != null) {
HashMap initParams = new HashMap();
initParams.put("sitemapURL",sitemapURLStr);
initParams.put("crawlingProfile",pe.handle());
importerThread.init(initParams);
importerThread.startIt();
}
} catch (Exception e) {
// mist
prop.put("info", 6);//Error with url
prop.put("info_crawlingStart", sitemapURLStr);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
}
}
}
if (post.containsKey("crawlingPerformance")) {
setPerformance(switchboard, post);
}
}
// performance settings
long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
int LCppm = (int) (60000L / LCbusySleep);
prop.put("crawlingSpeedMaxChecked", (LCppm >= 1000) ? 1 : 0);
prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 1000)) ? 1 : 0);
prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? 1 : 0);
prop.put("customPPMdefault", ((LCppm > 10) && (LCppm < 1000)) ? Integer.toString(LCppm) : "");
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
plasmaSwitchboard switchboard = (plasmaSwitchboard) env;
serverObjects prop = new serverObjects();
if (post == null) {
// not a crawl start, only monitoring
prop.put("info", 0);
} else {
prop.put("info", 0);
if (post.containsKey("continue")) {
// continue queue
String queue = post.get("continue", "");
if (queue.equals("localcrawler")) {
switchboard.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
switchboard.continueCrawlJob(plasmaSwitchboard.CRAWLJOB_GLOBAL_CRAWL_TRIGGER);
}
}
if (post.containsKey("pause")) {
// pause queue
String queue = post.get("pause", "");
if (queue.equals("localcrawler")) {
switchboard.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL);
} else if (queue.equals("remotecrawler")) {
switchboard.pauseCrawlJob(plasmaSwitchboard.CRAWLJOB_GLOBAL_CRAWL_TRIGGER);
}
}
if (post.containsKey("crawlingstart")) {
// init crawl
if (yacyCore.seedDB == null) {
prop.put("info", 3);
} else {
// set new properties
String newcrawlingfilter = post.get("crawlingFilter", ".*");
env.setConfig("crawlingFilter", newcrawlingfilter);
int newcrawlingdepth = Integer.parseInt(post.get("crawlingDepth", "0"));
env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth));
boolean crawlingIfOlderCheck = post.get("crawlingIfOlderCheck", "off").equals("on");
int crawlingIfOlderNumber = Integer.parseInt(post.get("crawlingIfOlderNumber", "-1"));
String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year");
int crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit);
env.setConfig("crawlingIfOlder", crawlingIfOlder);
boolean crawlingDomFilterCheck = post.get("crawlingDomFilterCheck", "off").equals("on");
int crawlingDomFilterDepth = (crawlingDomFilterCheck) ? Integer.parseInt(post.get("crawlingDomFilterDepth", "-1")) : -1;
env.setConfig("crawlingDomFilterDepth", Integer.toString(crawlingDomFilterDepth));
boolean crawlingDomMaxCheck = post.get("crawlingDomMaxCheck", "off").equals("on");
int crawlingDomMaxPages = (crawlingDomMaxCheck) ? Integer.parseInt(post.get("crawlingDomMaxPages", "-1")) : -1;
env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages));
boolean crawlingQ = post.get("crawlingQ", "off").equals("on");
env.setConfig("crawlingQ", (crawlingQ) ? "true" : "false");
boolean indexText = post.get("indexText", "off").equals("on");
env.setConfig("indexText", (indexText) ? "true" : "false");
boolean indexMedia = post.get("indexMedia", "off").equals("on");
env.setConfig("indexMedia", (indexMedia) ? "true" : "false");
boolean storeHTCache = post.get("storeHTCache", "off").equals("on");
env.setConfig("storeHTCache", (storeHTCache) ? "true" : "false");
boolean crawlOrder = post.get("crawlOrder", "off").equals("on");
env.setConfig("crawlOrder", (crawlOrder) ? "true" : "false");
boolean xsstopw = post.get("xsstopw", "off").equals("on");
env.setConfig("xsstopw", (xsstopw) ? "true" : "false");
boolean xdstopw = post.get("xdstopw", "off").equals("on");
env.setConfig("xdstopw", (xdstopw) ? "true" : "false");
boolean xpstopw = post.get("xpstopw", "off").equals("on");
env.setConfig("xpstopw", (xpstopw) ? "true" : "false");
String crawlingMode = post.get("crawlingMode","url");
if (crawlingMode.equals(CRAWLING_MODE_URL)) {
// getting the crawljob start url
String crawlingStart = post.get("crawlingURL","");
crawlingStart = crawlingStart.trim();
// adding the prefix http:// if necessary
int pos = crawlingStart.indexOf("://");
if (pos == -1) crawlingStart = "http://" + crawlingStart;
// normalizing URL
try {crawlingStart = new URL(crawlingStart).toNormalform();} catch (MalformedURLException e1) {}
// check if url is proper
URL crawlingStartURL = null;
try {
crawlingStartURL = new URL(crawlingStart);
} catch (MalformedURLException e) {
crawlingStartURL = null;
}
// check if pattern matches
if ((crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) {
// print error message
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_crawlingStart", crawlingStart);
} else try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// stack request
// first delete old entry, if exists
String urlhash = plasmaURL.urlHash(crawlingStart);
switchboard.wordIndex.loadedURL.remove(urlhash);
switchboard.noticeURL.remove(urlhash);
switchboard.errorURL.remove(urlhash);
// stack url
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(
crawlingStartURL.getHost(), crawlingStart, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
String reasonString = switchboard.sbStackCrawlThread.stackCrawl(crawlingStart, null, yacyCore.seedDB.mySeed.hash, "CRAWLING-ROOT", new Date(), 0, pe);
if (reasonString == null) {
// liftoff!
prop.put("info", 8);//start msg
prop.put("info_crawlingURL", ((String) post.get("crawlingURL")));
// generate a YaCyNews if the global flag was set
if (crawlOrder) {
Map m = new HashMap(pe.map()); // must be cloned
m.remove("specificDepth");
m.remove("indexText");
m.remove("indexMedia");
m.remove("remoteIndexing");
m.remove("xsstopw");
m.remove("xpstopw");
m.remove("xdstopw");
m.remove("storeTXCache");
m.remove("storeHTCache");
m.remove("generalFilter");
m.remove("specificFilter");
m.put("intention", post.get("intention", "").replace(',', '/'));
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_CRAWL_START, m));
}
} else {
prop.put("info", 5); //Crawling failed
prop.put("info_crawlingURL", ((String) post.get("crawlingURL")));
prop.put("info_reasonString", reasonString);
plasmaCrawlZURL.Entry ee = switchboard.errorURL.newEntry(crawlingStartURL, reasonString);
ee.store();
switchboard.errorURL.stackPushEntry(ee);
}
} catch (PatternSyntaxException e) {
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_error", e.getMessage());
} catch (Exception e) {
// mist
prop.put("info", 6);//Error with url
prop.put("info_crawlingStart", crawlingStart);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
} else if (crawlingMode.equals(CRAWLING_MODE_FILE)) {
if (post.containsKey("crawlingFile")) {
// getting the name of the uploaded file
String fileName = (String) post.get("crawlingFile");
try {
// check if the crawl filter works correctly
Pattern.compile(newcrawlingfilter);
// loading the file content
File file = new File(fileName);
// getting the content of the bookmark file
byte[] fileContent = (byte[]) post.get("crawlingFile$file");
// TODO: determine the real charset here ....
String fileString = new String(fileContent,"UTF-8");
// parsing the bookmark file and fetching the headline and contained links
htmlFilterContentScraper scraper = new htmlFilterContentScraper(new URL(file));
//OutputStream os = new htmlFilterOutputStream(null, scraper, null, false);
Writer writer = new htmlFilterWriter(null,null,scraper,null,false);
serverFileUtils.write(fileString,writer);
writer.close();
//String headline = scraper.getHeadline();
HashMap hyperlinks = (HashMap) scraper.getAnchors();
// creating a crawler profile
plasmaCrawlProfile.entry profile = switchboard.profiles.newEntry(fileName, "file://" + file.toString(), newcrawlingfilter, newcrawlingfilter, newcrawlingdepth, newcrawlingdepth, crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// loop through the contained links
Iterator interator = hyperlinks.entrySet().iterator();
int c = 0;
while (interator.hasNext()) {
Map.Entry e = (Map.Entry) interator.next();
String nexturlstring = (String) e.getKey();
if (nexturlstring == null) continue;
nexturlstring = nexturlstring.trim();
// normalizing URL
nexturlstring = new URL(nexturlstring).toNormalform();
// generating an url object
URL nexturlURL = null;
try {
nexturlURL = new URL(nexturlstring);
} catch (MalformedURLException ex) {
nexturlURL = null;
c++;
continue;
}
// enqueuing the url for crawling
String rejectReason = switchboard.sbStackCrawlThread.stackCrawl(nexturlstring, null, yacyCore.seedDB.mySeed.hash, (String)e.getValue(), new Date(), 1, profile);
// if something failed add the url into the errorURL list
if (rejectReason == null) {
c++;
} else {
plasmaCrawlZURL.Entry ee = switchboard.errorURL.newEntry(nexturlURL, rejectReason);
ee.store();
switchboard.errorURL.stackPushEntry(ee);
}
}
} catch (PatternSyntaxException e) {
// print error message
prop.put("info", 4); //crawlfilter does not match url
prop.put("info_newcrawlingfilter", newcrawlingfilter);
prop.put("info_error", e.getMessage());
} catch (Exception e) {
// mist
prop.put("info", 7);//Error with file
prop.put("info_crawlingStart", fileName);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
}
} else if (crawlingMode.equals(CRAWLING_MODE_SITEMAP)) {
String sitemapURLStr = null;
try {
// getting the sitemap URL
sitemapURLStr = post.get("sitemapURL","");
// create a new profile
plasmaCrawlProfile.entry pe = switchboard.profiles.newEntry(
sitemapURLStr, sitemapURLStr, newcrawlingfilter, newcrawlingfilter,
newcrawlingdepth, newcrawlingdepth,
crawlingIfOlder, crawlingDomFilterDepth, crawlingDomMaxPages,
crawlingQ,
indexText, indexMedia,
storeHTCache, true, crawlOrder, xsstopw, xdstopw, xpstopw);
// create a new sitemap importer
dbImporter importerThread = switchboard.dbImportManager.getNewImporter("sitemap");
if (importerThread != null) {
HashMap initParams = new HashMap();
initParams.put("sitemapURL",sitemapURLStr);
initParams.put("crawlingProfile",pe.handle());
importerThread.init(initParams);
importerThread.startIt();
}
} catch (Exception e) {
// mist
prop.put("info", 6);//Error with url
prop.put("info_crawlingStart", sitemapURLStr);
prop.put("info_error", e.getMessage());
e.printStackTrace();
}
}
}
}
if (post.containsKey("crawlingPerformance")) {
setPerformance(switchboard, post);
}
}
// performance settings
long LCbusySleep = Integer.parseInt(env.getConfig(plasmaSwitchboard.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, "100"));
int LCppm = (int) (60000L / Math.max(1,LCbusySleep));
prop.put("crawlingSpeedMaxChecked", (LCppm >= 1000) ? 1 : 0);
prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 1000)) ? 1 : 0);
prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? 1 : 0);
prop.put("customPPMdefault", ((LCppm > 10) && (LCppm < 1000)) ? Integer.toString(LCppm) : "");
// return rewrite properties
return prop;
}
|
diff --git a/nephele/nephele-common/src/test/java/eu/stratosphere/nephele/io/library/FileLineReadWriteTest.java b/nephele/nephele-common/src/test/java/eu/stratosphere/nephele/io/library/FileLineReadWriteTest.java
index 0086389a7..02eb8aba6 100644
--- a/nephele/nephele-common/src/test/java/eu/stratosphere/nephele/io/library/FileLineReadWriteTest.java
+++ b/nephele/nephele-common/src/test/java/eu/stratosphere/nephele/io/library/FileLineReadWriteTest.java
@@ -1,137 +1,137 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010-2012 by the Stratosphere project (http://stratosphere.eu)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
**********************************************************************************************************************/
package eu.stratosphere.nephele.io.library;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import eu.stratosphere.nephele.configuration.Configuration;
import eu.stratosphere.nephele.execution.Environment;
import eu.stratosphere.nephele.fs.FileInputSplit;
import eu.stratosphere.nephele.fs.Path;
import eu.stratosphere.nephele.io.RecordReader;
import eu.stratosphere.nephele.io.RecordWriter;
import eu.stratosphere.nephele.template.InputSplitProvider;
import eu.stratosphere.nephele.types.StringRecord;
/**
* This class checks the functionality of the {@link FileLineReader} and the {@link FileLineWriter} class.
*
* @author marrus
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(FileLineReader.class)
public class FileLineReadWriteTest {
@Mock
private Environment environment;
@Mock
private Configuration conf;
@Mock
private RecordReader<StringRecord> recordReader;
@Mock
private RecordWriter<StringRecord> recordWriter;
@Mock
private InputSplitProvider inputSplitProvider;
private File file = new File("./tmp");
/**
* Set up mocks
*
* @throws IOException
*/
@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
}
/**
* remove the temporary file
*/
@After
public void after() {
this.file.delete();
}
/**
* Tests the read and write methods
*
* @throws Exception
*/
@Test
public void testReadWrite() throws Exception {
this.file.createNewFile();
FileLineWriter writer = new FileLineWriter();
Whitebox.setInternalState(writer, "environment", this.environment);
Whitebox.setInternalState(writer, "input", this.recordReader);
when(this.environment.getTaskConfiguration()).thenReturn(this.conf);
when(this.conf.getString("outputPath", null)).thenReturn(this.file.toURI().toString());
when(this.recordReader.hasNext()).thenReturn(true, true, true, false);
StringRecord in = new StringRecord("abc");
try {
when(this.recordReader.next()).thenReturn(in);
} catch (IOException e) {
fail();
e.printStackTrace();
} catch (InterruptedException e) {
fail();
e.printStackTrace();
}
writer.invoke();
final FileInputSplit split = new FileInputSplit(0, new Path(this.file.toURI().toString()), 0,
- this.file.length(), null);
+ this.file.length(), new String[0]);
when(this.environment.getInputSplitProvider()).thenReturn(this.inputSplitProvider);
when(this.inputSplitProvider.getNextInputSplit()).thenReturn(split, (FileInputSplit) null);
FileLineReader reader = new FileLineReader();
Whitebox.setInternalState(reader, "environment", this.environment);
Whitebox.setInternalState(reader, "output", this.recordWriter);
StringRecord record = mock(StringRecord.class);
whenNew(StringRecord.class).withNoArguments().thenReturn(record);
reader.invoke();
// verify the correct bytes have been written and read
verify(record, times(3)).set(in.getBytes());
}
}
| true | true | public void testReadWrite() throws Exception {
this.file.createNewFile();
FileLineWriter writer = new FileLineWriter();
Whitebox.setInternalState(writer, "environment", this.environment);
Whitebox.setInternalState(writer, "input", this.recordReader);
when(this.environment.getTaskConfiguration()).thenReturn(this.conf);
when(this.conf.getString("outputPath", null)).thenReturn(this.file.toURI().toString());
when(this.recordReader.hasNext()).thenReturn(true, true, true, false);
StringRecord in = new StringRecord("abc");
try {
when(this.recordReader.next()).thenReturn(in);
} catch (IOException e) {
fail();
e.printStackTrace();
} catch (InterruptedException e) {
fail();
e.printStackTrace();
}
writer.invoke();
final FileInputSplit split = new FileInputSplit(0, new Path(this.file.toURI().toString()), 0,
this.file.length(), null);
when(this.environment.getInputSplitProvider()).thenReturn(this.inputSplitProvider);
when(this.inputSplitProvider.getNextInputSplit()).thenReturn(split, (FileInputSplit) null);
FileLineReader reader = new FileLineReader();
Whitebox.setInternalState(reader, "environment", this.environment);
Whitebox.setInternalState(reader, "output", this.recordWriter);
StringRecord record = mock(StringRecord.class);
whenNew(StringRecord.class).withNoArguments().thenReturn(record);
reader.invoke();
// verify the correct bytes have been written and read
verify(record, times(3)).set(in.getBytes());
}
| public void testReadWrite() throws Exception {
this.file.createNewFile();
FileLineWriter writer = new FileLineWriter();
Whitebox.setInternalState(writer, "environment", this.environment);
Whitebox.setInternalState(writer, "input", this.recordReader);
when(this.environment.getTaskConfiguration()).thenReturn(this.conf);
when(this.conf.getString("outputPath", null)).thenReturn(this.file.toURI().toString());
when(this.recordReader.hasNext()).thenReturn(true, true, true, false);
StringRecord in = new StringRecord("abc");
try {
when(this.recordReader.next()).thenReturn(in);
} catch (IOException e) {
fail();
e.printStackTrace();
} catch (InterruptedException e) {
fail();
e.printStackTrace();
}
writer.invoke();
final FileInputSplit split = new FileInputSplit(0, new Path(this.file.toURI().toString()), 0,
this.file.length(), new String[0]);
when(this.environment.getInputSplitProvider()).thenReturn(this.inputSplitProvider);
when(this.inputSplitProvider.getNextInputSplit()).thenReturn(split, (FileInputSplit) null);
FileLineReader reader = new FileLineReader();
Whitebox.setInternalState(reader, "environment", this.environment);
Whitebox.setInternalState(reader, "output", this.recordWriter);
StringRecord record = mock(StringRecord.class);
whenNew(StringRecord.class).withNoArguments().thenReturn(record);
reader.invoke();
// verify the correct bytes have been written and read
verify(record, times(3)).set(in.getBytes());
}
|
diff --git a/simulator/code/simulator/elevatorcontrol/DoorControl.java b/simulator/code/simulator/elevatorcontrol/DoorControl.java
index 224b0dd..d603884 100755
--- a/simulator/code/simulator/elevatorcontrol/DoorControl.java
+++ b/simulator/code/simulator/elevatorcontrol/DoorControl.java
@@ -1,347 +1,347 @@
/* 18649 Fall 2012
* (Group 17)
* Jesse Salazar (jessesal)
* Rajeev Sharma (rdsharma) - Author
* Collin Buchan (cbuchan)
* Jessica Tiu (jtiu)
*/
package simulator.elevatorcontrol;
import jSimPack.SimTime;
import simulator.elevatormodules.CarWeightCanPayloadTranslator;
import simulator.elevatormodules.DoorClosedCanPayloadTranslator;
import simulator.elevatormodules.DoorOpenedCanPayloadTranslator;
import simulator.elevatormodules.DoorReversalCanPayloadTranslator;
import simulator.framework.*;
import simulator.payloads.CanMailbox;
import simulator.payloads.CanMailbox.ReadableCanMailbox;
import simulator.payloads.CanMailbox.WriteableCanMailbox;
import simulator.payloads.DoorMotorPayload;
import simulator.payloads.DoorMotorPayload.WriteableDoorMotorPayload;
/**
* DoorControl controls DoorMotor objects based on current call and safety states.
*
* @author Rajeev Sharma
*/
public class DoorControl extends Controller {
/**
* ************************************************************************
* Declarations
* ************************************************************************
*/
//note that inputs are Readable objects, while outputs are Writeable objects
//local physical state
private WriteableDoorMotorPayload localDoorMotor;
private WriteableCanMailbox networkDoorMotorCommandOut;
private DoorMotorCommandCanPayloadTranslator mDoorMotorCommand;
private Utility.AtFloorArray networkAtFloorArray;
private ReadableCanMailbox networkDriveSpeed;
private DriveSpeedCanPayloadTranslator mDriveSpeed;
private ReadableCanMailbox networkDesiredFloor;
private DesiredFloorCanPayloadTranslator mDesiredFloor;
private ReadableCanMailbox networkDesiredDwell;
private DesiredDwellCanPayloadTranslator mDesiredDwell;
private ReadableCanMailbox networkDoorClosed;
private DoorClosedCanPayloadTranslator mDoorClosed;
private ReadableCanMailbox networkDoorOpened;
private DoorOpenedCanPayloadTranslator mDoorOpened;
private ReadableCanMailbox networkDoorReversal;
private DoorReversalCanPayloadTranslator mDoorReversal;
private Utility.CarCallArray networkCarCallArray;
private Utility.HallCallArray networkHallCallArray;
private ReadableCanMailbox networkCarWeight;
private CarWeightCanPayloadTranslator mCarWeight;
//these variables keep track of which instance this is.
private final Hallway hallway;
private final Side side;
// local state variables
private int dwell = 0;
private SimTime countDown = SimTime.ZERO;
//store the period for the controller
private SimTime period;
//internal constant declarations
//enumerate states
private enum State {
STATE_DOOR_CLOSING,
STATE_DOOR_CLOSED,
STATE_DOOR_OPENING,
STATE_DOOR_OPEN,
STATE_DOOR_OPEN_E,
}
//state variable initialized to the initial state DOOR_CLOSING
private State state = State.STATE_DOOR_CLOSING;
/**
* The arguments listed in the .cf configuration file should match the order and
* type given here.
* <p/>
* For your elevator controllers, you should make sure that the constructor matches
* the method signatures in ControllerBuilder.makeAll().
*/
public DoorControl(Hallway hallway, Side side, SimTime period, boolean verbose) {
//call to the Controller superclass constructor is required
super("DoorControl" + ReplicationComputer.makeReplicationString(hallway, side), verbose);
//stored the constructor arguments in internal state
this.period = period;
this.hallway = hallway;
this.side = side;
log("Created DoorControl[", this.hallway, "][", this.side, "]");
localDoorMotor = DoorMotorPayload.getWriteablePayload(hallway, side);
physicalInterface.sendTimeTriggered(localDoorMotor, period);
//initialize network interface
//create a can mailbox - this object has the binary representation of the message data
//the CAN message ids are declared in the MessageDictionary class. The ReplicationComputer
//class provides utility methods for computing offsets for replicated controllers
networkDoorMotorCommandOut = CanMailbox.getWriteableCanMailbox(
MessageDictionary.DOOR_MOTOR_COMMAND_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(hallway, side));
mDoorMotorCommand = new DoorMotorCommandCanPayloadTranslator(
networkDoorMotorCommandOut, hallway, side);
canInterface.sendTimeTriggered(networkDoorMotorCommandOut, period);
networkAtFloorArray = new Utility.AtFloorArray(canInterface);
networkDriveSpeed = CanMailbox.getReadableCanMailbox(
MessageDictionary.DRIVE_SPEED_CAN_ID);
mDriveSpeed = new DriveSpeedCanPayloadTranslator(networkDriveSpeed);
canInterface.registerTimeTriggered(networkDriveSpeed);
networkDesiredFloor = CanMailbox.getReadableCanMailbox(
MessageDictionary.DESIRED_FLOOR_CAN_ID);
mDesiredFloor = new DesiredFloorCanPayloadTranslator(networkDesiredFloor);
canInterface.registerTimeTriggered(networkDesiredFloor);
networkDesiredDwell = CanMailbox.getReadableCanMailbox(
MessageDictionary.DESIRED_DWELL_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(hallway));
mDesiredDwell = new DesiredDwellCanPayloadTranslator(
networkDesiredDwell, hallway);
canInterface.registerTimeTriggered(networkDesiredDwell);
networkDoorClosed = CanMailbox.getReadableCanMailbox(
MessageDictionary.DOOR_CLOSED_SENSOR_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(hallway, side));
mDoorClosed = new DoorClosedCanPayloadTranslator(
networkDoorClosed, hallway, side);
canInterface.registerTimeTriggered(networkDoorClosed);
networkDoorOpened = CanMailbox.getReadableCanMailbox(
MessageDictionary.DOOR_OPEN_SENSOR_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(hallway, side));
mDoorOpened = new DoorOpenedCanPayloadTranslator(
networkDoorOpened, hallway, side);
canInterface.registerTimeTriggered(networkDoorOpened);
networkDoorReversal = CanMailbox.getReadableCanMailbox(
MessageDictionary.DOOR_REVERSAL_SENSOR_BASE_CAN_ID +
ReplicationComputer.computeReplicationId(hallway, side));
mDoorReversal = new DoorReversalCanPayloadTranslator(
networkDoorReversal, hallway, side);
canInterface.registerTimeTriggered(networkDoorReversal);
networkCarCallArray = new Utility.CarCallArray(hallway, canInterface);
networkHallCallArray = new Utility.HallCallArray(canInterface);
networkCarWeight = CanMailbox.getReadableCanMailbox(
MessageDictionary.CAR_WEIGHT_CAN_ID);
mCarWeight = new CarWeightCanPayloadTranslator(networkCarWeight);
canInterface.registerTimeTriggered(networkCarWeight);
timer.start(period);
}
/*
* The timer callback is where the main controller code is executed. For time
* triggered design, this consists mainly of a switch block with a case block for
* each state. Each case block executes actions for that state, then executes
* a transition to the next state if the transition conditions are met.
*/
@Override
public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DOOR_CLOSING:
//state actions
localDoorMotor.set(DoorCommand.NUDGE);
mDoorMotorCommand.set(DoorCommand.NUDGE);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
//transitions -- note that transition conditions are mutually exclusive
//#transition 'T5.5'
if (isValidHallway() && isStopped()
&& ((isDesiredFloor() && isDesiredHallway())
|| (isOverweight() && !doorOpened())
|| (isDoorReversal() && !doorOpened()))) {
newState = State.STATE_DOOR_OPENING;
}
//#transition 'T5.1'
else if (doorClosed()) {
newState = State.STATE_DOOR_CLOSED;
} else {
newState = state;
}
break;
case STATE_DOOR_CLOSED:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
//transitions
//#transition 'T5.2'
if (isValidHallway() && isStopped()
&& ((isDesiredFloor() && isDesiredHallway())
|| (isOverweight() && !doorOpened())
|| (isDoorReversal() && !doorOpened()))) {
newState = State.STATE_DOOR_OPENING;
} else {
newState = state;
}
break;
case STATE_DOOR_OPENING:
//state actions
localDoorMotor.set(DoorCommand.OPEN);
mDoorMotorCommand.set(DoorCommand.OPEN);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
//transitions
//#transition 'T5.3'
if (doorOpened() && !isOverweight() && !isDoorReversal()) {
newState = State.STATE_DOOR_OPEN;
}
//#transition 'T5.6'
- else if (!doorOpened() && (isOverweight() || isDoorReversal())) {
+ else if (doorOpened() && (isOverweight() || isDoorReversal())) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.subtract(countDown, period);
//transitions
//#transition 'T5.4'
if (countDown.isLessThanOrEqual(SimTime.ZERO)) {
newState = State.STATE_DOOR_CLOSING;
}
//#transition 'T5.7'
else if (isOverweight() || isDoorReversal()) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN_E:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
//transitions
//#transition 'T5.8'
if (!isOverweight() && !isDoorReversal()) {
newState = State.STATE_DOOR_OPEN;
} else {
newState = state;
}
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
private Boolean isValidHallway() {
if (networkAtFloorArray.getCurrentFloor() == MessageDictionary.NONE) {
return false;
} else {
return Elevator.hasLanding(networkAtFloorArray.getCurrentFloor(), hallway);
}
}
private Boolean isStopped() {
return mDriveSpeed.getSpeed() == Speed.STOP;
}
private Boolean isOverweight() {
return mCarWeight.getWeight() >= Elevator.MaxCarCapacity;
}
private Boolean doorOpened() {
return mDoorOpened.getValue() == true;
}
private Boolean doorClosed() {
return mDoorClosed.getValue() == true;
}
private Boolean isDoorReversal() {
return mDoorReversal.getValue() == true;
}
private Boolean isDesiredFloor() {
return networkAtFloorArray.getCurrentFloor() == mDesiredFloor.getFloor();
}
private Boolean isDesiredHallway() {
return (hallway == mDesiredFloor.getHallway() || mDesiredFloor.getHallway() == Hallway.BOTH);
}
}
| true | true | public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DOOR_CLOSING:
//state actions
localDoorMotor.set(DoorCommand.NUDGE);
mDoorMotorCommand.set(DoorCommand.NUDGE);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
//transitions -- note that transition conditions are mutually exclusive
//#transition 'T5.5'
if (isValidHallway() && isStopped()
&& ((isDesiredFloor() && isDesiredHallway())
|| (isOverweight() && !doorOpened())
|| (isDoorReversal() && !doorOpened()))) {
newState = State.STATE_DOOR_OPENING;
}
//#transition 'T5.1'
else if (doorClosed()) {
newState = State.STATE_DOOR_CLOSED;
} else {
newState = state;
}
break;
case STATE_DOOR_CLOSED:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
//transitions
//#transition 'T5.2'
if (isValidHallway() && isStopped()
&& ((isDesiredFloor() && isDesiredHallway())
|| (isOverweight() && !doorOpened())
|| (isDoorReversal() && !doorOpened()))) {
newState = State.STATE_DOOR_OPENING;
} else {
newState = state;
}
break;
case STATE_DOOR_OPENING:
//state actions
localDoorMotor.set(DoorCommand.OPEN);
mDoorMotorCommand.set(DoorCommand.OPEN);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
//transitions
//#transition 'T5.3'
if (doorOpened() && !isOverweight() && !isDoorReversal()) {
newState = State.STATE_DOOR_OPEN;
}
//#transition 'T5.6'
else if (!doorOpened() && (isOverweight() || isDoorReversal())) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.subtract(countDown, period);
//transitions
//#transition 'T5.4'
if (countDown.isLessThanOrEqual(SimTime.ZERO)) {
newState = State.STATE_DOOR_CLOSING;
}
//#transition 'T5.7'
else if (isOverweight() || isDoorReversal()) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN_E:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
//transitions
//#transition 'T5.8'
if (!isOverweight() && !isDoorReversal()) {
newState = State.STATE_DOOR_OPEN;
} else {
newState = state;
}
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
| public void timerExpired(Object callbackData) {
State newState = state;
switch (state) {
case STATE_DOOR_CLOSING:
//state actions
localDoorMotor.set(DoorCommand.NUDGE);
mDoorMotorCommand.set(DoorCommand.NUDGE);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
//transitions -- note that transition conditions are mutually exclusive
//#transition 'T5.5'
if (isValidHallway() && isStopped()
&& ((isDesiredFloor() && isDesiredHallway())
|| (isOverweight() && !doorOpened())
|| (isDoorReversal() && !doorOpened()))) {
newState = State.STATE_DOOR_OPENING;
}
//#transition 'T5.1'
else if (doorClosed()) {
newState = State.STATE_DOOR_CLOSED;
} else {
newState = state;
}
break;
case STATE_DOOR_CLOSED:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.ZERO;
//transitions
//#transition 'T5.2'
if (isValidHallway() && isStopped()
&& ((isDesiredFloor() && isDesiredHallway())
|| (isOverweight() && !doorOpened())
|| (isDoorReversal() && !doorOpened()))) {
newState = State.STATE_DOOR_OPENING;
} else {
newState = state;
}
break;
case STATE_DOOR_OPENING:
//state actions
localDoorMotor.set(DoorCommand.OPEN);
mDoorMotorCommand.set(DoorCommand.OPEN);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
//transitions
//#transition 'T5.3'
if (doorOpened() && !isOverweight() && !isDoorReversal()) {
newState = State.STATE_DOOR_OPEN;
}
//#transition 'T5.6'
else if (doorOpened() && (isOverweight() || isDoorReversal())) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = SimTime.subtract(countDown, period);
//transitions
//#transition 'T5.4'
if (countDown.isLessThanOrEqual(SimTime.ZERO)) {
newState = State.STATE_DOOR_CLOSING;
}
//#transition 'T5.7'
else if (isOverweight() || isDoorReversal()) {
newState = State.STATE_DOOR_OPEN_E;
} else {
newState = state;
}
break;
case STATE_DOOR_OPEN_E:
//state actions
localDoorMotor.set(DoorCommand.STOP);
mDoorMotorCommand.set(DoorCommand.STOP);
dwell = mDesiredDwell.getDwell();
countDown = new SimTime(dwell, SimTime.SimTimeUnit.SECOND);
//transitions
//#transition 'T5.8'
if (!isOverweight() && !isDoorReversal()) {
newState = State.STATE_DOOR_OPEN;
} else {
newState = state;
}
break;
default:
throw new RuntimeException("State " + state + " was not recognized.");
}
//log the results of this iteration
if (state == newState) {
log("remains in state: ", state);
} else {
log("Transition:", state, "->", newState);
}
//update the state variable
state = newState;
//report the current state
setState(STATE_KEY, newState.toString());
//schedule the next iteration of the controller
//you must do this at the end of the timer callback in order to restart
//the timer
timer.start(period);
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/lib/UnpackedObjectLoader.java b/org.eclipse.jgit/src/org/eclipse/jgit/lib/UnpackedObjectLoader.java
index 968dada0..005df4b9 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/lib/UnpackedObjectLoader.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/lib/UnpackedObjectLoader.java
@@ -1,212 +1,211 @@
/*
* Copyright (C) 2007, Robin Rosenberg <[email protected]>
* Copyright (C) 2006-2008, Shawn O. Pearce <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.lib;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.util.IO;
import org.eclipse.jgit.util.MutableInteger;
import org.eclipse.jgit.util.RawParseUtils;
/**
* Loose object loader. This class loads an object not stored in a pack.
*/
public class UnpackedObjectLoader extends ObjectLoader {
private final int objectType;
private final int objectSize;
private final byte[] bytes;
/**
* Construct an ObjectLoader to read from the file.
*
* @param path
* location of the loose object to read.
* @param id
* expected identity of the object being loaded, if known.
* @throws FileNotFoundException
* the loose object file does not exist.
* @throws IOException
* the loose object file exists, but is corrupt.
*/
public UnpackedObjectLoader(final File path, final AnyObjectId id)
throws IOException {
this(IO.readFully(path), id);
}
/**
* Construct an ObjectLoader from a loose object's compressed form.
*
* @param compressed
* entire content of the loose object file.
* @throws CorruptObjectException
* The compressed data supplied does not match the format for a
* valid loose object.
*/
public UnpackedObjectLoader(final byte[] compressed)
throws CorruptObjectException {
this(compressed, null);
}
private UnpackedObjectLoader(final byte[] compressed, final AnyObjectId id)
throws CorruptObjectException {
// Try to determine if this is a legacy format loose object or
// a new style loose object. The legacy format was completely
// compressed with zlib so the first byte must be 0x78 (15-bit
// window size, deflated) and the first 16 bit word must be
// evenly divisible by 31. Otherwise its a new style loose
// object.
//
final Inflater inflater = InflaterCache.get();
try {
final int fb = compressed[0] & 0xff;
if (fb == 0x78 && (((fb << 8) | compressed[1] & 0xff) % 31) == 0) {
inflater.setInput(compressed);
final byte[] hdr = new byte[64];
int avail = 0;
while (!inflater.finished() && avail < hdr.length)
try {
avail += inflater.inflate(hdr, avail, hdr.length
- avail);
} catch (DataFormatException dfe) {
final CorruptObjectException coe;
coe = new CorruptObjectException(id, "bad stream");
coe.initCause(dfe);
- inflater.end();
throw coe;
}
if (avail < 5)
throw new CorruptObjectException(id, "no header");
final MutableInteger p = new MutableInteger();
objectType = Constants.decodeTypeString(id, hdr, (byte) ' ', p);
objectSize = RawParseUtils.parseBase10(hdr, p.value, p);
if (objectSize < 0)
throw new CorruptObjectException(id, "negative size");
if (hdr[p.value++] != 0)
throw new CorruptObjectException(id, "garbage after size");
bytes = new byte[objectSize];
if (p.value < avail)
System.arraycopy(hdr, p.value, bytes, 0, avail - p.value);
decompress(id, inflater, avail - p.value);
} else {
int p = 0;
int c = compressed[p++] & 0xff;
final int typeCode = (c >> 4) & 7;
int size = c & 15;
int shift = 4;
while ((c & 0x80) != 0) {
c = compressed[p++] & 0xff;
size += (c & 0x7f) << shift;
shift += 7;
}
switch (typeCode) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG:
objectType = typeCode;
break;
default:
throw new CorruptObjectException(id, "invalid type");
}
objectSize = size;
bytes = new byte[objectSize];
inflater.setInput(compressed, p, compressed.length - p);
decompress(id, inflater, 0);
}
} finally {
InflaterCache.release(inflater);
}
}
private void decompress(final AnyObjectId id, final Inflater inf, int p)
throws CorruptObjectException {
try {
while (!inf.finished())
p += inf.inflate(bytes, p, objectSize - p);
} catch (DataFormatException dfe) {
final CorruptObjectException coe;
coe = new CorruptObjectException(id, "bad stream");
coe.initCause(dfe);
throw coe;
}
if (p != objectSize)
throw new CorruptObjectException(id, "incorrect length");
}
@Override
public int getType() {
return objectType;
}
@Override
public long getSize() {
return objectSize;
}
@Override
public byte[] getCachedBytes() {
return bytes;
}
@Override
public int getRawType() {
return objectType;
}
@Override
public long getRawSize() {
return objectSize;
}
}
| true | true | private UnpackedObjectLoader(final byte[] compressed, final AnyObjectId id)
throws CorruptObjectException {
// Try to determine if this is a legacy format loose object or
// a new style loose object. The legacy format was completely
// compressed with zlib so the first byte must be 0x78 (15-bit
// window size, deflated) and the first 16 bit word must be
// evenly divisible by 31. Otherwise its a new style loose
// object.
//
final Inflater inflater = InflaterCache.get();
try {
final int fb = compressed[0] & 0xff;
if (fb == 0x78 && (((fb << 8) | compressed[1] & 0xff) % 31) == 0) {
inflater.setInput(compressed);
final byte[] hdr = new byte[64];
int avail = 0;
while (!inflater.finished() && avail < hdr.length)
try {
avail += inflater.inflate(hdr, avail, hdr.length
- avail);
} catch (DataFormatException dfe) {
final CorruptObjectException coe;
coe = new CorruptObjectException(id, "bad stream");
coe.initCause(dfe);
inflater.end();
throw coe;
}
if (avail < 5)
throw new CorruptObjectException(id, "no header");
final MutableInteger p = new MutableInteger();
objectType = Constants.decodeTypeString(id, hdr, (byte) ' ', p);
objectSize = RawParseUtils.parseBase10(hdr, p.value, p);
if (objectSize < 0)
throw new CorruptObjectException(id, "negative size");
if (hdr[p.value++] != 0)
throw new CorruptObjectException(id, "garbage after size");
bytes = new byte[objectSize];
if (p.value < avail)
System.arraycopy(hdr, p.value, bytes, 0, avail - p.value);
decompress(id, inflater, avail - p.value);
} else {
int p = 0;
int c = compressed[p++] & 0xff;
final int typeCode = (c >> 4) & 7;
int size = c & 15;
int shift = 4;
while ((c & 0x80) != 0) {
c = compressed[p++] & 0xff;
size += (c & 0x7f) << shift;
shift += 7;
}
switch (typeCode) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG:
objectType = typeCode;
break;
default:
throw new CorruptObjectException(id, "invalid type");
}
objectSize = size;
bytes = new byte[objectSize];
inflater.setInput(compressed, p, compressed.length - p);
decompress(id, inflater, 0);
}
} finally {
InflaterCache.release(inflater);
}
}
| private UnpackedObjectLoader(final byte[] compressed, final AnyObjectId id)
throws CorruptObjectException {
// Try to determine if this is a legacy format loose object or
// a new style loose object. The legacy format was completely
// compressed with zlib so the first byte must be 0x78 (15-bit
// window size, deflated) and the first 16 bit word must be
// evenly divisible by 31. Otherwise its a new style loose
// object.
//
final Inflater inflater = InflaterCache.get();
try {
final int fb = compressed[0] & 0xff;
if (fb == 0x78 && (((fb << 8) | compressed[1] & 0xff) % 31) == 0) {
inflater.setInput(compressed);
final byte[] hdr = new byte[64];
int avail = 0;
while (!inflater.finished() && avail < hdr.length)
try {
avail += inflater.inflate(hdr, avail, hdr.length
- avail);
} catch (DataFormatException dfe) {
final CorruptObjectException coe;
coe = new CorruptObjectException(id, "bad stream");
coe.initCause(dfe);
throw coe;
}
if (avail < 5)
throw new CorruptObjectException(id, "no header");
final MutableInteger p = new MutableInteger();
objectType = Constants.decodeTypeString(id, hdr, (byte) ' ', p);
objectSize = RawParseUtils.parseBase10(hdr, p.value, p);
if (objectSize < 0)
throw new CorruptObjectException(id, "negative size");
if (hdr[p.value++] != 0)
throw new CorruptObjectException(id, "garbage after size");
bytes = new byte[objectSize];
if (p.value < avail)
System.arraycopy(hdr, p.value, bytes, 0, avail - p.value);
decompress(id, inflater, avail - p.value);
} else {
int p = 0;
int c = compressed[p++] & 0xff;
final int typeCode = (c >> 4) & 7;
int size = c & 15;
int shift = 4;
while ((c & 0x80) != 0) {
c = compressed[p++] & 0xff;
size += (c & 0x7f) << shift;
shift += 7;
}
switch (typeCode) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG:
objectType = typeCode;
break;
default:
throw new CorruptObjectException(id, "invalid type");
}
objectSize = size;
bytes = new byte[objectSize];
inflater.setInput(compressed, p, compressed.length - p);
decompress(id, inflater, 0);
}
} finally {
InflaterCache.release(inflater);
}
}
|
diff --git a/src/gui/graphical/Panel.java b/src/gui/graphical/Panel.java
index 4238688..e06db37 100644
--- a/src/gui/graphical/Panel.java
+++ b/src/gui/graphical/Panel.java
@@ -1,116 +1,116 @@
package gui.graphical;
// Default Libraries
import java.io.IOException;
import java.lang.reflect.Field;
// Graphical Libraries (AWT)
import java.awt.*;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
// Graphical Libraries (Swing)
import javax.swing.*;
import javax.imageio.ImageIO;
import javax.swing.SwingUtilities;
// Libraries
import arena.Map;
import parameters.*;
/**
* <b>Graphical - Panel</b><br>
* Creates the main panel to exhibit
* the map.
* @see Graphical
* @see arena.Map
* @see arena.World
*
* @author Renato Cordeiro Ferreira
* @author Vinicius Silva
*/
public class Panel extends JPanel
implements Game
{
// Map made with cells
private Cell[][] cell = new Cell[MAP_SIZE][MAP_SIZE];
// Local variables
private Map map;
private int width;
private int height;
/**
* Create a Panel with dimensions width x height,
* containing MAP_SIZE² hexagons (built from a map).
* @see Cell
* @see Graphical
*
* @param R radius
* @param width Desired width of the screen
* @param height Desired height of the screen
* @param map Map over which the panel will
* create the GUI hexagons
*/
Panel(int R, int width, int height, Map map)
{
this.map = map;
// Dimensions
this.width = width;
this.height = height;
// Preferences
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(width, height));
int Dx = (int) ( 2*R * Math.sin(Math.PI/3) );
- int Dy = 3 * R/2;
+ int Dy = 3 * R/2 +1;
// Put images in the screen
int Δ = 0;
for (int i = 0; i < MAP_SIZE; i++)
for (int j = 0; j < MAP_SIZE; j++)
{
cell[i][j] = new Cell(
Δ + R + i*Dx, R + j*Dy, R, map.map[j][i]
);
Δ = (Δ == 0) ? Dx/2 : 0;
}
}
void blackPanel(Graphics g)
{
g.setColor(Color.black) ;
g.fillRect(0, 0, width, height);
}
/**
* Paint hexagons on the screen.<br>
* At each step, repaint the cells
* as they need changes.
* @param g Graphic object with all context
* needed to render the image
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < MAP_SIZE; i++)
for (int j = 0; j < MAP_SIZE; j++)
{
cell[i][j].draw(g);
if(cell[i][j].terrain.getItem() != null)
{
Images test = Images.valueOf(cell[i][j].terrain.getItem().name());
g2d.drawImage(test.img(), cell[i][j].x-13, cell[i][j].y-13, null);
}
if(cell[i][j].terrain.getScenario() != null)
{
Images test = Images.valueOf(cell[i][j].terrain.getScenario().name());
g2d.drawImage(test.img(), cell[i][j].x-13, cell[i][j].y-13, null);
}
}
}
}
| true | true | Panel(int R, int width, int height, Map map)
{
this.map = map;
// Dimensions
this.width = width;
this.height = height;
// Preferences
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(width, height));
int Dx = (int) ( 2*R * Math.sin(Math.PI/3) );
int Dy = 3 * R/2;
// Put images in the screen
int Δ = 0;
for (int i = 0; i < MAP_SIZE; i++)
for (int j = 0; j < MAP_SIZE; j++)
{
cell[i][j] = new Cell(
Δ + R + i*Dx, R + j*Dy, R, map.map[j][i]
);
Δ = (Δ == 0) ? Dx/2 : 0;
}
}
| Panel(int R, int width, int height, Map map)
{
this.map = map;
// Dimensions
this.width = width;
this.height = height;
// Preferences
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(width, height));
int Dx = (int) ( 2*R * Math.sin(Math.PI/3) );
int Dy = 3 * R/2 +1;
// Put images in the screen
int Δ = 0;
for (int i = 0; i < MAP_SIZE; i++)
for (int j = 0; j < MAP_SIZE; j++)
{
cell[i][j] = new Cell(
Δ + R + i*Dx, R + j*Dy, R, map.map[j][i]
);
Δ = (Δ == 0) ? Dx/2 : 0;
}
}
|
diff --git a/integration-tests/src/test/java/de/escidoc/core/test/om/container/rest/ContainerRetrieveRestTest.java b/integration-tests/src/test/java/de/escidoc/core/test/om/container/rest/ContainerRetrieveRestTest.java
index 794355776..82e520762 100644
--- a/integration-tests/src/test/java/de/escidoc/core/test/om/container/rest/ContainerRetrieveRestTest.java
+++ b/integration-tests/src/test/java/de/escidoc/core/test/om/container/rest/ContainerRetrieveRestTest.java
@@ -1,84 +1,84 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at license/ESCIDOC.LICENSE
* or http://www.escidoc.de/license.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at license/ESCIDOC.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2006-2008 Fachinformationszentrum Karlsruhe Gesellschaft
* fuer wissenschaftlich-technische Information mbH and Max-Planck-
* Gesellschaft zur Foerderung der Wissenschaft e.V.
* All rights reserved. Use is subject to license terms.
*/
package de.escidoc.core.test.om.container.rest;
import org.junit.Test;
import de.escidoc.core.test.EscidocRestSoapTestBase;
import de.escidoc.core.test.om.container.ContainerTestBase;
import de.escidoc.core.test.common.client.servlet.Constants;
/**
* Container tests with REST transport.
*
* @author MSC
*
*/
public class ContainerRetrieveRestTest extends ContainerTestBase {
private String theItemId;
/**
* Constructor.
*
*/
public ContainerRetrieveRestTest() {
super(Constants.TRANSPORT_REST);
}
/**
* Test successfully retrieving of container.
*
* @throws Exception
* Thrown if retrieve fails.
*/
@Test
public void testRetrieveResources() throws Exception {
String xmlData =
EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_ITEM_PATH
+ "/" + getTransport(false), "escidoc_item_198_for_create.xml");
String theItemXml = handleXmlResult(getItemClient().create(xmlData));
this.theItemId = getObjidValue(theItemXml);
xmlData =
- EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_CONTAINER_PATH,
+ EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_CONTAINER_PATH + "/rest",
"create_container_v1.1-forItem.xml");
String theContainerXml = create(xmlData.replaceAll("##ITEMID##", theItemId));
String theContainerId = getObjidValue(theContainerXml);
String resourcesXml = retrieveResources(theContainerId);
assertXmlValidContainer(resourcesXml);
}
}
| true | true | public void testRetrieveResources() throws Exception {
String xmlData =
EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_ITEM_PATH
+ "/" + getTransport(false), "escidoc_item_198_for_create.xml");
String theItemXml = handleXmlResult(getItemClient().create(xmlData));
this.theItemId = getObjidValue(theItemXml);
xmlData =
EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_CONTAINER_PATH,
"create_container_v1.1-forItem.xml");
String theContainerXml = create(xmlData.replaceAll("##ITEMID##", theItemId));
String theContainerId = getObjidValue(theContainerXml);
String resourcesXml = retrieveResources(theContainerId);
assertXmlValidContainer(resourcesXml);
}
| public void testRetrieveResources() throws Exception {
String xmlData =
EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_ITEM_PATH
+ "/" + getTransport(false), "escidoc_item_198_for_create.xml");
String theItemXml = handleXmlResult(getItemClient().create(xmlData));
this.theItemId = getObjidValue(theItemXml);
xmlData =
EscidocRestSoapTestBase.getTemplateAsString(TEMPLATE_CONTAINER_PATH + "/rest",
"create_container_v1.1-forItem.xml");
String theContainerXml = create(xmlData.replaceAll("##ITEMID##", theItemId));
String theContainerId = getObjidValue(theContainerXml);
String resourcesXml = retrieveResources(theContainerId);
assertXmlValidContainer(resourcesXml);
}
|
diff --git a/lilith/src/main/java/de/huxhorn/lilith/swing/table/tooltips/MessageTooltipGenerator.java b/lilith/src/main/java/de/huxhorn/lilith/swing/table/tooltips/MessageTooltipGenerator.java
index 4becbbf0..e9e0d97b 100644
--- a/lilith/src/main/java/de/huxhorn/lilith/swing/table/tooltips/MessageTooltipGenerator.java
+++ b/lilith/src/main/java/de/huxhorn/lilith/swing/table/tooltips/MessageTooltipGenerator.java
@@ -1,93 +1,93 @@
/*
* Lilith - a log event viewer.
* Copyright (C) 2007-2008 Joern Huxhorn
*
* 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 de.huxhorn.lilith.swing.table.tooltips;
import de.huxhorn.lilith.swing.table.TooltipGenerator;
import de.huxhorn.lilith.data.eventsource.EventWrapper;
import de.huxhorn.sulky.formatting.SimpleXml;
import javax.swing.JTable;
import de.huxhorn.lilith.data.logging.LoggingEvent;
import java.util.StringTokenizer;
public class MessageTooltipGenerator
implements TooltipGenerator
{
public String createTooltipText(JTable table, int row)
{
final int MAX_LINE_LENGTH=80;
final int MAX_LINES=20;
String tooltip=null;
Object value=table.getValueAt(row,0);
if(value instanceof EventWrapper)
{
EventWrapper wrapper=(EventWrapper)value;
Object eventObj = wrapper.getEvent();
if(eventObj instanceof LoggingEvent)
{
LoggingEvent event=(LoggingEvent) eventObj;
String text=event.getMessage();
if(text!=null)
{
// crop to a sane size, e.g. 80x25 characters
StringTokenizer tok=new StringTokenizer(text, "\n", false);
StringBuilder string=new StringBuilder();
int lineCounter=0;
while(tok.hasMoreTokens())
{
String line=tok.nextToken();
line=line.trim();
if(line.length()>0)
{
line=line.replace('\t',' ');
if(lineCounter<MAX_LINES)
{
if(lineCounter>0)
{
- string.append("\n>");
+ string.append("\n");
}
if(line.length()>MAX_LINE_LENGTH)
{
string.append(line.substring(0,MAX_LINE_LENGTH-4));
string.append("[..]");
}
else
{
string.append(line);
}
}
lineCounter++;
}
}
if(lineCounter>=MAX_LINES)
{
int remaining=lineCounter-MAX_LINES+1;
string.append("\n[.. ").append(remaining).append(" more lines ..]");
}
tooltip=SimpleXml.escape(string.toString());
tooltip=tooltip.replace("\n","<br>");
tooltip="<html><tt><pre>"+tooltip+"</pre></tt></html>";
}
}
}
return tooltip;
}
}
| true | true | public String createTooltipText(JTable table, int row)
{
final int MAX_LINE_LENGTH=80;
final int MAX_LINES=20;
String tooltip=null;
Object value=table.getValueAt(row,0);
if(value instanceof EventWrapper)
{
EventWrapper wrapper=(EventWrapper)value;
Object eventObj = wrapper.getEvent();
if(eventObj instanceof LoggingEvent)
{
LoggingEvent event=(LoggingEvent) eventObj;
String text=event.getMessage();
if(text!=null)
{
// crop to a sane size, e.g. 80x25 characters
StringTokenizer tok=new StringTokenizer(text, "\n", false);
StringBuilder string=new StringBuilder();
int lineCounter=0;
while(tok.hasMoreTokens())
{
String line=tok.nextToken();
line=line.trim();
if(line.length()>0)
{
line=line.replace('\t',' ');
if(lineCounter<MAX_LINES)
{
if(lineCounter>0)
{
string.append("\n>");
}
if(line.length()>MAX_LINE_LENGTH)
{
string.append(line.substring(0,MAX_LINE_LENGTH-4));
string.append("[..]");
}
else
{
string.append(line);
}
}
lineCounter++;
}
}
if(lineCounter>=MAX_LINES)
{
int remaining=lineCounter-MAX_LINES+1;
string.append("\n[.. ").append(remaining).append(" more lines ..]");
}
tooltip=SimpleXml.escape(string.toString());
tooltip=tooltip.replace("\n","<br>");
tooltip="<html><tt><pre>"+tooltip+"</pre></tt></html>";
}
}
}
return tooltip;
}
| public String createTooltipText(JTable table, int row)
{
final int MAX_LINE_LENGTH=80;
final int MAX_LINES=20;
String tooltip=null;
Object value=table.getValueAt(row,0);
if(value instanceof EventWrapper)
{
EventWrapper wrapper=(EventWrapper)value;
Object eventObj = wrapper.getEvent();
if(eventObj instanceof LoggingEvent)
{
LoggingEvent event=(LoggingEvent) eventObj;
String text=event.getMessage();
if(text!=null)
{
// crop to a sane size, e.g. 80x25 characters
StringTokenizer tok=new StringTokenizer(text, "\n", false);
StringBuilder string=new StringBuilder();
int lineCounter=0;
while(tok.hasMoreTokens())
{
String line=tok.nextToken();
line=line.trim();
if(line.length()>0)
{
line=line.replace('\t',' ');
if(lineCounter<MAX_LINES)
{
if(lineCounter>0)
{
string.append("\n");
}
if(line.length()>MAX_LINE_LENGTH)
{
string.append(line.substring(0,MAX_LINE_LENGTH-4));
string.append("[..]");
}
else
{
string.append(line);
}
}
lineCounter++;
}
}
if(lineCounter>=MAX_LINES)
{
int remaining=lineCounter-MAX_LINES+1;
string.append("\n[.. ").append(remaining).append(" more lines ..]");
}
tooltip=SimpleXml.escape(string.toString());
tooltip=tooltip.replace("\n","<br>");
tooltip="<html><tt><pre>"+tooltip+"</pre></tt></html>";
}
}
}
return tooltip;
}
|
diff --git a/src/main/java/ar/edu/itba/pdc/proxy/HttpSelectorProtocolClient.java b/src/main/java/ar/edu/itba/pdc/proxy/HttpSelectorProtocolClient.java
index c4030af..0d0ff39 100644
--- a/src/main/java/ar/edu/itba/pdc/proxy/HttpSelectorProtocolClient.java
+++ b/src/main/java/ar/edu/itba/pdc/proxy/HttpSelectorProtocolClient.java
@@ -1,207 +1,204 @@
package ar.edu.itba.pdc.proxy;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.channels.UnresolvedAddressException;
import java.util.HashMap;
import ar.edu.itba.pdc.parser.HttpRequest;
import ar.edu.itba.pdc.parser.Message;
import ar.edu.itba.pdc.parser.enumerations.ParsingState;
public class HttpSelectorProtocolClient implements TCPProtocol {
private HashMap<SocketChannel, ProxyConnection> proxyconnections = new HashMap<SocketChannel, ProxyConnection>();
public HttpSelectorProtocolClient(int bufSize) {
}
public void handleAccept(SocketChannel channel) throws IOException {
ProxyConnection conn = new ProxyConnection();
conn.setClient(channel);
proxyconnections.put(channel, conn);
}
public SocketChannel handleRead(SelectionKey key) throws IOException {
// Client socket channel has pending data
SocketChannel channel = (SocketChannel) key.channel();
ProxyConnection conn = proxyconnections.get(channel);
ByteBuffer buf = conn.getBuffer(channel);
long bytesRead = 0;
try {
bytesRead = channel.read(buf);
// System.out.println(new String(buf.array(), 0, 100));
} catch (IOException e) {
System.out.println("\nfallo el read");
e.printStackTrace();
return null;
}
System.out.println("\n[READ] " + bytesRead + " from "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
if (bytesRead == -1) { // Did the other end close?
if (conn.isClient(channel)) {
System.out.println("\n[RECEIVED CLOSE] from cliente "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
if (conn.getServer() != null) {
/* ----------------- CLOSE ----------------- */
conn.getServer().close(); // close the server channel
/* ----------------- CLOSE ----------------- */
System.out.println("\n[SENT CLOSE] to servidor remoto "
+ conn.getServer().socket().getInetAddress() + ":"
+ conn.getServer().socket().getPort());
}
/* ----------------- CLOSE ----------------- */
channel.close();
System.out.println("\n[SENT CLOSE] to cliente "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
/* ----------------- REMOVE ----------------- */
proxyconnections.remove(channel);
proxyconnections.remove(conn.getServer());
/* ----------------- CANCEL ----------------- */
key.cancel();
// de-reference the proxy connection as it is
// no longer useful
return null;
} else {
System.out.println("\n[RECEIVED CLOSE] from servidor remoto "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
/* ----------------- CLOSE ----------------- */
conn.getServer().close();
/* ----------------- CLOSE ----------------- */
// channel.close();
System.out.println("\n[SENT CLOSE] to servidor remoto "
+ conn.getServer().socket().getInetAddress() + ":"
+ conn.getServer().socket().getPort());
// proxyconnections.remove(channel);
// key.cancel();
// channel.write(buf.rewind());
conn.resetIncompleteMessage();
// proxyconnections.remove(channel);
proxyconnections.remove(conn.getServer());
conn.resetServer();
}
} else if (bytesRead > 0) {
/* ----------- PARSEO DE REQ/RESP ----------- */
Message message = conn.getMessage(channel);
message.increaseAmountRead((int) bytesRead); // DECIDIR SI INT O
message.setFrom("client" + channel.socket().getInetAddress()); // LONG
/* ----------- CONEXION A SERVIDOR DESTINO ----------- */
SocketChannel serverchannel;
if (conn.isClient(channel) && message.getState() != ParsingState.Body) {
return null;
}
if ((serverchannel = conn.getServer()) == null) {
String url = null;
if (((HttpRequest) message).getURI().startsWith("/"))
url = ((HttpRequest) message).getHeaders().get("host")
+ ((HttpRequest) message).getURI();
else
url = ((HttpRequest) message).getURI();
String[] splitted = url.split("http://");
url = "http://"
+ (splitted.length >= 2 ? splitted[1] : splitted[0]);
URL uri = new URL(url);
serverchannel = SocketChannel.open();
serverchannel.configureBlocking(false);
int port = uri.getPort() == -1 ? 80 : uri.getPort();
try {
if (!serverchannel.connect(new InetSocketAddress(uri.getHost(),
port))) {
// if (!serverchannel.connect(new
// InetSocketAddress("localhost",
// 8888))) {
while (!serverchannel.finishConnect()) {
Thread.sleep(30); // avoid massive polling
System.out.println("*");
}
}
} catch (UnresolvedAddressException e) { //TODO HACERLO DE LA FORMA BIEN. AGARRANDOLO DE UN ARCHIVO
String notFound = "HTTP/1.1 404 BAD REQUEST\r\n\r\n<html><body>404 Not Found<br><br>This may be a DNS problem or the page you were looking for doesn't exist.</body></html>\r\n";
ByteBuffer resp = ByteBuffer.allocate(notFound.length());
resp.put(notFound.getBytes());
resp.flip();
channel.write(resp);
channel.close();
proxyconnections.remove(channel);
return null;
} catch (InterruptedException e) {
e.printStackTrace();
}
conn.setServer(serverchannel);
proxyconnections.put(serverchannel, conn);
}
// Indicate via key that reading/writing are both of interest now.
key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
channel.register(key.selector(), SelectionKey.OP_WRITE);
- if (message.isFinished()) {
- System.out.println("finisheo");
- }
return serverchannel;
}
return null;
}
public void handleWrite(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ProxyConnection conn = proxyconnections.get(channel);
SocketChannel receiver = conn.getOppositeChannel(channel);
ByteBuffer buf = conn.getBuffer(channel);
Message message = conn.getIncompleteMessage();
ByteBuffer pHeadersBuf;
int byteswritten = 0;
if (message != null && (pHeadersBuf = message.getPartialHeadersBuffer()) != null) { // Headers came in different reads.
pHeadersBuf.flip();
receiver.write(pHeadersBuf);
message.finishWithLeftHeaders();
}
byteswritten = receiver.write(buf);
System.out.println("\n[WRITE] " + byteswritten + " to "
+ receiver.socket().getInetAddress() + ":"
+ receiver.socket().getPort());
buf.compact(); // Make room for more data to be read in
receiver.register(key.selector(), SelectionKey.OP_READ, conn); // receiver will write us back
key.interestOps(SelectionKey.OP_READ); // Sender has finished writing
}
}
| true | true | public SocketChannel handleRead(SelectionKey key) throws IOException {
// Client socket channel has pending data
SocketChannel channel = (SocketChannel) key.channel();
ProxyConnection conn = proxyconnections.get(channel);
ByteBuffer buf = conn.getBuffer(channel);
long bytesRead = 0;
try {
bytesRead = channel.read(buf);
// System.out.println(new String(buf.array(), 0, 100));
} catch (IOException e) {
System.out.println("\nfallo el read");
e.printStackTrace();
return null;
}
System.out.println("\n[READ] " + bytesRead + " from "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
if (bytesRead == -1) { // Did the other end close?
if (conn.isClient(channel)) {
System.out.println("\n[RECEIVED CLOSE] from cliente "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
if (conn.getServer() != null) {
/* ----------------- CLOSE ----------------- */
conn.getServer().close(); // close the server channel
/* ----------------- CLOSE ----------------- */
System.out.println("\n[SENT CLOSE] to servidor remoto "
+ conn.getServer().socket().getInetAddress() + ":"
+ conn.getServer().socket().getPort());
}
/* ----------------- CLOSE ----------------- */
channel.close();
System.out.println("\n[SENT CLOSE] to cliente "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
/* ----------------- REMOVE ----------------- */
proxyconnections.remove(channel);
proxyconnections.remove(conn.getServer());
/* ----------------- CANCEL ----------------- */
key.cancel();
// de-reference the proxy connection as it is
// no longer useful
return null;
} else {
System.out.println("\n[RECEIVED CLOSE] from servidor remoto "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
/* ----------------- CLOSE ----------------- */
conn.getServer().close();
/* ----------------- CLOSE ----------------- */
// channel.close();
System.out.println("\n[SENT CLOSE] to servidor remoto "
+ conn.getServer().socket().getInetAddress() + ":"
+ conn.getServer().socket().getPort());
// proxyconnections.remove(channel);
// key.cancel();
// channel.write(buf.rewind());
conn.resetIncompleteMessage();
// proxyconnections.remove(channel);
proxyconnections.remove(conn.getServer());
conn.resetServer();
}
} else if (bytesRead > 0) {
/* ----------- PARSEO DE REQ/RESP ----------- */
Message message = conn.getMessage(channel);
message.increaseAmountRead((int) bytesRead); // DECIDIR SI INT O
message.setFrom("client" + channel.socket().getInetAddress()); // LONG
/* ----------- CONEXION A SERVIDOR DESTINO ----------- */
SocketChannel serverchannel;
if (conn.isClient(channel) && message.getState() != ParsingState.Body) {
return null;
}
if ((serverchannel = conn.getServer()) == null) {
String url = null;
if (((HttpRequest) message).getURI().startsWith("/"))
url = ((HttpRequest) message).getHeaders().get("host")
+ ((HttpRequest) message).getURI();
else
url = ((HttpRequest) message).getURI();
String[] splitted = url.split("http://");
url = "http://"
+ (splitted.length >= 2 ? splitted[1] : splitted[0]);
URL uri = new URL(url);
serverchannel = SocketChannel.open();
serverchannel.configureBlocking(false);
int port = uri.getPort() == -1 ? 80 : uri.getPort();
try {
if (!serverchannel.connect(new InetSocketAddress(uri.getHost(),
port))) {
// if (!serverchannel.connect(new
// InetSocketAddress("localhost",
// 8888))) {
while (!serverchannel.finishConnect()) {
Thread.sleep(30); // avoid massive polling
System.out.println("*");
}
}
} catch (UnresolvedAddressException e) { //TODO HACERLO DE LA FORMA BIEN. AGARRANDOLO DE UN ARCHIVO
String notFound = "HTTP/1.1 404 BAD REQUEST\r\n\r\n<html><body>404 Not Found<br><br>This may be a DNS problem or the page you were looking for doesn't exist.</body></html>\r\n";
ByteBuffer resp = ByteBuffer.allocate(notFound.length());
resp.put(notFound.getBytes());
resp.flip();
channel.write(resp);
channel.close();
proxyconnections.remove(channel);
return null;
} catch (InterruptedException e) {
e.printStackTrace();
}
conn.setServer(serverchannel);
proxyconnections.put(serverchannel, conn);
}
// Indicate via key that reading/writing are both of interest now.
key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
channel.register(key.selector(), SelectionKey.OP_WRITE);
if (message.isFinished()) {
System.out.println("finisheo");
}
return serverchannel;
}
return null;
}
| public SocketChannel handleRead(SelectionKey key) throws IOException {
// Client socket channel has pending data
SocketChannel channel = (SocketChannel) key.channel();
ProxyConnection conn = proxyconnections.get(channel);
ByteBuffer buf = conn.getBuffer(channel);
long bytesRead = 0;
try {
bytesRead = channel.read(buf);
// System.out.println(new String(buf.array(), 0, 100));
} catch (IOException e) {
System.out.println("\nfallo el read");
e.printStackTrace();
return null;
}
System.out.println("\n[READ] " + bytesRead + " from "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
if (bytesRead == -1) { // Did the other end close?
if (conn.isClient(channel)) {
System.out.println("\n[RECEIVED CLOSE] from cliente "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
if (conn.getServer() != null) {
/* ----------------- CLOSE ----------------- */
conn.getServer().close(); // close the server channel
/* ----------------- CLOSE ----------------- */
System.out.println("\n[SENT CLOSE] to servidor remoto "
+ conn.getServer().socket().getInetAddress() + ":"
+ conn.getServer().socket().getPort());
}
/* ----------------- CLOSE ----------------- */
channel.close();
System.out.println("\n[SENT CLOSE] to cliente "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
/* ----------------- REMOVE ----------------- */
proxyconnections.remove(channel);
proxyconnections.remove(conn.getServer());
/* ----------------- CANCEL ----------------- */
key.cancel();
// de-reference the proxy connection as it is
// no longer useful
return null;
} else {
System.out.println("\n[RECEIVED CLOSE] from servidor remoto "
+ channel.socket().getInetAddress() + ":"
+ channel.socket().getPort());
/* ----------------- CLOSE ----------------- */
conn.getServer().close();
/* ----------------- CLOSE ----------------- */
// channel.close();
System.out.println("\n[SENT CLOSE] to servidor remoto "
+ conn.getServer().socket().getInetAddress() + ":"
+ conn.getServer().socket().getPort());
// proxyconnections.remove(channel);
// key.cancel();
// channel.write(buf.rewind());
conn.resetIncompleteMessage();
// proxyconnections.remove(channel);
proxyconnections.remove(conn.getServer());
conn.resetServer();
}
} else if (bytesRead > 0) {
/* ----------- PARSEO DE REQ/RESP ----------- */
Message message = conn.getMessage(channel);
message.increaseAmountRead((int) bytesRead); // DECIDIR SI INT O
message.setFrom("client" + channel.socket().getInetAddress()); // LONG
/* ----------- CONEXION A SERVIDOR DESTINO ----------- */
SocketChannel serverchannel;
if (conn.isClient(channel) && message.getState() != ParsingState.Body) {
return null;
}
if ((serverchannel = conn.getServer()) == null) {
String url = null;
if (((HttpRequest) message).getURI().startsWith("/"))
url = ((HttpRequest) message).getHeaders().get("host")
+ ((HttpRequest) message).getURI();
else
url = ((HttpRequest) message).getURI();
String[] splitted = url.split("http://");
url = "http://"
+ (splitted.length >= 2 ? splitted[1] : splitted[0]);
URL uri = new URL(url);
serverchannel = SocketChannel.open();
serverchannel.configureBlocking(false);
int port = uri.getPort() == -1 ? 80 : uri.getPort();
try {
if (!serverchannel.connect(new InetSocketAddress(uri.getHost(),
port))) {
// if (!serverchannel.connect(new
// InetSocketAddress("localhost",
// 8888))) {
while (!serverchannel.finishConnect()) {
Thread.sleep(30); // avoid massive polling
System.out.println("*");
}
}
} catch (UnresolvedAddressException e) { //TODO HACERLO DE LA FORMA BIEN. AGARRANDOLO DE UN ARCHIVO
String notFound = "HTTP/1.1 404 BAD REQUEST\r\n\r\n<html><body>404 Not Found<br><br>This may be a DNS problem or the page you were looking for doesn't exist.</body></html>\r\n";
ByteBuffer resp = ByteBuffer.allocate(notFound.length());
resp.put(notFound.getBytes());
resp.flip();
channel.write(resp);
channel.close();
proxyconnections.remove(channel);
return null;
} catch (InterruptedException e) {
e.printStackTrace();
}
conn.setServer(serverchannel);
proxyconnections.put(serverchannel, conn);
}
// Indicate via key that reading/writing are both of interest now.
key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
channel.register(key.selector(), SelectionKey.OP_WRITE);
return serverchannel;
}
return null;
}
|