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/hazelcast/src/main/java/com/hazelcast/impl/CMap.java b/hazelcast/src/main/java/com/hazelcast/impl/CMap.java
index 49cdd861..3649567c 100644
--- a/hazelcast/src/main/java/com/hazelcast/impl/CMap.java
+++ b/hazelcast/src/main/java/com/hazelcast/impl/CMap.java
@@ -1,1724 +1,1724 @@
/*
* Copyright (c) 2008-2010, Hazel Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.hazelcast.impl;
import com.hazelcast.cluster.ClusterImpl;
import com.hazelcast.config.MapConfig;
import com.hazelcast.config.MapStoreConfig;
import com.hazelcast.config.NearCacheConfig;
import com.hazelcast.core.*;
import com.hazelcast.impl.base.ScheduledAction;
import com.hazelcast.impl.concurrentmap.LFUMapEntryComparator;
import com.hazelcast.impl.concurrentmap.LRUMapEntryComparator;
import com.hazelcast.impl.concurrentmap.MultiData;
import com.hazelcast.logging.ILogger;
import com.hazelcast.nio.*;
import com.hazelcast.query.Expression;
import com.hazelcast.query.MapIndexService;
import com.hazelcast.util.SortedHashMap;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import static com.hazelcast.impl.ClusterOperation.*;
import static com.hazelcast.impl.Constants.Objects.OBJECT_REDO;
import static com.hazelcast.impl.LocalMapStatsImpl.Op;
import static com.hazelcast.impl.LocalMapStatsImpl.Op.*;
import static com.hazelcast.nio.IOUtil.toData;
import static com.hazelcast.nio.IOUtil.toObject;
public class CMap {
private static final Comparator<MapEntry> LRU_COMPARATOR = new LRUMapEntryComparator();
private static final Comparator<MapEntry> LFU_COMPARATOR = new LFUMapEntryComparator();
enum EvictionPolicy {
LRU,
LFU,
NONE
}
public final static int DEFAULT_MAP_SIZE = 10000;
final ILogger logger;
final ConcurrentMapManager concurrentMapManager;
final Node node;
final int PARTITION_COUNT;
final Block[] blocks;
final Address thisAddress;
final Map<Data, Record> mapRecords = new ConcurrentHashMap<Data, Record>(10000);
final String name;
final Map<Address, Boolean> mapListeners = new HashMap<Address, Boolean>(1);
final int backupCount;
final EvictionPolicy evictionPolicy;
final Comparator<MapEntry> evictionComparator;
final int maxSize;
final float evictionRate;
final long ttl; //ttl for entries
final long maxIdle; //maxIdle for entries
final Instance.InstanceType instanceType;
final MapLoader loader;
final MapStore store;
final long writeDelayMillis;
final long removeDelayMillis;
final long evictionDelayMillis;
final MapIndexService mapIndexService = new MapIndexService();
final LocallyOwnedMap locallyOwnedMap;
final MapNearCache mapNearCache;
final long creationTime;
volatile boolean ttlPerRecord = false;
volatile long lastEvictionTime = 0;
Lock lockEntireMap = null;
final LocalMapStatsImpl localMapStats = new LocalMapStatsImpl();
public CMap(ConcurrentMapManager concurrentMapManager, String name) {
this.concurrentMapManager = concurrentMapManager;
this.logger = concurrentMapManager.node.getLogger(CMap.class.getName());
this.PARTITION_COUNT = concurrentMapManager.PARTITION_COUNT;
this.blocks = concurrentMapManager.blocks;
this.node = concurrentMapManager.node;
this.thisAddress = concurrentMapManager.thisAddress;
this.name = name;
MapConfig mapConfig = null;
String mapConfigName = name.substring(2);
if (mapConfigName.startsWith("__hz_") || mapConfigName.startsWith("l:") || mapConfigName.startsWith("s:")) {
mapConfig = new MapConfig();
} else {
mapConfig = node.getConfig().getMapConfig(mapConfigName);
}
this.backupCount = mapConfig.getBackupCount();
ttl = mapConfig.getTimeToLiveSeconds() * 1000L;
evictionDelayMillis = mapConfig.getEvictionDelaySeconds() * 1000L;
maxIdle = mapConfig.getMaxIdleSeconds() * 1000L;
evictionPolicy = EvictionPolicy.valueOf(mapConfig.getEvictionPolicy());
if (evictionPolicy == EvictionPolicy.NONE) {
maxSize = Integer.MAX_VALUE;
evictionComparator = null;
} else {
maxSize = (mapConfig.getMaxSize() == 0) ? MapConfig.DEFAULT_MAX_SIZE : mapConfig.getMaxSize();
if (evictionPolicy == EvictionPolicy.LRU) {
evictionComparator = LRU_COMPARATOR;
} else {
evictionComparator = LFU_COMPARATOR;
}
}
evictionRate = mapConfig.getEvictionPercentage() / 100f;
instanceType = ConcurrentMapManager.getInstanceType(name);
MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
MapStore storeTemp = null;
MapLoader loaderTemp = null;
int writeDelaySeconds = -1;
- if (mapStoreConfig != null && mapStoreConfig.isEnabled()) {
+ if (!node.isSuperClient() && mapStoreConfig != null && mapStoreConfig.isEnabled()) {
try {
Object storeInstance = mapStoreConfig.getImplementation();
if (storeInstance == null) {
String mapStoreClassName = mapStoreConfig.getClassName();
storeInstance = Serializer.classForName(node.getConfig().getClassLoader(), mapStoreClassName).newInstance();
}
if (storeInstance instanceof MapLoader) {
loaderTemp = (MapLoader) storeInstance;
}
if (storeInstance instanceof MapStore) {
storeTemp = (MapStore) storeInstance;
}
} catch (Exception e) {
e.printStackTrace();
}
writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds();
}
- loader = loaderTemp;
- store = storeTemp;
+ if (!node.isSuperClient() && evictionPolicy == EvictionPolicy.NONE && instanceType == Instance.InstanceType.MAP) {
+ locallyOwnedMap = new LocallyOwnedMap(localMapStats);
+ concurrentMapManager.mapLocallyOwnedMaps.put(name, locallyOwnedMap);
+ } else {
+ locallyOwnedMap = null;
+ }
writeDelayMillis = (writeDelaySeconds == -1) ? -1L : writeDelaySeconds * 1000L;
if (writeDelaySeconds > 0) {
removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS + writeDelaySeconds;
} else {
removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS;
}
- if (evictionPolicy == EvictionPolicy.NONE && instanceType == Instance.InstanceType.MAP) {
- locallyOwnedMap = new LocallyOwnedMap(localMapStats);
- concurrentMapManager.mapLocallyOwnedMaps.put(name, locallyOwnedMap);
- } else {
- locallyOwnedMap = null;
- }
+ loader = loaderTemp;
+ store = storeTemp;
NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig();
if (nearCacheConfig == null) {
mapNearCache = null;
} else {
mapNearCache = new MapNearCache(this,
SortedHashMap.getOrderingTypeByName(mapConfig.getEvictionPolicy()),
nearCacheConfig.getMaxSize(),
nearCacheConfig.getTimeToLiveSeconds() * 1000L,
nearCacheConfig.getMaxIdleSeconds() * 1000L,
nearCacheConfig.isInvalidateOnChange());
concurrentMapManager.mapCaches.put(name, mapNearCache);
}
this.creationTime = System.currentTimeMillis();
}
public boolean checkLock(Request request) {
return (lockEntireMap == null
|| !lockEntireMap.isLocked()
|| lockEntireMap.isLockedBy(request.lockAddress, request.lockThreadId));
}
public void lockMap(Request request) {
if (request.operation == CONCURRENT_MAP_LOCK_MAP) {
if (lockEntireMap == null) {
lockEntireMap = new Lock();
}
boolean locked = lockEntireMap.lock(request.lockAddress, request.lockThreadId);
request.clearForResponse();
if (!locked) {
if (request.timeout == 0) {
request.response = Boolean.FALSE;
} else {
request.response = OBJECT_REDO;
}
} else {
request.response = Boolean.TRUE;
}
} else if (request.operation == CONCURRENT_MAP_UNLOCK_MAP) {
if (lockEntireMap != null) {
request.response = lockEntireMap.unlock(request.lockAddress, request.lockThreadId);
} else {
request.response = Boolean.TRUE;
}
}
}
class Lock {
Address lockAddress = null;
int lockThreadId = -1;
int lockCount;
Lock() {
}
Lock(Address address, int threadId) {
this.lockAddress = address;
this.lockThreadId = threadId;
this.lockCount = 1;
}
boolean isLocked() {
return lockCount > 0;
}
boolean isLockedBy(Address address, int threadId) {
return (this.lockThreadId == threadId && this.lockAddress.equals(address));
}
boolean lock(Address address, int threadId) {
if (this.lockCount == 0) {
this.lockAddress = address;
this.lockThreadId = threadId;
this.lockCount++;
return true;
} else if (isLockedBy(address, threadId)) {
this.lockCount++;
return true;
}
return false;
}
boolean unlock(Address address, int threadId) {
if (lockCount == 0) {
return false;
} else {
if (isLockedBy(address, threadId)) {
this.lockCount--;
if (lockCount == 0) {
this.lockAddress = null;
this.lockThreadId = -1;
}
return true;
}
}
return false;
}
public Address getLockAddress() {
return lockAddress;
}
public int getLockThreadId() {
return lockThreadId;
}
public int getLockCount() {
return lockCount;
}
@Override
public String toString() {
return "Lock{" +
"lockAddress=" + lockAddress +
", lockThreadId=" + lockThreadId +
", lockCount=" + lockCount +
'}';
}
}
public void addIndex(Expression expression, boolean ordered, int attributeIndex) {
mapIndexService.addIndex(expression, ordered, attributeIndex);
}
public Record getRecord(Data key) {
return mapRecords.get(key);
}
public int getBackupCount() {
return backupCount;
}
public void own(Request req) {
if (req.key == null || req.key.size() == 0) {
throw new RuntimeException("Key cannot be null " + req.key);
}
if (req.value == null) {
req.value = new Data();
}
Record record = toRecordAndStats(req, true);
if (req.ttl <= 0 || req.timeout <= 0) {
record.setInvalid();
} else {
record.setExpirationTime(req.ttl);
record.setMaxIdle(req.timeout);
}
markAsActive(record);
markAsDirty(record);
updateIndexes(record);
if (record.isLocked()) {
updateStats(LOCK, record, true, null);
}
record.setVersion(req.version);
}
public boolean isMultiMap() {
return (instanceType == Instance.InstanceType.MULTIMAP);
}
public boolean isSet() {
return (instanceType == Instance.InstanceType.SET);
}
public boolean isList() {
return (instanceType == Instance.InstanceType.LIST);
}
public boolean isMap() {
return (instanceType == Instance.InstanceType.MAP);
}
public boolean backup(Request req) {
if (req.key == null || req.key.size() == 0) {
throw new RuntimeException("Backup key size cannot be 0: " + req.key);
}
if (instanceType == Instance.InstanceType.MAP || instanceType == Instance.InstanceType.SET) {
return backupOneValue(req);
} else {
return backupMultiValue(req);
}
}
/**
* Map and Set have one value only so we can ignore the
* values with old version.
*
* @param req
* @return
*/
private boolean backupOneValue(Request req) {
Record record = getRecord(req.key);
if (record != null && record.isActive() && req.version < record.getVersion()) {
return false;
}
doBackup(req);
if (record != null) {
record.setVersion(req.version);
}
return true;
}
/**
* MultiMap and List have to use versioned backup
* because each key can have multiple values and
* we don't want to miss backing up each one.
*
* @param req
* @return
*/
private boolean backupMultiValue(Request req) {
Record record = getRecord(req.key);
if (record != null) {
record.setActive();
if (req.version > record.getVersion() + 1) {
Request reqCopy = req.hardCopy();
record.addBackupOp(new VersionedBackupOp(this, reqCopy));
return true;
} else if (req.version <= record.getVersion()) {
return false;
}
}
doBackup(req);
if (record != null) {
record.setVersion(req.version);
record.runBackupOps();
}
return true;
}
Record toRecordAndStats(Request req, boolean owned) {
Record record = getRecord(req.key);
Op op;
Data oldValue = null;
if (record == null || !record.isActive()) {
op = CREATE;
} else {
op = UPDATE;
oldValue = record.getValue();
}
record = toRecord(req);
updateStats(op, record, owned, oldValue);
return record;
}
public void doBackup(Request req) {
if (req.key == null || req.key.size() == 0) {
throw new RuntimeException("Backup key size cannot be zero! " + req.key);
}
if (req.operation == CONCURRENT_MAP_BACKUP_PUT) {
Record record = toRecordAndStats(req, false);
if (!record.isActive()) {
record.setActive();
record.setCreationTime(System.currentTimeMillis());
}
record.setVersion(req.version);
if (req.indexes != null) {
if (req.indexTypes == null) {
throw new RuntimeException("index types cannot be null!");
}
if (req.indexes.length != req.indexTypes.length) {
throw new RuntimeException("index and type lengths do not match");
}
record.setIndexes(req.indexes, req.indexTypes);
}
} else if (req.operation == CONCURRENT_MAP_BACKUP_REMOVE) {
Record record = getRecord(req.key);
if (record != null) {
if (record.isActive()) {
updateStats(REMOVE, record, false, null);
if (record.getCopyCount() > 0) {
record.decrementCopyCount();
}
markAsRemoved(record);
}
}
} else if (req.operation == CONCURRENT_MAP_BACKUP_LOCK) {
Record rec = toRecord(req);
if (rec.getVersion() == 0) {
rec.setVersion(req.version);
}
} else if (req.operation == CONCURRENT_MAP_BACKUP_ADD) {
add(req, true);
} else if (req.operation == CONCURRENT_MAP_BACKUP_REMOVE_MULTI) {
Record record = getRecord(req.key);
if (record != null) {
if (req.value == null) {
markAsRemoved(record);
} else {
if (record.containsValue(req.value)) {
if (record.getMultiValues() != null) {
Iterator<Data> itValues = record.getMultiValues().iterator();
while (itValues.hasNext()) {
Data value = itValues.next();
if (req.value.equals(value)) {
itValues.remove();
}
}
}
}
}
markAsRemoved(record);
}
} else {
logger.log(Level.SEVERE, "Unknown backup operation " + req.operation);
}
}
public LocalMapStatsImpl getLocalMapStats() {
ClusterImpl clusterImpl = node.getClusterImpl();
LocalMapStatsImpl stats = new LocalMapStatsImpl();
stats.setLockWaitCount(localMapStats.getLockWaitCount());
stats.setLockedEntryCount(localMapStats.getLockedEntryCount());
stats.setHits(localMapStats.getHits());
stats.setOwnedEntryCount(localMapStats.getOwnedEntryCount());
stats.setBackupEntryCount(localMapStats.getBackupEntryCount());
stats.setOwnedEntryMemoryCost(localMapStats.getOwnedEntryMemoryCost());
stats.setBackupEntryMemoryCost(localMapStats.getBackupEntryMemoryCost());
stats.setLastEvictionTime(clusterImpl.getClusterTimeFor(lastEvictionTime));
stats.setCreationTime(clusterImpl.getClusterTimeFor(creationTime));
stats.setLastAccessTime(clusterImpl.getClusterTimeFor(localMapStats.getLastAccessTime()));
stats.setLastUpdateTime(clusterImpl.getClusterTimeFor(localMapStats.getLastUpdateTime()));
return stats;
}
void resetLocalMapStats(Map<Address, Integer> distances) {
long now = System.currentTimeMillis();
int ownedEntryCount = 0;
int backupEntryCount = 0;
int markedAsRemovedEntryCount = 0;
int ownedEntryMemoryCost = 0;
int backupEntryMemoryCost = 0;
int markedAsRemovedMemoryCost = 0;
int hits = 0;
int lockedEntryCount = 0;
int lockWaitCount = 0;
ClusterImpl clusterImpl = node.getClusterImpl();
for (Record record : mapRecords.values()) {
if (!record.isActive() || !record.isValid(now)) {
markedAsRemovedEntryCount++;
markedAsRemovedMemoryCost += record.getCost();
} else {
Block block = concurrentMapManager.getOrCreateBlock(record.getBlockId());
boolean owned = thisAddress.equals(block.getOwner());
if (owned) {
ownedEntryCount += record.valueCount();
ownedEntryMemoryCost += record.getCost();
localMapStats.setLastAccessTime(record.getLastAccessTime());
localMapStats.setLastUpdateTime(record.getLastUpdateTime());
hits += record.getHits();
if (record.isLocked()) {
lockedEntryCount++;
lockWaitCount += record.getScheduledActionCount();
}
} else {
boolean unknown = false;
Address eventualOwner = (block.isMigrating()) ? block.getMigrationAddress() : block.getOwner();
if (!thisAddress.equals(eventualOwner)) {
Integer distance = distances.get(eventualOwner);
if (distance != null && distance > getBackupCount()) {
unknown = true;
}
}
if (unknown) {
markedAsRemovedEntryCount++;
markedAsRemovedMemoryCost += record.getCost();
markAsRemoved(record);
} else {
backupEntryCount += record.valueCount();
backupEntryMemoryCost += record.getCost();
}
}
}
}
localMapStats.setMarkedAsRemovedEntryCount(markedAsRemovedEntryCount);
localMapStats.setMarkedAsRemovedMemoryCost(markedAsRemovedMemoryCost);
localMapStats.setLockWaitCount(lockWaitCount);
localMapStats.setLockedEntryCount(lockedEntryCount);
localMapStats.setHits(hits);
localMapStats.setOwnedEntryCount(ownedEntryCount);
localMapStats.setBackupEntryCount(backupEntryCount);
localMapStats.setOwnedEntryMemoryCost(ownedEntryMemoryCost);
localMapStats.setBackupEntryMemoryCost(backupEntryMemoryCost);
localMapStats.setLastEvictionTime(clusterImpl.getClusterTimeFor(lastEvictionTime));
localMapStats.setCreationTime(clusterImpl.getClusterTimeFor(creationTime));
}
public LocalMapStatsImpl createLocalMapStats() {
long now = System.currentTimeMillis();
int ownedEntryCount = 0;
int backupEntryCount = 0;
int markedAsRemovedEntryCount = 0;
int ownedEntryMemoryCost = 0;
int backupEntryMemoryCost = 0;
int markedAsRemovedMemoryCost = 0;
int hits = 0;
int lockedEntryCount = 0;
int lockWaitCount = 0;
ClusterImpl clusterImpl = node.getClusterImpl();
LocalMapStatsImpl localMapStats = new LocalMapStatsImpl();
for (Record record : mapRecords.values()) {
if (!record.isActive() || !record.isValid(now)) {
markedAsRemovedEntryCount++;
markedAsRemovedMemoryCost += record.getCost();
} else {
if (isOwned(record)) {
ownedEntryCount += record.valueCount();
ownedEntryMemoryCost += record.getCost();
localMapStats.setLastAccessTime(clusterImpl.getClusterTimeFor(record.getLastAccessTime()));
localMapStats.setLastUpdateTime(clusterImpl.getClusterTimeFor(record.getLastUpdateTime()));
hits += record.getHits();
if (record.isLocked()) {
lockedEntryCount++;
lockWaitCount += record.getScheduledActionCount();
}
} else if (isBackup(record)) {
backupEntryCount += record.valueCount();
backupEntryMemoryCost += record.getCost();
} else {
markedAsRemovedEntryCount++;
markedAsRemovedMemoryCost += record.getCost();
}
}
}
localMapStats.setMarkedAsRemovedEntryCount(markedAsRemovedEntryCount);
localMapStats.setMarkedAsRemovedMemoryCost(markedAsRemovedMemoryCost);
localMapStats.setLockWaitCount(lockWaitCount);
localMapStats.setLockedEntryCount(lockedEntryCount);
localMapStats.setHits(hits);
localMapStats.setOwnedEntryCount(ownedEntryCount);
localMapStats.setBackupEntryCount(backupEntryCount);
localMapStats.setOwnedEntryMemoryCost(ownedEntryMemoryCost);
localMapStats.setBackupEntryMemoryCost(backupEntryMemoryCost);
localMapStats.setLastEvictionTime(clusterImpl.getClusterTimeFor(lastEvictionTime));
localMapStats.setCreationTime(clusterImpl.getClusterTimeFor(creationTime));
return localMapStats;
}
private void purgeIfNotOwnedOrBackup(Collection<Record> records) {
Map<Address, Integer> mapMemberDistances = new HashMap<Address, Integer>();
for (Record record : records) {
Block block = blocks[record.getBlockId()];
boolean owned = thisAddress.equals(block.getOwner());
if (!owned && !block.isMigrating()) {
Address owner = (block.isMigrating()) ? block.getMigrationAddress() : block.getOwner();
if (owner != null && !thisAddress.equals(owner)) {
int distance;
Integer d = mapMemberDistances.get(owner);
if (d == null) {
distance = concurrentMapManager.getDistance(owner, thisAddress);
mapMemberDistances.put(owner, distance);
} else {
distance = d;
}
if (distance > getBackupCount()) {
mapRecords.remove(record.getKey());
}
}
}
}
}
private boolean isOwned(Record record) {
PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl;
PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId());
Member owner = partition.getOwner();
return (owner != null && owner.localMember());
}
private boolean isBackup(Record record) {
PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl;
PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId());
Member ownerNow = partition.getOwner();
Member ownerEventual = partition.getEventualOwner();
if (ownerEventual != null && ownerNow != null && !ownerNow.localMember()) {
int distance = node.getClusterImpl().getDistanceFrom(ownerEventual);
return (distance != -1 && distance <= getBackupCount());
}
return false;
}
public int size() {
if (maxIdle > 0 || ttl > 0 || ttlPerRecord || isList() || isMultiMap()) {
long now = System.currentTimeMillis();
int size = 0;
Collection<Record> records = mapIndexService.getOwnedRecords();
for (Record record : records) {
if (record.isActive() && record.isValid(now)) {
size += record.valueCount();
}
}
return size;
} else {
return mapIndexService.size();
}
}
public boolean hasOwned(long blockId) {
Collection<Record> records = mapRecords.values();
for (Record record : records) {
if (record.getBlockId() == blockId && record.isActive()) {
return true;
}
}
return false;
}
public int valueCount(Data key) {
long now = System.currentTimeMillis();
int count = 0;
Record record = mapRecords.get(key);
if (record != null && record.isValid(now)) {
count = record.valueCount();
}
return count;
}
public boolean contains(Request req) {
Data key = req.key;
Data value = req.value;
if (key != null) {
Record record = getRecord(req.key);
if (record == null) {
return false;
} else {
if (record.isActive() && record.isValid()) {
touch(record);
updateStats(READ, record, true, null);
if (value == null) {
return record.valueCount() > 0;
} else {
return record.containsValue(value);
}
}
}
} else {
Collection<Record> records = mapRecords.values();
for (Record record : records) {
long now = System.currentTimeMillis();
if (record.isActive() && record.isValid(now)) {
Block block = blocks[record.getBlockId()];
if (thisAddress.equals(block.getOwner())) {
if (record.containsValue(value)) {
return true;
}
}
}
}
}
return false;
}
public void containsValue(Request request) {
if (isMultiMap()) {
boolean found = false;
Collection<Record> records = mapRecords.values();
for (Record record : records) {
long now = System.currentTimeMillis();
if (record.isActive() && record.isValid(now)) {
Block block = blocks[record.getBlockId()];
if (thisAddress.equals(block.getOwner())) {
if (record.containsValue(request.value)) {
found = true;
}
}
}
}
request.response = found;
} else {
request.response = mapIndexService.containsValue(request.value);
}
}
public CMapEntry getMapEntry(Request req) {
Record record = getRecord(req.key);
if (record == null || !record.isActive() || !record.isValid()) {
return null;
}
return new CMapEntry(record.getCost(), record.getExpirationTime(), record.getLastAccessTime(), record.getLastUpdateTime(),
record.getCreationTime(), record.getVersion(), record.getHits(), true);
}
public Data get(Request req) {
Record record = getRecord(req.key);
if (record == null)
return null;
if (!record.isActive()) return null;
if (!record.isValid()) {
if (record.isEvictable()) {
return null;
}
}
if (req.local && locallyOwnedMap != null) {
locallyOwnedMap.offerToCache(record);
}
record.setLastAccessed();
touch(record);
updateStats(READ, record, true, null);
Data data = record.getValue();
Data returnValue = null;
if (data != null) {
returnValue = data;
} else {
if (record.getMultiValues() != null) {
Values values = new Values(record.getMultiValues());
returnValue = toData(values);
}
}
return returnValue;
}
public boolean add(Request req, boolean backup) {
Record record = getRecord(req.key);
if (record == null) {
record = toRecord(req);
} else {
if (record.isActive() && req.operation == CONCURRENT_MAP_ADD_TO_SET) {
return false;
}
}
record.setActive(true);
record.incrementVersion();
record.incrementCopyCount();
if (!backup) {
updateIndexes(record);
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_ADDED, record);
}
return true;
}
void lock(Request request) {
Record rec = concurrentMapManager.ensureRecord(request);
if (request.operation == CONCURRENT_MAP_LOCK_AND_GET_VALUE) {
request.value = rec.getValue();
}
rec.lock(request.lockThreadId, request.lockAddress);
rec.incrementVersion();
request.version = rec.getVersion();
request.lockCount = rec.getLockCount();
updateStats(LOCK, rec, true, null);
markAsActive(rec);
request.response = Boolean.TRUE;
}
void unlock(Record record) {
record.setLockThreadId(-1);
record.setLockCount(0);
record.setLockAddress(null);
fireScheduledActions(record);
}
void fireScheduledActions(Record record) {
concurrentMapManager.checkServiceThread();
if (record.getLockCount() == 0) {
record.setLockThreadId(-1);
record.setLockAddress(null);
if (record.getScheduledActions() != null) {
while (record.getScheduledActions().size() > 0) {
ScheduledAction sa = record.getScheduledActions().remove(0);
node.clusterManager.deregisterScheduledAction(sa);
if (!sa.expired()) {
sa.consume();
if (record.isLocked()) {
return;
}
}
}
}
}
}
public void onDisconnect(Record record, Address deadAddress) {
if (record == null || deadAddress == null) return;
List<ScheduledAction> lsScheduledActions = record.getScheduledActions();
if (lsScheduledActions != null) {
if (lsScheduledActions.size() > 0) {
Iterator<ScheduledAction> it = lsScheduledActions.iterator();
while (it.hasNext()) {
ScheduledAction sa = it.next();
if (deadAddress.equals(sa.getRequest().caller)) {
node.clusterManager.deregisterScheduledAction(sa);
sa.setValid(false);
it.remove();
}
}
}
}
if (record.getLockCount() > 0) {
if (deadAddress.equals(record.getLockAddress())) {
unlock(record);
}
}
}
public boolean removeMulti(Request req) {
Record record = getRecord(req.key);
if (record == null) return false;
boolean removed = false;
if (req.value == null) {
removed = true;
markAsRemoved(record);
} else {
if (record.containsValue(req.value)) {
if (record.getMultiValues() != null) {
Iterator<Data> itValues = record.getMultiValues().iterator();
while (itValues.hasNext()) {
Data value = itValues.next();
if (req.value.equals(value)) {
itValues.remove();
removed = true;
}
}
}
}
}
if (removed) {
record.incrementVersion();
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_REMOVED, record.getKey(), req.value, record.getMapListeners());
logger.log(Level.FINEST, record.getValue() + " RemoveMulti " + record.getMultiValues());
}
req.version = record.getVersion();
return removed;
}
public boolean putMulti(Request req) {
Record record = getRecord(req.key);
boolean added = true;
if (record == null) {
record = toRecord(req);
} else {
if (!record.isActive()) {
markAsActive(record);
}
if (record.containsValue(req.value)) {
added = false;
}
}
if (added) {
Data value = req.value;
updateIndexes(record);
record.addValue(value);
record.incrementVersion();
touch(record);
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_ADDED, record.getKey(), value, record.getMapListeners());
}
if (req.txnId != -1) {
unlock(record);
}
logger.log(Level.FINEST, record.getValue() + " PutMulti " + record.getMultiValues());
req.clearForResponse();
req.version = record.getVersion();
return added;
}
public void put(Request req) {
long now = System.currentTimeMillis();
if (mapRecords.size() >= maxSize) {
//todo
}
if (req.value == null) {
req.value = new Data();
}
Record record = getRecord(req.key);
if (req.operation == CONCURRENT_MAP_PUT_IF_ABSENT) {
if (record != null && record.isActive() && record.isValid(now) && record.getValue() != null) {
req.clearForResponse();
req.response = record.getValue();
return;
}
} else if (req.operation == CONCURRENT_MAP_REPLACE_IF_NOT_NULL) {
if (record == null || !record.isActive() || !record.isValid(now) || record.getValue() == null) {
return;
}
} else if (req.operation == CONCURRENT_MAP_REPLACE_IF_SAME) {
if (record == null || !record.isActive() || !record.isValid(now)) {
req.response = Boolean.FALSE;
return;
}
MultiData multiData = (MultiData) toObject(req.value);
if (multiData == null || multiData.size() != 2) {
throw new RuntimeException("Illegal replaceIfSame argument: " + multiData);
}
Data expectedOldValue = multiData.getData(0);
req.value = multiData.getData(1);
if (!record.getValue().equals(expectedOldValue)) {
req.response = Boolean.FALSE;
return;
}
}
req.value.hash = (int) req.longValue;
Data oldValue = null;
Op op = UPDATE;
if (record == null) {
record = createNewRecord(req.key, req.value);
mapRecords.put(req.key, record);
op = CREATE;
} else {
if (!record.isActive()) {
op = CREATE;
}
markAsActive(record);
oldValue = (record.isValid(now)) ? record.getValue() : null;
record.setValue(req.value);
record.incrementVersion();
touch(record);
record.setLastUpdated();
}
if (req.ttl > 0) {
record.setExpirationTime(req.ttl);
ttlPerRecord = true;
}
if (oldValue == null) {
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_ADDED, record);
} else {
fireInvalidation(record);
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_UPDATED, record);
}
if (req.txnId != -1) {
unlock(record);
}
record.setIndexes(req.indexes, req.indexTypes);
updateStats(op, record, true, oldValue);
updateIndexes(record);
markAsDirty(record);
req.clearForResponse();
req.version = record.getVersion();
req.longValue = record.getCopyCount();
if (req.operation == CONCURRENT_MAP_REPLACE_IF_SAME) {
req.response = Boolean.TRUE;
} else {
req.response = oldValue;
}
}
private void executeStoreUpdate(final Map<Data, Data> entriesToStore, final Collection<Data> keysToDelete) {
final int entriesToStoreSize = entriesToStore.size();
final int keysToDeleteSize = keysToDelete.size();
if (entriesToStoreSize > 0 || keysToDeleteSize > 0) {
concurrentMapManager.node.executorManager.executeStoreTask(new Runnable() {
public void run() {
if (keysToDeleteSize > 0) {
if (keysToDeleteSize == 1) {
Data key = keysToDelete.iterator().next();
store.delete(toObject(key));
} else {
Collection realKeys = new HashSet();
for (Data key : keysToDelete) {
realKeys.add(toObject(key));
}
store.deleteAll(realKeys);
}
}
if (entriesToStoreSize > 0) {
Object keyFirst = null;
Object valueFirst = null;
Set<Map.Entry<Data, Data>> entries = entriesToStore.entrySet();
Map realEntries = new HashMap();
for (Map.Entry<Data, Data> entry : entries) {
Object key = toObject(entry.getKey());
Object value = toObject(entry.getValue());
realEntries.put(key, value);
if (keyFirst == null) {
keyFirst = key;
valueFirst = value;
}
}
if (entriesToStoreSize == 1) {
store.store(keyFirst, valueFirst);
} else {
store.storeAll(realEntries);
}
}
}
});
}
}
void startCleanup() {
final long now = System.currentTimeMillis();
final Map<Data, Data> entriesToStore = new HashMap<Data, Data>();
final Collection<Data> keysToDelete = new HashSet<Data>();
final Set<Record> recordsUnknown = new HashSet<Record>();
final Set<Record> recordsToPurge = new HashSet<Record>();
final Set<Record> recordsToEvict = new HashSet<Record>();
final Set<Record> sortedRecords = new TreeSet<Record>(evictionComparator);
final Collection<Record> records = mapRecords.values();
final boolean evictionAware = evictionComparator != null && maxSize > 0;
final PartitionServiceImpl partitionService = concurrentMapManager.partitionManager.partitionServiceImpl;
int recordsStillOwned = 0;
for (Record record : records) {
PartitionServiceImpl.PartitionProxy partition = partitionService.getPartition(record.getBlockId());
Member owner = partition.getOwner();
if (owner != null && !partition.isMigrating()) {
boolean owned = owner.localMember();
if (owned) {
if (store != null && record.isDirty()) {
if (now > record.getWriteTime()) {
if (record.getValue() != null) {
entriesToStore.put(record.getKey(), record.getValue());
} else {
keysToDelete.add(record.getKey());
}
record.setDirty(false);
}
} else if (shouldPurgeRecord(record, now)) {
recordsToPurge.add(record); // removed records
} else if (record.isActive() && !record.isValid(now)) {
recordsToEvict.add(record); // expired records
} else if (evictionAware && record.isActive() && record.isEvictable()) {
sortedRecords.add(record); // sorting for eviction
recordsStillOwned++;
} else {
recordsStillOwned++;
}
} else {
Member ownerEventual = partition.getEventualOwner();
boolean backup = false;
if (ownerEventual != null && owner != null && !owner.localMember()) {
int distance = node.getClusterImpl().getDistanceFrom(ownerEventual);
backup = (distance != -1 && distance <= getBackupCount());
}
if (backup) {
if (shouldPurgeRecord(record, now)) {
recordsToPurge.add(record);
}
} else {
recordsUnknown.add(record);
}
}
}
}
if (evictionAware && maxSize < recordsStillOwned) {
int numberOfRecordsToEvict = (int) (recordsStillOwned * evictionRate);
int evictedCount = 0;
for (Record record : sortedRecords) {
if (record.isActive() && record.isEvictable()) {
recordsToEvict.add(record);
if (++evictedCount >= numberOfRecordsToEvict) {
break;
}
}
}
}
Level levelLog = (concurrentMapManager.LOG_STATE) ? Level.INFO : Level.FINEST;
logger.log(levelLog, "Cleanup "
+ ", store:" + entriesToStore.size()
+ ", delete:" + keysToDelete.size()
+ ", purge:" + recordsToPurge.size()
+ ", evict:" + recordsToEvict.size()
+ ", unknown:" + recordsUnknown.size()
);
executeStoreUpdate(entriesToStore, keysToDelete);
executeEviction(recordsToEvict);
executePurge(recordsToPurge);
executePurgeUnknowns(recordsUnknown);
}
private void executePurgeUnknowns(final Set<Record> recordsUnknown) {
if (recordsUnknown.size() > 0) {
concurrentMapManager.enqueueAndReturn(new Processable() {
public void process() {
purgeIfNotOwnedOrBackup(recordsUnknown);
}
});
}
}
private void executePurge(final Set<Record> recordsToPurge) {
if (recordsToPurge.size() > 0) {
concurrentMapManager.enqueueAndReturn(new Processable() {
public void process() {
final long now = System.currentTimeMillis();
for (Record recordToPurge : recordsToPurge) {
if (shouldPurgeRecord(recordToPurge, now)) {
removeAndPurgeRecord(recordToPurge);
}
}
}
});
}
}
boolean shouldPurgeRecord(Record record, long now) {
return !record.isActive() && shouldRemove(record, now);
}
private void executeEviction(Collection<Record> lsRecordsToEvict) {
if (lsRecordsToEvict != null && lsRecordsToEvict.size() > 0) {
logger.log(Level.FINEST, lsRecordsToEvict.size() + " evicting");
for (final Record recordToEvict : lsRecordsToEvict) {
concurrentMapManager.evictAsync(recordToEvict.getName(), recordToEvict.getKey());
}
}
}
void fireInvalidation(Record record) {
if (mapNearCache != null && mapNearCache.shouldInvalidateOnChange()) {
for (MemberImpl member : concurrentMapManager.lsMembers) {
if (!member.localMember()) {
if (member.getAddress() != null) {
Packet packet = concurrentMapManager.obtainPacket();
packet.name = getName();
packet.key = record.getKey();
packet.operation = ClusterOperation.CONCURRENT_MAP_INVALIDATE;
boolean sent = concurrentMapManager.send(packet, member.getAddress());
if (!sent) {
concurrentMapManager.releasePacket(packet);
}
}
}
}
mapNearCache.invalidate(record.getKey());
}
}
Record toRecord(Request req) {
Record record = mapRecords.get(req.key);
if (record == null) {
if (isMultiMap()) {
record = createNewRecord(req.key, null);
record.addValue(req.value);
} else {
record = createNewRecord(req.key, req.value);
}
mapRecords.put(req.key, record);
} else {
if (req.value != null) {
if (isMultiMap()) {
record.addValue(req.value);
} else {
record.setValue(req.value);
}
}
}
record.setIndexes(req.indexes, req.indexTypes);
record.setCopyCount((int) req.longValue);
if (req.lockCount >= 0) {
record.setLockAddress(req.lockAddress);
record.setLockThreadId(req.lockThreadId);
record.setLockCount(req.lockCount);
}
return record;
}
public boolean removeItem(Request req) {
Record record = mapRecords.get(req.key);
if (record == null) {
return false;
}
if (req.txnId != -1) {
unlock(record);
}
boolean removed = false;
if (record.getCopyCount() > 0) {
record.decrementCopyCount();
removed = true;
} else if (record.getValue() != null) {
removed = true;
} else if (record.getMultiValues() != null) {
removed = true;
}
if (removed) {
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_REMOVED, record);
record.incrementVersion();
}
req.version = record.getVersion();
req.longValue = record.getCopyCount();
markAsRemoved(record);
return true;
}
boolean evict(Request req) {
Record record = getRecord(req.key);
if (record != null && record.isEvictable()) {
fireInvalidation(record);
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_EVICTED, record.getKey(), record.getValue(), record.getMapListeners());
record.incrementVersion();
updateStats(REMOVE, record, true, null);
markAsRemoved(record);
req.clearForResponse();
req.version = record.getVersion();
req.longValue = record.getCopyCount();
lastEvictionTime = System.currentTimeMillis();
return true;
}
return false;
}
public void remove(Request req) {
Record record = mapRecords.get(req.key);
if (record == null) {
req.clearForResponse();
return;
}
if (req.txnId != -1) {
unlock(record);
}
if (!record.isActive()) {
return;
}
if (!record.isValid()) {
if (record.isEvictable()) {
return;
}
}
if (req.value != null) {
if (record.getValue() != null) {
if (!record.getValue().equals(req.value)) {
return;
}
}
}
Data oldValue = record.getValue();
if (oldValue == null && record.getMultiValues() != null && record.getMultiValues().size() > 0) {
Values values = new Values(record.getMultiValues());
oldValue = toData(values);
}
if (oldValue != null) {
fireInvalidation(record);
concurrentMapManager.fireMapEvent(mapListeners, getName(), EntryEvent.TYPE_REMOVED, record.getKey(), oldValue, record.getMapListeners());
record.incrementVersion();
}
updateStats(REMOVE, record, true, null);
markAsRemoved(record);
req.clearForResponse();
req.version = record.getVersion();
req.longValue = record.getCopyCount();
req.response = oldValue;
}
void updateStats(Op op, Record record, boolean owned, Data oldValue) {
long updateCost = 0;
if (op == UPDATE) {
long newValueCost = (record.getValue() != null) ? record.getValue().size() : 0;
long oldValueCost = (oldValue != null) ? oldValue.size() : 0;
updateCost = (newValueCost - oldValueCost);
}
localMapStats.update(op, record, owned, updateCost);
}
public void incrementLockWaits(Record record) {
localMapStats.update(ADD_LOCK_WAIT, record, true, 0);
}
public void decrementLockWaits(Record record) {
localMapStats.update(REMOVE_LOCK_WAIT, record, true, 0);
}
void reset() {
if (locallyOwnedMap != null) {
locallyOwnedMap.reset();
}
mapRecords.clear();
mapIndexService.clear();
}
void touch(Record record) {
record.setLastTouchTime(System.currentTimeMillis());
}
void markAsDirty(Record record) {
if (!record.isDirty()) {
record.setDirty(true);
if (writeDelayMillis > 0) {
record.setWriteTime(System.currentTimeMillis() + writeDelayMillis);
}
}
}
void markAsActive(Record record) {
if (!record.isActive()) {
record.setActive();
record.setCreationTime(System.currentTimeMillis());
}
}
boolean shouldRemove(Record record, long now) {
return record.isRemovable() && ((now - record.getRemoveTime()) > removeDelayMillis);
}
void markAsRemoved(Record record) {
if (record.isActive()) {
record.markRemoved();
}
record.setValue(null);
record.setMultiValues(null);
updateIndexes(record);
markAsDirty(record);
}
void removeAndPurgeRecord(Record record) {
mapRecords.remove(record.getKey());
mapIndexService.remove(record);
}
void updateIndexes(Record record) {
mapIndexService.index(record);
}
Record createNewRecord(Data key, Data value) {
if (key == null || key.size() == 0) {
throw new RuntimeException("Cannot create record from a 0 size key: " + key);
}
int blockId = concurrentMapManager.getBlockId(key);
return new Record(node.factory, getName(), blockId, key, value, ttl, maxIdle, concurrentMapManager.newRecordId());
}
public void addListener(Data key, Address address, boolean includeValue) {
if (key == null || key.size() == 0) {
mapListeners.put(address, includeValue);
} else {
Record rec = getRecord(key);
if (rec == null) {
rec = createNewRecord(key, null);
mapRecords.put(key, rec);
}
rec.addListener(address, includeValue);
}
}
public void removeListener(Data key, Address address) {
if (key == null || key.size() == 0) {
mapListeners.remove(address);
} else {
Record rec = getRecord(key);
if (rec != null) {
rec.removeListener(address);
}
}
}
public void appendState(StringBuffer sbState) {
sbState.append("\nCMap [");
sbState.append(name);
sbState.append("] r:");
sbState.append(mapRecords.size());
if (locallyOwnedMap != null) {
locallyOwnedMap.appendState(sbState);
}
if (mapNearCache != null) {
mapNearCache.appendState(sbState);
}
mapIndexService.appendState(sbState);
}
public static class Values implements Collection, DataSerializable {
Collection<Data> lsValues = null;
public Values() {
}
public Values(Collection<Data> lsValues) {
super();
this.lsValues = lsValues;
}
public boolean add(Object o) {
throw new UnsupportedOperationException();
}
public boolean addAll(Collection c) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
public boolean contains(Object o) {
if (o == null) {
throw new IllegalArgumentException("Contains cannot have null argument.");
}
Iterator it = iterator();
while (it.hasNext()) {
Object v = it.next();
if (o.equals(v)) {
return true;
}
}
return false;
}
public boolean containsAll(Collection c) {
throw new UnsupportedOperationException();
}
public boolean isEmpty() {
return (size() == 0);
}
public Iterator iterator() {
return new ValueIterator(lsValues.iterator());
}
class ValueIterator implements Iterator {
final Iterator<Data> it;
public ValueIterator(Iterator<Data> it) {
super();
this.it = it;
}
public boolean hasNext() {
return it.hasNext();
}
public Object next() {
Data value = it.next();
return toObject(value);
}
public void remove() {
it.remove();
}
}
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
public boolean removeAll(Collection c) {
throw new UnsupportedOperationException();
}
public boolean retainAll(Collection c) {
throw new UnsupportedOperationException();
}
public int size() {
return (lsValues == null) ? 0 : lsValues.size();
}
public Object[] toArray() {
if (size() == 0) {
return null;
}
return toArray(new Object[size()]);
}
public Object[] toArray(Object[] a) {
int size = size();
if (size == 0) {
return null;
}
if (a == null || a.length < size) {
a = new Object[size];
}
Iterator<Data> it = lsValues.iterator();
int index = 0;
while (it.hasNext()) {
a[index++] = toObject(it.next());
}
return a;
}
public void readData(DataInput in) throws IOException {
int size = in.readInt();
lsValues = new ArrayList<Data>(size);
for (int i = 0; i < size; i++) {
Data data = new Data();
data.readData(in);
lsValues.add(data);
}
}
public void writeData(DataOutput out) throws IOException {
int size = (lsValues == null) ? 0 : lsValues.size();
out.writeInt(size);
if (size > 0) {
for (Data data : lsValues) {
data.writeData(out);
}
}
}
}
public static class CMapEntry implements HazelcastInstanceAware, MapEntry, DataSerializable {
private long cost = 0;
private long expirationTime = 0;
private long lastAccessTime = 0;
private long lastUpdateTime = 0;
private long creationTime = 0;
private long version = 0;
private int hits = 0;
private boolean valid = true;
private String name = null;
private Object key = null;
private Object value = null;
private HazelcastInstance hazelcastInstance = null;
public CMapEntry() {
}
public CMapEntry(long cost, long expirationTime, long lastAccessTime, long lastUpdateTime, long creationTime, long version, int hits, boolean valid) {
this.cost = cost;
this.expirationTime = expirationTime;
this.lastAccessTime = lastAccessTime;
this.lastUpdateTime = lastUpdateTime;
this.creationTime = creationTime;
this.version = version;
this.hits = hits;
this.valid = valid;
}
public void writeData(DataOutput out) throws IOException {
out.writeLong(cost);
out.writeLong(expirationTime);
out.writeLong(lastAccessTime);
out.writeLong(lastUpdateTime);
out.writeLong(creationTime);
out.writeLong(version);
out.writeInt(hits);
out.writeBoolean(valid);
}
public void readData(DataInput in) throws IOException {
cost = in.readLong();
expirationTime = in.readLong();
lastAccessTime = in.readLong();
lastUpdateTime = in.readLong();
creationTime = in.readLong();
version = in.readLong();
hits = in.readInt();
valid = in.readBoolean();
}
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
public void set(String name, Object key) {
this.name = name;
this.key = key;
}
public long getCost() {
return cost;
}
public long getCreationTime() {
return creationTime;
}
public long getExpirationTime() {
return expirationTime;
}
public long getLastUpdateTime() {
return lastUpdateTime;
}
public int getHits() {
return hits;
}
public long getLastAccessTime() {
return lastAccessTime;
}
public long getVersion() {
return version;
}
public boolean isValid() {
return valid;
}
public Object getKey() {
return key;
}
public Object getValue() {
if (value == null) {
FactoryImpl factory = (FactoryImpl) hazelcastInstance;
value = ((MProxy) factory.getOrCreateProxyByName(name)).get(key);
}
return value;
}
public Object setValue(Object value) {
Object oldValue = this.value;
FactoryImpl factory = (FactoryImpl) hazelcastInstance;
((MProxy) factory.getOrCreateProxyByName(name)).put(key, value);
return oldValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CMapEntry cMapEntry = (CMapEntry) o;
return !(key != null ? !key.equals(cMapEntry.key) : cMapEntry.key != null) &&
!(name != null ? !name.equals(cMapEntry.name) : cMapEntry.name != null);
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (key != null ? key.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("MapEntry");
sb.append("{key=").append(key);
sb.append(", valid=").append(valid);
sb.append(", hits=").append(hits);
sb.append(", version=").append(version);
sb.append(", creationTime=").append(creationTime);
sb.append(", lastUpdateTime=").append(lastUpdateTime);
sb.append(", lastAccessTime=").append(lastAccessTime);
sb.append(", expirationTime=").append(expirationTime);
sb.append(", cost=").append(cost);
sb.append('}');
return sb.toString();
}
}
@Override
public String toString() {
return "CMap [" + getName() + "] size=" + size();
}
/**
* @return the name
*/
public String getName() {
return name;
}
public MapIndexService getMapIndexService() {
return mapIndexService;
}
}
| false | true | public CMap(ConcurrentMapManager concurrentMapManager, String name) {
this.concurrentMapManager = concurrentMapManager;
this.logger = concurrentMapManager.node.getLogger(CMap.class.getName());
this.PARTITION_COUNT = concurrentMapManager.PARTITION_COUNT;
this.blocks = concurrentMapManager.blocks;
this.node = concurrentMapManager.node;
this.thisAddress = concurrentMapManager.thisAddress;
this.name = name;
MapConfig mapConfig = null;
String mapConfigName = name.substring(2);
if (mapConfigName.startsWith("__hz_") || mapConfigName.startsWith("l:") || mapConfigName.startsWith("s:")) {
mapConfig = new MapConfig();
} else {
mapConfig = node.getConfig().getMapConfig(mapConfigName);
}
this.backupCount = mapConfig.getBackupCount();
ttl = mapConfig.getTimeToLiveSeconds() * 1000L;
evictionDelayMillis = mapConfig.getEvictionDelaySeconds() * 1000L;
maxIdle = mapConfig.getMaxIdleSeconds() * 1000L;
evictionPolicy = EvictionPolicy.valueOf(mapConfig.getEvictionPolicy());
if (evictionPolicy == EvictionPolicy.NONE) {
maxSize = Integer.MAX_VALUE;
evictionComparator = null;
} else {
maxSize = (mapConfig.getMaxSize() == 0) ? MapConfig.DEFAULT_MAX_SIZE : mapConfig.getMaxSize();
if (evictionPolicy == EvictionPolicy.LRU) {
evictionComparator = LRU_COMPARATOR;
} else {
evictionComparator = LFU_COMPARATOR;
}
}
evictionRate = mapConfig.getEvictionPercentage() / 100f;
instanceType = ConcurrentMapManager.getInstanceType(name);
MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
MapStore storeTemp = null;
MapLoader loaderTemp = null;
int writeDelaySeconds = -1;
if (mapStoreConfig != null && mapStoreConfig.isEnabled()) {
try {
Object storeInstance = mapStoreConfig.getImplementation();
if (storeInstance == null) {
String mapStoreClassName = mapStoreConfig.getClassName();
storeInstance = Serializer.classForName(node.getConfig().getClassLoader(), mapStoreClassName).newInstance();
}
if (storeInstance instanceof MapLoader) {
loaderTemp = (MapLoader) storeInstance;
}
if (storeInstance instanceof MapStore) {
storeTemp = (MapStore) storeInstance;
}
} catch (Exception e) {
e.printStackTrace();
}
writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds();
}
loader = loaderTemp;
store = storeTemp;
writeDelayMillis = (writeDelaySeconds == -1) ? -1L : writeDelaySeconds * 1000L;
if (writeDelaySeconds > 0) {
removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS + writeDelaySeconds;
} else {
removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS;
}
if (evictionPolicy == EvictionPolicy.NONE && instanceType == Instance.InstanceType.MAP) {
locallyOwnedMap = new LocallyOwnedMap(localMapStats);
concurrentMapManager.mapLocallyOwnedMaps.put(name, locallyOwnedMap);
} else {
locallyOwnedMap = null;
}
NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig();
if (nearCacheConfig == null) {
mapNearCache = null;
} else {
mapNearCache = new MapNearCache(this,
SortedHashMap.getOrderingTypeByName(mapConfig.getEvictionPolicy()),
nearCacheConfig.getMaxSize(),
nearCacheConfig.getTimeToLiveSeconds() * 1000L,
nearCacheConfig.getMaxIdleSeconds() * 1000L,
nearCacheConfig.isInvalidateOnChange());
concurrentMapManager.mapCaches.put(name, mapNearCache);
}
this.creationTime = System.currentTimeMillis();
}
| public CMap(ConcurrentMapManager concurrentMapManager, String name) {
this.concurrentMapManager = concurrentMapManager;
this.logger = concurrentMapManager.node.getLogger(CMap.class.getName());
this.PARTITION_COUNT = concurrentMapManager.PARTITION_COUNT;
this.blocks = concurrentMapManager.blocks;
this.node = concurrentMapManager.node;
this.thisAddress = concurrentMapManager.thisAddress;
this.name = name;
MapConfig mapConfig = null;
String mapConfigName = name.substring(2);
if (mapConfigName.startsWith("__hz_") || mapConfigName.startsWith("l:") || mapConfigName.startsWith("s:")) {
mapConfig = new MapConfig();
} else {
mapConfig = node.getConfig().getMapConfig(mapConfigName);
}
this.backupCount = mapConfig.getBackupCount();
ttl = mapConfig.getTimeToLiveSeconds() * 1000L;
evictionDelayMillis = mapConfig.getEvictionDelaySeconds() * 1000L;
maxIdle = mapConfig.getMaxIdleSeconds() * 1000L;
evictionPolicy = EvictionPolicy.valueOf(mapConfig.getEvictionPolicy());
if (evictionPolicy == EvictionPolicy.NONE) {
maxSize = Integer.MAX_VALUE;
evictionComparator = null;
} else {
maxSize = (mapConfig.getMaxSize() == 0) ? MapConfig.DEFAULT_MAX_SIZE : mapConfig.getMaxSize();
if (evictionPolicy == EvictionPolicy.LRU) {
evictionComparator = LRU_COMPARATOR;
} else {
evictionComparator = LFU_COMPARATOR;
}
}
evictionRate = mapConfig.getEvictionPercentage() / 100f;
instanceType = ConcurrentMapManager.getInstanceType(name);
MapStoreConfig mapStoreConfig = mapConfig.getMapStoreConfig();
MapStore storeTemp = null;
MapLoader loaderTemp = null;
int writeDelaySeconds = -1;
if (!node.isSuperClient() && mapStoreConfig != null && mapStoreConfig.isEnabled()) {
try {
Object storeInstance = mapStoreConfig.getImplementation();
if (storeInstance == null) {
String mapStoreClassName = mapStoreConfig.getClassName();
storeInstance = Serializer.classForName(node.getConfig().getClassLoader(), mapStoreClassName).newInstance();
}
if (storeInstance instanceof MapLoader) {
loaderTemp = (MapLoader) storeInstance;
}
if (storeInstance instanceof MapStore) {
storeTemp = (MapStore) storeInstance;
}
} catch (Exception e) {
e.printStackTrace();
}
writeDelaySeconds = mapStoreConfig.getWriteDelaySeconds();
}
if (!node.isSuperClient() && evictionPolicy == EvictionPolicy.NONE && instanceType == Instance.InstanceType.MAP) {
locallyOwnedMap = new LocallyOwnedMap(localMapStats);
concurrentMapManager.mapLocallyOwnedMaps.put(name, locallyOwnedMap);
} else {
locallyOwnedMap = null;
}
writeDelayMillis = (writeDelaySeconds == -1) ? -1L : writeDelaySeconds * 1000L;
if (writeDelaySeconds > 0) {
removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS + writeDelaySeconds;
} else {
removeDelayMillis = concurrentMapManager.GLOBAL_REMOVE_DELAY_MILLIS;
}
loader = loaderTemp;
store = storeTemp;
NearCacheConfig nearCacheConfig = mapConfig.getNearCacheConfig();
if (nearCacheConfig == null) {
mapNearCache = null;
} else {
mapNearCache = new MapNearCache(this,
SortedHashMap.getOrderingTypeByName(mapConfig.getEvictionPolicy()),
nearCacheConfig.getMaxSize(),
nearCacheConfig.getTimeToLiveSeconds() * 1000L,
nearCacheConfig.getMaxIdleSeconds() * 1000L,
nearCacheConfig.isInvalidateOnChange());
concurrentMapManager.mapCaches.put(name, mapNearCache);
}
this.creationTime = System.currentTimeMillis();
}
|
diff --git a/src/main/java/uk/co/cameronhunter/aws/glacier/cli/GlacierDownload.java b/src/main/java/uk/co/cameronhunter/aws/glacier/cli/GlacierDownload.java
index f2781ae..475118c 100644
--- a/src/main/java/uk/co/cameronhunter/aws/glacier/cli/GlacierDownload.java
+++ b/src/main/java/uk/co/cameronhunter/aws/glacier/cli/GlacierDownload.java
@@ -1,43 +1,43 @@
package uk.co.cameronhunter.aws.glacier.cli;
import static org.apache.commons.lang.Validate.isTrue;
import static uk.co.cameronhunter.aws.glacier.utils.Check.notBlank;
import java.io.File;
import java.util.List;
import uk.co.cameronhunter.aws.glacier.Glacier;
public class GlacierDownload extends AbstractGlacierCli {
public GlacierDownload( String... parameters ) {
super( parameters );
}
public GlacierDownload( Glacier glacier, List<String> parameters ) {
super( glacier, parameters );
}
public static void main( String... parameters ) throws Exception {
new GlacierDownload( parameters ).run();
}
@Override
protected void validate( List<String> parameters ) {
isTrue( parameters.size() == 3 );
notBlank( parameters.get( 0 ), "No vault parameter given" );
notBlank( parameters.get( 1 ), "No archiveId parameter given" );
notBlank( parameters.get( 2 ), "No target parameter given" );
}
@Override
protected void execute( Glacier glacier, List<String> parameters ) throws Exception {
- String vault = parameters.get( 1 );
- String archiveId = parameters.get( 2 );
- String target = parameters.get( 3 );
+ String vault = parameters.get( 0 );
+ String archiveId = parameters.get( 1 );
+ String target = parameters.get( 2 );
File archive = glacier.download( vault, archiveId ).get();
archive.renameTo( new File( target ) );
}
}
| true | true | protected void execute( Glacier glacier, List<String> parameters ) throws Exception {
String vault = parameters.get( 1 );
String archiveId = parameters.get( 2 );
String target = parameters.get( 3 );
File archive = glacier.download( vault, archiveId ).get();
archive.renameTo( new File( target ) );
}
| protected void execute( Glacier glacier, List<String> parameters ) throws Exception {
String vault = parameters.get( 0 );
String archiveId = parameters.get( 1 );
String target = parameters.get( 2 );
File archive = glacier.download( vault, archiveId ).get();
archive.renameTo( new File( target ) );
}
|
diff --git a/src/environment/Environment.java b/src/environment/Environment.java
index 48fadc8..a850e90 100644
--- a/src/environment/Environment.java
+++ b/src/environment/Environment.java
@@ -1,248 +1,248 @@
package environment;
import actor.Predator;
import actor.Prey;
import policy.LearnedPolicy;
import policy.Policy;
import statespace.CompleteStateSpace;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Set;
public class Environment {
private CompleteStateSpace completeStateSpace;
private Prey prey;
private Predator predator;
private static final int MAX_ITERATIONS = 1000;
private final double THETA = 0.00001; // threshold for the loop end condition
private final double GAMMA = 0.8;
public enum action { NORTH, SOUTH, EAST, WEST, WAIT };
public Environment() {
this.completeStateSpace = new CompleteStateSpace();
this.predator = new Predator(new Coordinates(0,0), completeStateSpace);
this.prey = new Prey(new Coordinates(5,5), completeStateSpace);
}
public void simulate(int episodeCount) {
int episodes = episodeCount;
do {
// initialize Episode
this.predator.setCoordinates(new Coordinates(0, 0));
this.prey.setCoordinates(new Coordinates(5, 5));
this.prey.setAlive(true);
State initialState = this.completeStateSpace.getState(this.prey.getCoordinates(), this.predator.getCoordinates());
int rounds = 0;
while (!isEpisodeOver()) { // run episode
initialState = this.nextRound(initialState);
rounds++;
}
//REPORT
System.out.println("[simulate()] rounds: " + rounds);
episodes--;
} while (episodes > 0);
}
public boolean isEpisodeOver() { return !this.prey.getAlive(); }
public State nextRound(State s) {
State currentState = s;
this.predator.move(currentState);
// update currentState.
currentState = this.completeStateSpace.getState(this.prey.getCoordinates(), this.predator.getCoordinates());
this.collisionDetection();
this.prey.move(currentState);
this.collisionDetection();
return this.completeStateSpace.getState(this.prey.getCoordinates(), this.predator.getCoordinates());
}
private void collisionDetection() {
if (predator.getCoordinates().equals(prey.getCoordinates())) { prey.setAlive(false); }
}
/**
* Task 1.2
* For extensive explanation see : http://webdocs.cs.ualberta.ca/~sutton/book/ebook/node41.html
*/
public void policyEvaluation(/*Policy policy, */) {
double delta = 0.0; // defines the maximum difference observed in the stateValue of all states
int sweeps = 0;
Policy policy = this.predator.getPolicy();
do { // Repeat
delta = 0.0;
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State currState = completeStateSpace.next(); // for s in S+
double V_s = 0.0;
double v = currState.getStateValue();
for (action ac : Environment.action.values()) { // summation over a
double pi = policy.getActionProbability(currState, ac);
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(currState, ac);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
sum += p * (s_prime.getStateReward() + GAMMA * s_prime.getStateValue());
}
V_s += pi * sum;
}
currState.setStateValue(V_s);
delta = Math.max(Math.abs(V_s - v), delta);
}
sweeps++;
} while (delta > THETA);
// REPORT
Coordinates preyCoordinates = new Coordinates(0,0);
Coordinates predatorCoordinates = new Coordinates(0,0);
System.out.println(this.completeStateSpace.getState(preyCoordinates, predatorCoordinates));
System.out.println("[policyEvaluation()] Sweeps: " + sweeps);
// /REPORT
}
/**
* Task 1.3
*/
public boolean policyImprovement(/*Policy policy*/) {
boolean policyStable = true;
Policy policy = this.predator.getPolicy();
for (State s : this.completeStateSpace) {
action b = policy.getAction(s);
double max = 0.0;
action argmax_a = null;
for (action a : Environment.action.values()) {
double sum = 0.0;
for (State s_prime : this.completeStateSpace.getNeighbors(s)) {
double p;
if (this.completeStateSpace.getTransitionAction(s, s_prime) == a) { p = 1.0; }
else { p = 0.0; }
// P^(pi(s))_ss' has only two possible values: 1 if the action will lead to s', 0 otherwise
// // ac: the action that would be required to move to state st
double r = completeStateSpace.getActionReward(s, a);
sum += p * (r + GAMMA * s_prime.getStateValue());
}
if(sum > max) {
argmax_a = a;
max = sum;
}
}
policy.setUniqueAction(s, argmax_a);
if(argmax_a != b) { policyStable = false; }
}
return policyStable;
}
/**
* Task 1.3
*/
public void policyIteration(/*Policy policy*/) {
int debugIterations = 0;
Policy policy = this.predator.getPolicy();
this.completeStateSpace.initializeStateValues(0.0);
do {
this.policyEvaluation();
this.completeStateSpace.printActions(policy);
debugIterations++;
} while (!this.policyImprovement());
System.out.println("[policyIteration()] Number of Iterations : " + debugIterations);
}
public ValueIterationResult valueIteration(double local_gamma) {
double delta;
// initialization
this.completeStateSpace.initializeStateValues(0.0);
int numIterations = 0;
// calculation of the V(s)
do {
numIterations++;
delta = 0.0;
// for each s in S
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State s = stateSpaceIt.next();
double v = s.getStateValue();
double max = 0.0;
for (action a: Environment.action.values()) { // max over a
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(s, a);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
sum += p * (s_prime.getStateReward() + local_gamma * s_prime.getStateValue());
}
max = Math.max(max, sum);
}
double V_s = max;
s.setStateValue(V_s);
delta = Math.max(delta, Math.abs(s.getStateValue() - v));
}
if(numIterations >= this.MAX_ITERATIONS) { break; }
} while(delta > this.THETA);
// production of the policy
LearnedPolicy pi = new LearnedPolicy();
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State s = stateSpaceIt.next();
action argmax_a = action.WAIT;
double max = 0.0;
for (action a: Environment.action.values()) { // argmax over a
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(s, a);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
- sum += p * (s_prime.getStateReward() + GAMMA * s_prime.getStateValue());
+ sum += p * (s_prime.getStateReward() + local_gamma * s_prime.getStateValue());
}
if(sum > max) {
max = sum;
argmax_a = a;
}
}
pi.setUniqueAction(s, argmax_a);
}
// TODO: output State values somehow.
// this.state.printStateValues();
return new ValueIterationResult(numIterations,pi);
}
/**
* increases gamma with step 0.001. Outputs to results.csv. Used for plotting.
*/
public void valueIterationGammas() {
double gamma = 0.0;
int size = 1000;
ValueIterationResult[] iterations = new ValueIterationResult[size];
BufferedWriter br;
try {
br = new BufferedWriter(new FileWriter("results.csv"));
for(int i = 0; i < size-1; i++) {
gamma += 0.001;
System.out.println("gamma:"+gamma);
iterations[i] = this.valueIteration(gamma);
System.out.println("num iterations:"+iterations[i].getNumIterations());
String str = i+","+gamma+","+iterations[i].getNumIterations()+"\n";
System.out.println(str);
br.write(str);
} br.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
| true | true | public ValueIterationResult valueIteration(double local_gamma) {
double delta;
// initialization
this.completeStateSpace.initializeStateValues(0.0);
int numIterations = 0;
// calculation of the V(s)
do {
numIterations++;
delta = 0.0;
// for each s in S
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State s = stateSpaceIt.next();
double v = s.getStateValue();
double max = 0.0;
for (action a: Environment.action.values()) { // max over a
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(s, a);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
sum += p * (s_prime.getStateReward() + local_gamma * s_prime.getStateValue());
}
max = Math.max(max, sum);
}
double V_s = max;
s.setStateValue(V_s);
delta = Math.max(delta, Math.abs(s.getStateValue() - v));
}
if(numIterations >= this.MAX_ITERATIONS) { break; }
} while(delta > this.THETA);
// production of the policy
LearnedPolicy pi = new LearnedPolicy();
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State s = stateSpaceIt.next();
action argmax_a = action.WAIT;
double max = 0.0;
for (action a: Environment.action.values()) { // argmax over a
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(s, a);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
sum += p * (s_prime.getStateReward() + GAMMA * s_prime.getStateValue());
}
if(sum > max) {
max = sum;
argmax_a = a;
}
}
pi.setUniqueAction(s, argmax_a);
}
// TODO: output State values somehow.
// this.state.printStateValues();
return new ValueIterationResult(numIterations,pi);
}
| public ValueIterationResult valueIteration(double local_gamma) {
double delta;
// initialization
this.completeStateSpace.initializeStateValues(0.0);
int numIterations = 0;
// calculation of the V(s)
do {
numIterations++;
delta = 0.0;
// for each s in S
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State s = stateSpaceIt.next();
double v = s.getStateValue();
double max = 0.0;
for (action a: Environment.action.values()) { // max over a
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(s, a);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
sum += p * (s_prime.getStateReward() + local_gamma * s_prime.getStateValue());
}
max = Math.max(max, sum);
}
double V_s = max;
s.setStateValue(V_s);
delta = Math.max(delta, Math.abs(s.getStateValue() - v));
}
if(numIterations >= this.MAX_ITERATIONS) { break; }
} while(delta > this.THETA);
// production of the policy
LearnedPolicy pi = new LearnedPolicy();
Iterator<State> stateSpaceIt = this.completeStateSpace.iterator();
while(stateSpaceIt.hasNext()) {
State s = stateSpaceIt.next();
action argmax_a = action.WAIT;
double max = 0.0;
for (action a: Environment.action.values()) { // argmax over a
ProbableTransitions probableTransitions = completeStateSpace.getProbableTransitions(s, a);
Set<State> neighbours = probableTransitions.getStates();
double sum = 0.0;
for(State s_prime : neighbours){ // summation over s'
double p = probableTransitions.getProbability(s_prime);
sum += p * (s_prime.getStateReward() + local_gamma * s_prime.getStateValue());
}
if(sum > max) {
max = sum;
argmax_a = a;
}
}
pi.setUniqueAction(s, argmax_a);
}
// TODO: output State values somehow.
// this.state.printStateValues();
return new ValueIterationResult(numIterations,pi);
}
|
diff --git a/tests/org.eclipse.acceleo.tests/src/org/eclipse/acceleo/tests/suite/AllTests.java b/tests/org.eclipse.acceleo.tests/src/org/eclipse/acceleo/tests/suite/AllTests.java
index f8ffd993..f143981e 100644
--- a/tests/org.eclipse.acceleo.tests/src/org/eclipse/acceleo/tests/suite/AllTests.java
+++ b/tests/org.eclipse.acceleo.tests/src/org/eclipse/acceleo/tests/suite/AllTests.java
@@ -1,65 +1,65 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.tests.suite;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.eclipse.acceleo.compatibility.tests.suite.CompatibilityTestSuite;
import org.eclipse.acceleo.engine.tests.suite.EngineTestSuite;
import org.eclipse.acceleo.tests.suite.utils.TraceabilityActivationTest;
/**
* This suite will launch all the tests defined for the Acceleo project.
*
* @author <a href="mailto:[email protected]">Jonathan Musset</a>
*/
@SuppressWarnings("nls")
public class AllTests {
/**
* Launches the test with the given arguments.
*
* @param args
* Arguments of the testCase.
*/
public static void main(String[] args) {
TestRunner.run(suite());
}
/**
* Creates the {@link junit.framework.TestSuite TestSuite} for all the test.
*
* @return The test suite containing all the tests
*/
public static Test suite() {
final TestSuite suite = new TestSuite("Acceleo test suite");
final TestSuite classicSuite = new TestSuite("Testing Acceleo With Traceability Disabled");
classicSuite.addTest(CompatibilityTestSuite.suite());
classicSuite.addTest(EngineTestSuite.suite());
classicSuite.addTest(org.eclipse.acceleo.ide.ui.tests.suite.AllTests.suite());
classicSuite.addTest(org.eclipse.acceleo.parser.tests.suite.AllTests.suite());
final TestSuite traceabilitySuite = new TestSuite("Testing Acceleo With Traceability Enabled");
traceabilitySuite.addTestSuite(TraceabilityActivationTest.class);
traceabilitySuite.addTest(CompatibilityTestSuite.suite());
- classicSuite.addTest(EngineTestSuite.suite());
+ traceabilitySuite.addTest(EngineTestSuite.suite());
traceabilitySuite.addTest(org.eclipse.acceleo.ide.ui.tests.suite.AllTests.suite());
traceabilitySuite.addTest(org.eclipse.acceleo.parser.tests.suite.AllTests.suite());
suite.addTest(classicSuite);
suite.addTest(traceabilitySuite);
return suite;
}
}
| true | true | public static Test suite() {
final TestSuite suite = new TestSuite("Acceleo test suite");
final TestSuite classicSuite = new TestSuite("Testing Acceleo With Traceability Disabled");
classicSuite.addTest(CompatibilityTestSuite.suite());
classicSuite.addTest(EngineTestSuite.suite());
classicSuite.addTest(org.eclipse.acceleo.ide.ui.tests.suite.AllTests.suite());
classicSuite.addTest(org.eclipse.acceleo.parser.tests.suite.AllTests.suite());
final TestSuite traceabilitySuite = new TestSuite("Testing Acceleo With Traceability Enabled");
traceabilitySuite.addTestSuite(TraceabilityActivationTest.class);
traceabilitySuite.addTest(CompatibilityTestSuite.suite());
classicSuite.addTest(EngineTestSuite.suite());
traceabilitySuite.addTest(org.eclipse.acceleo.ide.ui.tests.suite.AllTests.suite());
traceabilitySuite.addTest(org.eclipse.acceleo.parser.tests.suite.AllTests.suite());
suite.addTest(classicSuite);
suite.addTest(traceabilitySuite);
return suite;
}
| public static Test suite() {
final TestSuite suite = new TestSuite("Acceleo test suite");
final TestSuite classicSuite = new TestSuite("Testing Acceleo With Traceability Disabled");
classicSuite.addTest(CompatibilityTestSuite.suite());
classicSuite.addTest(EngineTestSuite.suite());
classicSuite.addTest(org.eclipse.acceleo.ide.ui.tests.suite.AllTests.suite());
classicSuite.addTest(org.eclipse.acceleo.parser.tests.suite.AllTests.suite());
final TestSuite traceabilitySuite = new TestSuite("Testing Acceleo With Traceability Enabled");
traceabilitySuite.addTestSuite(TraceabilityActivationTest.class);
traceabilitySuite.addTest(CompatibilityTestSuite.suite());
traceabilitySuite.addTest(EngineTestSuite.suite());
traceabilitySuite.addTest(org.eclipse.acceleo.ide.ui.tests.suite.AllTests.suite());
traceabilitySuite.addTest(org.eclipse.acceleo.parser.tests.suite.AllTests.suite());
suite.addTest(classicSuite);
suite.addTest(traceabilitySuite);
return suite;
}
|
diff --git a/org.epic.debug/src/org/epic/debug/db/RE.java b/org.epic.debug/src/org/epic/debug/db/RE.java
index 4accaafb..cdb799c3 100644
--- a/org.epic.debug/src/org/epic/debug/db/RE.java
+++ b/org.epic.debug/src/org/epic/debug/db/RE.java
@@ -1,57 +1,57 @@
package org.epic.debug.db;
import gnu.regexp.REException;
import gnu.regexp.RESyntax;
/**
* Regular expressions used for parsing "perl -d" output
*/
class RE
{
final gnu.regexp.RE CMD_FINISHED1;
final gnu.regexp.RE CMD_FINISHED2;
final gnu.regexp.RE SESSION_FINISHED1;
final gnu.regexp.RE SESSION_FINISHED2;
final gnu.regexp.RE IP_POS;
final gnu.regexp.RE IP_POS_EVAL;
final gnu.regexp.RE IP_POS_CODE;
final gnu.regexp.RE SWITCH_FILE_FAIL;
final gnu.regexp.RE SET_LINE_BREAKPOINT;
final gnu.regexp.RE STACK_TRACE;
final gnu.regexp.RE ENTER_FRAME;
final gnu.regexp.RE EXIT_FRAME;
public RE()
{
CMD_FINISHED1 = newRE("\n\\s+DB<+\\d+>+", false);
CMD_FINISHED2 = newRE("^\\s+DB<\\d+>", false);
SESSION_FINISHED1 = newRE("Use `q' to quit or `R' to restart", false);
SESSION_FINISHED2 = newRE("Debugged program terminated.", false);
IP_POS = newRE("^[^\\(]*\\((.*):(\\d+)\\):[\\n\\t]", false);
IP_POS_EVAL = newRE("^[^\\(]*\\(eval\\s+\\d+\\)\\[(.*):(\\d+)\\]$", false);
IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\(([^:]*):(\\d+)\\):[\\n\\t]", false);
SWITCH_FILE_FAIL = newRE("^No file", false);
SET_LINE_BREAKPOINT = newRE("^Line \\d+ not breakable", false);
ENTER_FRAME = newRE("^\\s*entering", false);
EXIT_FRAME = newRE("^\\s*exited", false);
STACK_TRACE = newRE(
- "^(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*$",
- true);
+ "(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*",
+ false);
}
private gnu.regexp.RE newRE(String re, boolean multiline)
{
try
{
return new gnu.regexp.RE(
re,
multiline ? gnu.regexp.RE.REG_MULTILINE : 0,
RESyntax.RE_SYNTAX_PERL5);
}
catch (REException e)
{
// we have a bug in the constructor
throw new RuntimeException(e);
}
}
}
| true | true | public RE()
{
CMD_FINISHED1 = newRE("\n\\s+DB<+\\d+>+", false);
CMD_FINISHED2 = newRE("^\\s+DB<\\d+>", false);
SESSION_FINISHED1 = newRE("Use `q' to quit or `R' to restart", false);
SESSION_FINISHED2 = newRE("Debugged program terminated.", false);
IP_POS = newRE("^[^\\(]*\\((.*):(\\d+)\\):[\\n\\t]", false);
IP_POS_EVAL = newRE("^[^\\(]*\\(eval\\s+\\d+\\)\\[(.*):(\\d+)\\]$", false);
IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\(([^:]*):(\\d+)\\):[\\n\\t]", false);
SWITCH_FILE_FAIL = newRE("^No file", false);
SET_LINE_BREAKPOINT = newRE("^Line \\d+ not breakable", false);
ENTER_FRAME = newRE("^\\s*entering", false);
EXIT_FRAME = newRE("^\\s*exited", false);
STACK_TRACE = newRE(
"^(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*$",
true);
}
| public RE()
{
CMD_FINISHED1 = newRE("\n\\s+DB<+\\d+>+", false);
CMD_FINISHED2 = newRE("^\\s+DB<\\d+>", false);
SESSION_FINISHED1 = newRE("Use `q' to quit or `R' to restart", false);
SESSION_FINISHED2 = newRE("Debugged program terminated.", false);
IP_POS = newRE("^[^\\(]*\\((.*):(\\d+)\\):[\\n\\t]", false);
IP_POS_EVAL = newRE("^[^\\(]*\\(eval\\s+\\d+\\)\\[(.*):(\\d+)\\]$", false);
IP_POS_CODE = newRE("^.*CODE\\(0x[0-9a-fA-F]+\\)\\(([^:]*):(\\d+)\\):[\\n\\t]", false);
SWITCH_FILE_FAIL = newRE("^No file", false);
SET_LINE_BREAKPOINT = newRE("^Line \\d+ not breakable", false);
ENTER_FRAME = newRE("^\\s*entering", false);
EXIT_FRAME = newRE("^\\s*exited", false);
STACK_TRACE = newRE(
"(.)\\s+=\\s+(.*)called from .* \\`([^\\']+)\\'\\s*line (\\d+)\\s*",
false);
}
|
diff --git a/src/simpleserver/stream/StreamTunnel.java b/src/simpleserver/stream/StreamTunnel.java
index 6167aab..33bd8df 100644
--- a/src/simpleserver/stream/StreamTunnel.java
+++ b/src/simpleserver/stream/StreamTunnel.java
@@ -1,1076 +1,1077 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver.stream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.IllegalFormatException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import simpleserver.Color;
import simpleserver.Coordinate;
import simpleserver.Group;
import simpleserver.Player;
import simpleserver.Server;
import simpleserver.Coordinate.Dimension;
import simpleserver.command.LocalSayCommand;
import simpleserver.command.PlayerListCommand;
import simpleserver.config.ChestList.Chest;
public class StreamTunnel {
private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING");
private static final int IDLE_TIME = 30000;
private static final int BUFFER_SIZE = 1024;
private static final byte BLOCK_DESTROYED_STATUS = 2;
private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$");
private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-f]");
private static final String CONSOLE_CHAT_PATTERN = "\\(CONSOLE:.*\\)";
private static final int MESSAGE_SIZE = 60;
private static final int MAXIMUM_MESSAGE_SIZE = 119;
private final boolean isServerTunnel;
private final String streamType;
private final Player player;
private final Server server;
private final byte[] buffer;
private final Tunneler tunneler;
private DataInput in;
private DataOutput out;
private StreamDumper inputDumper;
private StreamDumper outputDumper;
private int motionCounter = 0;
private boolean inGame = false;
private volatile long lastRead;
private volatile boolean run = true;
private Byte lastPacket;
public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel,
Player player) {
this.isServerTunnel = isServerTunnel;
if (isServerTunnel) {
streamType = "ServerStream";
} else {
streamType = "PlayerStream";
}
this.player = player;
server = player.getServer();
DataInputStream dIn = new DataInputStream(new BufferedInputStream(in));
DataOutputStream dOut = new DataOutputStream(new BufferedOutputStream(out));
if (EXPENSIVE_DEBUG_LOGGING) {
try {
OutputStream dump = new FileOutputStream(streamType + "Input.debug");
InputStreamDumper dumper = new InputStreamDumper(dIn, dump);
inputDumper = dumper;
this.in = dumper;
} catch (FileNotFoundException e) {
System.out.println("Unable to open input debug dump!");
throw new RuntimeException(e);
}
try {
OutputStream dump = new FileOutputStream(streamType + "Output.debug");
OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump);
outputDumper = dumper;
this.out = dumper;
} catch (FileNotFoundException e) {
System.out.println("Unable to open output debug dump!");
throw new RuntimeException(e);
}
} else {
this.in = dIn;
this.out = dOut;
}
buffer = new byte[BUFFER_SIZE];
tunneler = new Tunneler();
tunneler.start();
lastRead = System.currentTimeMillis();
}
public void stop() {
run = false;
}
public boolean isAlive() {
return tunneler.isAlive();
}
public boolean isActive() {
return System.currentTimeMillis() - lastRead < IDLE_TIME
|| player.isRobot();
}
private void handlePacket() throws IOException {
Byte packetId = in.readByte();
int x;
byte y;
int z;
byte dimension;
Coordinate coordinate;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
break;
case 0x01: // Login Request/Response
write(packetId);
if (isServerTunnel) {
player.setEntityId(in.readInt());
write(player.getEntityId());
} else {
write(in.readInt());
}
write(readUTF16());
write(in.readLong());
dimension = in.readByte();
if (isServerTunnel) {
player.setDimension(Dimension.get(dimension));
}
write(dimension);
break;
case 0x02: // Handshake
String name = readUTF16();
if (isServerTunnel || player.setName(name)) {
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(name);
}
break;
case 0x03: // Chat Message
String message = readUTF16();
if (isServerTunnel && server.options.getBoolean("useMsgFormats")) {
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
Player friend = server.findPlayerExact(messageMatcher.group(1));
if (friend != null) {
String color = "f";
String title = "";
String format = server.options.get("msgFormat");
Group group = friend.getGroup();
if (group != null) {
color = group.getColor();
if (group.showTitle()) {
title = group.getName();
format = server.options.get("msgTitleFormat");
}
}
try {
message = String.format(format, friend.getName(), title, color)
+ messageMatcher.group(2);
} catch (IllegalFormatException e) {
System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!");
}
}
} else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.options.getBoolean("chatConsoleToOps")) {
break;
}
if (server.options.getBoolean("msgWrap")) {
sendMessage(message);
} else {
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
} else if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addMessage("\u00a7cYou are muted! You may not send messages to all players.");
break;
}
if (player.parseCommand(message)) {
break;
}
if (player.localChat() && !message.startsWith("/") && !message.startsWith("!")) {
player.execute(LocalSayCommand.class, message);
break;
}
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
break;
case 0x04: // Time Update
write(packetId);
long time = in.readLong();
server.setTime(time);
write(time);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readShort());
write(in.readShort());
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
break;
case 0x07: // Use Entity?
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
write(in.readBoolean());
break;
case 0x08: // Update Health
write(packetId);
copyNBytes(2);
break;
case 0x09: // Respawn
write(packetId);
dimension = in.readByte();
write(dimension);
player.setDimension(Dimension.get(dimension));
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if (server.options.getBoolean("showListOnConnect")) {
// display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
break;
case 0x0c: // Player Look
write(packetId);
copyNBytes(9);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyNBytes(8);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
coordinate = new Coordinate(x, y, z, player);
boolean[] perms = server.permissions.getPlayerBlockPermissions(player, coordinate, 0);
if (!perms[2] && status == 0) {
player.addMessage("\u00a7c " + server.l.get("USE_FORBIDDEN"));
break;
}
if (!perms[1] && status == 2) {
player.addMessage("\u00a7c " + server.l.get("DESTROY_FORBIDDEN"));
break;
}
boolean locked = server.chests.isLocked(coordinate);
if (!locked || player.isAdmin()) {
if (locked && status == BLOCK_DESTROYED_STATUS) {
server.chests.releaseLock(coordinate);
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if (status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
} else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
coordinate = new Coordinate(x, y, z, player);
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
}
boolean writePacket = true;
boolean drop = false;
boolean[] perms = server.permissions.getPlayerBlockPermissions(player, coordinate, dropItem);
if (isServerTunnel || server.chests.isChest(coordinate)) {
// continue
} else if ((dropItem != -1 && !perms[0]) || (dropItem == -1 && !perms[2])) {
if (dropItem == -1) {
player.addMessage("\u00a7c " + server.l.get("USE_FORBIDDEN"));
} else {
player.addMessage("\u00a7c " + server.l.get("PLACE_FORBIDDEN"));
}
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player);
Chest adjacentChest = server.chests.adjacentChest(targetBlock);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addMessage("\u00a7c " + server.l.get("ADJ_CHEST_LOCKED"));
writePacket = false;
drop = true;
} else {
player.placingChest(targetBlock);
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if (dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
player.openingChest(coordinate);
} else if (drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // ???
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
write(packetId);
write(in.readInt());
write(readUTF16());
copyNBytes(16);
break;
case 0x15: // Pickup spawn
write(packetId);
copyNBytes(24);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
int flag = in.readInt();
write(flag);
if (flag > 0) {
write(in.readShort());
write(in.readShort());
write(in.readShort());
}
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
copyUnknownBlob();
break;
case 0x19: // Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1b: // ???
write(packetId);
copyNBytes(18);
break;
case 0x1c: // Entity Velocity?
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
copyNBytes(4);
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x26: // Entity status?
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity?
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x32: // Pre-Chunk
write(packetId);
copyNBytes(9);
break;
case 0x33: // Map Chunk
write(packetId);
copyNBytes(13);
int chunkSize = in.readInt();
write(chunkSize);
copyNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
write(packetId);
copyNBytes(8);
short arraySize = in.readShort();
write(arraySize);
copyNBytes(arraySize * 4);
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte blockType = in.readByte();
byte metadata = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (blockType == 54 && player.placedChest(coordinate)) {
lockChest(coordinate);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // ???
write(packetId);
copyNBytes(12);
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
break;
case 0x3d: // Unknown
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
break;
case 0x46: // Invalid Bed
write(packetId);
copyNBytes(1);
break;
case 0x47: // Thunder
write(packetId);
copyNBytes(17);
break;
case 0x64: // Open window
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = in.readUTF();
byte unknownByte = in.readByte();
if (invtype == 0) {
if (!server.permissions.canOpenChests(player, player.openedChest())) {
player.addMessage(Color.RED, "You can't use chests here");
break;
} else if (server.chests.canOpen(player, player.openedChest()) || player.isAdmin()) {
if (server.chests.isLocked(player.openedChest())) {
if (player.isAttemptingUnlock()) {
server.chests.unlock(player.openedChest());
player.setAttemptedAction(null);
player.addMessage("\u00a77 " + server.l.get("CHEST_UNLOCKED"));
typeString = "Open Chest";
} else {
typeString = server.chests.chestName(player.openedChest());
}
} else {
typeString = "Open Chest";
if (player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = player.nextChestName();
}
}
} else {
player.addMessage("\u00a7c " + server.l.get("CHEST_LOCKED"));
break;
}
}
write(packetId);
write(id);
write(invtype);
write8(typeString);
write(unknownByte);
break;
case 0x65:
write(packetId);
write(in.readByte());
break;
case 0x66: // Inventory Item Move
byte typeFrom = in.readByte();
short slotFrom = in.readShort();
byte typeTo = in.readByte();
short slotTo = in.readShort();
write(packetId);
write(typeFrom);
write(slotFrom);
write(typeTo);
write(slotTo);
write(in.readBoolean());
short moveItem = in.readShort();
write(moveItem);
if (moveItem != -1) {
write(in.readByte());
write(in.readShort());
}
break;
case 0x67: // Inventory Item Update
byte type67 = in.readByte();
short slot = in.readShort();
short setItem = in.readShort();
write(packetId);
write(type67);
write(slot);
write(setItem);
if (setItem != -1) {
write(in.readByte());
write(in.readShort());
}
break;
case 0x68: // Inventory
byte type = in.readByte();
write(packetId);
write(type);
short count = in.readShort();
write(count);
for (int c = 0; c < count; ++c) {
short item = in.readShort();
write(item);
if (item != -1) {
write(in.readByte());
write(in.readShort());
}
}
break;
case 0x69:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte) 0x83: // Map data
write(packetId);
write(in.readShort());
write(in.readShort());
byte length = in.readByte();
write(length);
copyNBytes(0xff & length);
break;
case (byte) 0xc8: // Statistic
write(packetId);
copyNBytes(5);
break;
case (byte) 0xe6: // ModLoaderMP by SDK
+ write(packetId);
write(in.readInt()); // mod
write(in.readInt()); // packet id
copyNBytes(write(in.readInt()) * 4); // ints
copyNBytes(write(in.readInt()) * 4); // floats
int sizeString = write(in.readInt()); // strings
for (int i = 0; i < sizeString; i++) {
copyNBytes(write(in.readInt()));
}
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
} else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName() + " (after 0x" + Integer.toHexString(lastPacket));
}
}
packetFinished();
lastPacket = packetId;
}
private String readUTF16() throws IOException {
short length = in.readShort();
byte[] bytes = new byte[length * 2 + 2];
for (short i = 0; i < length * 2; i++) {
bytes[i + 2] = in.readByte();
}
bytes[0] = (byte) 0xfffffffe;
bytes[1] = (byte) 0xffffffff;
return new String(bytes, "UTF-16");
}
private void lockChest(Coordinate coordinate) {
Chest adjacentChest = server.chests.adjacentChest(coordinate);
if (player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) {
if (adjacentChest != null && !adjacentChest.isOpen()) {
server.chests.giveLock(adjacentChest.owner(), coordinate, false, adjacentChest.name());
} else {
if (adjacentChest != null) {
adjacentChest.lock(player);
adjacentChest.rename(player.nextChestName());
}
server.chests.giveLock(player, coordinate, false, player.nextChestName());
}
player.setAttemptedAction(null);
player.addMessage("\u00a77This chest is now locked.");
} else if (!server.chests.isChest(coordinate)) {
server.chests.addOpenChest(coordinate);
}
}
private void copyPlayerLocation() throws IOException {
if (!isServerTunnel) {
motionCounter++;
}
if (!isServerTunnel && motionCounter % 8 == 0) {
double x = in.readDouble();
double y = in.readDouble();
double stance = in.readDouble();
double z = in.readDouble();
player.updateLocation(x, y, z, stance);
write(x);
write(y);
write(stance);
write(z);
copyNBytes(1);
} else {
copyNBytes(33);
}
}
private void copyUnknownBlob() throws IOException {
byte unknown = in.readByte();
write(unknown);
while (unknown != 0x7f) {
int type = (unknown & 0xE0) >> 5;
switch (type) {
case 0:
write(in.readByte());
break;
case 1:
write(in.readShort());
break;
case 2:
write(in.readInt());
break;
case 3:
write(in.readFloat());
break;
case 4:
write(readUTF16());
break;
case 5:
write(in.readShort());
write(in.readByte());
write(in.readShort());
break;
case 6:
write(in.readInt());
write(in.readInt());
write(in.readInt());
}
unknown = in.readByte();
write(unknown);
}
}
private byte write(byte b) throws IOException {
out.writeByte(b);
return b;
}
private short write(short s) throws IOException {
out.writeShort(s);
return s;
}
private int write(int i) throws IOException {
out.writeInt(i);
return i;
}
private long write(long l) throws IOException {
out.writeLong(l);
return l;
}
private float write(float f) throws IOException {
out.writeFloat(f);
return f;
}
private double write(double d) throws IOException {
out.writeDouble(d);
return d;
}
private String write(String s) throws IOException {
byte[] bytes = s.getBytes("UTF-16");
if (s.length() == 0) {
write((byte) 0x00);
write((byte) 0x00);
return s;
}
bytes[0] = (byte) ((s.length() >> 8) & 0xFF);
bytes[1] = (byte) ((s.length() & 0xFF));
for (byte b : bytes) {
write(b);
}
return s;
}
private String write8(String s) throws IOException {
out.writeUTF(s);
return s;
}
private boolean write(boolean b) throws IOException {
out.writeBoolean(b);
return b;
}
private void skipNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
}
private void copyNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
out.write(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
out.write(buffer, 0, bytes % buffer.length);
}
private void kick(String reason) throws IOException {
write((byte) 0xff);
write(reason);
packetFinished();
}
private String getLastColorCode(String message) {
String colorCode = "";
int lastIndex = message.lastIndexOf('\u00a7');
if (lastIndex != -1 && lastIndex + 1 < message.length()) {
colorCode = message.substring(lastIndex, lastIndex + 2);
}
return colorCode;
}
private void sendMessage(String message) throws IOException {
if (message.length() > MESSAGE_SIZE) {
int end = MESSAGE_SIZE - 1;
while (end > 0 && message.charAt(end) != ' ') {
end--;
}
if (end == 0) {
end = MESSAGE_SIZE;
} else {
end++;
}
if (message.charAt(end) == '\u00a7') {
end--;
}
String firstPart = message.substring(0, end);
sendMessagePacket(firstPart);
sendMessage(getLastColorCode(firstPart) + message.substring(end));
} else {
sendMessagePacket(message);
}
}
private void sendMessagePacket(String message) throws IOException {
if (message.length() > MESSAGE_SIZE) {
System.out.println("[SimpleServer] Invalid message size: " + message);
return;
}
write(0x03);
write(message);
packetFinished();
}
private void packetFinished() throws IOException {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.packetFinished();
outputDumper.packetFinished();
}
}
private void flushAll() throws IOException {
try {
((OutputStream) out).flush();
} finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.flush();
}
}
}
private final class Tunneler extends Thread {
@Override
public void run() {
try {
while (run) {
lastRead = System.currentTimeMillis();
try {
handlePacket();
if (isServerTunnel) {
while (player.hasMessages()) {
sendMessage(player.getMessage());
}
}
flushAll();
} catch (IOException e) {
if (run && !player.isRobot()) {
System.out.println("[SimpleServer] " + e);
System.out.println("[SimpleServer] " + streamType
+ " error handling traffic for " + player.getIPAddress());
}
break;
}
}
try {
if (player.isKicked()) {
kick(player.getKickMsg());
}
flushAll();
} catch (IOException e) {
}
} finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.cleanup();
outputDumper.cleanup();
}
}
}
}
}
| true | true | private void handlePacket() throws IOException {
Byte packetId = in.readByte();
int x;
byte y;
int z;
byte dimension;
Coordinate coordinate;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
break;
case 0x01: // Login Request/Response
write(packetId);
if (isServerTunnel) {
player.setEntityId(in.readInt());
write(player.getEntityId());
} else {
write(in.readInt());
}
write(readUTF16());
write(in.readLong());
dimension = in.readByte();
if (isServerTunnel) {
player.setDimension(Dimension.get(dimension));
}
write(dimension);
break;
case 0x02: // Handshake
String name = readUTF16();
if (isServerTunnel || player.setName(name)) {
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(name);
}
break;
case 0x03: // Chat Message
String message = readUTF16();
if (isServerTunnel && server.options.getBoolean("useMsgFormats")) {
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
Player friend = server.findPlayerExact(messageMatcher.group(1));
if (friend != null) {
String color = "f";
String title = "";
String format = server.options.get("msgFormat");
Group group = friend.getGroup();
if (group != null) {
color = group.getColor();
if (group.showTitle()) {
title = group.getName();
format = server.options.get("msgTitleFormat");
}
}
try {
message = String.format(format, friend.getName(), title, color)
+ messageMatcher.group(2);
} catch (IllegalFormatException e) {
System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!");
}
}
} else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.options.getBoolean("chatConsoleToOps")) {
break;
}
if (server.options.getBoolean("msgWrap")) {
sendMessage(message);
} else {
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
} else if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addMessage("\u00a7cYou are muted! You may not send messages to all players.");
break;
}
if (player.parseCommand(message)) {
break;
}
if (player.localChat() && !message.startsWith("/") && !message.startsWith("!")) {
player.execute(LocalSayCommand.class, message);
break;
}
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
break;
case 0x04: // Time Update
write(packetId);
long time = in.readLong();
server.setTime(time);
write(time);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readShort());
write(in.readShort());
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
break;
case 0x07: // Use Entity?
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
write(in.readBoolean());
break;
case 0x08: // Update Health
write(packetId);
copyNBytes(2);
break;
case 0x09: // Respawn
write(packetId);
dimension = in.readByte();
write(dimension);
player.setDimension(Dimension.get(dimension));
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if (server.options.getBoolean("showListOnConnect")) {
// display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
break;
case 0x0c: // Player Look
write(packetId);
copyNBytes(9);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyNBytes(8);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
coordinate = new Coordinate(x, y, z, player);
boolean[] perms = server.permissions.getPlayerBlockPermissions(player, coordinate, 0);
if (!perms[2] && status == 0) {
player.addMessage("\u00a7c " + server.l.get("USE_FORBIDDEN"));
break;
}
if (!perms[1] && status == 2) {
player.addMessage("\u00a7c " + server.l.get("DESTROY_FORBIDDEN"));
break;
}
boolean locked = server.chests.isLocked(coordinate);
if (!locked || player.isAdmin()) {
if (locked && status == BLOCK_DESTROYED_STATUS) {
server.chests.releaseLock(coordinate);
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if (status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
} else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
coordinate = new Coordinate(x, y, z, player);
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
}
boolean writePacket = true;
boolean drop = false;
boolean[] perms = server.permissions.getPlayerBlockPermissions(player, coordinate, dropItem);
if (isServerTunnel || server.chests.isChest(coordinate)) {
// continue
} else if ((dropItem != -1 && !perms[0]) || (dropItem == -1 && !perms[2])) {
if (dropItem == -1) {
player.addMessage("\u00a7c " + server.l.get("USE_FORBIDDEN"));
} else {
player.addMessage("\u00a7c " + server.l.get("PLACE_FORBIDDEN"));
}
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player);
Chest adjacentChest = server.chests.adjacentChest(targetBlock);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addMessage("\u00a7c " + server.l.get("ADJ_CHEST_LOCKED"));
writePacket = false;
drop = true;
} else {
player.placingChest(targetBlock);
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if (dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
player.openingChest(coordinate);
} else if (drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // ???
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
write(packetId);
write(in.readInt());
write(readUTF16());
copyNBytes(16);
break;
case 0x15: // Pickup spawn
write(packetId);
copyNBytes(24);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
int flag = in.readInt();
write(flag);
if (flag > 0) {
write(in.readShort());
write(in.readShort());
write(in.readShort());
}
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
copyUnknownBlob();
break;
case 0x19: // Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1b: // ???
write(packetId);
copyNBytes(18);
break;
case 0x1c: // Entity Velocity?
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
copyNBytes(4);
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x26: // Entity status?
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity?
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x32: // Pre-Chunk
write(packetId);
copyNBytes(9);
break;
case 0x33: // Map Chunk
write(packetId);
copyNBytes(13);
int chunkSize = in.readInt();
write(chunkSize);
copyNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
write(packetId);
copyNBytes(8);
short arraySize = in.readShort();
write(arraySize);
copyNBytes(arraySize * 4);
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte blockType = in.readByte();
byte metadata = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (blockType == 54 && player.placedChest(coordinate)) {
lockChest(coordinate);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // ???
write(packetId);
copyNBytes(12);
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
break;
case 0x3d: // Unknown
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
break;
case 0x46: // Invalid Bed
write(packetId);
copyNBytes(1);
break;
case 0x47: // Thunder
write(packetId);
copyNBytes(17);
break;
case 0x64: // Open window
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = in.readUTF();
byte unknownByte = in.readByte();
if (invtype == 0) {
if (!server.permissions.canOpenChests(player, player.openedChest())) {
player.addMessage(Color.RED, "You can't use chests here");
break;
} else if (server.chests.canOpen(player, player.openedChest()) || player.isAdmin()) {
if (server.chests.isLocked(player.openedChest())) {
if (player.isAttemptingUnlock()) {
server.chests.unlock(player.openedChest());
player.setAttemptedAction(null);
player.addMessage("\u00a77 " + server.l.get("CHEST_UNLOCKED"));
typeString = "Open Chest";
} else {
typeString = server.chests.chestName(player.openedChest());
}
} else {
typeString = "Open Chest";
if (player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = player.nextChestName();
}
}
} else {
player.addMessage("\u00a7c " + server.l.get("CHEST_LOCKED"));
break;
}
}
write(packetId);
write(id);
write(invtype);
write8(typeString);
write(unknownByte);
break;
case 0x65:
write(packetId);
write(in.readByte());
break;
case 0x66: // Inventory Item Move
byte typeFrom = in.readByte();
short slotFrom = in.readShort();
byte typeTo = in.readByte();
short slotTo = in.readShort();
write(packetId);
write(typeFrom);
write(slotFrom);
write(typeTo);
write(slotTo);
write(in.readBoolean());
short moveItem = in.readShort();
write(moveItem);
if (moveItem != -1) {
write(in.readByte());
write(in.readShort());
}
break;
case 0x67: // Inventory Item Update
byte type67 = in.readByte();
short slot = in.readShort();
short setItem = in.readShort();
write(packetId);
write(type67);
write(slot);
write(setItem);
if (setItem != -1) {
write(in.readByte());
write(in.readShort());
}
break;
case 0x68: // Inventory
byte type = in.readByte();
write(packetId);
write(type);
short count = in.readShort();
write(count);
for (int c = 0; c < count; ++c) {
short item = in.readShort();
write(item);
if (item != -1) {
write(in.readByte());
write(in.readShort());
}
}
break;
case 0x69:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte) 0x83: // Map data
write(packetId);
write(in.readShort());
write(in.readShort());
byte length = in.readByte();
write(length);
copyNBytes(0xff & length);
break;
case (byte) 0xc8: // Statistic
write(packetId);
copyNBytes(5);
break;
case (byte) 0xe6: // ModLoaderMP by SDK
write(in.readInt()); // mod
write(in.readInt()); // packet id
copyNBytes(write(in.readInt()) * 4); // ints
copyNBytes(write(in.readInt()) * 4); // floats
int sizeString = write(in.readInt()); // strings
for (int i = 0; i < sizeString; i++) {
copyNBytes(write(in.readInt()));
}
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
} else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName() + " (after 0x" + Integer.toHexString(lastPacket));
}
}
packetFinished();
lastPacket = packetId;
}
| private void handlePacket() throws IOException {
Byte packetId = in.readByte();
int x;
byte y;
int z;
byte dimension;
Coordinate coordinate;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
break;
case 0x01: // Login Request/Response
write(packetId);
if (isServerTunnel) {
player.setEntityId(in.readInt());
write(player.getEntityId());
} else {
write(in.readInt());
}
write(readUTF16());
write(in.readLong());
dimension = in.readByte();
if (isServerTunnel) {
player.setDimension(Dimension.get(dimension));
}
write(dimension);
break;
case 0x02: // Handshake
String name = readUTF16();
if (isServerTunnel || player.setName(name)) {
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(name);
}
break;
case 0x03: // Chat Message
String message = readUTF16();
if (isServerTunnel && server.options.getBoolean("useMsgFormats")) {
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
Player friend = server.findPlayerExact(messageMatcher.group(1));
if (friend != null) {
String color = "f";
String title = "";
String format = server.options.get("msgFormat");
Group group = friend.getGroup();
if (group != null) {
color = group.getColor();
if (group.showTitle()) {
title = group.getName();
format = server.options.get("msgTitleFormat");
}
}
try {
message = String.format(format, friend.getName(), title, color)
+ messageMatcher.group(2);
} catch (IllegalFormatException e) {
System.out.println("[SimpleServer] There is an error in your msgFormat/msgTitleFormat settings!");
}
}
} else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.options.getBoolean("chatConsoleToOps")) {
break;
}
if (server.options.getBoolean("msgWrap")) {
sendMessage(message);
} else {
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
} else if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addMessage("\u00a7cYou are muted! You may not send messages to all players.");
break;
}
if (player.parseCommand(message)) {
break;
}
if (player.localChat() && !message.startsWith("/") && !message.startsWith("!")) {
player.execute(LocalSayCommand.class, message);
break;
}
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
break;
case 0x04: // Time Update
write(packetId);
long time = in.readLong();
server.setTime(time);
write(time);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readShort());
write(in.readShort());
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
break;
case 0x07: // Use Entity?
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
write(in.readBoolean());
break;
case 0x08: // Update Health
write(packetId);
copyNBytes(2);
break;
case 0x09: // Respawn
write(packetId);
dimension = in.readByte();
write(dimension);
player.setDimension(Dimension.get(dimension));
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if (server.options.getBoolean("showListOnConnect")) {
// display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
break;
case 0x0c: // Player Look
write(packetId);
copyNBytes(9);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyNBytes(8);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
coordinate = new Coordinate(x, y, z, player);
boolean[] perms = server.permissions.getPlayerBlockPermissions(player, coordinate, 0);
if (!perms[2] && status == 0) {
player.addMessage("\u00a7c " + server.l.get("USE_FORBIDDEN"));
break;
}
if (!perms[1] && status == 2) {
player.addMessage("\u00a7c " + server.l.get("DESTROY_FORBIDDEN"));
break;
}
boolean locked = server.chests.isLocked(coordinate);
if (!locked || player.isAdmin()) {
if (locked && status == BLOCK_DESTROYED_STATUS) {
server.chests.releaseLock(coordinate);
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if (status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
} else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
coordinate = new Coordinate(x, y, z, player);
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
}
boolean writePacket = true;
boolean drop = false;
boolean[] perms = server.permissions.getPlayerBlockPermissions(player, coordinate, dropItem);
if (isServerTunnel || server.chests.isChest(coordinate)) {
// continue
} else if ((dropItem != -1 && !perms[0]) || (dropItem == -1 && !perms[2])) {
if (dropItem == -1) {
player.addMessage("\u00a7c " + server.l.get("USE_FORBIDDEN"));
} else {
player.addMessage("\u00a7c " + server.l.get("PLACE_FORBIDDEN"));
}
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player);
Chest adjacentChest = server.chests.adjacentChest(targetBlock);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addMessage("\u00a7c " + server.l.get("ADJ_CHEST_LOCKED"));
writePacket = false;
drop = true;
} else {
player.placingChest(targetBlock);
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if (dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
player.openingChest(coordinate);
} else if (drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // ???
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
write(packetId);
write(in.readInt());
write(readUTF16());
copyNBytes(16);
break;
case 0x15: // Pickup spawn
write(packetId);
copyNBytes(24);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
int flag = in.readInt();
write(flag);
if (flag > 0) {
write(in.readShort());
write(in.readShort());
write(in.readShort());
}
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
copyUnknownBlob();
break;
case 0x19: // Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1b: // ???
write(packetId);
copyNBytes(18);
break;
case 0x1c: // Entity Velocity?
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
copyNBytes(4);
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x26: // Entity status?
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity?
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x32: // Pre-Chunk
write(packetId);
copyNBytes(9);
break;
case 0x33: // Map Chunk
write(packetId);
copyNBytes(13);
int chunkSize = in.readInt();
write(chunkSize);
copyNBytes(chunkSize);
break;
case 0x34: // Multi Block Change
write(packetId);
copyNBytes(8);
short arraySize = in.readShort();
write(arraySize);
copyNBytes(arraySize * 4);
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte blockType = in.readByte();
byte metadata = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (blockType == 54 && player.placedChest(coordinate)) {
lockChest(coordinate);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // ???
write(packetId);
copyNBytes(12);
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
break;
case 0x3d: // Unknown
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
break;
case 0x46: // Invalid Bed
write(packetId);
copyNBytes(1);
break;
case 0x47: // Thunder
write(packetId);
copyNBytes(17);
break;
case 0x64: // Open window
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = in.readUTF();
byte unknownByte = in.readByte();
if (invtype == 0) {
if (!server.permissions.canOpenChests(player, player.openedChest())) {
player.addMessage(Color.RED, "You can't use chests here");
break;
} else if (server.chests.canOpen(player, player.openedChest()) || player.isAdmin()) {
if (server.chests.isLocked(player.openedChest())) {
if (player.isAttemptingUnlock()) {
server.chests.unlock(player.openedChest());
player.setAttemptedAction(null);
player.addMessage("\u00a77 " + server.l.get("CHEST_UNLOCKED"));
typeString = "Open Chest";
} else {
typeString = server.chests.chestName(player.openedChest());
}
} else {
typeString = "Open Chest";
if (player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = player.nextChestName();
}
}
} else {
player.addMessage("\u00a7c " + server.l.get("CHEST_LOCKED"));
break;
}
}
write(packetId);
write(id);
write(invtype);
write8(typeString);
write(unknownByte);
break;
case 0x65:
write(packetId);
write(in.readByte());
break;
case 0x66: // Inventory Item Move
byte typeFrom = in.readByte();
short slotFrom = in.readShort();
byte typeTo = in.readByte();
short slotTo = in.readShort();
write(packetId);
write(typeFrom);
write(slotFrom);
write(typeTo);
write(slotTo);
write(in.readBoolean());
short moveItem = in.readShort();
write(moveItem);
if (moveItem != -1) {
write(in.readByte());
write(in.readShort());
}
break;
case 0x67: // Inventory Item Update
byte type67 = in.readByte();
short slot = in.readShort();
short setItem = in.readShort();
write(packetId);
write(type67);
write(slot);
write(setItem);
if (setItem != -1) {
write(in.readByte());
write(in.readShort());
}
break;
case 0x68: // Inventory
byte type = in.readByte();
write(packetId);
write(type);
short count = in.readShort();
write(count);
for (int c = 0; c < count; ++c) {
short item = in.readShort();
write(item);
if (item != -1) {
write(in.readByte());
write(in.readShort());
}
}
break;
case 0x69:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a:
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte) 0x83: // Map data
write(packetId);
write(in.readShort());
write(in.readShort());
byte length = in.readByte();
write(length);
copyNBytes(0xff & length);
break;
case (byte) 0xc8: // Statistic
write(packetId);
copyNBytes(5);
break;
case (byte) 0xe6: // ModLoaderMP by SDK
write(packetId);
write(in.readInt()); // mod
write(in.readInt()); // packet id
copyNBytes(write(in.readInt()) * 4); // ints
copyNBytes(write(in.readInt()) * 4); // floats
int sizeString = write(in.readInt()); // strings
for (int i = 0; i < sizeString; i++) {
copyNBytes(write(in.readInt()));
}
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
} else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName() + " (after 0x" + Integer.toHexString(lastPacket));
}
}
packetFinished();
lastPacket = packetId;
}
|
diff --git a/MainApplication/app/models/ma/ResidentRequest.java b/MainApplication/app/models/ma/ResidentRequest.java
index e12010ae..1ad73172 100644
--- a/MainApplication/app/models/ma/ResidentRequest.java
+++ b/MainApplication/app/models/ma/ResidentRequest.java
@@ -1,255 +1,255 @@
package models.ma;
import controllers.security.Secure;
import models.main.Person;
import models.rh.Department;
import models.security.User;
import play.data.binding.As;
import play.db.jpa.Model;
import utils.Utils;
import javax.persistence.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
@Entity
public class ResidentRequest extends Model {
@ManyToOne
public Person resident;
@Temporal(TemporalType.DATE)
public Date requestStart;
@Temporal(TemporalType.DATE)
public Date requestEnd;
@Temporal(TemporalType.DATE)
public Date rdvDay;
@As("dd-MM-yyyy HH:mm")
@Temporal(TemporalType.TIME)
public Date rdvTime;
public int status;
public boolean enabled;
public boolean medicalReport;
@ManyToOne
public Person contactPerson;
public String applicant;
@ManyToOne
public Person personHome;
@Lob
public String comment;
public boolean room;
public boolean interview;
@ManyToOne
public User user;
public int modalityHome;
public int applicantHome;
public int prevailingSituation;
public int livingPlace;
public int lastLivingPlace;
public static List<ResidentRequest> getCurrents() {
return ResidentRequest.find("byEnabled", true).fetch();
}
public static void saveRequest(ResidentRequest request, Person resident,
String firstAction, Date creationDate, Date endDate) {
resident.name = resident.name.toLowerCase();
resident.firstname = resident.firstname.toLowerCase();
// Reservation d'une chambre ou annulation de celle ci
Hostel h = Hostel.find("byName", "Petits Riens").first();
if (firstAction != null && firstAction.equals("room")) {
if (!request.room) {
h.bookedUp++;
h.save();
}
request.room = true;
request.interview = false;
} else {
if (request.room) {
h.bookedUp--;
h.save();
}
request.interview = true;
request.room = false;
}
if (creationDate == null) {
request.requestStart = new Date();
}else{
request.requestStart = creationDate;
}
if (endDate == null) {
request.requestEnd = new Date();
}else{
request.requestEnd = endDate;
}
// la demande d'hebergement est acceptée
if (request.status == 2) {
if (resident.folderNumber == 0) {
resident.folderNumber = Person.getNewFolderNumber();
}
if (request.room) {
h.bookedUp--;
h.save();
}
Stay s = Stay.lastActif(resident.id);
if (s != null) {
s.actif = false;
s.save();
Stay.closeStay(s);
}
Department dep = Department.getX();
resident.department = dep;
resident.enabled = true;
resident.setToResident();
resident.save();
s = new Stay();
s.actif = true;
s.inDate = request.requestEnd;
s.resident = resident;
s.stayNumber = Stay.nbStays(resident) + 1;
s.department = dep;
s.save();
InSummary in = new InSummary();
in.actif = true;
in.resident = resident;
in.stay = s;
in.save();
Evaluation e = new Evaluation();
e.actif = true;
e.resident = resident;
e.stay = s;
GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.WEEK_OF_YEAR, 6);
e.evaluationDate = d.getTime();
e.save();
Activation act = new Activation();
act.activationID = s.id;
act.activationType = 5;
act.person = s.resident;
act.personType = s.resident.getPersonType();
act.startDate = new Date();
act.save();
Report report = Report.find("byReportDate", new GregorianCalendar()).first();
if (report == null) {
report = new Report();
report.reportDate = new GregorianCalendar();
report.save();
}
ReportCategory rc = ReportCategory.getInOut();
String link = Utils.residentFolderLink(resident);
String rq = "Entrant : " + link + " - " + resident.folderNumber;
ReportMessage rm = new ReportMessage();
rm.createAt = new Date();
rm.message = rq;
- rm.messageOrder = (int) count("report = ?",report);
+ rm.messageOrder = (int) ReportMessage.count("report = ?",report);
rm.report = report;
rm.reportCategory = rc;
rm.user = User.find("username = ?", Secure.Security.connected()).first();
rm.save();
resident.nbStays = Stay.nbStays(resident);
}
// demande refusé, annule la reservation de la chambre s'il y avait une
if (request.status > 2) {
if (request.room && request.enabled) {
h.bookedUp--;
h.save();
}
resident.personStatus.remove("001");
resident.personStatus.add("004");
}
User user = User.loadFromSession();
request.contactPerson = user.person;
if (ResidentRequest.count("resident = ?", resident) == 1) {
resident.withPig = true;
resident.driverLicence = -1;
}
resident.save();
request.resident = resident;
if (request.status != 1) {
request.enabled = false;
}
request.save();
}
public static void saveOldRequest(ResidentRequest request, Person resident,
String firstAction, Date creationDate, Date endDate){
resident.name = resident.name.toLowerCase();
resident.firstname = resident.firstname.toLowerCase();
if (firstAction != null && firstAction.equals("room")) {
request.room = true;
request.interview = false;
} else {
request.interview = true;
request.room = false;
}
if (creationDate != null) {
request.requestStart = creationDate;
}
if (endDate != null) {
request.requestEnd = endDate;
}else{
request.requestEnd = new Date();
}
resident.save();
request.resident = resident;
request.save();
}
public static long nbOldRequest() {
return ResidentRequest.count("enabled = false and status != 2");
}
public static List<ResidentRequest> getOldRequests(int page,int perPage) {
return ResidentRequest.find("enabled = false "
+ "and status != 2 "
+ "order by rdvDay desc,resident.name,resident.firstname ").fetch(page, perPage);
}
public static ResidentRequest lastDone(Person resident) {
return ResidentRequest.find("requestEnd is not null "
+ "and resident = ? "
+ "order by requestEnd desc", resident).first();
}
public static List<ResidentRequest> byPeriod(Calendar from,Calendar to) {
return ResidentRequest.find("requestStart >= ? " +
"and requestStart <= ?",from.getTime(),to.getTime()).fetch();
}
}
| true | true | public static void saveRequest(ResidentRequest request, Person resident,
String firstAction, Date creationDate, Date endDate) {
resident.name = resident.name.toLowerCase();
resident.firstname = resident.firstname.toLowerCase();
// Reservation d'une chambre ou annulation de celle ci
Hostel h = Hostel.find("byName", "Petits Riens").first();
if (firstAction != null && firstAction.equals("room")) {
if (!request.room) {
h.bookedUp++;
h.save();
}
request.room = true;
request.interview = false;
} else {
if (request.room) {
h.bookedUp--;
h.save();
}
request.interview = true;
request.room = false;
}
if (creationDate == null) {
request.requestStart = new Date();
}else{
request.requestStart = creationDate;
}
if (endDate == null) {
request.requestEnd = new Date();
}else{
request.requestEnd = endDate;
}
// la demande d'hebergement est acceptée
if (request.status == 2) {
if (resident.folderNumber == 0) {
resident.folderNumber = Person.getNewFolderNumber();
}
if (request.room) {
h.bookedUp--;
h.save();
}
Stay s = Stay.lastActif(resident.id);
if (s != null) {
s.actif = false;
s.save();
Stay.closeStay(s);
}
Department dep = Department.getX();
resident.department = dep;
resident.enabled = true;
resident.setToResident();
resident.save();
s = new Stay();
s.actif = true;
s.inDate = request.requestEnd;
s.resident = resident;
s.stayNumber = Stay.nbStays(resident) + 1;
s.department = dep;
s.save();
InSummary in = new InSummary();
in.actif = true;
in.resident = resident;
in.stay = s;
in.save();
Evaluation e = new Evaluation();
e.actif = true;
e.resident = resident;
e.stay = s;
GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.WEEK_OF_YEAR, 6);
e.evaluationDate = d.getTime();
e.save();
Activation act = new Activation();
act.activationID = s.id;
act.activationType = 5;
act.person = s.resident;
act.personType = s.resident.getPersonType();
act.startDate = new Date();
act.save();
Report report = Report.find("byReportDate", new GregorianCalendar()).first();
if (report == null) {
report = new Report();
report.reportDate = new GregorianCalendar();
report.save();
}
ReportCategory rc = ReportCategory.getInOut();
String link = Utils.residentFolderLink(resident);
String rq = "Entrant : " + link + " - " + resident.folderNumber;
ReportMessage rm = new ReportMessage();
rm.createAt = new Date();
rm.message = rq;
rm.messageOrder = (int) count("report = ?",report);
rm.report = report;
rm.reportCategory = rc;
rm.user = User.find("username = ?", Secure.Security.connected()).first();
rm.save();
resident.nbStays = Stay.nbStays(resident);
}
// demande refusé, annule la reservation de la chambre s'il y avait une
if (request.status > 2) {
if (request.room && request.enabled) {
h.bookedUp--;
h.save();
}
resident.personStatus.remove("001");
resident.personStatus.add("004");
}
User user = User.loadFromSession();
request.contactPerson = user.person;
if (ResidentRequest.count("resident = ?", resident) == 1) {
resident.withPig = true;
resident.driverLicence = -1;
}
resident.save();
request.resident = resident;
if (request.status != 1) {
request.enabled = false;
}
request.save();
}
| public static void saveRequest(ResidentRequest request, Person resident,
String firstAction, Date creationDate, Date endDate) {
resident.name = resident.name.toLowerCase();
resident.firstname = resident.firstname.toLowerCase();
// Reservation d'une chambre ou annulation de celle ci
Hostel h = Hostel.find("byName", "Petits Riens").first();
if (firstAction != null && firstAction.equals("room")) {
if (!request.room) {
h.bookedUp++;
h.save();
}
request.room = true;
request.interview = false;
} else {
if (request.room) {
h.bookedUp--;
h.save();
}
request.interview = true;
request.room = false;
}
if (creationDate == null) {
request.requestStart = new Date();
}else{
request.requestStart = creationDate;
}
if (endDate == null) {
request.requestEnd = new Date();
}else{
request.requestEnd = endDate;
}
// la demande d'hebergement est acceptée
if (request.status == 2) {
if (resident.folderNumber == 0) {
resident.folderNumber = Person.getNewFolderNumber();
}
if (request.room) {
h.bookedUp--;
h.save();
}
Stay s = Stay.lastActif(resident.id);
if (s != null) {
s.actif = false;
s.save();
Stay.closeStay(s);
}
Department dep = Department.getX();
resident.department = dep;
resident.enabled = true;
resident.setToResident();
resident.save();
s = new Stay();
s.actif = true;
s.inDate = request.requestEnd;
s.resident = resident;
s.stayNumber = Stay.nbStays(resident) + 1;
s.department = dep;
s.save();
InSummary in = new InSummary();
in.actif = true;
in.resident = resident;
in.stay = s;
in.save();
Evaluation e = new Evaluation();
e.actif = true;
e.resident = resident;
e.stay = s;
GregorianCalendar d = new GregorianCalendar();
d.add(Calendar.WEEK_OF_YEAR, 6);
e.evaluationDate = d.getTime();
e.save();
Activation act = new Activation();
act.activationID = s.id;
act.activationType = 5;
act.person = s.resident;
act.personType = s.resident.getPersonType();
act.startDate = new Date();
act.save();
Report report = Report.find("byReportDate", new GregorianCalendar()).first();
if (report == null) {
report = new Report();
report.reportDate = new GregorianCalendar();
report.save();
}
ReportCategory rc = ReportCategory.getInOut();
String link = Utils.residentFolderLink(resident);
String rq = "Entrant : " + link + " - " + resident.folderNumber;
ReportMessage rm = new ReportMessage();
rm.createAt = new Date();
rm.message = rq;
rm.messageOrder = (int) ReportMessage.count("report = ?",report);
rm.report = report;
rm.reportCategory = rc;
rm.user = User.find("username = ?", Secure.Security.connected()).first();
rm.save();
resident.nbStays = Stay.nbStays(resident);
}
// demande refusé, annule la reservation de la chambre s'il y avait une
if (request.status > 2) {
if (request.room && request.enabled) {
h.bookedUp--;
h.save();
}
resident.personStatus.remove("001");
resident.personStatus.add("004");
}
User user = User.loadFromSession();
request.contactPerson = user.person;
if (ResidentRequest.count("resident = ?", resident) == 1) {
resident.withPig = true;
resident.driverLicence = -1;
}
resident.save();
request.resident = resident;
if (request.status != 1) {
request.enabled = false;
}
request.save();
}
|
diff --git a/mail/src/main/java/org/bouncycastle/mail/smime/examples/SendSignedAndEncryptedMail.java b/mail/src/main/java/org/bouncycastle/mail/smime/examples/SendSignedAndEncryptedMail.java
index 8822bafc1..2d67ba6fd 100644
--- a/mail/src/main/java/org/bouncycastle/mail/smime/examples/SendSignedAndEncryptedMail.java
+++ b/mail/src/main/java/org/bouncycastle/mail/smime/examples/SendSignedAndEncryptedMail.java
@@ -1,192 +1,192 @@
package org.bouncycastle.mail.smime.examples;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.IssuerAndSerialNumber;
import org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute;
import org.bouncycastle.asn1.smime.SMIMECapability;
import org.bouncycastle.asn1.smime.SMIMECapabilityVector;
import org.bouncycastle.asn1.smime.SMIMEEncryptionKeyPreferenceAttribute;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSAlgorithm;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoGeneratorBuilder;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.cms.jcajce.JceKeyTransRecipientInfoGenerator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.mail.smime.SMIMEEnvelopedGenerator;
import org.bouncycastle.mail.smime.SMIMEException;
import org.bouncycastle.mail.smime.SMIMESignedGenerator;
import org.bouncycastle.util.Store;
import org.bouncycastle.util.Strings;
/**
* Example that sends a signed and encrypted mail message.
*/
public class SendSignedAndEncryptedMail
{
public static void main(String args[])
{
if (args.length != 5)
{
System.err
.println("usage: SendSignedAndEncryptedMail <pkcs12Keystore> <password> <keyalias> <smtp server> <email address>");
System.exit(0);
}
try
{
MailcapCommandMap mailcap = (MailcapCommandMap)CommandMap
.getDefaultCommandMap();
mailcap
.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
mailcap
.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
mailcap
.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
mailcap
.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
mailcap
.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
/* Add BC */
Security.addProvider(new BouncyCastleProvider());
/* Open the keystore */
KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
keystore.load(new FileInputStream(args[0]), args[1].toCharArray());
Certificate[] chain = keystore.getCertificateChain(args[2]);
/* Get the private key to sign the message with */
PrivateKey privateKey = (PrivateKey)keystore.getKey(args[2],
args[1].toCharArray());
if (privateKey == null)
{
throw new Exception("cannot find private key for alias: "
+ args[2]);
}
/* Create the message to sign and encrypt */
Properties props = System.getProperties();
props.put("mail.smtp.host", args[3]);
Session session = Session.getDefaultInstance(props, null);
MimeMessage body = new MimeMessage(session);
body.setFrom(new InternetAddress(args[4]));
body.setRecipient(Message.RecipientType.TO, new InternetAddress(
args[4]));
body.setSubject("example encrypted message");
body.setContent("example encrypted message", "text/plain");
body.saveChanges();
/* Create the SMIMESignedGenerator */
SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
capabilities.addCapability(SMIMECapability.dES_CBC);
ASN1EncodableVector attributes = new ASN1EncodableVector();
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
new IssuerAndSerialNumber(
new X500Name(((X509Certificate)chain[0])
.getIssuerDN().getName()),
((X509Certificate)chain[0]).getSerialNumber())));
attributes.add(new SMIMECapabilitiesAttribute(capabilities));
SMIMESignedGenerator signer = new SMIMESignedGenerator();
- signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(attributes)).build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withDSA", privateKey, (X509Certificate)chain[0]));
+ signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(attributes)).build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, (X509Certificate)chain[0]));
/* Add the list of certs to the generator */
List certList = new ArrayList();
certList.add(chain[0]);
Store certs = new JcaCertStore(certList);
signer.addCertificates(certs);
/* Sign the message */
MimeMultipart mm = signer.generate(body, "BC");
MimeMessage signedMessage = new MimeMessage(session);
/* Set all original MIME headers in the signed message */
Enumeration headers = body.getAllHeaderLines();
while (headers.hasMoreElements())
{
signedMessage.addHeaderLine((String)headers.nextElement());
}
/* Set the content of the signed message */
signedMessage.setContent(mm);
signedMessage.saveChanges();
/* Create the encrypter */
SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate)chain[0]).setProvider("BC"));
/* Encrypt the message */
MimeBodyPart encryptedPart = encrypter.generate(signedMessage,
new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).setProvider("BC").build());
/*
* Create a new MimeMessage that contains the encrypted and signed
* content
*/
ByteArrayOutputStream out = new ByteArrayOutputStream();
encryptedPart.writeTo(out);
MimeMessage encryptedMessage = new MimeMessage(session,
new ByteArrayInputStream(out.toByteArray()));
/* Set all original MIME headers in the encrypted message */
headers = body.getAllHeaderLines();
while (headers.hasMoreElements())
{
String headerLine = (String)headers.nextElement();
/*
* Make sure not to override any content-* headers from the
* original message
*/
if (!Strings.toLowerCase(headerLine).startsWith("content-"))
{
encryptedMessage.addHeaderLine(headerLine);
}
}
Transport.send(encryptedMessage);
}
catch (SMIMEException ex)
{
ex.getUnderlyingException().printStackTrace(System.err);
ex.printStackTrace(System.err);
}
catch (Exception ex)
{
ex.printStackTrace(System.err);
}
}
}
| true | true | public static void main(String args[])
{
if (args.length != 5)
{
System.err
.println("usage: SendSignedAndEncryptedMail <pkcs12Keystore> <password> <keyalias> <smtp server> <email address>");
System.exit(0);
}
try
{
MailcapCommandMap mailcap = (MailcapCommandMap)CommandMap
.getDefaultCommandMap();
mailcap
.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
mailcap
.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
mailcap
.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
mailcap
.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
mailcap
.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
/* Add BC */
Security.addProvider(new BouncyCastleProvider());
/* Open the keystore */
KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
keystore.load(new FileInputStream(args[0]), args[1].toCharArray());
Certificate[] chain = keystore.getCertificateChain(args[2]);
/* Get the private key to sign the message with */
PrivateKey privateKey = (PrivateKey)keystore.getKey(args[2],
args[1].toCharArray());
if (privateKey == null)
{
throw new Exception("cannot find private key for alias: "
+ args[2]);
}
/* Create the message to sign and encrypt */
Properties props = System.getProperties();
props.put("mail.smtp.host", args[3]);
Session session = Session.getDefaultInstance(props, null);
MimeMessage body = new MimeMessage(session);
body.setFrom(new InternetAddress(args[4]));
body.setRecipient(Message.RecipientType.TO, new InternetAddress(
args[4]));
body.setSubject("example encrypted message");
body.setContent("example encrypted message", "text/plain");
body.saveChanges();
/* Create the SMIMESignedGenerator */
SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
capabilities.addCapability(SMIMECapability.dES_CBC);
ASN1EncodableVector attributes = new ASN1EncodableVector();
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
new IssuerAndSerialNumber(
new X500Name(((X509Certificate)chain[0])
.getIssuerDN().getName()),
((X509Certificate)chain[0]).getSerialNumber())));
attributes.add(new SMIMECapabilitiesAttribute(capabilities));
SMIMESignedGenerator signer = new SMIMESignedGenerator();
signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(attributes)).build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withDSA", privateKey, (X509Certificate)chain[0]));
/* Add the list of certs to the generator */
List certList = new ArrayList();
certList.add(chain[0]);
Store certs = new JcaCertStore(certList);
signer.addCertificates(certs);
/* Sign the message */
MimeMultipart mm = signer.generate(body, "BC");
MimeMessage signedMessage = new MimeMessage(session);
/* Set all original MIME headers in the signed message */
Enumeration headers = body.getAllHeaderLines();
while (headers.hasMoreElements())
{
signedMessage.addHeaderLine((String)headers.nextElement());
}
/* Set the content of the signed message */
signedMessage.setContent(mm);
signedMessage.saveChanges();
/* Create the encrypter */
SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate)chain[0]).setProvider("BC"));
/* Encrypt the message */
MimeBodyPart encryptedPart = encrypter.generate(signedMessage,
new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).setProvider("BC").build());
/*
* Create a new MimeMessage that contains the encrypted and signed
* content
*/
ByteArrayOutputStream out = new ByteArrayOutputStream();
encryptedPart.writeTo(out);
MimeMessage encryptedMessage = new MimeMessage(session,
new ByteArrayInputStream(out.toByteArray()));
/* Set all original MIME headers in the encrypted message */
headers = body.getAllHeaderLines();
while (headers.hasMoreElements())
{
String headerLine = (String)headers.nextElement();
/*
* Make sure not to override any content-* headers from the
* original message
*/
if (!Strings.toLowerCase(headerLine).startsWith("content-"))
{
encryptedMessage.addHeaderLine(headerLine);
}
}
Transport.send(encryptedMessage);
}
catch (SMIMEException ex)
{
ex.getUnderlyingException().printStackTrace(System.err);
ex.printStackTrace(System.err);
}
catch (Exception ex)
{
ex.printStackTrace(System.err);
}
}
| public static void main(String args[])
{
if (args.length != 5)
{
System.err
.println("usage: SendSignedAndEncryptedMail <pkcs12Keystore> <password> <keyalias> <smtp server> <email address>");
System.exit(0);
}
try
{
MailcapCommandMap mailcap = (MailcapCommandMap)CommandMap
.getDefaultCommandMap();
mailcap
.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
mailcap
.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
mailcap
.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
mailcap
.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
mailcap
.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
/* Add BC */
Security.addProvider(new BouncyCastleProvider());
/* Open the keystore */
KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
keystore.load(new FileInputStream(args[0]), args[1].toCharArray());
Certificate[] chain = keystore.getCertificateChain(args[2]);
/* Get the private key to sign the message with */
PrivateKey privateKey = (PrivateKey)keystore.getKey(args[2],
args[1].toCharArray());
if (privateKey == null)
{
throw new Exception("cannot find private key for alias: "
+ args[2]);
}
/* Create the message to sign and encrypt */
Properties props = System.getProperties();
props.put("mail.smtp.host", args[3]);
Session session = Session.getDefaultInstance(props, null);
MimeMessage body = new MimeMessage(session);
body.setFrom(new InternetAddress(args[4]));
body.setRecipient(Message.RecipientType.TO, new InternetAddress(
args[4]));
body.setSubject("example encrypted message");
body.setContent("example encrypted message", "text/plain");
body.saveChanges();
/* Create the SMIMESignedGenerator */
SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
capabilities.addCapability(SMIMECapability.dES_CBC);
ASN1EncodableVector attributes = new ASN1EncodableVector();
attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
new IssuerAndSerialNumber(
new X500Name(((X509Certificate)chain[0])
.getIssuerDN().getName()),
((X509Certificate)chain[0]).getSerialNumber())));
attributes.add(new SMIMECapabilitiesAttribute(capabilities));
SMIMESignedGenerator signer = new SMIMESignedGenerator();
signer.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").setSignedAttributeGenerator(new AttributeTable(attributes)).build("DSA".equals(privateKey.getAlgorithm()) ? "SHA1withDSA" : "MD5withRSA", privateKey, (X509Certificate)chain[0]));
/* Add the list of certs to the generator */
List certList = new ArrayList();
certList.add(chain[0]);
Store certs = new JcaCertStore(certList);
signer.addCertificates(certs);
/* Sign the message */
MimeMultipart mm = signer.generate(body, "BC");
MimeMessage signedMessage = new MimeMessage(session);
/* Set all original MIME headers in the signed message */
Enumeration headers = body.getAllHeaderLines();
while (headers.hasMoreElements())
{
signedMessage.addHeaderLine((String)headers.nextElement());
}
/* Set the content of the signed message */
signedMessage.setContent(mm);
signedMessage.saveChanges();
/* Create the encrypter */
SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
encrypter.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate)chain[0]).setProvider("BC"));
/* Encrypt the message */
MimeBodyPart encryptedPart = encrypter.generate(signedMessage,
new JceCMSContentEncryptorBuilder(CMSAlgorithm.RC2_CBC).setProvider("BC").build());
/*
* Create a new MimeMessage that contains the encrypted and signed
* content
*/
ByteArrayOutputStream out = new ByteArrayOutputStream();
encryptedPart.writeTo(out);
MimeMessage encryptedMessage = new MimeMessage(session,
new ByteArrayInputStream(out.toByteArray()));
/* Set all original MIME headers in the encrypted message */
headers = body.getAllHeaderLines();
while (headers.hasMoreElements())
{
String headerLine = (String)headers.nextElement();
/*
* Make sure not to override any content-* headers from the
* original message
*/
if (!Strings.toLowerCase(headerLine).startsWith("content-"))
{
encryptedMessage.addHeaderLine(headerLine);
}
}
Transport.send(encryptedMessage);
}
catch (SMIMEException ex)
{
ex.getUnderlyingException().printStackTrace(System.err);
ex.printStackTrace(System.err);
}
catch (Exception ex)
{
ex.printStackTrace(System.err);
}
}
|
diff --git a/src/main/java/net/stuffrepos/tactics16/util/image/ColorUtil.java b/src/main/java/net/stuffrepos/tactics16/util/image/ColorUtil.java
index 97a8fed..895896e 100644
--- a/src/main/java/net/stuffrepos/tactics16/util/image/ColorUtil.java
+++ b/src/main/java/net/stuffrepos/tactics16/util/image/ColorUtil.java
@@ -1,154 +1,154 @@
package net.stuffrepos.tactics16.util.image;
import org.newdawn.slick.Color;
/**
*
* @author Eduardo H. Bogoni <[email protected]>
*/
public class ColorUtil {
/**
* Atalho para applyFactor(color, 0.5f).
* @param color
* @return
*/
public static Color dark(Color color) {
return applyFactor(color, 0.5f);
}
/**
* Atalho para applyFactor(color, 1.5f).
* @param color
* @return
*/
public static Color light(Color color) {
return applyFactor(color, 1.5f);
}
public static Color grayScale(Color color) {
int c = Math.max(color.getRed(), Math.max(color.getGreen(), color.getBlue()));
return new Color(c, c, c);
}
public static Color getBetweenColor(Color beginColor, Color endColor, float factor) {
return new Color(
limitColor((endColor.getRed() - beginColor.getRed()) * factor + beginColor.getRed()),
limitColor((endColor.getGreen() - beginColor.getGreen()) * factor + beginColor.getGreen()),
limitColor((endColor.getBlue() - beginColor.getBlue()) * factor + beginColor.getBlue()));
}
public static Color applyFactor(Color color, float factor) {
if (color.getAlpha() > 0) {
return new Color(
limitColor(color.getRed() * factor),
limitColor(color.getGreen() * factor),
limitColor(color.getBlue() * factor),
limitColor(color.getAlpha() * factor));
} else {
- return new Color(0);
+ return new Color(0, 0, 0, 0);
}
}
public static int getRgbBitmask(int rgba) {
Color color = new Color(rgba);
if (color.getAlpha() < 0x100 / 2) {
return 0x00FFFFFF & rgba;
} else {
return 0xFF000000 | rgba;
}
}
public static Color getColorBitmask(Color color) {
return byRgba(getRgbBitmask(rgba(color)));
}
private static int limitColor(float color) {
return limitColor((int) color);
}
private static int limitColor(int color) {
color = Math.abs(color);
if (color < 0) {
return color;
} else if (color > 0xFF) {
return 0xFF;
} else {
return color;
}
}
public static Color transparent(Color color, float alpha) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), (int) (0xFF * alpha));
}
public static Color getBetweenColor(int min, int max, float factor) {
return getBetweenColor(new Color(min), new Color(max), factor);
}
public static float getBetweenFactor(int playerColorMin, int playerColorMax, int originalRgb) {
return getBetweenFactor(
new Color(playerColorMin),
new Color(playerColorMax),
new Color(originalRgb));
}
public static float getBetweenFactor(Color min, Color max, Color color) {
//System.out.printf("Min: %s, Max: %s, Color: %s\n", min, max, color);
return getColorComponentBetweenFactor(
sumColorComponents(min),
sumColorComponents(max),
sumColorComponents(color));
}
private static int sumColorComponents(Color color) {
return color.getRed() + color.getGreen() + color.getBlue();
}
private static float getColorComponentBetweenFactor(int min, int max, int component) {
//System.out.printf("Min: %d, Max: %d, Component: %s\n", min, max, component);
return (float) (component - min) / (float) (max - min);
}
public static int compareColor(int rgb1, int rgb2) {
return compareColor(new Color(rgb1), new Color(rgb2));
}
public static int compareColor(Color color1, Color color2) {
return new Integer(sumColorComponents(color1)).compareTo(sumColorComponents(color2));
}
public static int rgba(Color color) {
return (color.getAlpha() << 24)
+ (color.getRed() << 16)
+ (color.getGreen() << 8)
+ color.getBlue();
}
public static int getAlpha(int rgba) {
return (rgba & 0xFF000000) >> 24;
}
public static int getRed(int rgba) {
return (rgba & 0x00FF0000) >> 16;
}
public static int getGreen(int rgba) {
return (rgba & 0x0000FF00) >> 8;
}
public static int getBlue(int rgba) {
return (rgba & 0x000000FF);
}
public static Color byRgba(int rgba) {
return new Color(getRed(rgba), getGreen(rgba), getBlue(rgba), getAlpha(rgba));
}
public static Color opaque(Color c) {
return new Color(c.getRed(), c.getGreen(), c.getBlue());
}
}
| true | true | public static Color applyFactor(Color color, float factor) {
if (color.getAlpha() > 0) {
return new Color(
limitColor(color.getRed() * factor),
limitColor(color.getGreen() * factor),
limitColor(color.getBlue() * factor),
limitColor(color.getAlpha() * factor));
} else {
return new Color(0);
}
}
| public static Color applyFactor(Color color, float factor) {
if (color.getAlpha() > 0) {
return new Color(
limitColor(color.getRed() * factor),
limitColor(color.getGreen() * factor),
limitColor(color.getBlue() * factor),
limitColor(color.getAlpha() * factor));
} else {
return new Color(0, 0, 0, 0);
}
}
|
diff --git a/com/nakkaya/gui/PreferencesWindow.java b/com/nakkaya/gui/PreferencesWindow.java
index e7e04d3..377cd17 100644
--- a/com/nakkaya/gui/PreferencesWindow.java
+++ b/com/nakkaya/gui/PreferencesWindow.java
@@ -1,440 +1,441 @@
package com.nakkaya.gui;
import java.awt.Container;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import org.jdesktop.layout.GroupLayout;
import org.jdesktop.layout.LayoutStyle;
/*
* Created by JFormDesigner on Wed May 20 19:11:55 EEST 2009
*/
import java.awt.Toolkit;
import java.net.URL;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.prefs.Preferences;
import com.nakkaya.lib.arp.*;
import com.nakkaya.lib.Defaults;
/**
* @author Nurullah Akkaya
*/
public class PreferencesWindow extends JFrame {
Preferences preferences = Preferences.userRoot();
public PreferencesWindow() {
URL imageURL =
this.getClass().getClassLoader().getResource( "icons/mocha25.png" );
Image image = Toolkit.getDefaultToolkit().getImage(imageURL);
setIconImage( image );
initComponents();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
// your stuf here
savePreferences();
}
});
}
public void savePreferences(){
int arpWatchInterval = 5;
try{
arpWatchInterval = Integer.parseInt( arpRefreshIntervalField.getText() );
}catch( Exception ex ) {
arpWatchInterval = 5;
}
preferences.putInt( "mocha.arp.interval", arpWatchInterval );
preferences.putBoolean( "mocha.notify.firewall",
notifyFirewallCheckBox.isSelected());
preferences.put( "mocha.arp.command", arpCommandField.getText() );
preferences.put( "mocha.firewall.log", logFileField.getText() );
int maxLogs = Defaults.mocha_log_size;
try{
maxLogs = Integer.parseInt( numOfLogMessagesToShow.getText() );
}catch( Exception ex ) {
maxLogs = 5;
}
preferences.putInt( "mocha.log.size", maxLogs );
preferences.putBoolean( "mocha.suppress.incomplete",
suppressIncompleteWarningCheckBox.isSelected() );
preferences.putBoolean( "mocha.suppress.newhost",
suppressNewHostMessagesCheckBox.isSelected() );
preferences.putBoolean( "mocha.notify.mail",
sendMailWarningCheckBox.isSelected() );
preferences.put( "mocha.smtp.server", serverNameField.getText() );
int serverPort = Defaults.mocha_smtp_port;
try{
serverPort = Integer.parseInt( serverPortField.getText() );
}catch( Exception ex ) {
serverPort = Defaults.mocha_smtp_port;
}
preferences.putInt( "mocha.smtp.port", serverPort );
preferences.put( "mocha.smtp.username", userNameField.getText() );
preferences.put( "mocha.smtp.password", passWordField.getText() );
preferences.put( "mocha.smtp.email", toFromField.getText() );
}
public void loadPreferences(){
Integer tmpValue = preferences.getInt( "mocha.arp.interval", Defaults.mocha_arp_interval );
arpRefreshIntervalField.setText( tmpValue.toString() );
boolean bool = preferences.getBoolean
("mocha.notify.firewall" , Defaults.mocha_notify_firewall);
notifyFirewallCheckBox.setSelected( bool );
String tmpString = preferences.get( "mocha.arp.command", Defaults.mocha_arp_command );
arpCommandField.setText( tmpString );
tmpString = preferences.get( "mocha.firewall.log", Defaults.mocha_firewall_log );
logFileField.setText( tmpString );
tmpValue = preferences.getInt
( "mocha.log.size", Defaults.mocha_log_size );
numOfLogMessagesToShow.setText( tmpValue.toString() );
bool = preferences.getBoolean
("mocha.suppress.incomplete" ,Defaults.mocha_suppress_incomplete);
suppressIncompleteWarningCheckBox.setSelected( bool );
bool = preferences.getBoolean
("mocha.suppress.newhost",Defaults.mocha_suppress_newhost);
suppressNewHostMessagesCheckBox.setSelected(bool);
bool = preferences.getBoolean
("mocha.notify.mail",Defaults.mocha_notify_mail);
sendMailWarningCheckBox.setSelected(bool);
tmpString = preferences.get( "mocha.smtp.server", Defaults.mocha_smtp_server );
serverNameField.setText( tmpString );
tmpValue = preferences.getInt
( "mocha.smtp.port", Defaults.mocha_smtp_port );
serverPortField.setText( tmpValue.toString() );
tmpString = preferences.get( "mocha.smtp.username", Defaults.mocha_smtp_username );
userNameField.setText( tmpString );
tmpString = preferences.get( "mocha.smtp.password", Defaults.mocha_smtp_password );
passWordField.setText( tmpString );
tmpString = preferences.get( "mocha.smtp.email", Defaults.mocha_smtp_email );
toFromField.setText( tmpString );
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panel8 = new JPanel();
label9 = new JLabel();
arpRefreshIntervalField = new JTextField();
label16 = new JLabel();
arpCommandField = new JTextField();
label10 = new JLabel();
label17 = new JLabel();
logFileField = new JTextField();
label12 = new JLabel();
numOfLogMessagesToShow = new JTextField();
label13 = new JLabel();
panel7 = new JPanel();
suppressIncompleteWarningCheckBox = new JCheckBox();
suppressNewHostMessagesCheckBox = new JCheckBox();
notifyFirewallCheckBox = new JCheckBox();
panel1 = new JPanel();
sendMailWarningCheckBox = new JCheckBox();
checkBox2 = new JCheckBox();
label1 = new JLabel();
serverNameField = new JTextField();
label3 = new JLabel();
userNameField = new JTextField();
label4 = new JLabel();
passWordField = new JPasswordField();
label2 = new JLabel();
serverPortField = new JTextField();
label5 = new JLabel();
toFromField = new JTextField();
//======== this ========
setTitle("Settings");
setResizable(false);
Container contentPane = getContentPane();
//======== panel8 ========
{
panel8.setBorder(new TitledBorder("General"));
//---- label9 ----
label9.setText("Arp Table Refresh Interval:");
//---- label16 ----
label16.setText("Arp Command:");
//---- label10 ----
label10.setText("seconds");
//---- label17 ----
label17.setText("Firewall Log:");
//---- label12 ----
label12.setText("Show Last");
//---- label13 ----
label13.setText("Log Messages");
GroupLayout panel8Layout = new GroupLayout(panel8);
panel8.setLayout(panel8Layout);
panel8Layout.setHorizontalGroup(
panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.addContainerGap()
.add(panel8Layout.createParallelGroup()
.add(label9)
.add(label16)
.add(label17)
.add(label12))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.add(numOfLogMessagesToShow, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(label13))
.add(panel8Layout.createSequentialGroup()
.add(arpRefreshIntervalField, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(label10))
.add(logFileField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
.add(arpCommandField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
panel8Layout.setVerticalGroup(
panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.add(5, 5, 5)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label9)
.add(arpRefreshIntervalField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label10))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label16)
.add(arpCommandField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label17)
.add(logFileField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label12)
.add(numOfLogMessagesToShow, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label13))
.addContainerGap(31, Short.MAX_VALUE))
);
}
//======== panel7 ========
{
panel7.setBorder(new TitledBorder("Notification"));
//---- suppressIncompleteWarningCheckBox ----
suppressIncompleteWarningCheckBox.setText("Suppress Incomplete Warnings");
//---- suppressNewHostMessagesCheckBox ----
suppressNewHostMessagesCheckBox.setText("Suppress New Host Messages");
//---- notifyFirewallCheckBox ----
notifyFirewallCheckBox.setText("Notify Firewall Activity");
GroupLayout panel7Layout = new GroupLayout(panel7);
panel7.setLayout(panel7Layout);
panel7Layout.setHorizontalGroup(
panel7Layout.createParallelGroup()
.add(panel7Layout.createSequentialGroup()
.addContainerGap()
.add(panel7Layout.createParallelGroup()
.add(notifyFirewallCheckBox)
.add(suppressIncompleteWarningCheckBox)
.add(suppressNewHostMessagesCheckBox))
.addContainerGap(160, Short.MAX_VALUE))
);
panel7Layout.setVerticalGroup(
panel7Layout.createParallelGroup()
.add(panel7Layout.createSequentialGroup()
.add(5, 5, 5)
.add(notifyFirewallCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(suppressIncompleteWarningCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(suppressNewHostMessagesCheckBox)
.addContainerGap())
);
}
//======== panel1 ========
{
panel1.setBorder(new TitledBorder("SMTP Settings"));
//---- sendMailWarningCheckBox ----
sendMailWarningCheckBox.setText("Send Warnings via E-Mail");
//---- checkBox2 ----
checkBox2.setText("Use SSL");
checkBox2.setSelected(true);
checkBox2.setEnabled(false);
//---- label1 ----
label1.setText("Server:");
//---- label3 ----
label3.setText("Username:");
//---- label4 ----
label4.setText("Password:");
//---- label2 ----
label2.setText("Port:");
//---- label5 ----
label5.setText("To/From:");
GroupLayout panel1Layout = new GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup()
.add(panel1Layout.createSequentialGroup()
.addContainerGap()
.add(panel1Layout.createParallelGroup()
.add(sendMailWarningCheckBox)
.add(checkBox2)
.add(panel1Layout.createSequentialGroup()
.add(panel1Layout.createParallelGroup()
.add(label3)
.add(label1))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel1Layout.createParallelGroup()
.add(panel1Layout.createParallelGroup(GroupLayout.TRAILING, false)
.add(GroupLayout.LEADING, passWordField)
.add(GroupLayout.LEADING, userNameField, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE))
.add(GroupLayout.TRAILING, panel1Layout.createSequentialGroup()
.add(panel1Layout.createParallelGroup(GroupLayout.TRAILING)
.add(GroupLayout.LEADING, toFromField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.add(serverNameField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE))
.addPreferredGap(LayoutStyle.RELATED)
.add(label2)
.addPreferredGap(LayoutStyle.RELATED)
.add(serverPortField, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10))))
.add(label4)
.add(label5))
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup()
.add(panel1Layout.createSequentialGroup()
.add(sendMailWarningCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(checkBox2)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label1)
.add(serverNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label2)
.add(serverPortField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label3)
.add(userNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label4)
.add(passWordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label5)
.add(toFromField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
- .addContainerGap(31, Short.MAX_VALUE))
+ .addContainerGap(26, Short.MAX_VALUE))
);
}
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.add(GroupLayout.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap()
.add(contentPaneLayout.createParallelGroup(GroupLayout.TRAILING)
.add(GroupLayout.LEADING, panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(GroupLayout.LEADING, panel8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(GroupLayout.LEADING, panel7, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.add(contentPaneLayout.createSequentialGroup()
.addContainerGap()
.add(panel8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(panel7, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
- .add(panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .add(panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap())
);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel panel8;
private JLabel label9;
private JTextField arpRefreshIntervalField;
private JLabel label16;
private JTextField arpCommandField;
private JLabel label10;
private JLabel label17;
private JTextField logFileField;
private JLabel label12;
private JTextField numOfLogMessagesToShow;
private JLabel label13;
private JPanel panel7;
private JCheckBox suppressIncompleteWarningCheckBox;
private JCheckBox suppressNewHostMessagesCheckBox;
private JCheckBox notifyFirewallCheckBox;
private JPanel panel1;
private JCheckBox sendMailWarningCheckBox;
private JCheckBox checkBox2;
private JLabel label1;
private JTextField serverNameField;
private JLabel label3;
private JTextField userNameField;
private JLabel label4;
private JPasswordField passWordField;
private JLabel label2;
private JTextField serverPortField;
private JLabel label5;
private JTextField toFromField;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
| false | true | private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panel8 = new JPanel();
label9 = new JLabel();
arpRefreshIntervalField = new JTextField();
label16 = new JLabel();
arpCommandField = new JTextField();
label10 = new JLabel();
label17 = new JLabel();
logFileField = new JTextField();
label12 = new JLabel();
numOfLogMessagesToShow = new JTextField();
label13 = new JLabel();
panel7 = new JPanel();
suppressIncompleteWarningCheckBox = new JCheckBox();
suppressNewHostMessagesCheckBox = new JCheckBox();
notifyFirewallCheckBox = new JCheckBox();
panel1 = new JPanel();
sendMailWarningCheckBox = new JCheckBox();
checkBox2 = new JCheckBox();
label1 = new JLabel();
serverNameField = new JTextField();
label3 = new JLabel();
userNameField = new JTextField();
label4 = new JLabel();
passWordField = new JPasswordField();
label2 = new JLabel();
serverPortField = new JTextField();
label5 = new JLabel();
toFromField = new JTextField();
//======== this ========
setTitle("Settings");
setResizable(false);
Container contentPane = getContentPane();
//======== panel8 ========
{
panel8.setBorder(new TitledBorder("General"));
//---- label9 ----
label9.setText("Arp Table Refresh Interval:");
//---- label16 ----
label16.setText("Arp Command:");
//---- label10 ----
label10.setText("seconds");
//---- label17 ----
label17.setText("Firewall Log:");
//---- label12 ----
label12.setText("Show Last");
//---- label13 ----
label13.setText("Log Messages");
GroupLayout panel8Layout = new GroupLayout(panel8);
panel8.setLayout(panel8Layout);
panel8Layout.setHorizontalGroup(
panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.addContainerGap()
.add(panel8Layout.createParallelGroup()
.add(label9)
.add(label16)
.add(label17)
.add(label12))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.add(numOfLogMessagesToShow, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(label13))
.add(panel8Layout.createSequentialGroup()
.add(arpRefreshIntervalField, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(label10))
.add(logFileField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
.add(arpCommandField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
panel8Layout.setVerticalGroup(
panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.add(5, 5, 5)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label9)
.add(arpRefreshIntervalField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label10))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label16)
.add(arpCommandField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label17)
.add(logFileField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label12)
.add(numOfLogMessagesToShow, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label13))
.addContainerGap(31, Short.MAX_VALUE))
);
}
//======== panel7 ========
{
panel7.setBorder(new TitledBorder("Notification"));
//---- suppressIncompleteWarningCheckBox ----
suppressIncompleteWarningCheckBox.setText("Suppress Incomplete Warnings");
//---- suppressNewHostMessagesCheckBox ----
suppressNewHostMessagesCheckBox.setText("Suppress New Host Messages");
//---- notifyFirewallCheckBox ----
notifyFirewallCheckBox.setText("Notify Firewall Activity");
GroupLayout panel7Layout = new GroupLayout(panel7);
panel7.setLayout(panel7Layout);
panel7Layout.setHorizontalGroup(
panel7Layout.createParallelGroup()
.add(panel7Layout.createSequentialGroup()
.addContainerGap()
.add(panel7Layout.createParallelGroup()
.add(notifyFirewallCheckBox)
.add(suppressIncompleteWarningCheckBox)
.add(suppressNewHostMessagesCheckBox))
.addContainerGap(160, Short.MAX_VALUE))
);
panel7Layout.setVerticalGroup(
panel7Layout.createParallelGroup()
.add(panel7Layout.createSequentialGroup()
.add(5, 5, 5)
.add(notifyFirewallCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(suppressIncompleteWarningCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(suppressNewHostMessagesCheckBox)
.addContainerGap())
);
}
//======== panel1 ========
{
panel1.setBorder(new TitledBorder("SMTP Settings"));
//---- sendMailWarningCheckBox ----
sendMailWarningCheckBox.setText("Send Warnings via E-Mail");
//---- checkBox2 ----
checkBox2.setText("Use SSL");
checkBox2.setSelected(true);
checkBox2.setEnabled(false);
//---- label1 ----
label1.setText("Server:");
//---- label3 ----
label3.setText("Username:");
//---- label4 ----
label4.setText("Password:");
//---- label2 ----
label2.setText("Port:");
//---- label5 ----
label5.setText("To/From:");
GroupLayout panel1Layout = new GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup()
.add(panel1Layout.createSequentialGroup()
.addContainerGap()
.add(panel1Layout.createParallelGroup()
.add(sendMailWarningCheckBox)
.add(checkBox2)
.add(panel1Layout.createSequentialGroup()
.add(panel1Layout.createParallelGroup()
.add(label3)
.add(label1))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel1Layout.createParallelGroup()
.add(panel1Layout.createParallelGroup(GroupLayout.TRAILING, false)
.add(GroupLayout.LEADING, passWordField)
.add(GroupLayout.LEADING, userNameField, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE))
.add(GroupLayout.TRAILING, panel1Layout.createSequentialGroup()
.add(panel1Layout.createParallelGroup(GroupLayout.TRAILING)
.add(GroupLayout.LEADING, toFromField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.add(serverNameField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE))
.addPreferredGap(LayoutStyle.RELATED)
.add(label2)
.addPreferredGap(LayoutStyle.RELATED)
.add(serverPortField, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10))))
.add(label4)
.add(label5))
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup()
.add(panel1Layout.createSequentialGroup()
.add(sendMailWarningCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(checkBox2)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label1)
.add(serverNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label2)
.add(serverPortField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label3)
.add(userNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label4)
.add(passWordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label5)
.add(toFromField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(31, Short.MAX_VALUE))
);
}
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.add(GroupLayout.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap()
.add(contentPaneLayout.createParallelGroup(GroupLayout.TRAILING)
.add(GroupLayout.LEADING, panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(GroupLayout.LEADING, panel8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(GroupLayout.LEADING, panel7, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.add(contentPaneLayout.createSequentialGroup()
.addContainerGap()
.add(panel8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(panel7, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
| private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panel8 = new JPanel();
label9 = new JLabel();
arpRefreshIntervalField = new JTextField();
label16 = new JLabel();
arpCommandField = new JTextField();
label10 = new JLabel();
label17 = new JLabel();
logFileField = new JTextField();
label12 = new JLabel();
numOfLogMessagesToShow = new JTextField();
label13 = new JLabel();
panel7 = new JPanel();
suppressIncompleteWarningCheckBox = new JCheckBox();
suppressNewHostMessagesCheckBox = new JCheckBox();
notifyFirewallCheckBox = new JCheckBox();
panel1 = new JPanel();
sendMailWarningCheckBox = new JCheckBox();
checkBox2 = new JCheckBox();
label1 = new JLabel();
serverNameField = new JTextField();
label3 = new JLabel();
userNameField = new JTextField();
label4 = new JLabel();
passWordField = new JPasswordField();
label2 = new JLabel();
serverPortField = new JTextField();
label5 = new JLabel();
toFromField = new JTextField();
//======== this ========
setTitle("Settings");
setResizable(false);
Container contentPane = getContentPane();
//======== panel8 ========
{
panel8.setBorder(new TitledBorder("General"));
//---- label9 ----
label9.setText("Arp Table Refresh Interval:");
//---- label16 ----
label16.setText("Arp Command:");
//---- label10 ----
label10.setText("seconds");
//---- label17 ----
label17.setText("Firewall Log:");
//---- label12 ----
label12.setText("Show Last");
//---- label13 ----
label13.setText("Log Messages");
GroupLayout panel8Layout = new GroupLayout(panel8);
panel8.setLayout(panel8Layout);
panel8Layout.setHorizontalGroup(
panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.addContainerGap()
.add(panel8Layout.createParallelGroup()
.add(label9)
.add(label16)
.add(label17)
.add(label12))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.add(numOfLogMessagesToShow, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(label13))
.add(panel8Layout.createSequentialGroup()
.add(arpRefreshIntervalField, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(label10))
.add(logFileField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE)
.add(arpCommandField, GroupLayout.PREFERRED_SIZE, 174, GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
panel8Layout.setVerticalGroup(
panel8Layout.createParallelGroup()
.add(panel8Layout.createSequentialGroup()
.add(5, 5, 5)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label9)
.add(arpRefreshIntervalField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label10))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label16)
.add(arpCommandField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label17)
.add(logFileField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel8Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label12)
.add(numOfLogMessagesToShow, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label13))
.addContainerGap(31, Short.MAX_VALUE))
);
}
//======== panel7 ========
{
panel7.setBorder(new TitledBorder("Notification"));
//---- suppressIncompleteWarningCheckBox ----
suppressIncompleteWarningCheckBox.setText("Suppress Incomplete Warnings");
//---- suppressNewHostMessagesCheckBox ----
suppressNewHostMessagesCheckBox.setText("Suppress New Host Messages");
//---- notifyFirewallCheckBox ----
notifyFirewallCheckBox.setText("Notify Firewall Activity");
GroupLayout panel7Layout = new GroupLayout(panel7);
panel7.setLayout(panel7Layout);
panel7Layout.setHorizontalGroup(
panel7Layout.createParallelGroup()
.add(panel7Layout.createSequentialGroup()
.addContainerGap()
.add(panel7Layout.createParallelGroup()
.add(notifyFirewallCheckBox)
.add(suppressIncompleteWarningCheckBox)
.add(suppressNewHostMessagesCheckBox))
.addContainerGap(160, Short.MAX_VALUE))
);
panel7Layout.setVerticalGroup(
panel7Layout.createParallelGroup()
.add(panel7Layout.createSequentialGroup()
.add(5, 5, 5)
.add(notifyFirewallCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(suppressIncompleteWarningCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(suppressNewHostMessagesCheckBox)
.addContainerGap())
);
}
//======== panel1 ========
{
panel1.setBorder(new TitledBorder("SMTP Settings"));
//---- sendMailWarningCheckBox ----
sendMailWarningCheckBox.setText("Send Warnings via E-Mail");
//---- checkBox2 ----
checkBox2.setText("Use SSL");
checkBox2.setSelected(true);
checkBox2.setEnabled(false);
//---- label1 ----
label1.setText("Server:");
//---- label3 ----
label3.setText("Username:");
//---- label4 ----
label4.setText("Password:");
//---- label2 ----
label2.setText("Port:");
//---- label5 ----
label5.setText("To/From:");
GroupLayout panel1Layout = new GroupLayout(panel1);
panel1.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup()
.add(panel1Layout.createSequentialGroup()
.addContainerGap()
.add(panel1Layout.createParallelGroup()
.add(sendMailWarningCheckBox)
.add(checkBox2)
.add(panel1Layout.createSequentialGroup()
.add(panel1Layout.createParallelGroup()
.add(label3)
.add(label1))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel1Layout.createParallelGroup()
.add(panel1Layout.createParallelGroup(GroupLayout.TRAILING, false)
.add(GroupLayout.LEADING, passWordField)
.add(GroupLayout.LEADING, userNameField, GroupLayout.PREFERRED_SIZE, 115, GroupLayout.PREFERRED_SIZE))
.add(GroupLayout.TRAILING, panel1Layout.createSequentialGroup()
.add(panel1Layout.createParallelGroup(GroupLayout.TRAILING)
.add(GroupLayout.LEADING, toFromField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.add(serverNameField, GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE))
.addPreferredGap(LayoutStyle.RELATED)
.add(label2)
.addPreferredGap(LayoutStyle.RELATED)
.add(serverPortField, GroupLayout.PREFERRED_SIZE, 33, GroupLayout.PREFERRED_SIZE)
.add(10, 10, 10))))
.add(label4)
.add(label5))
.addContainerGap())
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup()
.add(panel1Layout.createSequentialGroup()
.add(sendMailWarningCheckBox)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(checkBox2)
.addPreferredGap(LayoutStyle.UNRELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label1)
.add(serverNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(label2)
.add(serverPortField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.RELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label3)
.add(userNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.UNRELATED)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label4)
.add(passWordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.add(18, 18, 18)
.add(panel1Layout.createParallelGroup(GroupLayout.BASELINE)
.add(label5)
.add(toFromField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
}
GroupLayout contentPaneLayout = new GroupLayout(contentPane);
contentPane.setLayout(contentPaneLayout);
contentPaneLayout.setHorizontalGroup(
contentPaneLayout.createParallelGroup()
.add(GroupLayout.TRAILING, contentPaneLayout.createSequentialGroup()
.addContainerGap()
.add(contentPaneLayout.createParallelGroup(GroupLayout.TRAILING)
.add(GroupLayout.LEADING, panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(GroupLayout.LEADING, panel8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.add(GroupLayout.LEADING, panel7, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
contentPaneLayout.setVerticalGroup(
contentPaneLayout.createParallelGroup()
.add(contentPaneLayout.createSequentialGroup()
.addContainerGap()
.add(panel8, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.RELATED)
.add(panel7, GroupLayout.PREFERRED_SIZE, 123, GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(panel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
|
diff --git a/src/fr/frozentux/craftguard2/listener/PlayerListener.java b/src/fr/frozentux/craftguard2/listener/PlayerListener.java
index 79d7969..a6b56cc 100644
--- a/src/fr/frozentux/craftguard2/listener/PlayerListener.java
+++ b/src/fr/frozentux/craftguard2/listener/PlayerListener.java
@@ -1,62 +1,62 @@
package fr.frozentux.craftguard2.listener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.inventory.InventoryType.SlotType;
import org.bukkit.inventory.ItemStack;
import fr.frozentux.craftguard2.CraftGuardPlugin;
/**
* Listener for all players-related actions including login and inventory click
* @author FrozenTux
*
*/
public class PlayerListener implements Listener {
private CraftGuardPlugin plugin;
public PlayerListener(CraftGuardPlugin plugin){
this.plugin = plugin;
}
@EventHandler
public void onInventoryClick(InventoryClickEvent e){
SlotType slotType = e.getSlotType();
InventoryType invType = e.getInventory().getType();
int slot = e.getSlot();
Player player = (Player)e.getWhoClicked();
- if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.CRAFTING)) && slot == 0 && e.getInventory().getItem(0) != null){
+ if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.WORKBENCH)) && slot == 0 && e.getInventory().getItem(0) != null){
ItemStack object = e.getInventory().getItem(slot);
int id = object.getTypeId();
byte metadata = object.getData().getData();
e.setCancelled(!CraftPermissionChecker.checkCraft(player, id, metadata, plugin));
}
if(!plugin.getConfiguration().getBooleanKey("checkfurnaces"))return;
if(invType.equals(InventoryType.FURNACE) && (slotType == SlotType.CONTAINER || slotType == SlotType.FUEL || slotType == SlotType.QUICKBAR) && (e.isShiftClick() || e.getSlot() == 0 || e.getSlot() == 1)){
ItemStack object;
if(e.isShiftClick())object = e.getCurrentItem();
else{
if(e.getSlot() == 0 && e.getCursor() != null)object = e.getCursor();
else if(e.getSlot() == 1 && e.getInventory().getItem(0) != null)object = e.getInventory().getItem(0);
else return;
}
int id = object.getTypeId();
byte metadata = object.getData().getData();
CraftPermissionChecker.checkFurnace(player, id, metadata, plugin);
}
}
}
| true | true | public void onInventoryClick(InventoryClickEvent e){
SlotType slotType = e.getSlotType();
InventoryType invType = e.getInventory().getType();
int slot = e.getSlot();
Player player = (Player)e.getWhoClicked();
if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.CRAFTING)) && slot == 0 && e.getInventory().getItem(0) != null){
ItemStack object = e.getInventory().getItem(slot);
int id = object.getTypeId();
byte metadata = object.getData().getData();
e.setCancelled(!CraftPermissionChecker.checkCraft(player, id, metadata, plugin));
}
if(!plugin.getConfiguration().getBooleanKey("checkfurnaces"))return;
if(invType.equals(InventoryType.FURNACE) && (slotType == SlotType.CONTAINER || slotType == SlotType.FUEL || slotType == SlotType.QUICKBAR) && (e.isShiftClick() || e.getSlot() == 0 || e.getSlot() == 1)){
ItemStack object;
if(e.isShiftClick())object = e.getCurrentItem();
else{
if(e.getSlot() == 0 && e.getCursor() != null)object = e.getCursor();
else if(e.getSlot() == 1 && e.getInventory().getItem(0) != null)object = e.getInventory().getItem(0);
else return;
}
int id = object.getTypeId();
byte metadata = object.getData().getData();
CraftPermissionChecker.checkFurnace(player, id, metadata, plugin);
}
}
| public void onInventoryClick(InventoryClickEvent e){
SlotType slotType = e.getSlotType();
InventoryType invType = e.getInventory().getType();
int slot = e.getSlot();
Player player = (Player)e.getWhoClicked();
if(slotType == SlotType.RESULT && (invType.equals(InventoryType.CRAFTING) || invType.equals(InventoryType.WORKBENCH)) && slot == 0 && e.getInventory().getItem(0) != null){
ItemStack object = e.getInventory().getItem(slot);
int id = object.getTypeId();
byte metadata = object.getData().getData();
e.setCancelled(!CraftPermissionChecker.checkCraft(player, id, metadata, plugin));
}
if(!plugin.getConfiguration().getBooleanKey("checkfurnaces"))return;
if(invType.equals(InventoryType.FURNACE) && (slotType == SlotType.CONTAINER || slotType == SlotType.FUEL || slotType == SlotType.QUICKBAR) && (e.isShiftClick() || e.getSlot() == 0 || e.getSlot() == 1)){
ItemStack object;
if(e.isShiftClick())object = e.getCurrentItem();
else{
if(e.getSlot() == 0 && e.getCursor() != null)object = e.getCursor();
else if(e.getSlot() == 1 && e.getInventory().getItem(0) != null)object = e.getInventory().getItem(0);
else return;
}
int id = object.getTypeId();
byte metadata = object.getData().getData();
CraftPermissionChecker.checkFurnace(player, id, metadata, plugin);
}
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java b/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java
index ebfeff4e5..451caa427 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java
@@ -1,204 +1,207 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* 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 me.eccentric_nz.TARDIS.travel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.database.ResultSetAreas;
import me.eccentric_nz.TARDIS.database.ResultSetCurrentLocation;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
/**
* The control or console room of the Doctor's TARDIS is the space in which the
* operation of the craft is usually effected. It is dominated by a large,
* hexagonal console, typically in or near the middle of the room.
*
* @author eccentric_nz
*/
public class TARDISArea {
private TARDIS plugin;
public TARDISArea(TARDIS plugin) {
this.plugin = plugin;
}
/**
* Checks if a location is contained within any TARDIS area.
*
* @param l a location object to check.
* @return true or false depending on whether the location is within an
* existing TARDIS area
*/
public boolean areaCheckInExisting(Location l) {
boolean chk = true;
String w = l.getWorld().getName();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("world", w);
ResultSetAreas rsa = new ResultSetAreas(plugin, where, true);
if (rsa.resultSet()) {
ArrayList<HashMap<String, String>> data = rsa.getData();
for (HashMap<String, String> map : data) {
int minx = plugin.utils.parseNum(map.get("minx"));
int minz = plugin.utils.parseNum(map.get("minz"));
int maxx = plugin.utils.parseNum(map.get("maxx"));
int maxz = plugin.utils.parseNum(map.get("maxz"));
// is clicked block within a defined TARDIS area?
if (l.getX() <= maxx && l.getZ() <= maxz && l.getX() >= minx && l.getZ() >= minz) {
chk = false;
break;
}
}
}
return chk;
}
/**
* Checks if a location is contained within a specific TARDIS area.
*
* @param a the TARDIS area to check in.
* @param l a location object to check.
* @return true or false depending on whether the location is in the
* specified TARDIS area
*/
public boolean areaCheckInExile(String a, Location l) {
boolean chk = true;
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("area_name", a);
ResultSetAreas rsa = new ResultSetAreas(plugin, where, false);
if (rsa.resultSet()) {
String w = rsa.getWorld();
String lw = l.getWorld().getName();
int minx = rsa.getMinx();
int minz = rsa.getMinz();
int maxx = rsa.getMaxx();
int maxz = rsa.getMaxz();
// is clicked block within a defined TARDIS area?
if (w.equals(lw) && (l.getX() <= maxx && l.getZ() <= maxz && l.getX() >= minx && l.getZ() >= minz)) {
chk = false;
}
}
return chk;
}
/**
* Checks if a player has permission to travel to a TARDIS area.
*
* @param p a player to check.
* @param l a location object to check.
* @return true or false depending on whether the player has permission
*/
public boolean areaCheckLocPlayer(Player p, Location l) {
boolean chk = false;
String w = l.getWorld().getName();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("world", w);
ResultSetAreas rsa = new ResultSetAreas(plugin, where, true);
int i = 1;
if (rsa.resultSet()) {
ArrayList<HashMap<String, String>> data = rsa.getData();
for (HashMap<String, String> map : data) {
String n = map.get("area_name");
int minx = plugin.utils.parseNum(map.get("minx"));
int minz = plugin.utils.parseNum(map.get("minz"));
int maxx = plugin.utils.parseNum(map.get("maxx"));
int maxz = plugin.utils.parseNum(map.get("maxz"));
// is time travel destination within a defined TARDIS area?
if (l.getX() <= maxx && l.getZ() <= maxz && l.getX() >= minx && l.getZ() >= minz) {
// does the player have permmission to travel here
if (!p.hasPermission("tardis.area." + n) || !p.isPermissionSet("tardis.area." + n)) {
plugin.trackPerm.put(p.getName(), "tardis.area." + n);
chk = true;
break;
}
}
i++;
}
}
return chk;
}
/**
* Gets the next available parking spot in a specified TARDIS area.
*
* @param a the TARDIS area to look in.
* @return the next free Location in an area
*/
public Location getNextSpot(String a) {
Location location = null;
// find the next available slot in this area
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("area_name", a);
ResultSetAreas rsa = new ResultSetAreas(plugin, where, false);
if (rsa.resultSet()) {
int minx = rsa.getMinx();
int x = minx + 2;
int minz = rsa.getMinz();
int z = minz + 2;
int maxx = rsa.getMaxx();
int maxz = rsa.getMaxz();
String wStr = rsa.getWorld();
boolean chk = false;
// only loop for the size of the TARDIS area
+ outerloop:
for (int xx = x; xx <= maxx; xx += 5) {
for (int zz = z; zz <= maxz; zz += 5) {
HashMap<String, Object> wherec = new HashMap<String, Object>();
wherec.put("world", wStr);
- wherec.put("x", x);
- wherec.put("z", z);
+ wherec.put("x", xx);
+ wherec.put("z", zz);
ResultSetCurrentLocation rs = new ResultSetCurrentLocation(plugin, wherec);
if (!rs.resultSet()) {
chk = true;
- break;
+ break outerloop;
+ } else {
+ plugin.debug("Location " + wStr + ":" + xx + ":" + zz + " occupied");
}
}
}
if (chk == true) {
World w = plugin.getServer().getWorld(wStr);
int y = rsa.getY();
if (y == 0) {
y = w.getHighestBlockYAt(x, z);
}
location = w.getBlockAt(x, y, z).getLocation();
}
}
return location;
}
/**
* Gets the TARDIS area a player is exiled to.
*
* @param p a player to check.
* @return the area the player has been exiled to
*/
public String getExileArea(Player p) {
Set<PermissionAttachmentInfo> perms = p.getEffectivePermissions();
String area = "";
for (PermissionAttachmentInfo pai : perms) {
if (pai.getPermission().contains("tardis.area")) {
int len = pai.getPermission().length();
area = pai.getPermission().substring(12, len);
}
}
return area;
}
}
| false | true | public Location getNextSpot(String a) {
Location location = null;
// find the next available slot in this area
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("area_name", a);
ResultSetAreas rsa = new ResultSetAreas(plugin, where, false);
if (rsa.resultSet()) {
int minx = rsa.getMinx();
int x = minx + 2;
int minz = rsa.getMinz();
int z = minz + 2;
int maxx = rsa.getMaxx();
int maxz = rsa.getMaxz();
String wStr = rsa.getWorld();
boolean chk = false;
// only loop for the size of the TARDIS area
for (int xx = x; xx <= maxx; xx += 5) {
for (int zz = z; zz <= maxz; zz += 5) {
HashMap<String, Object> wherec = new HashMap<String, Object>();
wherec.put("world", wStr);
wherec.put("x", x);
wherec.put("z", z);
ResultSetCurrentLocation rs = new ResultSetCurrentLocation(plugin, wherec);
if (!rs.resultSet()) {
chk = true;
break;
}
}
}
if (chk == true) {
World w = plugin.getServer().getWorld(wStr);
int y = rsa.getY();
if (y == 0) {
y = w.getHighestBlockYAt(x, z);
}
location = w.getBlockAt(x, y, z).getLocation();
}
}
return location;
}
| public Location getNextSpot(String a) {
Location location = null;
// find the next available slot in this area
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("area_name", a);
ResultSetAreas rsa = new ResultSetAreas(plugin, where, false);
if (rsa.resultSet()) {
int minx = rsa.getMinx();
int x = minx + 2;
int minz = rsa.getMinz();
int z = minz + 2;
int maxx = rsa.getMaxx();
int maxz = rsa.getMaxz();
String wStr = rsa.getWorld();
boolean chk = false;
// only loop for the size of the TARDIS area
outerloop:
for (int xx = x; xx <= maxx; xx += 5) {
for (int zz = z; zz <= maxz; zz += 5) {
HashMap<String, Object> wherec = new HashMap<String, Object>();
wherec.put("world", wStr);
wherec.put("x", xx);
wherec.put("z", zz);
ResultSetCurrentLocation rs = new ResultSetCurrentLocation(plugin, wherec);
if (!rs.resultSet()) {
chk = true;
break outerloop;
} else {
plugin.debug("Location " + wStr + ":" + xx + ":" + zz + " occupied");
}
}
}
if (chk == true) {
World w = plugin.getServer().getWorld(wStr);
int y = rsa.getY();
if (y == 0) {
y = w.getHighestBlockYAt(x, z);
}
location = w.getBlockAt(x, y, z).getLocation();
}
}
return location;
}
|
diff --git a/src/tests/java/net/sf/picard/analysis/CollectAlignmentSummaryMetricsTest.java b/src/tests/java/net/sf/picard/analysis/CollectAlignmentSummaryMetricsTest.java
index 7dd9066..a378faf 100644
--- a/src/tests/java/net/sf/picard/analysis/CollectAlignmentSummaryMetricsTest.java
+++ b/src/tests/java/net/sf/picard/analysis/CollectAlignmentSummaryMetricsTest.java
@@ -1,244 +1,244 @@
/*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* 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 net.sf.picard.analysis;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;
import net.sf.picard.analysis.CollectAlignmentSummaryMetrics;
import org.testng.Assert;
import org.testng.annotations.Test;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.analysis.AlignmentSummaryMetrics;
/**
* Tests CollectAlignmentSummaryStatistics
*
* @author Doug Voet (dvoet at broadinstitute dot org)
*/
public class CollectAlignmentSummaryMetricsTest {
private static File TEST_DATA_DIR = new File("testdata/net/sf/picard/sam");
@Test
public void test() throws IOException {
File input = new File(TEST_DATA_DIR, "summary_alignment_stats_test.sam");
File reference = new File(TEST_DATA_DIR, "summary_alignment_stats_test.fasta");
File outfile = File.createTempFile("alignmentMetrics", ".txt");
outfile.deleteOnExit();
int result = new CollectAlignmentSummaryMetrics().instanceMain(new String[] {
"INPUT=" + input.getAbsolutePath(),
"OUTPUT=" + outfile.getAbsolutePath(),
"REFERENCE_SEQUENCE=" + reference.getAbsolutePath(),
});
Assert.assertEquals(result, 0);
MetricsFile<AlignmentSummaryMetrics, Comparable<?>> output = new MetricsFile<AlignmentSummaryMetrics, Comparable<?>>();
output.read(new FileReader(outfile));
for (AlignmentSummaryMetrics metrics : output.getMetrics()) {
Assert.assertEquals(metrics.MEAN_READ_LENGTH, 101.0);
switch (metrics.CATEGORY) {
case FIRST_OF_PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 9);
Assert.assertEquals(metrics.PF_READS, 7);
Assert.assertEquals(metrics.PF_NOISE_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_READS, 3);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_Q20_BASES, 59);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 19.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 303);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*58D/303D*/0.191419);
Assert.assertEquals(metrics.BAD_CYCLES, 19);
break;
case SECOND_OF_PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 9);
Assert.assertEquals(metrics.PF_READS, 9);
Assert.assertEquals(metrics.PF_NOISE_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_READS, 7);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_Q20_BASES, 239);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 707);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*19D/707D*/0.026874);
Assert.assertEquals(metrics.BAD_CYCLES, 3);
break;
case PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 18);
Assert.assertEquals(metrics.PF_READS, 16);
Assert.assertEquals(metrics.PF_NOISE_READS, 2);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_READS, 10);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_Q20_BASES, 298);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 1010);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*77D/1010D*/0.076238);
Assert.assertEquals(metrics.BAD_CYCLES, 22);
break;
case UNPAIRED:
default:
Assert.fail("Data does not contain this category: " + metrics.CATEGORY);
}
}
}
@Test
public void testBisulfite() throws IOException {
File input = new File(TEST_DATA_DIR, "summary_alignment_bisulfite_test.sam");
File reference = new File(TEST_DATA_DIR, "summary_alignment_stats_test.fasta");
File outfile = File.createTempFile("alignmentMetrics", ".txt");
outfile.deleteOnExit();
int result = new CollectAlignmentSummaryMetrics().instanceMain(new String[] {
"INPUT=" + input.getAbsolutePath(),
"OUTPUT=" + outfile.getAbsolutePath(),
"REFERENCE_SEQUENCE=" + reference.getAbsolutePath(),
"IS_BISULFITE_SEQUENCED=true"
});
Assert.assertEquals(result, 0);
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(4);
MetricsFile<AlignmentSummaryMetrics, Comparable<?>> output = new MetricsFile<AlignmentSummaryMetrics, Comparable<?>>();
output.read(new FileReader(outfile));
for (AlignmentSummaryMetrics metrics : output.getMetrics()) {
Assert.assertEquals(metrics.MEAN_READ_LENGTH, 101.0);
switch (metrics.CATEGORY) {
case FIRST_OF_PAIR:
// 19 no-calls, one potentially methylated base, one mismatch at a potentially methylated base
Assert.assertEquals(metrics.TOTAL_READS, 1);
Assert.assertEquals(metrics.PF_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 20.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, 20D/100D);
Assert.assertEquals(metrics.BAD_CYCLES, 20);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(20/(double)100));
break;
case SECOND_OF_PAIR:
// Three no-calls, two potentially methylated bases
Assert.assertEquals(metrics.TOTAL_READS, 1);
Assert.assertEquals(metrics.PF_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*3D/99D*/0.030303);
Assert.assertEquals(metrics.BAD_CYCLES, 3);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(3/(double)99));
break;
case PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 2);
Assert.assertEquals(metrics.PF_READS, 2);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 202);
- Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
+ Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 11.5);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 202);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*23D/199D*/0.115578);
Assert.assertEquals(metrics.BAD_CYCLES, 23);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(23/(double)199));
break;
case UNPAIRED:
default:
Assert.fail("Data does not contain this category: " + metrics.CATEGORY);
}
}
}
@Test
public void testNoReference() throws IOException {
File input = new File(TEST_DATA_DIR, "summary_alignment_stats_test.sam");
File outfile = File.createTempFile("alignmentMetrics", ".txt");
outfile.deleteOnExit();
int result = new CollectAlignmentSummaryMetrics().instanceMain(new String[] {
"INPUT=" + input.getAbsolutePath(),
"OUTPUT=" + outfile.getAbsolutePath(),
});
Assert.assertEquals(result, 0);
MetricsFile<AlignmentSummaryMetrics, Comparable<?>> output = new MetricsFile<AlignmentSummaryMetrics, Comparable<?>>();
output.read(new FileReader(outfile));
for (AlignmentSummaryMetrics metrics : output.getMetrics()) {
Assert.assertEquals(metrics.MEAN_READ_LENGTH, 101.0);
switch (metrics.CATEGORY) {
case FIRST_OF_PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 9);
Assert.assertEquals(metrics.PF_READS, 7);
Assert.assertEquals(metrics.PF_NOISE_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_READS, 0);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_Q20_BASES, 0);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 0.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 0);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, 0.0);
Assert.assertEquals(metrics.BAD_CYCLES, 19);
break;
case SECOND_OF_PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 9);
Assert.assertEquals(metrics.PF_READS, 9);
Assert.assertEquals(metrics.PF_NOISE_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_READS, 0);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_Q20_BASES, 0);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 0.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 0);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, 0.0);
Assert.assertEquals(metrics.BAD_CYCLES, 3);
break;
case PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 18);
Assert.assertEquals(metrics.PF_READS, 16);
Assert.assertEquals(metrics.PF_NOISE_READS, 2);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_READS, 0);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_Q20_BASES, 0);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 0.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 0);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, 0.0);
Assert.assertEquals(metrics.BAD_CYCLES, 22);
break;
case UNPAIRED:
default:
Assert.fail("Data does not contain this category: " + metrics.CATEGORY);
}
}
}
@Test
public void testZeroLengthReads() throws IOException {
File input = new File(TEST_DATA_DIR, "summary_alignment_stats_test2.sam");
File outfile = File.createTempFile("alignmentMetrics", ".txt");
outfile.deleteOnExit();
int result = new CollectAlignmentSummaryMetrics().instanceMain(new String[] {
"INPUT=" + input.getAbsolutePath(),
"OUTPUT=" + outfile.getAbsolutePath(),
});
Assert.assertEquals(result, 0);
MetricsFile<AlignmentSummaryMetrics, Comparable<?>> output = new MetricsFile<AlignmentSummaryMetrics, Comparable<?>>();
output.read(new FileReader(outfile));
for (AlignmentSummaryMetrics metrics : output.getMetrics()) {
// test that it doesn't blow up
}
}
}
| true | true | public void testBisulfite() throws IOException {
File input = new File(TEST_DATA_DIR, "summary_alignment_bisulfite_test.sam");
File reference = new File(TEST_DATA_DIR, "summary_alignment_stats_test.fasta");
File outfile = File.createTempFile("alignmentMetrics", ".txt");
outfile.deleteOnExit();
int result = new CollectAlignmentSummaryMetrics().instanceMain(new String[] {
"INPUT=" + input.getAbsolutePath(),
"OUTPUT=" + outfile.getAbsolutePath(),
"REFERENCE_SEQUENCE=" + reference.getAbsolutePath(),
"IS_BISULFITE_SEQUENCED=true"
});
Assert.assertEquals(result, 0);
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(4);
MetricsFile<AlignmentSummaryMetrics, Comparable<?>> output = new MetricsFile<AlignmentSummaryMetrics, Comparable<?>>();
output.read(new FileReader(outfile));
for (AlignmentSummaryMetrics metrics : output.getMetrics()) {
Assert.assertEquals(metrics.MEAN_READ_LENGTH, 101.0);
switch (metrics.CATEGORY) {
case FIRST_OF_PAIR:
// 19 no-calls, one potentially methylated base, one mismatch at a potentially methylated base
Assert.assertEquals(metrics.TOTAL_READS, 1);
Assert.assertEquals(metrics.PF_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 20.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, 20D/100D);
Assert.assertEquals(metrics.BAD_CYCLES, 20);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(20/(double)100));
break;
case SECOND_OF_PAIR:
// Three no-calls, two potentially methylated bases
Assert.assertEquals(metrics.TOTAL_READS, 1);
Assert.assertEquals(metrics.PF_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*3D/99D*/0.030303);
Assert.assertEquals(metrics.BAD_CYCLES, 3);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(3/(double)99));
break;
case PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 2);
Assert.assertEquals(metrics.PF_READS, 2);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 202);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 202);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*23D/199D*/0.115578);
Assert.assertEquals(metrics.BAD_CYCLES, 23);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(23/(double)199));
break;
case UNPAIRED:
default:
Assert.fail("Data does not contain this category: " + metrics.CATEGORY);
}
}
}
| public void testBisulfite() throws IOException {
File input = new File(TEST_DATA_DIR, "summary_alignment_bisulfite_test.sam");
File reference = new File(TEST_DATA_DIR, "summary_alignment_stats_test.fasta");
File outfile = File.createTempFile("alignmentMetrics", ".txt");
outfile.deleteOnExit();
int result = new CollectAlignmentSummaryMetrics().instanceMain(new String[] {
"INPUT=" + input.getAbsolutePath(),
"OUTPUT=" + outfile.getAbsolutePath(),
"REFERENCE_SEQUENCE=" + reference.getAbsolutePath(),
"IS_BISULFITE_SEQUENCED=true"
});
Assert.assertEquals(result, 0);
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(4);
MetricsFile<AlignmentSummaryMetrics, Comparable<?>> output = new MetricsFile<AlignmentSummaryMetrics, Comparable<?>>();
output.read(new FileReader(outfile));
for (AlignmentSummaryMetrics metrics : output.getMetrics()) {
Assert.assertEquals(metrics.MEAN_READ_LENGTH, 101.0);
switch (metrics.CATEGORY) {
case FIRST_OF_PAIR:
// 19 no-calls, one potentially methylated base, one mismatch at a potentially methylated base
Assert.assertEquals(metrics.TOTAL_READS, 1);
Assert.assertEquals(metrics.PF_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 20.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, 20D/100D);
Assert.assertEquals(metrics.BAD_CYCLES, 20);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(20/(double)100));
break;
case SECOND_OF_PAIR:
// Three no-calls, two potentially methylated bases
Assert.assertEquals(metrics.TOTAL_READS, 1);
Assert.assertEquals(metrics.PF_READS, 1);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 3.0);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 101);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*3D/99D*/0.030303);
Assert.assertEquals(metrics.BAD_CYCLES, 3);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(3/(double)99));
break;
case PAIR:
Assert.assertEquals(metrics.TOTAL_READS, 2);
Assert.assertEquals(metrics.PF_READS, 2);
Assert.assertEquals(metrics.PF_HQ_ALIGNED_BASES, 202);
Assert.assertEquals(metrics.PF_HQ_MEDIAN_MISMATCHES, 11.5);
Assert.assertEquals(metrics.PF_ALIGNED_BASES, 202);
Assert.assertEquals(metrics.PF_MISMATCH_RATE, /*23D/199D*/0.115578);
Assert.assertEquals(metrics.BAD_CYCLES, 23);
Assert.assertEquals(format.format(metrics.PF_HQ_ERROR_RATE), format.format(23/(double)199));
break;
case UNPAIRED:
default:
Assert.fail("Data does not contain this category: " + metrics.CATEGORY);
}
}
}
|
diff --git a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/util/OrccLogger.java b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/util/OrccLogger.java
index 83dc93915..1c18512db 100644
--- a/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/util/OrccLogger.java
+++ b/eclipse/plugins/net.sf.orcc.core/src/net/sf/orcc/util/OrccLogger.java
@@ -1,354 +1,356 @@
/*
* Copyright (c) 2012, IETR/INSA of Rennes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the IETR/INSA of Rennes nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package net.sf.orcc.util;
import java.text.DateFormat;
import java.util.Date;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Define the singleton managing Orcc loggers. When using this helper class,
* your debug, info, warning and errors messages will be displayed in the right
* eclipse console. If no Eclipse GUI plugin is loaded (i.e. executing a job in
* command line), all the messages will be sent to the system console.
*
* The log methods (in descending order) are the following:
*
* <ul>
* <li> {@link #severe(String)}
* <li> {@link #info(String)}
* <li> {@link #notice(String)}
* <li> {@link #warn(String)}
* <li> {@link #trace(String)}
* <li> {@link #debug(String)}
* </ul>
*
*
* @author Antoine Lorence
*
*/
public class OrccLogger {
/**
* Define how text must be printed to logger (Eclipse or System console)
*
* @author Antoine Lorence
*
*/
private static class DefaultOrccFormatter extends Formatter {
/*
* (non-Javadoc)
*
* @see java.util.logging.Formatter#format(java.util.logging.LogRecord)
*/
@Override
public String format(LogRecord record) {
String output = "";
if (!(record.getParameters() != null
&& record.getParameters().length > 0 && record
.getParameters()[0].equals("-raw"))) {
Date date = new Date(record.getMillis());
DateFormat df = DateFormat.getTimeInstance();
- output += df.format(date);
+ output += df.format(date) + " ";
// Default printing for warn & severe
- if (record.getLevel().intValue() > NOTICE.intValue()) {
- output += " " + record.getLevel();
- } else if (record.getLevel().intValue() == NOTICE.intValue()) {
- output += " NOTICE";
- } else if (record.getLevel().intValue() == DEBUG.intValue()) {
- output += " DEBUG";
+ if (record.getLevel() == SEVERE) {
+ output += "!! ERROR !!";
+ } else if (record.getLevel() == WARNING) {
+ output += "<<WARNING>>";
+ } else if (record.getLevel() == TRACE) {
+ output += "<<TRACE>>";
+ } else if (record.getLevel() == DEBUG) {
+ output += "<<DEBUG>>";
}
- output += " : ";
+ output += ": ";
}
output += record.getMessage();
return output;
}
}
/** Log Levels in descending order */
public final static Level SEVERE = Level.SEVERE;
public final static Level INFO = Level.INFO;
public final static Level NOTICE = Level.CONFIG;
public final static Level WARNING = Level.FINE;
public final static Level TRACE = Level.FINER;
public final static Level DEBUG = Level.FINEST;
public final static Level ALL = Level.ALL;
private static Logger logger;
/**
* Register specific log Handler to display messages sent threw OrccLogger.
* If this method is never called, the default Handler will be
* {@link java.util.logging.ConsoleHandler}
*
* @param handler
*/
public static void configureLoggerWithHandler(Handler handler) {
logger = null;
Logger newLog = Logger.getAnonymousLogger();
newLog.addHandler(handler);
newLog.setUseParentHandlers(false);
handler.setFormatter(new DefaultOrccFormatter());
logger = newLog;
setLevel(TRACE);
}
/**
* Display a debug message to current console.
*
* @param message
*/
public static void debug(String message) {
getLogger().log(DEBUG, message);
}
/**
* Display a debug message to current console, appended with a line
* separator character.
*
* @param message
*/
public static void debugln(String message) {
debug(message + System.getProperty("line.separator"));
}
/**
* Display a debug message on the current console, without any prepended
* string (time or level info).
*
* @param message
*/
public static void debugRaw(String message) {
LogRecord record = new LogRecord(DEBUG, message);
record.setParameters(new Object[] { "-raw" });
getLogger().log(record);
}
/**
* Return the current logger, or a newly created one if it doesn't exists.
* If it is created here, a default ConsoleHandler is used as Logger's
* Handler.
*
* @return
*/
private static Logger getLogger() {
if (logger == null) {
configureLoggerWithHandler(new ConsoleHandler());
}
return logger;
}
/**
* Display an information message on current console.
*
* @param message
*/
public static void info(String message) {
getLogger().log(INFO, message);
}
/**
* Display an information message on current console. The message will be
* appended with a line separator character.
*
* @param message
*/
public static void infoln(String message) {
info(message + System.getProperty("line.separator"));
}
/**
* Display an information message on current console, without any prepended
* string (time or level info).
*
* @param message
*/
public static void infoRaw(String message) {
LogRecord record = new LogRecord(INFO, message);
record.setParameters(new Object[] { "-raw" });
getLogger().log(record);
}
/**
* Display a notice message to current console.
*
* @param message
*/
public static void notice(String message) {
getLogger().log(NOTICE, message);
}
/**
* Display a notice message to current console, appended with a line
* separator character.
*
* @param message
*/
public static void noticeln(String message) {
notice(message + System.getProperty("line.separator"));
}
/**
* Display a notice message on the current console, without any prepended
* string (time or level info).
*
* @param message
*/
public static void noticeRaw(String message) {
LogRecord record = new LogRecord(NOTICE, message);
record.setParameters(new Object[] { "-raw" });
getLogger().log(record);
}
/**
* Set the minimum level displayed. By default, OrccLogger display messages
* from INFO level and highest. Call this method with DEBUG or ALL as
* argument to display debug messages.
*
* @param level
*/
public static void setLevel(Level level) {
getLogger().setLevel(level);
for (Handler handler : getLogger().getHandlers()) {
handler.setLevel(level);
}
}
/**
* Display an error line on the current console.
*
* @param message
*/
public static void severe(String message) {
getLogger().log(SEVERE, message);
}
/**
* Display an error line on the current console, appended with a line
* separator character.
*
* @param message
*/
public static void severeln(String message) {
severe(message + System.getProperty("line.separator"));
}
/**
* Display an error line on the current console, without any prepended
* string (time or level info).
*
* @param message
*/
public static void severeRaw(String message) {
LogRecord record = new LogRecord(SEVERE, message);
record.setParameters(new Object[] { "-raw" });
getLogger().log(record);
}
/**
* Display an information message on current console.
*
* @param message
*/
public static void trace(String message) {
getLogger().log(TRACE, message);
}
/**
* Display an information message on current console. The message will be
* appended with a line separator character.
*
* @param message
*/
public static void traceln(String message) {
trace(message + System.getProperty("line.separator"));
}
/**
* Display an information message on the current console, without any
* prepended string (time or level info).
*
* @param message
*/
public static void traceRaw(String message) {
LogRecord record = new LogRecord(TRACE, message);
record.setParameters(new Object[] { "-raw" });
getLogger().log(record);
}
/**
* Display a warning line on the current console.
*
* @param message
*/
public static void warn(String message) {
getLogger().log(WARNING, message);
}
/**
* Display a warning line on the current console, appended with a line
* separator character.
*
* @param message
*/
public static void warnln(String message) {
warn(message + System.getProperty("line.separator"));
}
/**
* Display a warning line on the current console, without any prepended
* string (time or level info).
*
* @param message
*/
public static void warnRaw(String message) {
LogRecord record = new LogRecord(WARNING, message);
record.setParameters(new Object[] { "-raw" });
getLogger().log(record);
}
/**
* Ensure class can't be instantiated
*/
private OrccLogger() {
}
}
| false | true | public String format(LogRecord record) {
String output = "";
if (!(record.getParameters() != null
&& record.getParameters().length > 0 && record
.getParameters()[0].equals("-raw"))) {
Date date = new Date(record.getMillis());
DateFormat df = DateFormat.getTimeInstance();
output += df.format(date);
// Default printing for warn & severe
if (record.getLevel().intValue() > NOTICE.intValue()) {
output += " " + record.getLevel();
} else if (record.getLevel().intValue() == NOTICE.intValue()) {
output += " NOTICE";
} else if (record.getLevel().intValue() == DEBUG.intValue()) {
output += " DEBUG";
}
output += " : ";
}
output += record.getMessage();
return output;
}
| public String format(LogRecord record) {
String output = "";
if (!(record.getParameters() != null
&& record.getParameters().length > 0 && record
.getParameters()[0].equals("-raw"))) {
Date date = new Date(record.getMillis());
DateFormat df = DateFormat.getTimeInstance();
output += df.format(date) + " ";
// Default printing for warn & severe
if (record.getLevel() == SEVERE) {
output += "!! ERROR !!";
} else if (record.getLevel() == WARNING) {
output += "<<WARNING>>";
} else if (record.getLevel() == TRACE) {
output += "<<TRACE>>";
} else if (record.getLevel() == DEBUG) {
output += "<<DEBUG>>";
}
output += ": ";
}
output += record.getMessage();
return output;
}
|
diff --git a/src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java b/src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
index 743811142..ed92a55e0 100644
--- a/src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
+++ b/src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
@@ -1,245 +1,245 @@
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.tools;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Node;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.selectors.FilenameSelector;
/**
* Ant task which inspects a file set for Java interfaces which extend the
* {@link org.apache.fop.events.EventProducer} interface. For all such interfaces an event model
* file and a translation file for the human-readable messages generated by the events is
* created and/or updated.
*/
public class EventProducerCollectorTask extends Task {
private List filesets = new java.util.ArrayList();
private File modelFile;
private File translationFile;
/** {@inheritDoc} */
public void execute() throws BuildException {
try {
EventProducerCollector collector = new EventProducerCollector();
processFileSets(collector);
File parentDir = getModelFile().getParentFile();
if (!parentDir.exists() && !parentDir.mkdirs()) {
throw new BuildException(
"Could not create target directory for event model file: " + parentDir);
}
collector.saveModelToXML(getModelFile());
log("Event model written to " + getModelFile());
if (getTranslationFile() != null) {
updateTranslationFile();
}
} catch (ClassNotFoundException e) {
throw new BuildException(e);
} catch (EventConventionException ece) {
throw new BuildException(ece);
} catch (IOException ioe) {
throw new BuildException(ioe);
}
}
private static final String MODEL2TRANSLATION = "model2translation.xsl";
private static final String MERGETRANSLATION = "merge-translation.xsl";
/**
* Updates the translation file with new entries for newly found event producer methods.
* @throws IOException if an I/O error occurs
*/
protected void updateTranslationFile() throws IOException {
try {
boolean resultExists = getTranslationFile().exists();
SAXTransformerFactory tFactory
= (SAXTransformerFactory)SAXTransformerFactory.newInstance();
//Generate fresh generated translation file as template
- Source src = new StreamSource(getModelFile());
+ Source src = new StreamSource(getModelFile().toURI().toURL().toExternalForm());
StreamSource xslt1 = new StreamSource(
getClass().getResourceAsStream(MODEL2TRANSLATION));
if (xslt1.getInputStream() == null) {
throw new FileNotFoundException(MODEL2TRANSLATION + " not found");
}
DOMResult domres = new DOMResult();
Transformer transformer = tFactory.newTransformer(xslt1);
transformer.transform(src, domres);
final Node generated = domres.getNode();
Node sourceDocument;
if (resultExists) {
//Load existing translation file into memory (because we overwrite it later)
- src = new StreamSource(getTranslationFile());
+ src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm());
domres = new DOMResult();
transformer = tFactory.newTransformer();
transformer.transform(src, domres);
sourceDocument = domres.getNode();
} else {
//Simply use generated as source document
sourceDocument = generated;
}
//Generate translation file (with potentially new translations)
src = new DOMSource(sourceDocument);
- Result res = new StreamResult(getTranslationFile());
+ Result res = new StreamResult(getTranslationFile().toURI().toURL().toExternalForm());
StreamSource xslt2 = new StreamSource(
getClass().getResourceAsStream(MERGETRANSLATION));
if (xslt2.getInputStream() == null) {
throw new FileNotFoundException(MERGETRANSLATION + " not found");
}
transformer = tFactory.newTransformer(xslt2);
transformer.setURIResolver(new URIResolver() {
public Source resolve(String href, String base) throws TransformerException {
if ("my:dom".equals(href)) {
return new DOMSource(generated);
}
return null;
}
});
if (resultExists) {
transformer.setParameter("generated-url", "my:dom");
}
transformer.transform(src, res);
if (resultExists) {
log("Translation file updated: " + getTranslationFile());
} else {
log("Translation file generated: " + getTranslationFile());
}
} catch (TransformerException te) {
throw new IOException(te.getMessage());
}
}
/**
* Processes the file sets defined for the task.
* @param collector the collector to use for collecting the event producers
* @throws IOException if an I/O error occurs
* @throws EventConventionException if the EventProducer conventions are violated
* @throws ClassNotFoundException if a required class cannot be found
*/
protected void processFileSets(EventProducerCollector collector)
throws IOException, EventConventionException, ClassNotFoundException {
Iterator iter = filesets.iterator();
while (iter.hasNext()) {
FileSet fs = (FileSet)iter.next();
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
String[] srcFiles = ds.getIncludedFiles();
File directory = fs.getDir(getProject());
for (int i = 0, c = srcFiles.length; i < c; i++) {
String filename = srcFiles[i];
File src = new File(directory, filename);
collector.scanFile(src);
}
}
}
/**
* Adds a file set.
* @param set the file set
*/
public void addFileset(FileSet set) {
filesets.add(set);
}
/**
* Sets the model file to be written.
* @param f the model file
*/
public void setModelFile(File f) {
this.modelFile = f;
}
/**
* Returns the model file to be written.
* @return the model file
*/
public File getModelFile() {
return this.modelFile;
}
/**
* Sets the translation file for the event producer methods.
* @param f the translation file
*/
public void setTranslationFile(File f) {
this.translationFile = f;
}
/**
* Returns the translation file for the event producer methods.
* @return the translation file
*/
public File getTranslationFile() {
return this.translationFile;
}
/**
* Command-line interface for testing purposes.
* @param args the command-line arguments
*/
public static void main(String[] args) {
try {
Project project = new Project();
EventProducerCollectorTask generator = new EventProducerCollectorTask();
generator.setProject(project);
project.setName("Test");
FileSet fileset = new FileSet();
fileset.setDir(new File("test/java"));
FilenameSelector selector = new FilenameSelector();
selector.setName("**/*.java");
fileset.add(selector);
generator.addFileset(fileset);
File targetDir = new File("build/codegen1");
targetDir.mkdirs();
generator.setModelFile(new File("D:/out.xml"));
generator.setTranslationFile(new File("D:/out1.xml"));
generator.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| false | true | protected void updateTranslationFile() throws IOException {
try {
boolean resultExists = getTranslationFile().exists();
SAXTransformerFactory tFactory
= (SAXTransformerFactory)SAXTransformerFactory.newInstance();
//Generate fresh generated translation file as template
Source src = new StreamSource(getModelFile());
StreamSource xslt1 = new StreamSource(
getClass().getResourceAsStream(MODEL2TRANSLATION));
if (xslt1.getInputStream() == null) {
throw new FileNotFoundException(MODEL2TRANSLATION + " not found");
}
DOMResult domres = new DOMResult();
Transformer transformer = tFactory.newTransformer(xslt1);
transformer.transform(src, domres);
final Node generated = domres.getNode();
Node sourceDocument;
if (resultExists) {
//Load existing translation file into memory (because we overwrite it later)
src = new StreamSource(getTranslationFile());
domres = new DOMResult();
transformer = tFactory.newTransformer();
transformer.transform(src, domres);
sourceDocument = domres.getNode();
} else {
//Simply use generated as source document
sourceDocument = generated;
}
//Generate translation file (with potentially new translations)
src = new DOMSource(sourceDocument);
Result res = new StreamResult(getTranslationFile());
StreamSource xslt2 = new StreamSource(
getClass().getResourceAsStream(MERGETRANSLATION));
if (xslt2.getInputStream() == null) {
throw new FileNotFoundException(MERGETRANSLATION + " not found");
}
transformer = tFactory.newTransformer(xslt2);
transformer.setURIResolver(new URIResolver() {
public Source resolve(String href, String base) throws TransformerException {
if ("my:dom".equals(href)) {
return new DOMSource(generated);
}
return null;
}
});
if (resultExists) {
transformer.setParameter("generated-url", "my:dom");
}
transformer.transform(src, res);
if (resultExists) {
log("Translation file updated: " + getTranslationFile());
} else {
log("Translation file generated: " + getTranslationFile());
}
} catch (TransformerException te) {
throw new IOException(te.getMessage());
}
}
| protected void updateTranslationFile() throws IOException {
try {
boolean resultExists = getTranslationFile().exists();
SAXTransformerFactory tFactory
= (SAXTransformerFactory)SAXTransformerFactory.newInstance();
//Generate fresh generated translation file as template
Source src = new StreamSource(getModelFile().toURI().toURL().toExternalForm());
StreamSource xslt1 = new StreamSource(
getClass().getResourceAsStream(MODEL2TRANSLATION));
if (xslt1.getInputStream() == null) {
throw new FileNotFoundException(MODEL2TRANSLATION + " not found");
}
DOMResult domres = new DOMResult();
Transformer transformer = tFactory.newTransformer(xslt1);
transformer.transform(src, domres);
final Node generated = domres.getNode();
Node sourceDocument;
if (resultExists) {
//Load existing translation file into memory (because we overwrite it later)
src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm());
domres = new DOMResult();
transformer = tFactory.newTransformer();
transformer.transform(src, domres);
sourceDocument = domres.getNode();
} else {
//Simply use generated as source document
sourceDocument = generated;
}
//Generate translation file (with potentially new translations)
src = new DOMSource(sourceDocument);
Result res = new StreamResult(getTranslationFile().toURI().toURL().toExternalForm());
StreamSource xslt2 = new StreamSource(
getClass().getResourceAsStream(MERGETRANSLATION));
if (xslt2.getInputStream() == null) {
throw new FileNotFoundException(MERGETRANSLATION + " not found");
}
transformer = tFactory.newTransformer(xslt2);
transformer.setURIResolver(new URIResolver() {
public Source resolve(String href, String base) throws TransformerException {
if ("my:dom".equals(href)) {
return new DOMSource(generated);
}
return null;
}
});
if (resultExists) {
transformer.setParameter("generated-url", "my:dom");
}
transformer.transform(src, res);
if (resultExists) {
log("Translation file updated: " + getTranslationFile());
} else {
log("Translation file generated: " + getTranslationFile());
}
} catch (TransformerException te) {
throw new IOException(te.getMessage());
}
}
|
diff --git a/src/main/java/signature/DAG.java b/src/main/java/signature/DAG.java
index 53fe5cd..d8ac834 100644
--- a/src/main/java/signature/DAG.java
+++ b/src/main/java/signature/DAG.java
@@ -1,666 +1,666 @@
package signature;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A directed acyclic graph that is the core data structure of a signature. It
* is the DAG that is canonized by sorting its layers of nodes.
*
* @author maclean
*
*/
public class DAG implements Iterable<List<DAG.Node>> {
/**
* The direction up and down the DAG. UP is from leaves to root.
*
*/
public enum Direction { UP, DOWN };
/**
* A node of the directed acyclic graph
*
*/
public class Node implements Comparable<Node>, VisitableDAG {
/**
* The index of the vertex in the graph. Note that for signatures that
* cover only part of the graph (with a height less than the diameter)
* this index may have to be mapped to the original index
*/
public int vertexIndex;
/**
* The parent nodes in the DAG
*/
public List<Node> parents;
/**
* The child nodes in the DAG
*/
public List<Node> children;
/**
* What layer this node is in
*/
public int layer;
/**
* The vertex label
*/
public String vertexLabel;
/**
* Labels for the edges between this node and the parent nodes
*/
// public Map<Integer, String> edgeLabels; TODO
public Map<Integer, Integer> edgeColors;
/**
* The final computed invariant, used for sorting children when printing
*/
public int invariant;
/**
* Make a Node that refers to a vertex, in a layer, and with a label.
*
* @param vertexIndex the graph vertex index
* @param layer the layer of this Node
* @param label the label of the vertex
*/
public Node(int vertexIndex, int layer, String label) {
this.vertexIndex = vertexIndex;
this.layer = layer;
this.parents = new ArrayList<Node>();
this.children = new ArrayList<Node>();
this.vertexLabel = label;
// this.edgeLabels = new HashMap<Integer, String>();
this.edgeColors = new HashMap<Integer, Integer>();
}
public void addParent(Node node) {
this.parents.add(node);
}
public void addChild(Node node) {
this.children.add(node);
}
// public void addEdgeLabel(int partnerIndex, String edgeLabel) {
// this.edgeLabels.put(partnerIndex, edgeLabel);
// } XXX
public void addEdgeColor(int partnerIndex, int edgeColor) {
this.edgeColors.put(partnerIndex, edgeColor);
}
public void accept(DAGVisitor visitor) {
visitor.visit(this);
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuffer parentString = new StringBuffer();
parentString.append('[');
for (Node parent : this.parents) {
parentString.append(parent.vertexIndex).append(',');
}
if (parentString.length() > 1) {
parentString.setCharAt(parentString.length() - 1, ']');
} else {
parentString.append(']');
}
StringBuffer childString = new StringBuffer();
childString.append('[');
for (Node child : this.children) {
childString.append(child.vertexIndex).append(',');
}
if (childString.length() > 1) {
childString.setCharAt(childString.length() - 1, ']');
} else {
childString.append(']');
}
return vertexIndex + " "
+ vertexLabel + " (" + parentString + ", " + childString + ")";
}
public int compareTo(Node o) {
int c = this.vertexLabel.compareTo(o.vertexLabel);
if (c == 0) {
if (this.invariant < o.invariant) {
return - 1;
} else if (this.invariant > o.invariant) {
return 1;
} else {
return 0;
}
} else {
return c;
}
}
}
/**
* An arc of the directed acyclic graph
*
*/
public class Arc {
public int a;
public int b;
public Arc(int a, int b) {
this.a = a;
this.b = b;
}
public boolean equals(Object other) {
if (other instanceof Arc) {
Arc o = (Arc) other;
return (this.a == o.a && this.b == o.b)
|| (this.a == o.b && this.b == o.a);
} else {
return false;
}
}
}
/**
* The layers of the DAG
*/
private List<List<Node>> layers;
/**
* The counts of parents for vertices
*/
private int[] parentCounts;
/**
* The counts of children for vertices
*/
private int[] childCounts;
/**
* Vertex labels (if any) - for a chemical graph, these are likely to be
* element symbols (C, N, O, etc)
*/
private String[] vertexLabels;
private Invariants invariants;
/**
* Convenience reference to the nodes of the DAG
*/
private List<DAG.Node> nodes;
/**
* A convenience record of the number of vertices
*/
private int vertexCount;
private int graphVertexCount;
/**
* Create a DAG from a graph, starting at the root vertex.
*
* @param rootVertexIndex the vertex to start from
* @param graphVertexCount the number of vertices in the original graph
* @param rootLabel the string label for the root vertex
*/
public DAG(int rootVertexIndex, int graphVertexCount, String rootLabel) {
this.layers = new ArrayList<List<Node>>();
this.nodes = new ArrayList<Node>();
List<Node> rootLayer = new ArrayList<Node>();
Node rootNode = new Node(rootVertexIndex, 0, rootLabel);
rootLayer.add(rootNode);
this.layers.add(rootLayer);
this.nodes.add(rootNode);
this.vertexLabels = new String[graphVertexCount];
this.vertexLabels[rootVertexIndex] = rootLabel;
this.vertexCount = 1;
this.parentCounts = new int[graphVertexCount];
this.childCounts = new int[graphVertexCount];
this.graphVertexCount = graphVertexCount;
}
/**
* Reset a DAG starting at another root vertex.
*
* @param rootVertexIndex the vertex to start from
* @param rootLabel the string label for the root vertex
*/
public void resetDAG(int rootVertexIndex, String rootLabel) {
this.layers.clear();
this.nodes.clear();
List<Node> rootLayer = new ArrayList<Node>();
Node rootNode = new Node(rootVertexIndex, 0, rootLabel);
rootLayer.add(rootNode);
this.layers.add(rootLayer);
this.nodes.add(rootNode);
this.parentCounts = new int[graphVertexCount];
this.childCounts = new int[graphVertexCount];
}
public Iterator<List<Node>> iterator() {
return layers.iterator();
}
public List<DAG.Node> getRootLayer() {
return this.layers.get(0);
}
public DAG.Node getRoot() {
return this.layers.get(0).get(0);
}
public Invariants copyInvariants() {
return (Invariants) this.invariants.clone();
}
/**
* Initialize the invariants, assuming that the vertex count for the
* signature is the same as the graph vertex count.
*/
public void initialize() {
this.invariants = new Invariants(vertexCount, nodes.size());
this.initializeVertexInvariants();
}
/**
* Initialize the invariants, given that the signature covers <code>
* signatureVertexCount</code> number of vertices.
*
* @param signatureVertexCount
* the number of vertices covered by the signature
*/
public void initialize(int signatureVertexCount) {
vertexCount = signatureVertexCount;
this.invariants = new Invariants(vertexCount, nodes.size());
this.initializeVertexInvariants();
}
public void setVertexLabel(int vertexIndex, String label) {
this.vertexLabels[vertexIndex] = label;
}
public void setColor(int vertexIndex, int color) {
this.invariants.setColor(vertexIndex, color);
}
public int occurences(int vertexIndex) {
int count = 0;
for (Node node : nodes) {
if (node.vertexIndex == vertexIndex) {
count++;
}
}
return count;
}
public void setInvariants(Invariants invariants) {
// this.invariants = invariants;
this.invariants.colors = invariants.colors.clone();
this.invariants.nodeInvariants = invariants.nodeInvariants.clone();
this.invariants.vertexInvariants = invariants.vertexInvariants.clone();
}
/**
* Create and return a DAG.Node, while setting some internal references to
* the same data. Does not add the node to a layer.
*
* @param vertexIndex the index of the vertex in the original graph
* @param layer the index of the layer
* @param vertexLabel the label of the vertex
* @return the new node
*/
public DAG.Node makeNode(
int vertexIndex, int layer, String vertexLabel) {
DAG.Node node = new DAG.Node(vertexIndex, layer, vertexLabel);
this.vertexLabels[vertexIndex] = vertexLabel;
this.nodes.add(node);
return node;
}
/**
* Create and return a DAG.Node, while setting some internal references to
* the same data. Note: also adds the node to a layer, creating it if
* necessary.
*
* @param vertexIndex the index of the vertex in the original graph
* @param layer the index of the layer
* @param vertexLabel the label of the vertex
* @return the new node
*/
public DAG.Node makeNodeInLayer(
int vertexIndex, int layer, String vertexLabel) {
DAG.Node node = this.makeNode(vertexIndex, layer, vertexLabel);
if (layers.size() <= layer) {
this.layers.add(new ArrayList<DAG.Node>());
}
this.layers.get(layer).add(node);
return node;
}
public void addRelation(DAG.Node childNode, DAG.Node parentNode) {
childNode.parents.add(parentNode);
parentCounts[childNode.vertexIndex]++;
childCounts[parentNode.vertexIndex]++;
parentNode.children.add(childNode);
}
public int[] getParentsInFinalString() {
int[] counts = new int[vertexCount];
getParentsInFinalString(
counts, getRoot(), null, new ArrayList<DAG.Arc>());
return counts;
}
private void getParentsInFinalString(int[] counts, DAG.Node node,
DAG.Node parent, List<DAG.Arc> arcs) {
if (parent != null) {
counts[node.vertexIndex]++;
}
Collections.sort(node.children);
for (DAG.Node child : node.children) {
DAG.Arc arc = new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
arcs.add(arc);
getParentsInFinalString(counts, child, node, arcs);
}
}
}
/**
* Count the occurrences of each vertex index in the final signature string.
* Since duplicate DAG edges are removed, this count will not be the same as
* the simple count of occurrences in the DAG before printing.
*
* @return
*/
public int[] getOccurrences() {
int[] occurences = new int[vertexCount];
getOccurences(occurences, getRoot(), null, new ArrayList<DAG.Arc>());
return occurences;
}
private void getOccurences(int[] occurences, DAG.Node node,
DAG.Node parent, List<DAG.Arc> arcs) {
occurences[node.vertexIndex]++;
Collections.sort(node.children);
for (DAG.Node child : node.children) {
DAG.Arc arc = new Arc(node.vertexIndex, child.vertexIndex);
if (arcs.contains(arc)) {
continue;
} else {
arcs.add(arc);
getOccurences(occurences, child, node, arcs);
}
}
}
public List<InvariantIntIntPair> getInvariantPairs(int[] parents) {
List<InvariantIntIntPair> pairs = new ArrayList<InvariantIntIntPair>();
for (int i = 0; i < this.vertexCount; i++) {
if (invariants.getColor(i) == -1
&& parents[i] >= 2) {
pairs.add(
new InvariantIntIntPair(
invariants.getVertexInvariant(i), i));
}
}
Collections.sort(pairs);
return pairs;
}
public int colorFor(int vertexIndex) {
return this.invariants.getColor(vertexIndex);
}
public void accept(DAGVisitor visitor) {
this.getRoot().accept(visitor);
}
public void addLayer(List<Node> layer) {
this.layers.add(layer);
}
public void initializeVertexInvariants() {
List<InvariantIntStringPair> pairs =
new ArrayList<InvariantIntStringPair>();
for (int i = 0; i < vertexCount; i++) {
String l = vertexLabels[i];
int p = parentCounts[i];
pairs.add(new InvariantIntStringPair(l, p, i));
}
Collections.sort(pairs);
if (pairs.size() == 0) return;
int order = 1;
this.invariants.setVertexInvariant(pairs.get(0).originalIndex, order);
for (int i = 1; i < pairs.size(); i++) {
InvariantIntStringPair a = pairs.get(i - 1);
InvariantIntStringPair b = pairs.get(i);
if (!a.equals(b)) {
order++;
}
this.invariants.setVertexInvariant(b.originalIndex, order);
}
// System.out.println(this);
// System.out.println(Arrays.toString(childCounts));
}
public List<Integer> createOrbit(int[] parents) {
// get the orbits
Map<Integer, List<Integer>> orbits =
new HashMap<Integer, List<Integer>>();
for (int j = 0; j < vertexCount; j++) {
if (parents[j] >= 2) {
int invariant = invariants.getVertexInvariant(j);
List<Integer> orbit;
if (orbits.containsKey(invariant)) {
orbit = orbits.get(invariant);
} else {
orbit = new ArrayList<Integer>();
orbits.put(invariant, orbit);
}
orbit.add(j);
}
}
// System.out.println("Orbits " + orbits);
// find the largest orbit
if (orbits.isEmpty()) {
return new ArrayList<Integer>();
} else {
List<Integer> maxOrbit = null;
List<Integer> invariants = new ArrayList<Integer>(orbits.keySet());
Collections.sort(invariants);
for (int invariant : invariants) {
List<Integer> orbit = orbits.get(invariant);
if (maxOrbit == null || orbit.size() > maxOrbit.size()) {
maxOrbit = orbit;
}
}
return maxOrbit;
}
}
public void computeVertexInvariants() {
Map<Integer, int[]> layerInvariants = new HashMap<Integer, int[]>();
for (int i = 0; i < this.nodes.size(); i++) {
DAG.Node node = this.nodes.get(i);
int j = node.vertexIndex;
int[] layerInvariantsJ;
if (layerInvariants.containsKey(j)) {
layerInvariantsJ = layerInvariants.get(j);
} else {
layerInvariantsJ = new int[this.layers.size()];
layerInvariants.put(j, layerInvariantsJ);
}
layerInvariantsJ[node.layer] = invariants.getNodeInvariant(i);
}
List<InvariantArray> invariantLists = new ArrayList<InvariantArray>();
for (int i : layerInvariants.keySet()) {
InvariantArray invArr = new InvariantArray(layerInvariants.get(i), i);
invariantLists.add(invArr);
}
Collections.sort(invariantLists);
int order = 1;
int first = invariantLists.get(0).originalIndex;
invariants.setVertexInvariant(first, 1);
for (int i = 1; i < invariantLists.size(); i++) {
InvariantArray a = invariantLists.get(i - 1);
InvariantArray b = invariantLists.get(i);
if (!a.equals(b)) {
order++;
}
invariants.setVertexInvariant(b.originalIndex, order);
}
}
public void updateVertexInvariants() {
int[] oldInvariants = new int[vertexCount];
boolean invariantSame = true;
while (invariantSame) {
oldInvariants = invariants.getVertexInvariantCopy();
updateNodeInvariants(Direction.UP); // From the leaves to the root
// This is needed here otherwise there will be cases where a node
// invariant is reset when the tree is traversed down.
// This is not mentioned in Faulon's paper.
computeVertexInvariants();
updateNodeInvariants(Direction.DOWN); // From the root to the leaves
computeVertexInvariants();
invariantSame =
checkInvariantChange(
oldInvariants, invariants.getVertexInvariants());
// System.out.println(Arrays.toString(invariants.getVertexInvariants()));
}
// finally, copy the node invariants into the nodes, for easy sorting
for (int i = 0; i < this.nodes.size(); i++) {
this.nodes.get(i).invariant = invariants.getNodeInvariant(i);
}
}
public boolean checkInvariantChange(int[] a, int[] b) {
for (int i = 0; i < vertexCount; i++) {
if (a[i] != b[i]) {
return true;
}
}
return false;
}
public void updateNodeInvariants(DAG.Direction direction) {
int start, end, increment;
if (direction == Direction.UP) {
start = this.layers.size() - 1;
// The root node is not included but it doesn't matter since it
// is always alone.
end = -1;
increment = -1;
} else {
start = 0;
end = this.layers.size();
increment = 1;
}
for (int i = start; i != end; i += increment) {
this.updateLayer(this.layers.get(i), direction);
}
}
public void updateLayer(List<DAG.Node> layer, DAG.Direction direction) {
List<InvariantList> nodeInvariantList =
new ArrayList<InvariantList>();
for (int i = 0; i < layer.size(); i++) {
DAG.Node layerNode = layer.get(i);
int x = layerNode.vertexIndex;
InvariantList nodeInvariant =
new InvariantList(nodes.indexOf(layerNode));
nodeInvariant.add(this.invariants.getColor(x));
nodeInvariant.add(this.invariants.getVertexInvariant(x));
List<Integer> relativeInvariants = new ArrayList<Integer>();
// If we go up we should check the children.
List<DAG.Node> relatives = (direction == Direction.UP) ?
layerNode.children : layerNode.parents;
for (Node relative : relatives) {
int j = this.nodes.indexOf(relative);
int inv = this.invariants.getNodeInvariant(j);
// System.out.println(layerNode.edgeColors + " getting " + relative.vertexIndex);
int edgeColor;
if (direction == Direction.UP) {
edgeColor = relative.edgeColors.get(layerNode.vertexIndex);
} else {
edgeColor = layerNode.edgeColors.get(relative.vertexIndex);
}
// relativeInvariants.add(inv * edgeColor);
- relativeInvariants.add(inv * (edgeColor + 1));
+// relativeInvariants.add(inv * (edgeColor + 1));
-// relativeInvariants.add(inv);
-// relativeInvariants.add(vertexCount + 1 + edgeColor);
+ relativeInvariants.add(inv);
+ relativeInvariants.add(vertexCount + 1 + edgeColor);
}
Collections.sort(relativeInvariants);
nodeInvariant.addAll(relativeInvariants);
nodeInvariantList.add(nodeInvariant);
}
Collections.sort(nodeInvariantList);
// System.out.println(nodeInvariantList + " for layer " + layer + " " + direction);
int order = 1;
int first = nodeInvariantList.get(0).originalIndex;
this.invariants.setNodeInvariant(first, order);
for (int i = 1; i < nodeInvariantList.size(); i++) {
InvariantList a = nodeInvariantList.get(i - 1);
InvariantList b = nodeInvariantList.get(i);
if (!a.equals(b)) {
order++;
}
this.invariants.setNodeInvariant(b.originalIndex, order);
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
for (List<Node> layer : this) {
buffer.append(layer);
buffer.append("\n");
}
return buffer.toString();
}
}
| false | true | public void updateLayer(List<DAG.Node> layer, DAG.Direction direction) {
List<InvariantList> nodeInvariantList =
new ArrayList<InvariantList>();
for (int i = 0; i < layer.size(); i++) {
DAG.Node layerNode = layer.get(i);
int x = layerNode.vertexIndex;
InvariantList nodeInvariant =
new InvariantList(nodes.indexOf(layerNode));
nodeInvariant.add(this.invariants.getColor(x));
nodeInvariant.add(this.invariants.getVertexInvariant(x));
List<Integer> relativeInvariants = new ArrayList<Integer>();
// If we go up we should check the children.
List<DAG.Node> relatives = (direction == Direction.UP) ?
layerNode.children : layerNode.parents;
for (Node relative : relatives) {
int j = this.nodes.indexOf(relative);
int inv = this.invariants.getNodeInvariant(j);
// System.out.println(layerNode.edgeColors + " getting " + relative.vertexIndex);
int edgeColor;
if (direction == Direction.UP) {
edgeColor = relative.edgeColors.get(layerNode.vertexIndex);
} else {
edgeColor = layerNode.edgeColors.get(relative.vertexIndex);
}
// relativeInvariants.add(inv * edgeColor);
relativeInvariants.add(inv * (edgeColor + 1));
// relativeInvariants.add(inv);
// relativeInvariants.add(vertexCount + 1 + edgeColor);
}
Collections.sort(relativeInvariants);
nodeInvariant.addAll(relativeInvariants);
nodeInvariantList.add(nodeInvariant);
}
Collections.sort(nodeInvariantList);
// System.out.println(nodeInvariantList + " for layer " + layer + " " + direction);
int order = 1;
int first = nodeInvariantList.get(0).originalIndex;
this.invariants.setNodeInvariant(first, order);
for (int i = 1; i < nodeInvariantList.size(); i++) {
InvariantList a = nodeInvariantList.get(i - 1);
InvariantList b = nodeInvariantList.get(i);
if (!a.equals(b)) {
order++;
}
this.invariants.setNodeInvariant(b.originalIndex, order);
}
}
| public void updateLayer(List<DAG.Node> layer, DAG.Direction direction) {
List<InvariantList> nodeInvariantList =
new ArrayList<InvariantList>();
for (int i = 0; i < layer.size(); i++) {
DAG.Node layerNode = layer.get(i);
int x = layerNode.vertexIndex;
InvariantList nodeInvariant =
new InvariantList(nodes.indexOf(layerNode));
nodeInvariant.add(this.invariants.getColor(x));
nodeInvariant.add(this.invariants.getVertexInvariant(x));
List<Integer> relativeInvariants = new ArrayList<Integer>();
// If we go up we should check the children.
List<DAG.Node> relatives = (direction == Direction.UP) ?
layerNode.children : layerNode.parents;
for (Node relative : relatives) {
int j = this.nodes.indexOf(relative);
int inv = this.invariants.getNodeInvariant(j);
// System.out.println(layerNode.edgeColors + " getting " + relative.vertexIndex);
int edgeColor;
if (direction == Direction.UP) {
edgeColor = relative.edgeColors.get(layerNode.vertexIndex);
} else {
edgeColor = layerNode.edgeColors.get(relative.vertexIndex);
}
// relativeInvariants.add(inv * edgeColor);
// relativeInvariants.add(inv * (edgeColor + 1));
relativeInvariants.add(inv);
relativeInvariants.add(vertexCount + 1 + edgeColor);
}
Collections.sort(relativeInvariants);
nodeInvariant.addAll(relativeInvariants);
nodeInvariantList.add(nodeInvariant);
}
Collections.sort(nodeInvariantList);
// System.out.println(nodeInvariantList + " for layer " + layer + " " + direction);
int order = 1;
int first = nodeInvariantList.get(0).originalIndex;
this.invariants.setNodeInvariant(first, order);
for (int i = 1; i < nodeInvariantList.size(); i++) {
InvariantList a = nodeInvariantList.get(i - 1);
InvariantList b = nodeInvariantList.get(i);
if (!a.equals(b)) {
order++;
}
this.invariants.setNodeInvariant(b.originalIndex, order);
}
}
|
diff --git a/src/main/java/stirling/console/commands/Profile.java b/src/main/java/stirling/console/commands/Profile.java
index 767de4a8..8e072bf1 100644
--- a/src/main/java/stirling/console/commands/Profile.java
+++ b/src/main/java/stirling/console/commands/Profile.java
@@ -1,68 +1,68 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package stirling.console.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import stirling.console.Arguments;
import stirling.console.ConsoleClient;
import stirling.fix.messages.MessageFactory;
public class Profile implements Command {
private static final String ARGUMENT_NAME = "Name";
private Map<String, MessageFactory> factories = new HashMap<String, MessageFactory>();
public Profile() {
factories.put("default", new stirling.fix.messages.fix42.DefaultMessageFactory());
factories.put("bats-europe", new stirling.fix.messages.fix42.bats.europe.MessageFactory());
factories.put("mb-trading", new stirling.fix.messages.fix44.mbtrading.MessageFactory());
factories.put("burgundy", new stirling.fix.messages.fix44.burgundy.MessageFactory());
factories.put("hotspot-fx", new stirling.fix.messages.fix42.hotspotfx.MessageFactory());
factories.put("lime", new stirling.fix.messages.fix42.lime.MessageFactory());
- factories.put("nasdaq-omx", new stirling.fix.messages.fix42.nasdaqomx.MessageFactory());
+ factories.put("nasdaq-omx", new stirling.nasdaqomx.fix.MessageFactory());
}
public void execute(ConsoleClient client, Scanner scanner) throws CommandException {
String profile = new Arguments(scanner).requiredValue(ARGUMENT_NAME);
MessageFactory factory = factories.get(profile);
if (factory == null)
throw new CommandArgException("unknown profile: " + profile);
client.setMessageFactory(factory);
}
@Override public String[] getArgumentNames(ConsoleClient client) {
List<String> profiles = new ArrayList<String>(factories.keySet());
List<String> argumentNames = new ArrayList<String>();
Collections.sort(profiles);
for (String profile : profiles)
argumentNames.add(ARGUMENT_NAME + "=" + profile);
return argumentNames.toArray(new String[0]);
}
@Override public String description() {
return "Sets profile which will be used for creating and sending messages.";
}
@Override public String usage() {
return ARGUMENT_NAME + "=<profile> : " + description();
}
}
| true | true | public Profile() {
factories.put("default", new stirling.fix.messages.fix42.DefaultMessageFactory());
factories.put("bats-europe", new stirling.fix.messages.fix42.bats.europe.MessageFactory());
factories.put("mb-trading", new stirling.fix.messages.fix44.mbtrading.MessageFactory());
factories.put("burgundy", new stirling.fix.messages.fix44.burgundy.MessageFactory());
factories.put("hotspot-fx", new stirling.fix.messages.fix42.hotspotfx.MessageFactory());
factories.put("lime", new stirling.fix.messages.fix42.lime.MessageFactory());
factories.put("nasdaq-omx", new stirling.fix.messages.fix42.nasdaqomx.MessageFactory());
}
| public Profile() {
factories.put("default", new stirling.fix.messages.fix42.DefaultMessageFactory());
factories.put("bats-europe", new stirling.fix.messages.fix42.bats.europe.MessageFactory());
factories.put("mb-trading", new stirling.fix.messages.fix44.mbtrading.MessageFactory());
factories.put("burgundy", new stirling.fix.messages.fix44.burgundy.MessageFactory());
factories.put("hotspot-fx", new stirling.fix.messages.fix42.hotspotfx.MessageFactory());
factories.put("lime", new stirling.fix.messages.fix42.lime.MessageFactory());
factories.put("nasdaq-omx", new stirling.nasdaqomx.fix.MessageFactory());
}
|
diff --git a/InteractionManagerUI/src/org/mongkie/ui/im/CategoryPanel.java b/InteractionManagerUI/src/org/mongkie/ui/im/CategoryPanel.java
index 1407f0b..6abeba2 100644
--- a/InteractionManagerUI/src/org/mongkie/ui/im/CategoryPanel.java
+++ b/InteractionManagerUI/src/org/mongkie/ui/im/CategoryPanel.java
@@ -1,91 +1,91 @@
/*
* This file is part of MONGKIE. Visit <http://www.mongkie.org/> for details.
* Visit <http://www.mongkie.org> for details about MONGKIE.
* Copyright (C) 2012 Korean Bioinformation Center (KOBIC)
*
* MONGKIE 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.
*
* MONGKIE 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, see <http://www.gnu.org/licenses/>.
*/
package org.mongkie.ui.im;
import java.awt.Component;
import javax.swing.SwingUtilities;
import org.mongkie.im.InteractionController;
import org.mongkie.im.SourceModel;
import org.mongkie.im.SourceModelChangeListener;
import org.mongkie.im.spi.InteractionSource;
import org.mongkie.visualization.MongkieDisplay;
import org.openide.util.Lookup;
/**
*
* @author Yeongjun Jang <[email protected]>
*/
public class CategoryPanel extends javax.swing.JPanel implements SourceModelChangeListener {
private MongkieDisplay d;
private String category;
/**
* Creates new form ProcessPanel
*/
public CategoryPanel(MongkieDisplay d, String category) {
this.d = d;
this.category = category;
initComponents();
for (InteractionSource is : Lookup.getDefault().lookup(InteractionController.class).getInteractionSources(category)) {
add(new SourcePanel(d, is));
}
Lookup.getDefault().lookup(InteractionController.class).addModelChangeListener(d, CategoryPanel.this);
}
@Override
public void modelAdded(final SourceModel model) {
if (category.equals(model.getInteractionSource().getCategory())
&& category.equals(InteractionController.CATEGORY_OTHERS)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
- add(new SourcePanel(d, model.getInteractionSource()), getComponentCount() - 2);
+ add(new SourcePanel(d, model.getInteractionSource()), getComponentCount());
}
});
}
}
@Override
public void modelRemoved(SourceModel model) {
for (Component c : getComponents()) {
if (c instanceof SourcePanel && model.getInteractionSource().equals(((SourcePanel) c).getInteractionSource())) {
remove(c);
revalidate();
repaint();
}
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setBorder(javax.swing.BorderFactory.createEmptyBorder(4, 1, 4, 1));
setOpaque(false);
setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| true | true | public void modelAdded(final SourceModel model) {
if (category.equals(model.getInteractionSource().getCategory())
&& category.equals(InteractionController.CATEGORY_OTHERS)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
add(new SourcePanel(d, model.getInteractionSource()), getComponentCount() - 2);
}
});
}
}
| public void modelAdded(final SourceModel model) {
if (category.equals(model.getInteractionSource().getCategory())
&& category.equals(InteractionController.CATEGORY_OTHERS)) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
add(new SourcePanel(d, model.getInteractionSource()), getComponentCount());
}
});
}
}
|
diff --git a/src/com/android/mms/util/ContactInfoCache.java b/src/com/android/mms/util/ContactInfoCache.java
index ca59918..72a21c6 100644
--- a/src/com/android/mms/util/ContactInfoCache.java
+++ b/src/com/android/mms/util/ContactInfoCache.java
@@ -1,520 +1,520 @@
/*
* Copyright (C) 2008 Esmertec AG.
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mms.util;
import com.android.mms.ui.MessageUtils;
import com.google.android.mms.util.SqliteWrapper;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Presence;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Telephony.Mms;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
/**
* This class caches query results of contact database and provides convenient
* methods to return contact display name, etc.
*
* TODO: To improve performance, we should make contacts query by ourselves instead of
* doing it one by one calling the CallerInfo API. In the long term, the contacts
* database could have a caching layer to ease the work for all apps.
*/
public class ContactInfoCache {
private static final String TAG = "Mms/cache";
private static final boolean LOCAL_DEBUG = false;
private static final String SEPARATOR = ";";
// query params for caller id lookup
// TODO this query uses non-public API. Figure out a way to expose this functionality
private static final String CALLER_ID_SELECTION = "PHONE_NUMBERS_EQUAL(" + Phone.NUMBER
+ ",?) AND " + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'"
+ " AND " + Data.RAW_CONTACT_ID + " IN "
+ "(SELECT raw_contact_id "
+ " FROM phone_lookup"
+ " WHERE normalized_number GLOB('+*'))";
// Utilizing private API
private static final Uri PHONES_WITH_PRESENCE_URI = Data.CONTENT_URI;
private static final String[] CALLER_ID_PROJECTION = new String[] {
Phone.NUMBER, // 0
Phone.LABEL, // 1
Phone.DISPLAY_NAME, // 2
Phone.CONTACT_ID, // 3
Phone.CONTACT_PRESENCE, // 4
Phone.CONTACT_STATUS, // 5
};
private static final int PHONE_NUMBER_COLUMN = 0;
private static final int PHONE_LABEL_COLUMN = 1;
private static final int CONTACT_NAME_COLUMN = 2;
private static final int CONTACT_ID_COLUMN = 3;
private static final int CONTACT_PRESENCE_COLUMN = 4;
private static final int CONTACT_STATUS_COLUMN = 5;
// query params for contact lookup by email
private static final Uri EMAIL_WITH_PRESENCE_URI = Data.CONTENT_URI;
private static final String EMAIL_SELECTION = Email.DATA + "=? AND " + Data.MIMETYPE + "='"
+ Email.CONTENT_ITEM_TYPE + "'";
private static final String[] EMAIL_PROJECTION = new String[] {
Email.DISPLAY_NAME, // 0
Email.CONTACT_PRESENCE, // 1
Email.CONTACT_ID, // 2
Phone.DISPLAY_NAME, //
};
private static final int EMAIL_NAME_COLUMN = 0;
private static final int EMAIL_STATUS_COLUMN = 1;
private static final int EMAIL_ID_COLUMN = 2;
private static final int EMAIL_CONTACT_NAME_COLUMN = 3;
private static ContactInfoCache sInstance;
private final Context mContext;
private String[] mContactInfoSelectionArgs = new String[1];
// cached contact info
private final HashMap<String, CacheEntry> mCache = new HashMap<String, CacheEntry>();
// for background cache rebuilding
private Thread mCacheRebuilder = null;
private Object mCacheRebuildLock = new Object();
private boolean mPhoneCacheInvalidated = false;
private boolean mEmailCacheInvalidated = false;
/**
* CacheEntry stores the caller id or email lookup info.
*/
public class CacheEntry {
/**
* phone number
*/
public String phoneNumber;
/**
* phone label
*/
public String phoneLabel;
/**
* name of the contact
*/
public String name;
/**
* the contact id in the contacts people table
*/
public long person_id;
/**
* the presence icon resource id
*/
public int presenceResId;
/*
* custom presence
*/
public String presenceText;
/**
* Avatar image for this contact.
*/
public BitmapDrawable mAvatar;
/**
* If true, it indicates the CacheEntry has old info. We want to give the user of this
* class a chance to use the old info, as it can still be useful for displaying something
* rather than nothing in the UI. But this flag indicates that the CacheEntry needs to be
* updated.
*/
private boolean isStale;
/**
* Returns true if this CacheEntry needs to be updated. However, cache may still contain
* the old information.
*
*/
public boolean isStale() {
return isStale;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("name=" + name);
buf.append(", phone=" + phoneNumber);
buf.append(", pid=" + person_id);
buf.append(", presence=" + presenceResId);
buf.append(", stale=" + isStale);
return buf.toString();
}
};
private ContactInfoCache(Context context) {
mContext = context;
}
/**
* invalidates the cache entries by marking CacheEntry.isStale to true.
*/
public void invalidateCache() {
synchronized (mCache) {
for (Map.Entry<String, CacheEntry> e: mCache.entrySet()) {
CacheEntry entry = e.getValue();
entry.isStale = true;
}
}
}
/**
* invalidates a single cache entry. Can pass in an email or number.
*/
public void invalidateContact(String emailOrNumber) {
synchronized (mCache) {
CacheEntry entry = mCache.get(emailOrNumber);
if (entry != null) {
entry.isStale = true;
}
}
}
/**
* Initialize the global instance. Should call only once.
*/
public static void init(Context context) {
sInstance = new ContactInfoCache(context);
}
/**
* Get the global instance.
*/
public static ContactInfoCache getInstance() {
return sInstance;
}
public void dump() {
synchronized (mCache) {
Log.i(TAG, "ContactInfoCache.dump");
for (String name : mCache.keySet()) {
CacheEntry entry = mCache.get(name);
if (entry != null) {
Log.i(TAG, "key=" + name + ", cacheEntry={" + entry.toString() + '}');
} else {
Log.i(TAG, "key=" + name + ", cacheEntry={null}");
}
}
}
}
/**
* Returns the caller info in CacheEntry.
*/
public CacheEntry getContactInfo(String numberOrEmail, boolean allowQuery) {
if (Mms.isEmailAddress(numberOrEmail)) {
return getContactInfoForEmailAddress(numberOrEmail, allowQuery);
} else {
return getContactInfoForPhoneNumber(numberOrEmail, allowQuery);
}
}
public CacheEntry getContactInfo(String numberOrEmail) {
return getContactInfo(numberOrEmail, true);
}
/**
* Returns the caller info in a CacheEntry. If 'noQuery' is set to true, then this
* method only checks in the cache and makes no content provider query.
*
* @param number the phone number for the contact.
* @param allowQuery allow (potentially blocking) query the content provider if true.
* @return the CacheEntry containing the contact info.
*/
public CacheEntry getContactInfoForPhoneNumber(String number, boolean allowQuery) {
// TODO: numbers like "6501234567" and "+16501234567" are equivalent.
// we should convert them into a uniform format so that we don't cache
// them twice.
number = PhoneNumberUtils.stripSeparators(number);
synchronized (mCache) {
if (mCache.containsKey(number)) {
CacheEntry entry = mCache.get(number);
if (LOCAL_DEBUG) {
log("getContactInfo: number=" + number + ", name=" + entry.name +
", presence=" + entry.presenceResId);
}
if (!allowQuery || !entry.isStale()) {
return entry;
}
} else if (!allowQuery) {
return null;
}
}
CacheEntry entry = queryContactInfoByNumber(number);
synchronized (mCache) {
mCache.put(number, entry);
}
return entry;
}
/**
* Queries the caller id info with the phone number.
* @return a CacheEntry containing the caller id info corresponding to the number.
*/
private CacheEntry queryContactInfoByNumber(String number) {
CacheEntry entry = new CacheEntry();
entry.phoneNumber = number;
//if (LOCAL_DEBUG) log("queryContactInfoByNumber: number=" + number);
mContactInfoSelectionArgs[0] = number;
// We need to include the phone number in the selection string itself rather then
// selection arguments, because SQLite needs to see the exact pattern of GLOB
// to generate the correct query plan
String selection = CALLER_ID_SELECTION.replace("+",
- PhoneNumberUtils.getStrippedReversed(number));
+ PhoneNumberUtils.toCallerIDMinMatch(number));
Cursor cursor = mContext.getContentResolver().query(
PHONES_WITH_PRESENCE_URI,
CALLER_ID_PROJECTION,
selection,
mContactInfoSelectionArgs,
null);
if (cursor == null) {
Log.w(TAG, "queryContactInfoByNumber(" + number + ") returned NULL cursor!" +
" contact uri used " + PHONES_WITH_PRESENCE_URI);
return entry;
}
try {
if (cursor.moveToFirst()) {
entry.phoneLabel = cursor.getString(PHONE_LABEL_COLUMN);
entry.name = cursor.getString(CONTACT_NAME_COLUMN);
entry.person_id = cursor.getLong(CONTACT_ID_COLUMN);
entry.presenceResId = getPresenceIconResourceId(
cursor.getInt(CONTACT_PRESENCE_COLUMN));
entry.presenceText = cursor.getString(CONTACT_STATUS_COLUMN);
if (LOCAL_DEBUG) {
log("queryContactInfoByNumber: name=" + entry.name + ", number=" + number +
", presence=" + entry.presenceResId);
}
loadAvatar(entry, cursor);
}
} finally {
cursor.close();
}
return entry;
}
private void loadAvatar(CacheEntry entry, Cursor cursor) {
if (entry.person_id == 0 || entry.mAvatar != null) {
return;
}
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, entry.person_id);
InputStream avatarDataStream =
Contacts.openContactPhotoInputStream(
mContext.getContentResolver(),
contactUri);
if (avatarDataStream != null) {
Bitmap b = BitmapFactory.decodeStream(avatarDataStream);
BitmapDrawable bd =
new BitmapDrawable(mContext.getResources(), b);
entry.mAvatar = bd;
try {
avatarDataStream.close();
} catch (IOException e) {
entry.mAvatar = null;
}
}
}
/**
* Get the display names of contacts. Contacts can be either email address or
* phone number.
*
* @param address the addresses to lookup, separated by ";"
* @return a nicely formatted version of the contact names to display
*/
public String getContactName(String address) {
if (TextUtils.isEmpty(address)) {
return "";
}
StringBuilder result = new StringBuilder();
for (String value : address.split(SEPARATOR)) {
if (value.length() > 0) {
result.append(SEPARATOR);
if (MessageUtils.isLocalNumber(value)) {
result.append(mContext.getString(com.android.internal.R.string.me));
} else if (Mms.isEmailAddress(value)) {
result.append(getDisplayName(value));
} else {
result.append(getCallerId(value));
}
}
}
if (result.length() > 0) {
// Skip the first ";"
return result.substring(1);
}
return "";
}
/**
* Get the display name of an email address. If the address already contains
* the name, parse and return it. Otherwise, query the contact database. Cache
* query results for repeated queries.
*/
public String getDisplayName(String email) {
Matcher match = Mms.NAME_ADDR_EMAIL_PATTERN.matcher(email);
if (match.matches()) {
// email has display name
return getEmailDisplayName(match.group(1));
}
CacheEntry entry = getContactInfoForEmailAddress(email, true /* allow query */);
if (entry != null && entry.name != null) {
return entry.name;
}
return email;
}
/**
* Returns the contact info for a given email address
*
* @param email the email address.
* @param allowQuery allow making (potentially blocking) content provider queries if true.
* @return a CacheEntry if the contact is found.
*/
public CacheEntry getContactInfoForEmailAddress(String email, boolean allowQuery) {
synchronized (mCache) {
if (mCache.containsKey(email)) {
CacheEntry entry = mCache.get(email);
if (!allowQuery || !entry.isStale()) {
return entry;
}
} else if (!allowQuery) {
return null;
}
}
CacheEntry entry = queryEmailDisplayName(email);
synchronized (mCache) {
mCache.put(email, entry);
return entry;
}
}
/**
* A cached version of CallerInfo.getCallerId().
*/
private String getCallerId(String number) {
ContactInfoCache.CacheEntry entry = getContactInfo(number);
if (entry != null && !TextUtils.isEmpty(entry.name)) {
return entry.name;
}
return number;
}
private static String getEmailDisplayName(String displayString) {
Matcher match = Mms.QUOTED_STRING_PATTERN.matcher(displayString);
if (match.matches()) {
return match.group(1);
}
return displayString;
}
private int getPresenceIconResourceId(int presence) {
if (presence != Presence.OFFLINE) {
return Presence.getPresenceIconResourceId(presence);
}
return 0;
}
/**
* Query the contact email table to get the name of an email address.
*/
private CacheEntry queryEmailDisplayName(String email) {
CacheEntry entry = new CacheEntry();
mContactInfoSelectionArgs[0] = email;
Cursor cursor = SqliteWrapper.query(mContext, mContext.getContentResolver(),
EMAIL_WITH_PRESENCE_URI,
EMAIL_PROJECTION,
EMAIL_SELECTION,
mContactInfoSelectionArgs,
null);
if (cursor != null) {
try {
while (cursor.moveToNext()) {
entry.presenceResId = getPresenceIconResourceId(
cursor.getInt(EMAIL_STATUS_COLUMN));
entry.person_id = cursor.getLong(EMAIL_ID_COLUMN);
String name = cursor.getString(EMAIL_NAME_COLUMN);
if (TextUtils.isEmpty(name)) {
name = cursor.getString(EMAIL_CONTACT_NAME_COLUMN);
}
if (!TextUtils.isEmpty(name)) {
entry.name = name;
loadAvatar(entry, cursor);
if (LOCAL_DEBUG) {
log("queryEmailDisplayName: name=" + entry.name + ", email=" + email +
", presence=" + entry.presenceResId);
}
break;
}
}
} finally {
cursor.close();
}
}
return entry;
}
private void log(String msg) {
Log.d(TAG, "[ContactInfoCache] " + msg);
}
}
| true | true | private CacheEntry queryContactInfoByNumber(String number) {
CacheEntry entry = new CacheEntry();
entry.phoneNumber = number;
//if (LOCAL_DEBUG) log("queryContactInfoByNumber: number=" + number);
mContactInfoSelectionArgs[0] = number;
// We need to include the phone number in the selection string itself rather then
// selection arguments, because SQLite needs to see the exact pattern of GLOB
// to generate the correct query plan
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.getStrippedReversed(number));
Cursor cursor = mContext.getContentResolver().query(
PHONES_WITH_PRESENCE_URI,
CALLER_ID_PROJECTION,
selection,
mContactInfoSelectionArgs,
null);
if (cursor == null) {
Log.w(TAG, "queryContactInfoByNumber(" + number + ") returned NULL cursor!" +
" contact uri used " + PHONES_WITH_PRESENCE_URI);
return entry;
}
try {
if (cursor.moveToFirst()) {
entry.phoneLabel = cursor.getString(PHONE_LABEL_COLUMN);
entry.name = cursor.getString(CONTACT_NAME_COLUMN);
entry.person_id = cursor.getLong(CONTACT_ID_COLUMN);
entry.presenceResId = getPresenceIconResourceId(
cursor.getInt(CONTACT_PRESENCE_COLUMN));
entry.presenceText = cursor.getString(CONTACT_STATUS_COLUMN);
if (LOCAL_DEBUG) {
log("queryContactInfoByNumber: name=" + entry.name + ", number=" + number +
", presence=" + entry.presenceResId);
}
loadAvatar(entry, cursor);
}
} finally {
cursor.close();
}
return entry;
}
| private CacheEntry queryContactInfoByNumber(String number) {
CacheEntry entry = new CacheEntry();
entry.phoneNumber = number;
//if (LOCAL_DEBUG) log("queryContactInfoByNumber: number=" + number);
mContactInfoSelectionArgs[0] = number;
// We need to include the phone number in the selection string itself rather then
// selection arguments, because SQLite needs to see the exact pattern of GLOB
// to generate the correct query plan
String selection = CALLER_ID_SELECTION.replace("+",
PhoneNumberUtils.toCallerIDMinMatch(number));
Cursor cursor = mContext.getContentResolver().query(
PHONES_WITH_PRESENCE_URI,
CALLER_ID_PROJECTION,
selection,
mContactInfoSelectionArgs,
null);
if (cursor == null) {
Log.w(TAG, "queryContactInfoByNumber(" + number + ") returned NULL cursor!" +
" contact uri used " + PHONES_WITH_PRESENCE_URI);
return entry;
}
try {
if (cursor.moveToFirst()) {
entry.phoneLabel = cursor.getString(PHONE_LABEL_COLUMN);
entry.name = cursor.getString(CONTACT_NAME_COLUMN);
entry.person_id = cursor.getLong(CONTACT_ID_COLUMN);
entry.presenceResId = getPresenceIconResourceId(
cursor.getInt(CONTACT_PRESENCE_COLUMN));
entry.presenceText = cursor.getString(CONTACT_STATUS_COLUMN);
if (LOCAL_DEBUG) {
log("queryContactInfoByNumber: name=" + entry.name + ", number=" + number +
", presence=" + entry.presenceResId);
}
loadAvatar(entry, cursor);
}
} finally {
cursor.close();
}
return entry;
}
|
diff --git a/src/org/shininet/bukkit/playerheads/PlayerHeadsListener.java b/src/org/shininet/bukkit/playerheads/PlayerHeadsListener.java
index a73495d..3911319 100644
--- a/src/org/shininet/bukkit/playerheads/PlayerHeadsListener.java
+++ b/src/org/shininet/bukkit/playerheads/PlayerHeadsListener.java
@@ -1,229 +1,229 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.shininet.bukkit.playerheads;
import java.util.Iterator;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.SkullType;
import org.bukkit.block.Block;
import org.bukkit.block.Skull;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.inventory.ItemStack;
/**
* @author meiskam
*/
public class PlayerHeadsListener implements Listener {
private final Random prng = new Random();
private PlayerHeads plugin;
public PlayerHeadsListener(PlayerHeads plugin) {
this.plugin = plugin;
}
@SuppressWarnings("incomplete-switch")
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityDeath(EntityDeathEvent event) {
Player killer = event.getEntity().getKiller();
double lootingrate = 1;
if (killer != null) {
ItemStack weapon = killer.getItemInHand();
if (weapon != null) {
lootingrate = 1+(plugin.configFile.getDouble("lootingrate")*weapon.getEnchantmentLevel(Enchantment.LOOT_BONUS_MOBS));
}
}
//if (event.getEntityType() == EntityType.PLAYER) {
switch (event.getEntityType()) {
case PLAYER:
//((Player)(event.getEntity())).sendMessage("Hehe, you died");
Double dropchance = prng.nextDouble();
Player player = (Player)event.getEntity();
- if ((dropchance >= plugin.configFile.getDouble("droprate")*lootingrate) && !killer.hasPermission("playerheads.alwaysbehead")) { return; }
+ if ((dropchance >= plugin.configFile.getDouble("droprate")*lootingrate) && ((killer == null) || !killer.hasPermission("playerheads.alwaysbehead"))) { return; }
if (!player.hasPermission("playerheads.canloosehead")) { return; }
if (plugin.configFile.getBoolean("pkonly") && ((killer == null) || (killer == player) || !killer.hasPermission("playerheads.canbehead"))) { return; }
String skullOwner;
if (plugin.configFile.getBoolean("dropboringplayerheads")) {
skullOwner = "";
} else {
skullOwner = player.getName();
}
if (plugin.configFile.getBoolean("antideathchest")) {
Location location = player.getLocation();
location.getWorld().dropItemNaturally(location, PlayerHeads.Skull(skullOwner));
} else {
event.getDrops().add(PlayerHeads.Skull(skullOwner)); // drop the precious player head
}
if (plugin.configFile.getBoolean("broadcast")) {
if (killer == null) {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_GENERIC, player.getDisplayName() + ChatColor.RESET));
} else if (killer == player) {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_SELF, player.getDisplayName() + ChatColor.RESET));
} else {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_OTHER, player.getDisplayName() + ChatColor.RESET, killer.getDisplayName() + ChatColor.RESET));
}
}
break;
case CREEPER:
EntityDeathHelper(event, SkullType.CREEPER, plugin.configFile.getDouble("creeperdroprate")*lootingrate);
break;
case ZOMBIE:
EntityDeathHelper(event, SkullType.ZOMBIE, plugin.configFile.getDouble("zombiedroprate")*lootingrate);
break;
case SKELETON:
if (((Skeleton)event.getEntity()).getSkeletonType() == Skeleton.SkeletonType.NORMAL) {
EntityDeathHelper(event, SkullType.SKELETON, plugin.configFile.getDouble("skeletondroprate")*lootingrate);
} else if (((Skeleton)event.getEntity()).getSkeletonType() == Skeleton.SkeletonType.WITHER) {
for (Iterator<ItemStack> it = event.getDrops().iterator(); it.hasNext(); ) {
if (it.next().getType() == Material.SKULL_ITEM) {
it.remove();
}
}
EntityDeathHelper(event, SkullType.WITHER, plugin.configFile.getDouble("witherdroprate")*lootingrate);
}
break;
case SPIDER:
EntityDeathHelper(event, CustomSkullType.SPIDER, plugin.configFile.getDouble("spiderdroprate")*lootingrate);
break;
case ENDERMAN:
EntityDeathHelper(event, CustomSkullType.ENDERMAN, plugin.configFile.getDouble("endermandroprate")*lootingrate);
break;
case BLAZE:
EntityDeathHelper(event, CustomSkullType.BLAZE, plugin.configFile.getDouble("blazedroprate")*lootingrate);
break;
}
}
public void EntityDeathHelper(EntityDeathEvent event, Enum<?> type, Double droprate) {
Double dropchance = prng.nextDouble();
Player killer = event.getEntity().getKiller();
if ((dropchance >= droprate) && ((killer == null) || !killer.hasPermission("playerheads.alwaysbeheadmob"))) { return; }
if (plugin.configFile.getBoolean("mobpkonly") && ((killer == null) || !killer.hasPermission("playerheads.canbeheadmob"))) { return; }
if (type instanceof SkullType) {
event.getDrops().add(PlayerHeads.Skull((SkullType)type));
} else if (type instanceof CustomSkullType) {
event.getDrops().add(PlayerHeads.Skull((CustomSkullType)type));
}
}
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerInteract(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
Player player = event.getPlayer();
if (block != null && block.getType() == Material.SKULL && plugin.configFile.getBoolean("clickinfo")) {
Skull skullState = (Skull)block.getState();
switch (skullState.getSkullType()) {
case PLAYER:
if (skullState.hasOwner()) {
String owner = skullState.getOwner();
String ownerStrip = ChatColor.stripColor(owner);
if (ownerStrip.equals(CustomSkullType.BLAZE.getOwner())) {
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, CustomSkullType.BLAZE.getDisplayName());
} else if (ownerStrip.equals(CustomSkullType.ENDERMAN.getOwner())) {
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, CustomSkullType.ENDERMAN.getDisplayName());
} else if (ownerStrip.equals(CustomSkullType.SPIDER.getOwner())) {
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, CustomSkullType.SPIDER.getDisplayName());
} else {
PlayerHeads.formatMsg(player, Lang.CLICKINFO, owner);
}
} else {
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, Lang.HEAD);
}
break;
case CREEPER:
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, Lang.HEAD_CREEPER);
break;
case SKELETON:
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, Lang.HEAD_SKELETON);
break;
case WITHER:
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, Lang.HEAD_WITHER);
break;
case ZOMBIE:
PlayerHeads.formatMsg(player, Lang.CLICKINFO2, Lang.HEAD_ZOMBIE);
break;
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockBreak(BlockBreakEvent event) {
if (event instanceof FakeBlockBreakEvent) {
return;
}
Block block = event.getBlock();
if (block.getType() == Material.SKULL) {
Skull skull = (Skull)block.getState();
if (skull.hasOwner()) {
String owner = ChatColor.stripColor(skull.getOwner());
if ((owner.equals(CustomSkullType.BLAZE.getOwner()))
|| (owner.equals(CustomSkullType.ENDERMAN.getOwner()))
|| (owner.equals(CustomSkullType.SPIDER.getOwner()))) {
Player player = event.getPlayer();
plugin.getServer().getPluginManager().callEvent(new PlayerAnimationEvent(player));
plugin.getServer().getPluginManager().callEvent(new BlockDamageEvent(player, block, player.getItemInHand(), true));
FakeBlockBreakEvent fakebreak = new FakeBlockBreakEvent(block, player);
plugin.getServer().getPluginManager().callEvent(fakebreak);
if (fakebreak.isCancelled()) {
event.setCancelled(true);
} else {
Location location = block.getLocation();
ItemStack item = null;
if (owner.equals(CustomSkullType.BLAZE.getOwner())) {
item = PlayerHeads.Skull(CustomSkullType.BLAZE);
} else if (owner.equals(CustomSkullType.ENDERMAN.getOwner())) {
item = PlayerHeads.Skull(CustomSkullType.ENDERMAN);
} else if (owner.equals(CustomSkullType.SPIDER.getOwner())) {
item = PlayerHeads.Skull(CustomSkullType.SPIDER);
}
if (item != null) {
event.setCancelled(true);
block.setType(Material.AIR);
location.getWorld().dropItemNaturally(location, item);
}
}
}
}
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event)
{
Player player = event.getPlayer();
if(player.hasPermission("playerheads.update") && plugin.getUpdateReady())
{
PlayerHeads.formatMsg(player, Lang.UPDATE1, plugin.getUpdateName(), String.valueOf(plugin.getUpdateSize()));
PlayerHeads.formatMsg(player, Lang.UPDATE2);
}
}
}
| true | true | public void onEntityDeath(EntityDeathEvent event) {
Player killer = event.getEntity().getKiller();
double lootingrate = 1;
if (killer != null) {
ItemStack weapon = killer.getItemInHand();
if (weapon != null) {
lootingrate = 1+(plugin.configFile.getDouble("lootingrate")*weapon.getEnchantmentLevel(Enchantment.LOOT_BONUS_MOBS));
}
}
//if (event.getEntityType() == EntityType.PLAYER) {
switch (event.getEntityType()) {
case PLAYER:
//((Player)(event.getEntity())).sendMessage("Hehe, you died");
Double dropchance = prng.nextDouble();
Player player = (Player)event.getEntity();
if ((dropchance >= plugin.configFile.getDouble("droprate")*lootingrate) && !killer.hasPermission("playerheads.alwaysbehead")) { return; }
if (!player.hasPermission("playerheads.canloosehead")) { return; }
if (plugin.configFile.getBoolean("pkonly") && ((killer == null) || (killer == player) || !killer.hasPermission("playerheads.canbehead"))) { return; }
String skullOwner;
if (plugin.configFile.getBoolean("dropboringplayerheads")) {
skullOwner = "";
} else {
skullOwner = player.getName();
}
if (plugin.configFile.getBoolean("antideathchest")) {
Location location = player.getLocation();
location.getWorld().dropItemNaturally(location, PlayerHeads.Skull(skullOwner));
} else {
event.getDrops().add(PlayerHeads.Skull(skullOwner)); // drop the precious player head
}
if (plugin.configFile.getBoolean("broadcast")) {
if (killer == null) {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_GENERIC, player.getDisplayName() + ChatColor.RESET));
} else if (killer == player) {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_SELF, player.getDisplayName() + ChatColor.RESET));
} else {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_OTHER, player.getDisplayName() + ChatColor.RESET, killer.getDisplayName() + ChatColor.RESET));
}
}
break;
case CREEPER:
EntityDeathHelper(event, SkullType.CREEPER, plugin.configFile.getDouble("creeperdroprate")*lootingrate);
break;
case ZOMBIE:
EntityDeathHelper(event, SkullType.ZOMBIE, plugin.configFile.getDouble("zombiedroprate")*lootingrate);
break;
case SKELETON:
if (((Skeleton)event.getEntity()).getSkeletonType() == Skeleton.SkeletonType.NORMAL) {
EntityDeathHelper(event, SkullType.SKELETON, plugin.configFile.getDouble("skeletondroprate")*lootingrate);
} else if (((Skeleton)event.getEntity()).getSkeletonType() == Skeleton.SkeletonType.WITHER) {
for (Iterator<ItemStack> it = event.getDrops().iterator(); it.hasNext(); ) {
if (it.next().getType() == Material.SKULL_ITEM) {
it.remove();
}
}
EntityDeathHelper(event, SkullType.WITHER, plugin.configFile.getDouble("witherdroprate")*lootingrate);
}
break;
case SPIDER:
EntityDeathHelper(event, CustomSkullType.SPIDER, plugin.configFile.getDouble("spiderdroprate")*lootingrate);
break;
case ENDERMAN:
EntityDeathHelper(event, CustomSkullType.ENDERMAN, plugin.configFile.getDouble("endermandroprate")*lootingrate);
break;
case BLAZE:
EntityDeathHelper(event, CustomSkullType.BLAZE, plugin.configFile.getDouble("blazedroprate")*lootingrate);
break;
}
}
| public void onEntityDeath(EntityDeathEvent event) {
Player killer = event.getEntity().getKiller();
double lootingrate = 1;
if (killer != null) {
ItemStack weapon = killer.getItemInHand();
if (weapon != null) {
lootingrate = 1+(plugin.configFile.getDouble("lootingrate")*weapon.getEnchantmentLevel(Enchantment.LOOT_BONUS_MOBS));
}
}
//if (event.getEntityType() == EntityType.PLAYER) {
switch (event.getEntityType()) {
case PLAYER:
//((Player)(event.getEntity())).sendMessage("Hehe, you died");
Double dropchance = prng.nextDouble();
Player player = (Player)event.getEntity();
if ((dropchance >= plugin.configFile.getDouble("droprate")*lootingrate) && ((killer == null) || !killer.hasPermission("playerheads.alwaysbehead"))) { return; }
if (!player.hasPermission("playerheads.canloosehead")) { return; }
if (plugin.configFile.getBoolean("pkonly") && ((killer == null) || (killer == player) || !killer.hasPermission("playerheads.canbehead"))) { return; }
String skullOwner;
if (plugin.configFile.getBoolean("dropboringplayerheads")) {
skullOwner = "";
} else {
skullOwner = player.getName();
}
if (plugin.configFile.getBoolean("antideathchest")) {
Location location = player.getLocation();
location.getWorld().dropItemNaturally(location, PlayerHeads.Skull(skullOwner));
} else {
event.getDrops().add(PlayerHeads.Skull(skullOwner)); // drop the precious player head
}
if (plugin.configFile.getBoolean("broadcast")) {
if (killer == null) {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_GENERIC, player.getDisplayName() + ChatColor.RESET));
} else if (killer == player) {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_SELF, player.getDisplayName() + ChatColor.RESET));
} else {
plugin.getServer().broadcastMessage(PlayerHeads.format(Lang.BEHEAD_OTHER, player.getDisplayName() + ChatColor.RESET, killer.getDisplayName() + ChatColor.RESET));
}
}
break;
case CREEPER:
EntityDeathHelper(event, SkullType.CREEPER, plugin.configFile.getDouble("creeperdroprate")*lootingrate);
break;
case ZOMBIE:
EntityDeathHelper(event, SkullType.ZOMBIE, plugin.configFile.getDouble("zombiedroprate")*lootingrate);
break;
case SKELETON:
if (((Skeleton)event.getEntity()).getSkeletonType() == Skeleton.SkeletonType.NORMAL) {
EntityDeathHelper(event, SkullType.SKELETON, plugin.configFile.getDouble("skeletondroprate")*lootingrate);
} else if (((Skeleton)event.getEntity()).getSkeletonType() == Skeleton.SkeletonType.WITHER) {
for (Iterator<ItemStack> it = event.getDrops().iterator(); it.hasNext(); ) {
if (it.next().getType() == Material.SKULL_ITEM) {
it.remove();
}
}
EntityDeathHelper(event, SkullType.WITHER, plugin.configFile.getDouble("witherdroprate")*lootingrate);
}
break;
case SPIDER:
EntityDeathHelper(event, CustomSkullType.SPIDER, plugin.configFile.getDouble("spiderdroprate")*lootingrate);
break;
case ENDERMAN:
EntityDeathHelper(event, CustomSkullType.ENDERMAN, plugin.configFile.getDouble("endermandroprate")*lootingrate);
break;
case BLAZE:
EntityDeathHelper(event, CustomSkullType.BLAZE, plugin.configFile.getDouble("blazedroprate")*lootingrate);
break;
}
}
|
diff --git a/modules/dCache/org/dcache/services/info/secondaryInfoProviders/NormalisedAccessSpaceMaintainer.java b/modules/dCache/org/dcache/services/info/secondaryInfoProviders/NormalisedAccessSpaceMaintainer.java
index 7ffbc7c9d7..857052d05e 100644
--- a/modules/dCache/org/dcache/services/info/secondaryInfoProviders/NormalisedAccessSpaceMaintainer.java
+++ b/modules/dCache/org/dcache/services/info/secondaryInfoProviders/NormalisedAccessSpaceMaintainer.java
@@ -1,571 +1,575 @@
package org.dcache.services.info.secondaryInfoProviders;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.dcache.services.info.base.StateExhibitor;
import org.dcache.services.info.base.StatePath;
import org.dcache.services.info.base.StateTransition;
import org.dcache.services.info.base.StateUpdate;
import org.dcache.services.info.stateInfo.LinkInfo;
import org.dcache.services.info.stateInfo.LinkInfoVisitor;
import org.dcache.services.info.stateInfo.PoolSpaceVisitor;
import org.dcache.services.info.stateInfo.SpaceInfo;
/**
* The NormalisaedAccessSpace (NAS) maintainer updates the <code>nas</code>
* branch of the dCache state based on changes to pool space usage or
* pool-link membership.
*
* A NAS is a set of pools. They are somewhat similar to a poolgroup except
* that dCache PSU has no knowledge of them. Each NAS has the following
* properties:
* <ol>
* <li>all pools are a member of precisely one NAS,
* <li>all NAS have at least one member pool,
* <li>all pools within a NAS have the same "access", where access is the set
* of units that might select these pools and the set of operations permitted
* through the link.
* </ol>
*
* Because of the way NAS are constructed, all pools of a single NAS have
* well-defined relationship to the links: for each link, either all pools of
* the same NAS are accessible or all pools are not accessible.
* <p>
* NAS association with a link is not exclusive. Pools in a NAS that is
* accessible from one link may be accessible from a different link. Those
* pools accessible in a NAS accessible through a link may share that link
* with other pools.
*/
public class NormalisedAccessSpaceMaintainer extends AbstractStateWatcher {
private static Logger _log =
Logger.getLogger( NormalisedAccessSpaceMaintainer.class);
/**
* How we want to represent the different LinkInfo.UNIT_TYPE values as
* path elements in the resulting metrics
*/
@SuppressWarnings("serial")
private static final Map<LinkInfo.UNIT_TYPE, String> UNIT_TYPE_STORAGE_NAME =
Collections.unmodifiableMap( new HashMap<LinkInfo.UNIT_TYPE, String>() {
{
put( LinkInfo.UNIT_TYPE.DCACHE, "dcache");
put( LinkInfo.UNIT_TYPE.STORE, "store");
}
});
/**
* How we want to represent the different LinkInfo.OPERATION values as
* path elements in resulting metrics
*/
@SuppressWarnings("serial")
private static final Map<LinkInfo.OPERATION, String> OPERATION_STORAGE_NAME =
Collections.unmodifiableMap( new HashMap<LinkInfo.OPERATION, String>() {
{
put( LinkInfo.OPERATION.READ, "read");
put( LinkInfo.OPERATION.WRITE, "write");
put( LinkInfo.OPERATION.CACHE, "stage");
}
});
private static final String PREDICATE_PATHS[] =
{ "links.*.pools.*", "links.*.units.store.*",
"links.*.units.dcache.*", "pools.*.space.*" };
private static final StatePath NAS_PATH = new StatePath( "nas");
/**
* A class describing the "paint" information for a pool. Each pool has a
* PaintInfo object that describes the different access methods for this
* pool. Pools with the same PaintInfo are members of the same NAS.
*/
static private class PaintInfo {
/**
* The Set of LinkInfo.OPERATIONS that we paint a pool on.
*/
private static final Set<LinkInfo.OPERATION> CONSIDERED_OPERATIONS =
new HashSet<LinkInfo.OPERATION>( Arrays.asList( LinkInfo.OPERATION.READ,
LinkInfo.OPERATION.WRITE,
LinkInfo.OPERATION.CACHE));
/**
* The Set of LinkInfo.UNIT_TYPES that we paint a pool on.
*/
private static final Set<LinkInfo.UNIT_TYPE> CONSIDERED_UNIT_TYPES =
new HashSet<LinkInfo.UNIT_TYPE>( Arrays.asList( LinkInfo.UNIT_TYPE.DCACHE,
LinkInfo.UNIT_TYPE.STORE));
private final String _poolId;
private final Set<String> _access = new HashSet<String>();
private final Set<String> _links = new HashSet<String>();
/** Store all units by unit-type and operation */
// FIXME the following is ugly
private final Map<LinkInfo.UNIT_TYPE, Map<LinkInfo.OPERATION, Set<String>>> _storedUnits;
public PaintInfo( String poolId) {
_poolId = poolId;
Map<LinkInfo.UNIT_TYPE, Map<LinkInfo.OPERATION, Set<String>>> storedUnits =
new HashMap<LinkInfo.UNIT_TYPE, Map<LinkInfo.OPERATION, Set<String>>>();
_storedUnits = Collections.unmodifiableMap( storedUnits);
for( LinkInfo.UNIT_TYPE unitType : CONSIDERED_UNIT_TYPES) {
Map<LinkInfo.OPERATION, Set<String>> storedUnitsForType =
new HashMap<LinkInfo.OPERATION, Set<String>>();
storedUnits.put(
unitType,
Collections.unmodifiableMap( storedUnitsForType));
for( LinkInfo.OPERATION operation : CONSIDERED_OPERATIONS)
storedUnitsForType.put( operation, new HashSet<String>());
}
}
/**
* Add paint information for a set of units of the same type
* ("store", "network", etc) that select for the specific link.
* <p>
* We only care about "dcache" and "store" units; protocol and
* network ones are ignored. Pools that differ only in their access
* by network or protocol units are grouped together into a common
* NAS.
*
* @param link The LinkInfo object that describes the link
* @param unitTypeName the name given to these type of unit by
* LinkInfoVisitor
* @param units the Set of unit names.
*/
void addAccess( LinkInfo link) {
for( LinkInfo.OPERATION operation : CONSIDERED_OPERATIONS) {
if( !link.isAccessableFor( operation))
continue;
for( LinkInfo.UNIT_TYPE unitType : CONSIDERED_UNIT_TYPES)
for( String unit : link.getUnits( unitType))
addAccessForUnit( link.getId(), operation, unitType,
unit);
}
}
/**
* Update paint information for a specific unit.
*
* @param linkName the String identifier for this link
* @param operation one of the LinkInfo.OPERATIONS {READ, WRITE,
* CACHE, P2P}
* @param unitType one of LinkInfo.UNIT_TYPE {DCACHE, STORE, NETWORK,
* PROTO}
* @param unitName the String identifier for this unit.
*/
private void addAccessForUnit( String linkName,
LinkInfo.OPERATION operation,
LinkInfo.UNIT_TYPE unitType,
String unitName) {
// Remember this unit.
_storedUnits.get( unitType).get( operation).add( unitName);
String thisAccess = unitType + "-" + unitName + "-" + operation;
_access.add( thisAccess);
_links.add( linkName);
}
/**
* Return the name of the NAS this painted pool should be within.
*
* @return a unique name for the NAS this PaintInfo is representative
* of.
*/
String getNasName() {
return Integer.toHexString( _access.hashCode());
}
protected Set<String> getAccess() {
return _access;
}
protected Set<String> getLinks() {
return _links;
}
String getPoolId() {
return _poolId;
}
/**
* Return the Set of units that match for links that were painted to
* this pool's information.
*
* @param unitType the type of unit {DCACHE, STORE, NETWORK, PROTO}
* @param operation the type of operation {READ, WRITE, P2P, STAGE}
* @return the Set of units, or null if the selection is invalid.
*/
public Set<String> getUnits( LinkInfo.UNIT_TYPE unitType,
LinkInfo.OPERATION operation) {
Map<LinkInfo.OPERATION, Set<String>> storedUnitsForType =
getUnits( unitType);
if( storedUnitsForType == null ||
!storedUnitsForType.containsKey( operation))
return null;
return Collections.unmodifiableSet( storedUnitsForType.get( operation));
}
/**
* Obtain a Map between operations (such as read, write, ...) and the
* Set of units that select those operations for a given unitType
* (such as dcache, store, ..)
*
* @param unitType a considered unit type.
* @return the corresponding Mapping or null if unit type isn't
* considered.
*/
public Map<LinkInfo.OPERATION, Set<String>> getUnits(
LinkInfo.UNIT_TYPE unitType) {
if( !_storedUnits.containsKey( unitType))
return null;
return Collections.unmodifiableMap( _storedUnits.get( unitType));
}
@Override
public int hashCode() {
return _access.hashCode() ^ _links.hashCode() ^
_storedUnits.hashCode();
}
@Override
public boolean equals( Object otherObject) {
if( !(otherObject instanceof PaintInfo))
return false;
PaintInfo otherPI = (PaintInfo) otherObject;
if( !_access.equals( otherPI._access))
return false;
if( !_links.equals( otherPI.getLinks()))
return false;
if( !_storedUnits.equals( otherPI._storedUnits))
return false;
return true;
}
}
/**
* Information about a particular NAS. A NAS is something like a
* poolgroup, but with the restriction that every pool is a member of
* precisely one NAS.
* <p>
* The partitioning of NAS is via store and dcache units that potentially
* select the pools.
*/
static private class NasInfo {
private final SpaceInfo _spaceInfo = new SpaceInfo();
private final Set<String> _pools = new HashSet<String>();
private PaintInfo _representativePaintInfo = null;
/**
* Add a pool to this NAS. If this is the first pool then the set of
* links store unit and dCache units is set. It is anticipated that
* any subsequent pools added to this NAS will have the same set of
* links (so, same set of store and dCache units). This is checked.
*
* @param poolId
* @param spaceInfo
* @param pInfo
*/
void addPool( String poolId, SpaceInfo spaceInfo, PaintInfo pInfo) {
_pools.add( poolId);
_spaceInfo.add( spaceInfo);
if( _representativePaintInfo == null)
_representativePaintInfo = pInfo;
else if( !_representativePaintInfo.equals( pInfo))
throw new RuntimeException(
"Adding pool " +
poolId +
" with differeing paintInfo from first pool " +
_representativePaintInfo.getPoolId());
}
/**
* Report a NAS' overall storage information.
*
* @return
*/
SpaceInfo getSpaceInfo() {
return _spaceInfo;
}
/**
* Discover all links that refer to a NAS
*
* @return
*/
Set<String> getLinks() {
return _representativePaintInfo.getLinks();
}
/**
* Discover whether any of the pools given in the Set of poolIDs has
* been registered as part of this NAS.
*
* @param pools the Set of PoolIDs
* @return true if at least one member of the provided Set is a
* member of this NAS.
*/
boolean havePoolInSet( Set<String> pools) {
return !Collections.disjoint( pools, _pools);
}
/**
* Add a set of metrics for this NAS
*
* @param update
*/
void addMetrics( StateUpdate update, String nasName) {
StatePath thisNasPath = NAS_PATH.newChild( nasName);
// Add a list of pools in this NAS
StatePath thisNasPoolsPath = thisNasPath.newChild( "pools");
update.appendUpdateCollection( thisNasPoolsPath, _pools, true);
// Add the space information
_spaceInfo.addMetrics( update, thisNasPath.newChild( "space"), true);
// Add the list of links
StatePath thisNasLinksPath = thisNasPath.newChild( "links");
update.appendUpdateCollection( thisNasLinksPath,
_representativePaintInfo.getLinks(),
true);
// Add the units information
StatePath thisNasUnitsPath = thisNasPath.newChild( "units");
for( LinkInfo.UNIT_TYPE type : PaintInfo.CONSIDERED_UNIT_TYPES) {
Map<LinkInfo.OPERATION, Set<String>> unitsMap =
_representativePaintInfo.getUnits( type);
if( unitsMap == null) {
_log.error( "A considered unit-type query to getUnits() gave null reply. This is unexpected.");
continue;
}
if( !UNIT_TYPE_STORAGE_NAME.containsKey( type)) {
_log.error( "Unmapped unit type " + type);
continue;
}
StatePath thisNasUnitTypePath =
thisNasUnitsPath.newChild( UNIT_TYPE_STORAGE_NAME.get( type));
for( Map.Entry<LinkInfo.OPERATION, Set<String>> entry : unitsMap.entrySet()) {
LinkInfo.OPERATION operation = entry.getKey();
Set<String> units = entry.getValue();
if( !OPERATION_STORAGE_NAME.containsKey( operation)) {
_log.error( "Unmapped operation " + operation);
continue;
}
update.appendUpdateCollection(
thisNasUnitTypePath.newChild( OPERATION_STORAGE_NAME.get( operation)),
units, true);
}
}
}
}
private final StateExhibitor _exhibitor;
/**
* Create a new secondary information provider that uses the provided
* StateExhibitor to query the current and future dCache state.
*
* @param exhibitor
*/
public NormalisedAccessSpaceMaintainer( StateExhibitor exhibitor) {
_exhibitor = exhibitor;
}
@Override
protected String[] getPredicates() {
return PREDICATE_PATHS;
}
@Override
public void trigger( StateTransition transition, StateUpdate update) {
Map<String, LinkInfo> currentLinks =
LinkInfoVisitor.getDetails( _exhibitor);
Map<String, LinkInfo> futureLinks =
LinkInfoVisitor.getDetails( _exhibitor, transition);
Map<String, SpaceInfo> currentPools =
PoolSpaceVisitor.getDetails( _exhibitor);
Map<String, SpaceInfo> futurePools =
PoolSpaceVisitor.getDetails( _exhibitor, transition);
buildUpdate( update, currentPools, futurePools, currentLinks,
futureLinks);
}
/**
* Build a mapping of NasInfo objects.
*
* @param links
*/
private Map<String, NasInfo> buildNas(
Map<String, SpaceInfo> poolSpaceInfo,
Map<String, LinkInfo> links) {
// Build initially "white" (unpainted) set of paint info.
Map<String, PaintInfo> paintedPools = new HashMap<String, PaintInfo>();
for( String poolId : poolSpaceInfo.keySet())
paintedPools.put( poolId, new PaintInfo( poolId));
// For each link in dCache and for each pool accessible via this link
// build the paint info.
for( LinkInfo linkInfo : links.values()) {
for( String linkPool : linkInfo.getPools()) {
PaintInfo poolPaintInfo = paintedPools.get( linkPool);
- // Check for an inconsistency bug. Report it and work around
- // the issue.
+ /*
+ * It is possible that a pool is accessible from a link yet
+ * no such pool is known; for example, as the info service is
+ * "booting up". We work-around this issue by creating a new
+ * PaintInfo for for this pool.
+ */
if( poolPaintInfo == null) {
- _log.warn( "Inconsistency in information: pool " +
- linkPool + " accessable via link " +
+ _log.debug( "Inconsistency in information: pool " +
+ linkPool + " accessible via link " +
linkInfo.getId() +
- " but not present under poolspace ");
+ " but not present as a pool");
poolPaintInfo = new PaintInfo( linkPool);
paintedPools.put( linkPool, poolPaintInfo);
}
poolPaintInfo.addAccess( linkInfo);
}
}
// Build the set of NAS by iterating over all paint information (so,
// iterating over all pools)
Map<String, NasInfo> nas = new HashMap<String, NasInfo>();
for( Map.Entry<String, PaintInfo> paintEntry : paintedPools.entrySet()) {
PaintInfo poolPaintInfo = paintEntry.getValue();
String poolId = paintEntry.getKey();
String nasName = poolPaintInfo.getNasName();
NasInfo _thisNas;
if( !nas.containsKey( nasName)) {
_thisNas = new NasInfo();
nas.put( nasName, _thisNas);
} else {
_thisNas = nas.get( nasName);
}
_thisNas.addPool( poolId, poolSpaceInfo.get( poolId), poolPaintInfo);
}
return nas;
}
/**
* Build a StateUpdate with the metrics that need to be updated.
*
* @param update
* @param existingLinks
* @param futureLinks
*/
private StateUpdate buildUpdate( StateUpdate update,
Map<String, SpaceInfo> currentPools,
Map<String, SpaceInfo> futurePools,
Map<String, LinkInfo> currentLinks,
Map<String, LinkInfo> futureLinks) {
boolean buildAll = false;
Set<String> alteredPools = null;
Map<String, NasInfo> nas = buildNas( futurePools, futureLinks);
/**
* If the link structure has changed then we know that there may be
* NAS that are no longer valid. To keep things simple, we invalidate
* all stored NAS information and repopulate everything.
*/
if( !currentLinks.equals( futureLinks)) {
update.purgeUnder( NAS_PATH);
buildAll = true;
} else {
/**
* If the structure is the same, then we only need to update NAS
* that contain a pool that has changed a space metric
*/
alteredPools =
identifyPoolsThatHaveChanged( currentPools, futurePools);
}
// Add those NAS that have changed, or all of them if buildAll is set
for( Map.Entry<String, NasInfo> e : nas.entrySet()) {
String nasName = e.getKey();
NasInfo nasInfo = e.getValue();
if( buildAll || nasInfo.havePoolInSet( alteredPools))
nasInfo.addMetrics( update, nasName);
}
return update;
}
/**
* Build up a Set of pools that have altered; either pools that have been
* added, that have been removed or have changed their details. More
* succinctly, this is:
*
* <pre>
* (currentPools \ futurePools) U (futurePools \ currentPools)
* </pre>
*
* where the sets here are each Map's Map.EntrySet.
*
* @param currentPools Map between poolID and corresponding SpaceInfo for
* current pools
* @param futurePools Map between poolID and corresponding SpaceInfo for
* future pools
* @return a Set of poolIDs for pools that have, in some way, changed.
*/
private Set<String> identifyPoolsThatHaveChanged(
Map<String, SpaceInfo> currentPools,
Map<String, SpaceInfo> futurePools) {
Set<String> alteredPools = new HashSet<String>();
Set<Map.Entry<String, SpaceInfo>> d1 =
new HashSet<Map.Entry<String, SpaceInfo>>(
currentPools.entrySet());
Set<Map.Entry<String, SpaceInfo>> d2 =
new HashSet<Map.Entry<String, SpaceInfo>>(
futurePools.entrySet());
d1.removeAll( futurePools.entrySet());
d2.removeAll( currentPools.entrySet());
for( Map.Entry<String, SpaceInfo> e : d1)
alteredPools.add( e.getKey());
for( Map.Entry<String, SpaceInfo> e : d2)
alteredPools.add( e.getKey());
return alteredPools;
}
}
| false | true | private Map<String, NasInfo> buildNas(
Map<String, SpaceInfo> poolSpaceInfo,
Map<String, LinkInfo> links) {
// Build initially "white" (unpainted) set of paint info.
Map<String, PaintInfo> paintedPools = new HashMap<String, PaintInfo>();
for( String poolId : poolSpaceInfo.keySet())
paintedPools.put( poolId, new PaintInfo( poolId));
// For each link in dCache and for each pool accessible via this link
// build the paint info.
for( LinkInfo linkInfo : links.values()) {
for( String linkPool : linkInfo.getPools()) {
PaintInfo poolPaintInfo = paintedPools.get( linkPool);
// Check for an inconsistency bug. Report it and work around
// the issue.
if( poolPaintInfo == null) {
_log.warn( "Inconsistency in information: pool " +
linkPool + " accessable via link " +
linkInfo.getId() +
" but not present under poolspace ");
poolPaintInfo = new PaintInfo( linkPool);
paintedPools.put( linkPool, poolPaintInfo);
}
poolPaintInfo.addAccess( linkInfo);
}
}
// Build the set of NAS by iterating over all paint information (so,
// iterating over all pools)
Map<String, NasInfo> nas = new HashMap<String, NasInfo>();
for( Map.Entry<String, PaintInfo> paintEntry : paintedPools.entrySet()) {
PaintInfo poolPaintInfo = paintEntry.getValue();
String poolId = paintEntry.getKey();
String nasName = poolPaintInfo.getNasName();
NasInfo _thisNas;
if( !nas.containsKey( nasName)) {
_thisNas = new NasInfo();
nas.put( nasName, _thisNas);
} else {
_thisNas = nas.get( nasName);
}
_thisNas.addPool( poolId, poolSpaceInfo.get( poolId), poolPaintInfo);
}
return nas;
}
| private Map<String, NasInfo> buildNas(
Map<String, SpaceInfo> poolSpaceInfo,
Map<String, LinkInfo> links) {
// Build initially "white" (unpainted) set of paint info.
Map<String, PaintInfo> paintedPools = new HashMap<String, PaintInfo>();
for( String poolId : poolSpaceInfo.keySet())
paintedPools.put( poolId, new PaintInfo( poolId));
// For each link in dCache and for each pool accessible via this link
// build the paint info.
for( LinkInfo linkInfo : links.values()) {
for( String linkPool : linkInfo.getPools()) {
PaintInfo poolPaintInfo = paintedPools.get( linkPool);
/*
* It is possible that a pool is accessible from a link yet
* no such pool is known; for example, as the info service is
* "booting up". We work-around this issue by creating a new
* PaintInfo for for this pool.
*/
if( poolPaintInfo == null) {
_log.debug( "Inconsistency in information: pool " +
linkPool + " accessible via link " +
linkInfo.getId() +
" but not present as a pool");
poolPaintInfo = new PaintInfo( linkPool);
paintedPools.put( linkPool, poolPaintInfo);
}
poolPaintInfo.addAccess( linkInfo);
}
}
// Build the set of NAS by iterating over all paint information (so,
// iterating over all pools)
Map<String, NasInfo> nas = new HashMap<String, NasInfo>();
for( Map.Entry<String, PaintInfo> paintEntry : paintedPools.entrySet()) {
PaintInfo poolPaintInfo = paintEntry.getValue();
String poolId = paintEntry.getKey();
String nasName = poolPaintInfo.getNasName();
NasInfo _thisNas;
if( !nas.containsKey( nasName)) {
_thisNas = new NasInfo();
nas.put( nasName, _thisNas);
} else {
_thisNas = nas.get( nasName);
}
_thisNas.addPool( poolId, poolSpaceInfo.get( poolId), poolPaintInfo);
}
return nas;
}
|
diff --git a/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java b/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java
index 97cff83..afbc1f2 100644
--- a/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java
+++ b/src/org/apache/hadoop/hive/contrib/serde2/JsonSerde.java
@@ -1,269 +1,275 @@
/**
* JSON SerDe for Hive
*/
package org.apache.hadoop.hive.contrib.serde2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.serde.Constants;
import org.apache.hadoop.hive.serde2.SerDe;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.json.JSONException;
import org.json.JSONObject;
/**
* JSON SerDe for Hive
* <p>
* This SerDe can be used to read data in JSON format. For example, if your JSON
* files had the following contents:
*
* <pre>
* {"field1":"data1","field2":100,"field3":"more data1"}
* {"field1":"data2","field2":200,"field3":"more data2"}
* {"field1":"data3","field2":300,"field3":"more data3"}
* {"field1":"data4","field2":400,"field3":"more data4"}
* </pre>
*
* The following steps can be used to read this data:
* <ol>
* <li>Build this project using <code>ant build</code></li>
* <li>Copy <code>hive-json-serde.jar</code> to the Hive server</li>
* <li>Inside the Hive client, run
*
* <pre>
* ADD JAR /home/hadoop/hive-json-serde.jar;
* </pre>
*
* </li>
* <li>Create a table that uses files where each line is JSON object
*
* <pre>
* CREATE EXTERNAL TABLE IF NOT EXISTS my_table (
* field1 string, field2 int, field3 string
* )
* ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde'
* LOCATION '/my_data/my_table/';
* </pre>
*
* </li>
* <li>Copy your JSON files to <code>/my_data/my_table/</code>. You can now
* select data using normal SELECT statements
*
* <pre>
* SELECT * FROM my_table LIMIT 10;
* </pre>
*
* </li>
* </ol>
* <p>
* The table does not have to have the same columns as the JSON files, and
* vice-versa. If the table has a column that does not exist in the JSON object,
* it will have a NULL value. If the JSON file contains fields that are not
* columns in the table, they will be ignored and not visible to the table.
*
* @see <a href="http://code.google.com/p/hive-json-serde/">hive-json-serde on
* Google Code</a>
* @author Peter Sankauskas
*/
public class JsonSerde implements SerDe {
/**
* Apache commons logger
*/
private static final Log LOG = LogFactory.getLog(JsonSerde.class.getName());
/**
* The number of columns in the table this SerDe is being used with
*/
private int numColumns;
/**
* List of column names in the table
*/
private List<String> columnNames;
/**
* An ObjectInspector to be used as meta-data about a deserialized row
*/
private StructObjectInspector rowOI;
/**
* List of row objects
*/
private ArrayList<Object> row;
/**
* List of column type information
*/
private List<TypeInfo> columnTypes;
/**
* Initialize this SerDe with the system properties and table properties
*/
@Override
public void initialize(Configuration sysProps, Properties tblProps)
throws SerDeException {
LOG.debug("Initializing JsonSerde");
// Get the names of the columns for the table this SerDe is being used
// with
String columnNameProperty = tblProps
.getProperty(Constants.LIST_COLUMNS);
columnNames = Arrays.asList(columnNameProperty.split(","));
// Convert column types from text to TypeInfo objects
String columnTypeProperty = tblProps
.getProperty(Constants.LIST_COLUMN_TYPES);
columnTypes = TypeInfoUtils
.getTypeInfosFromTypeString(columnTypeProperty);
assert columnNames.size() == columnTypes.size();
numColumns = columnNames.size();
// Create ObjectInspectors from the type information for each column
List<ObjectInspector> columnOIs = new ArrayList<ObjectInspector>(
columnNames.size());
ObjectInspector oi;
for (int c = 0; c < numColumns; c++) {
oi = TypeInfoUtils
.getStandardJavaObjectInspectorFromTypeInfo(columnTypes
.get(c));
columnOIs.add(oi);
}
rowOI = ObjectInspectorFactory.getStandardStructObjectInspector(
columnNames, columnOIs);
// Create an empty row object to be reused during deserialization
row = new ArrayList<Object>(numColumns);
for (int c = 0; c < numColumns; c++) {
row.add(null);
}
LOG.debug("JsonSerde initialization complete");
}
/**
* Gets the ObjectInspector for a row deserialized by this SerDe
*/
@Override
public ObjectInspector getObjectInspector() throws SerDeException {
return rowOI;
}
/**
* Deserialize a JSON Object into a row for the table
*/
@Override
public Object deserialize(Writable blob) throws SerDeException {
Text rowText = (Text) blob;
LOG.debug("Deserialize row: " + rowText.toString());
// Try parsing row into JSON object
JSONObject jObj;
try {
jObj = new JSONObject(rowText.toString()) {
/**
* In Hive column names are case insensitive, so lower-case all
* field names
*
* @see org.json.JSONObject#put(java.lang.String,
* java.lang.Object)
*/
@Override
public JSONObject put(String key, Object value)
throws JSONException {
return super.put(key.toLowerCase(), value);
}
};
} catch (JSONException e) {
// If row is not a JSON object, make the whole row NULL
LOG.error("Row is not a valid JSON Object - JSONException: "
+ e.getMessage());
return null;
}
// Loop over columns in table and set values
String colName;
Object value;
for (int c = 0; c < numColumns; c++) {
colName = columnNames.get(c);
TypeInfo ti = columnTypes.get(c);
try {
// Get type-safe JSON values
if (jObj.isNull(colName)) {
value = null;
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.DOUBLE_TYPE_NAME)) {
value = jObj.getDouble(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.BIGINT_TYPE_NAME)) {
value = jObj.getLong(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.INT_TYPE_NAME)) {
value = jObj.getInt(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.TINYINT_TYPE_NAME)) {
value = Byte.valueOf(jObj.getString(colName));
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.FLOAT_TYPE_NAME)) {
value = Float.valueOf(jObj.getString(colName));
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.BOOLEAN_TYPE_NAME)) {
value = jObj.getBoolean(colName);
+ } else if (ti.getTypeName().equalsIgnoreCase(
+ Constants.STRING_TYPE_NAME)
+ && jObj.get(colName) instanceof java.lang.Number) {
+ // Convert JSON numbers to strings to match the type of the
+ // column definition
+ value = jObj.getString(colName);
} else {
// Fall back, just get an object
value = jObj.get(colName);
}
} catch (JSONException e) {
// If the column cannot be found, just make it a NULL value and
// skip over it
if (LOG.isDebugEnabled()) {
LOG.debug("Column '" + colName + "' not found in row: "
+ rowText.toString() + " - JSONException: "
+ e.getMessage());
}
value = null;
}
row.set(c, value);
}
return row;
}
/**
* Not sure - something to do with serialization of data
*/
@Override
public Class<? extends Writable> getSerializedClass() {
return Text.class;
}
/**
* Serializes a row of data into a JSON object
*
* @todo Implement this - sorry!
*/
@Override
public Writable serialize(Object obj, ObjectInspector objInspector)
throws SerDeException {
LOG.info("-----------------------------");
LOG.info("--------- serialize ---------");
LOG.info("-----------------------------");
LOG.info(obj.toString());
LOG.info(objInspector.toString());
return null;
}
}
| true | true | public Object deserialize(Writable blob) throws SerDeException {
Text rowText = (Text) blob;
LOG.debug("Deserialize row: " + rowText.toString());
// Try parsing row into JSON object
JSONObject jObj;
try {
jObj = new JSONObject(rowText.toString()) {
/**
* In Hive column names are case insensitive, so lower-case all
* field names
*
* @see org.json.JSONObject#put(java.lang.String,
* java.lang.Object)
*/
@Override
public JSONObject put(String key, Object value)
throws JSONException {
return super.put(key.toLowerCase(), value);
}
};
} catch (JSONException e) {
// If row is not a JSON object, make the whole row NULL
LOG.error("Row is not a valid JSON Object - JSONException: "
+ e.getMessage());
return null;
}
// Loop over columns in table and set values
String colName;
Object value;
for (int c = 0; c < numColumns; c++) {
colName = columnNames.get(c);
TypeInfo ti = columnTypes.get(c);
try {
// Get type-safe JSON values
if (jObj.isNull(colName)) {
value = null;
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.DOUBLE_TYPE_NAME)) {
value = jObj.getDouble(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.BIGINT_TYPE_NAME)) {
value = jObj.getLong(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.INT_TYPE_NAME)) {
value = jObj.getInt(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.TINYINT_TYPE_NAME)) {
value = Byte.valueOf(jObj.getString(colName));
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.FLOAT_TYPE_NAME)) {
value = Float.valueOf(jObj.getString(colName));
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.BOOLEAN_TYPE_NAME)) {
value = jObj.getBoolean(colName);
} else {
// Fall back, just get an object
value = jObj.get(colName);
}
} catch (JSONException e) {
// If the column cannot be found, just make it a NULL value and
// skip over it
if (LOG.isDebugEnabled()) {
LOG.debug("Column '" + colName + "' not found in row: "
+ rowText.toString() + " - JSONException: "
+ e.getMessage());
}
value = null;
}
row.set(c, value);
}
return row;
}
| public Object deserialize(Writable blob) throws SerDeException {
Text rowText = (Text) blob;
LOG.debug("Deserialize row: " + rowText.toString());
// Try parsing row into JSON object
JSONObject jObj;
try {
jObj = new JSONObject(rowText.toString()) {
/**
* In Hive column names are case insensitive, so lower-case all
* field names
*
* @see org.json.JSONObject#put(java.lang.String,
* java.lang.Object)
*/
@Override
public JSONObject put(String key, Object value)
throws JSONException {
return super.put(key.toLowerCase(), value);
}
};
} catch (JSONException e) {
// If row is not a JSON object, make the whole row NULL
LOG.error("Row is not a valid JSON Object - JSONException: "
+ e.getMessage());
return null;
}
// Loop over columns in table and set values
String colName;
Object value;
for (int c = 0; c < numColumns; c++) {
colName = columnNames.get(c);
TypeInfo ti = columnTypes.get(c);
try {
// Get type-safe JSON values
if (jObj.isNull(colName)) {
value = null;
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.DOUBLE_TYPE_NAME)) {
value = jObj.getDouble(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.BIGINT_TYPE_NAME)) {
value = jObj.getLong(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.INT_TYPE_NAME)) {
value = jObj.getInt(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.TINYINT_TYPE_NAME)) {
value = Byte.valueOf(jObj.getString(colName));
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.FLOAT_TYPE_NAME)) {
value = Float.valueOf(jObj.getString(colName));
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.BOOLEAN_TYPE_NAME)) {
value = jObj.getBoolean(colName);
} else if (ti.getTypeName().equalsIgnoreCase(
Constants.STRING_TYPE_NAME)
&& jObj.get(colName) instanceof java.lang.Number) {
// Convert JSON numbers to strings to match the type of the
// column definition
value = jObj.getString(colName);
} else {
// Fall back, just get an object
value = jObj.get(colName);
}
} catch (JSONException e) {
// If the column cannot be found, just make it a NULL value and
// skip over it
if (LOG.isDebugEnabled()) {
LOG.debug("Column '" + colName + "' not found in row: "
+ rowText.toString() + " - JSONException: "
+ e.getMessage());
}
value = null;
}
row.set(c, value);
}
return row;
}
|
diff --git a/src/tv/studer/smssync/SmsSyncService.java b/src/tv/studer/smssync/SmsSyncService.java
index 68773ee..f1dba05 100755
--- a/src/tv/studer/smssync/SmsSyncService.java
+++ b/src/tv/studer/smssync/SmsSyncService.java
@@ -1,542 +1,541 @@
/* Copyright (c) 2009 Christoph Studer <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.studer.smssync;
import java.net.URLEncoder;
import java.util.List;
import tv.studer.smssync.CursorToMessage.ConversionResult;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.Process;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import com.android.email.mail.Folder;
import com.android.email.mail.Message;
import com.android.email.mail.MessagingException;
import com.android.email.mail.Folder.FolderType;
import com.android.email.mail.Folder.OpenMode;
import com.android.email.mail.store.ImapStore;
public class SmsSyncService extends Service {
/** Number of messages sent per sync request. */
private static final int MAX_MSG_PER_REQUEST = 1;
/** Flag indicating whether this service is already running. */
// Should this be split into sIsRunning and sIsWorking? One for the
// service, the other for the actual backing up?
private static boolean sIsRunning = false;
// State information
/** Current state. See {@link #getState()}. */
private static SmsSyncState sState = SmsSyncState.IDLE;
/**
* Number of messages that currently need a sync. Only valid when sState ==
* SYNC.
*/
private static int sItemsToSync;
/**
* Number of messages already synced during this cycle. Only valid when
* sState == SYNC.
*/
private static int sCurrentSyncedItems;
/**
* Field containing a description of the last error. See
* {@link #getErrorDescription()}.
*/
private static String sLastError;
/**
* This {@link StateChangeListener} is notified whenever {@link #sState} is
* updated.
*/
private static StateChangeListener sStateChangeListener;
/**
* A wakelock held while this service is working.
*/
private static WakeLock sWakeLock;
/**
* A wifilock held while this service is working.
*/
private static WifiLock sWifiLock;
/**
* Indicates that the user canceled the current backup and that this service
* should finish working ASAP.
*/
private static boolean sCanceled;
public enum SmsSyncState {
IDLE, CALC, LOGIN, SYNC, AUTH_FAILED, GENERAL_ERROR, CANCELED;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
private static void acquireWakeLock(Context ctx) {
if (sWakeLock == null) {
PowerManager pMgr = (PowerManager) ctx.getSystemService(POWER_SERVICE);
sWakeLock = pMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"SmsSyncService.sync() wakelock.");
WifiManager wMgr = (WifiManager) ctx.getSystemService(WIFI_SERVICE);
sWifiLock = wMgr.createWifiLock("SMS Backup");
}
sWakeLock.acquire();
sWifiLock.acquire();
}
private static void releaseWakeLock(Context ctx) {
sWakeLock.release();
sWifiLock.release();
}
@Override
//TODO(chstuder): Clean this flow up a bit and split it into multiple
// methods. Make clean distinction between onStart(...) and backup(...).
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
synchronized (this.getClass()) {
// Only start a sync if there's no other sync going on at this time.
if (!sIsRunning) {
acquireWakeLock(this);
sIsRunning = true;
// Start sync in new thread.
new Thread() {
public void run() {
// Lower thread priority a little. We're not the UI.
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
try {
// On first sync we need to know whether to skip or
// sync current messages.
if (PrefStore.isFirstSync(SmsSyncService.this)
&& !intent.hasExtra(Consts.KEY_SKIP_MESSAGES)) {
throw new GeneralErrorException(SmsSyncService.this,
R.string.err_first_sync_needs_skip_flag, null);
}
boolean skipMessages = intent.getBooleanExtra(Consts.KEY_SKIP_MESSAGES,
false);
int numRetries = intent.getIntExtra(Consts.KEY_NUM_RETRIES, 0);
GeneralErrorException lastException = null;
// Try sync numRetries + 1 times.
while (numRetries >= 0) {
try {
backup(skipMessages);
break;
} catch (GeneralErrorException e) {
Log.w(Consts.TAG, e.getMessage());
Log.i(Consts.TAG, "Retrying sync in 2 seconds. (" + (numRetries - 1) + ")");
lastException = e;
if (numRetries > 1) {
try {
Thread.sleep(2000);
} catch (InterruptedException e1) { /* ignore */ }
}
}
numRetries--;
}
if (lastException != null) {
throw lastException;
}
} catch (GeneralErrorException e) {
Log.i(Consts.TAG, "", e);
sLastError = e.getLocalizedMessage();
updateState(SmsSyncState.GENERAL_ERROR);
} catch (AuthenticationErrorException e) {
Log.i(Consts.TAG, "", e);
sLastError = e.getLocalizedMessage();
updateState(SmsSyncState.AUTH_FAILED);
} finally {
stopSelf();
Alarms.scheduleRegularSync(SmsSyncService.this);
sIsRunning = false;
releaseWakeLock(SmsSyncService.this);
}
}
}.start();
} else {
Log.d(Consts.TAG, "SmsSyncService.onStart(): Already running.");
}
}
}
/**
* <p>
* This is the main method that defines the general flow for a
* synchronization.
* </p>
* <h2>Typical flow</h2>
* <p>
* This is a typical sync flow (for <code>skipMessages == false</code>):
* </p>
* <ol>
* <li>{@link SmsSyncState#CALC}: The list of messages requiring a sync is
* determined. This is done by querying the SMS content provider for
* messages with
* <code>ID > {@link #getMaxSyncedDate()} AND type != {@link #MESSAGE_TYPE_DRAFT}</code>
* .</li>
* <li>{@link SmsSyncState#LOGIN}: An SSL connection is opened to the Gmail IMAP
* server using the user provided credentials.</li>
* <li>{@link SmsSyncState#SYNC}: The messages determined in step #1 are
* sent to the server, possibly in chunks of a maximum of
* {@link #MAX_MSG_PER_REQUEST} per request. After each successful sync
* request, the maximum ID of synced messages is updated such that future
* syncs will skip.</li>
* <li>{@link SmsSyncState#CANCELED}: If {@link #cancel()} was called during
* backup, the backup will stop at the next possible occasion.</li>
* </ol>
*
* <h2>Preconditions</h2>
* <p>
* This method requires the login information to be set. If either username
* or password are unset, a {@link GeneralErrorException} is thrown.
* </p>
*
* <h2>Sync or skip?</h2>
* <p>
* <code>skipMessages</code>: If this parameter is <code>true</code>, all
* current messages stored on the device are skipped and marked as "synced".
* Future backups will ignore these messages and only messages arrived
* afterwards will be sent to the server.
* </p>
*
* @param skipMessages whether to skip all messages on this device.
* @throws GeneralErrorException Thrown when there there was an error during
* sync.
*/
private void backup(boolean skipMessages) throws GeneralErrorException,
AuthenticationErrorException {
Log.i(Consts.TAG, "Starting backup...");
sCanceled = false;
if (!PrefStore.isLoginInformationSet(this)) {
throw new GeneralErrorException(this, R.string.err_sync_requires_login_info, null);
}
String username = PrefStore.getLoginUsername(this);
String password = PrefStore.getLoginPassword(this);
updateState(SmsSyncState.CALC);
sItemsToSync = 0;
sCurrentSyncedItems = 0;
if (skipMessages) {
// Only update the max synced ID, do not really sync.
updateMaxSyncedDate(getMaxItemDate());
PrefStore.setLastSync(this);
sItemsToSync = 0;
sCurrentSyncedItems = 0;
updateState(SmsSyncState.IDLE);
Log.i(Consts.TAG, "All messages skipped.");
return;
}
Cursor items = getItemsToSync();
int maxItemsPerSync = PrefStore.getMaxItemsPerSync(this);
sItemsToSync = Math.min(items.getCount(), maxItemsPerSync);
Log.d(Consts.TAG, "Total messages to backup: " + sItemsToSync);
if (sItemsToSync == 0) {
PrefStore.setLastSync(this);
if (PrefStore.isFirstSync(this)) {
// If this is the first backup we need to write something to PREF_MAX_SYNCED_DATE
// such that we know that we've performed a backup before.
PrefStore.setMaxSyncedDate(this, PrefStore.DEFAULT_MAX_SYNCED_DATE);
}
updateState(SmsSyncState.IDLE);
Log.d(Consts.TAG, "Nothing to do.");
return;
}
updateState(SmsSyncState.LOGIN);
ImapStore imapStore;
Folder folder;
boolean folderExists;
String label = PrefStore.getImapFolder(this);
try {
imapStore = new ImapStore(String.format(Consts.IMAP_URI, URLEncoder.encode(username),
URLEncoder.encode(password).replace("+", "%20")));
folder = imapStore.getFolder(label);
folderExists = folder.exists();
if (!folderExists) {
Log.i(Consts.TAG, "Label '" + label + "' does not exist yet. Creating.");
folder.create(FolderType.HOLDS_MESSAGES);
}
folder.open(OpenMode.READ_WRITE);
} catch (MessagingException e) {
throw new AuthenticationErrorException(e);
}
CursorToMessage converter = new CursorToMessage(this, username);
- while (true) {
- try {
+ try {
+ while (true) {
// Cancel sync if requested by the user.
if (sCanceled) {
Log.i(Consts.TAG, "Backup canceled by user.");
updateState(SmsSyncState.CANCELED);
break;
}
updateState(SmsSyncState.SYNC);
ConversionResult result = converter.cursorToMessageArray(items,
MAX_MSG_PER_REQUEST);
List<Message> messages = result.messageList;
// Stop the sync if all items where uploaded or if the maximum number
// of messages per sync was uploaded.
if (messages.size() == 0
|| sCurrentSyncedItems >= maxItemsPerSync) {
Log.i(Consts.TAG, "Sync done: " + sCurrentSyncedItems + " items uploaded.");
PrefStore.setLastSync(SmsSyncService.this);
updateState(SmsSyncState.IDLE);
folder.close(true);
break;
}
Log.d(Consts.TAG, "Sending " + messages.size() + " messages to server.");
folder.appendMessages(messages.toArray(new Message[messages.size()]));
sCurrentSyncedItems += messages.size();
updateState(SmsSyncState.SYNC);
updateMaxSyncedDate(result.maxDate);
result = null;
messages = null;
- } catch (MessagingException e) {
- throw new GeneralErrorException(this, R.string.err_communication_error, e);
- } finally {
- // Close the cursor
- items.close();
}
+ } catch (MessagingException e) {
+ throw new GeneralErrorException(this, R.string.err_communication_error, e);
+ } finally {
+ items.close();
}
}
/**
* Returns a cursor of SMS messages that have not yet been synced with the
* server. This includes all messages with
* <code>date < {@link #getMaxSyncedDate()}</code> which are no drafs.
*/
private Cursor getItemsToSync() {
ContentResolver r = getContentResolver();
String selection = String.format("%s > ? AND %s <> ?",
SmsConsts.DATE, SmsConsts.TYPE);
String[] selectionArgs = new String[] {
String.valueOf(getMaxSyncedDate()), String.valueOf(SmsConsts.MESSAGE_TYPE_DRAFT)
};
String sortOrder = SmsConsts.DATE + " LIMIT " + PrefStore.getMaxItemsPerSync(this);
return r.query(Uri.parse("content://sms"), null, selection, selectionArgs, sortOrder);
}
/**
* Returns the maximum date of all SMS messages (except for drafts).
*/
private long getMaxItemDate() {
ContentResolver r = getContentResolver();
String selection = SmsConsts.TYPE + " <> ?";
String[] selectionArgs = new String[] {
String.valueOf(SmsConsts.MESSAGE_TYPE_DRAFT)
};
String[] projection = new String[] {
SmsConsts.DATE
};
Cursor result = r.query(Uri.parse("content://sms"), projection, selection, selectionArgs,
SmsConsts.DATE + " DESC LIMIT 1");
try
{
if (result.moveToFirst()) {
return result.getLong(0);
} else {
return PrefStore.DEFAULT_MAX_SYNCED_DATE;
}
}
catch (RuntimeException e)
{
result.close();
throw e;
}
}
/**
* Returns the largest date of all messages that have successfully been synced
* with the server.
*/
private long getMaxSyncedDate() {
return PrefStore.getMaxSyncedDate(this);
}
/**
* Persists the provided ID so it can later on be retrieved using
* {@link #getMaxSyncedDate()}. This should be called when after each
* successful sync request to a server.
*
* @param maxSyncedId
*/
private void updateMaxSyncedDate(long maxSyncedDate) {
PrefStore.setMaxSyncedDate(this, maxSyncedDate);
Log.d(Consts.TAG, "Max synced date set to: " + maxSyncedDate);
}
// Actions available from other classes.
/**
* Cancels the current ongoing backup.
*
* TODO(chstuder): Clean up this interface a bit. It's strange the backup is
* started by an intent but canceling is done through a static method.
*
* But all other alternatives seem strange too. An intent just to cancel a backup?
*/
static void cancel() {
if (SmsSyncService.sIsRunning) {
SmsSyncService.sCanceled = true;
}
}
// Statistics accessible from other classes.
/**
* Returns whether there is currently a backup going on or not.
*
*/
static boolean isWorking() {
return sIsRunning;
}
/**
* Returns the current state of the service. Also see
* {@link #setStateChangeListener(StateChangeListener)} to get notified when
* the state changes.
*/
static SmsSyncState getState() {
return sState;
}
/**
* Returns a description of the last error. Only valid if
* <code>{@link #getState()} == {@link SmsSyncState#GENERAL_ERROR}</code>.
*/
static String getErrorDescription() {
return (sState == SmsSyncState.GENERAL_ERROR) ? sLastError : null;
}
/**
* Returns the number of messages that require sync during the current
* cycle.
*/
static int getItemsToSyncCount() {
return sItemsToSync;
}
/**
* Returns the number of already synced messages during the current cycle.
*/
static int getCurrentSyncedItems() {
return sCurrentSyncedItems;
}
/**
* Registers a {@link StateChangeListener} that is notified whenever the
* state of the service changes. Note that at most one listener can be
* registered and you need to call {@link #unsetStateChangeListener()} in
* between calls to this method.
*
* @see #getState()
* @see #unsetStateChangeListener()
*/
static void setStateChangeListener(StateChangeListener listener) {
if (sStateChangeListener != null) {
throw new IllegalStateException("setStateChangeListener(...) called when there"
+ " was still some other listener "
+ "registered. Use unsetStateChangeListener() first.");
}
sStateChangeListener = listener;
}
/**
* Unregisters the currently registered {@link StateChangeListener}.
*
* @see #setStateChangeListener(StateChangeListener)
*/
static void unsetStateChangeListener() {
sStateChangeListener = null;
}
/**
* Internal method that needs to be called whenever the state of the service
* changes.
*/
private static void updateState(SmsSyncState newState) {
SmsSyncState old = sState;
sState = newState;
if (sStateChangeListener != null) {
sStateChangeListener.stateChanged(old, newState);
}
}
/**
* A state change listener interface that provides a callback that is called
* whenever the state of the {@link SmsSyncService} changes.
*
* @see SmsSyncService#setStateChangeListener(StateChangeListener)
*/
public interface StateChangeListener {
/**
* Called whenever the sync state of the service changed.
*/
public void stateChanged(SmsSyncState oldState, SmsSyncState newState);
}
/**
* Exception indicating an error while synchronizing.
*/
public static class GeneralErrorException extends Exception {
private static final long serialVersionUID = 1L;
public GeneralErrorException(String msg, Throwable t) {
super(msg, t);
}
public GeneralErrorException(Context ctx, int msgId, Throwable t) {
super(ctx.getString(msgId), t);
}
}
public static class AuthenticationErrorException extends Exception {
private static final long serialVersionUID = 1L;
public AuthenticationErrorException(Throwable t) {
super(t.getLocalizedMessage(), t);
}
}
}
| false | true | private void backup(boolean skipMessages) throws GeneralErrorException,
AuthenticationErrorException {
Log.i(Consts.TAG, "Starting backup...");
sCanceled = false;
if (!PrefStore.isLoginInformationSet(this)) {
throw new GeneralErrorException(this, R.string.err_sync_requires_login_info, null);
}
String username = PrefStore.getLoginUsername(this);
String password = PrefStore.getLoginPassword(this);
updateState(SmsSyncState.CALC);
sItemsToSync = 0;
sCurrentSyncedItems = 0;
if (skipMessages) {
// Only update the max synced ID, do not really sync.
updateMaxSyncedDate(getMaxItemDate());
PrefStore.setLastSync(this);
sItemsToSync = 0;
sCurrentSyncedItems = 0;
updateState(SmsSyncState.IDLE);
Log.i(Consts.TAG, "All messages skipped.");
return;
}
Cursor items = getItemsToSync();
int maxItemsPerSync = PrefStore.getMaxItemsPerSync(this);
sItemsToSync = Math.min(items.getCount(), maxItemsPerSync);
Log.d(Consts.TAG, "Total messages to backup: " + sItemsToSync);
if (sItemsToSync == 0) {
PrefStore.setLastSync(this);
if (PrefStore.isFirstSync(this)) {
// If this is the first backup we need to write something to PREF_MAX_SYNCED_DATE
// such that we know that we've performed a backup before.
PrefStore.setMaxSyncedDate(this, PrefStore.DEFAULT_MAX_SYNCED_DATE);
}
updateState(SmsSyncState.IDLE);
Log.d(Consts.TAG, "Nothing to do.");
return;
}
updateState(SmsSyncState.LOGIN);
ImapStore imapStore;
Folder folder;
boolean folderExists;
String label = PrefStore.getImapFolder(this);
try {
imapStore = new ImapStore(String.format(Consts.IMAP_URI, URLEncoder.encode(username),
URLEncoder.encode(password).replace("+", "%20")));
folder = imapStore.getFolder(label);
folderExists = folder.exists();
if (!folderExists) {
Log.i(Consts.TAG, "Label '" + label + "' does not exist yet. Creating.");
folder.create(FolderType.HOLDS_MESSAGES);
}
folder.open(OpenMode.READ_WRITE);
} catch (MessagingException e) {
throw new AuthenticationErrorException(e);
}
CursorToMessage converter = new CursorToMessage(this, username);
while (true) {
try {
// Cancel sync if requested by the user.
if (sCanceled) {
Log.i(Consts.TAG, "Backup canceled by user.");
updateState(SmsSyncState.CANCELED);
break;
}
updateState(SmsSyncState.SYNC);
ConversionResult result = converter.cursorToMessageArray(items,
MAX_MSG_PER_REQUEST);
List<Message> messages = result.messageList;
// Stop the sync if all items where uploaded or if the maximum number
// of messages per sync was uploaded.
if (messages.size() == 0
|| sCurrentSyncedItems >= maxItemsPerSync) {
Log.i(Consts.TAG, "Sync done: " + sCurrentSyncedItems + " items uploaded.");
PrefStore.setLastSync(SmsSyncService.this);
updateState(SmsSyncState.IDLE);
folder.close(true);
break;
}
Log.d(Consts.TAG, "Sending " + messages.size() + " messages to server.");
folder.appendMessages(messages.toArray(new Message[messages.size()]));
sCurrentSyncedItems += messages.size();
updateState(SmsSyncState.SYNC);
updateMaxSyncedDate(result.maxDate);
result = null;
messages = null;
} catch (MessagingException e) {
throw new GeneralErrorException(this, R.string.err_communication_error, e);
} finally {
// Close the cursor
items.close();
}
}
}
| private void backup(boolean skipMessages) throws GeneralErrorException,
AuthenticationErrorException {
Log.i(Consts.TAG, "Starting backup...");
sCanceled = false;
if (!PrefStore.isLoginInformationSet(this)) {
throw new GeneralErrorException(this, R.string.err_sync_requires_login_info, null);
}
String username = PrefStore.getLoginUsername(this);
String password = PrefStore.getLoginPassword(this);
updateState(SmsSyncState.CALC);
sItemsToSync = 0;
sCurrentSyncedItems = 0;
if (skipMessages) {
// Only update the max synced ID, do not really sync.
updateMaxSyncedDate(getMaxItemDate());
PrefStore.setLastSync(this);
sItemsToSync = 0;
sCurrentSyncedItems = 0;
updateState(SmsSyncState.IDLE);
Log.i(Consts.TAG, "All messages skipped.");
return;
}
Cursor items = getItemsToSync();
int maxItemsPerSync = PrefStore.getMaxItemsPerSync(this);
sItemsToSync = Math.min(items.getCount(), maxItemsPerSync);
Log.d(Consts.TAG, "Total messages to backup: " + sItemsToSync);
if (sItemsToSync == 0) {
PrefStore.setLastSync(this);
if (PrefStore.isFirstSync(this)) {
// If this is the first backup we need to write something to PREF_MAX_SYNCED_DATE
// such that we know that we've performed a backup before.
PrefStore.setMaxSyncedDate(this, PrefStore.DEFAULT_MAX_SYNCED_DATE);
}
updateState(SmsSyncState.IDLE);
Log.d(Consts.TAG, "Nothing to do.");
return;
}
updateState(SmsSyncState.LOGIN);
ImapStore imapStore;
Folder folder;
boolean folderExists;
String label = PrefStore.getImapFolder(this);
try {
imapStore = new ImapStore(String.format(Consts.IMAP_URI, URLEncoder.encode(username),
URLEncoder.encode(password).replace("+", "%20")));
folder = imapStore.getFolder(label);
folderExists = folder.exists();
if (!folderExists) {
Log.i(Consts.TAG, "Label '" + label + "' does not exist yet. Creating.");
folder.create(FolderType.HOLDS_MESSAGES);
}
folder.open(OpenMode.READ_WRITE);
} catch (MessagingException e) {
throw new AuthenticationErrorException(e);
}
CursorToMessage converter = new CursorToMessage(this, username);
try {
while (true) {
// Cancel sync if requested by the user.
if (sCanceled) {
Log.i(Consts.TAG, "Backup canceled by user.");
updateState(SmsSyncState.CANCELED);
break;
}
updateState(SmsSyncState.SYNC);
ConversionResult result = converter.cursorToMessageArray(items,
MAX_MSG_PER_REQUEST);
List<Message> messages = result.messageList;
// Stop the sync if all items where uploaded or if the maximum number
// of messages per sync was uploaded.
if (messages.size() == 0
|| sCurrentSyncedItems >= maxItemsPerSync) {
Log.i(Consts.TAG, "Sync done: " + sCurrentSyncedItems + " items uploaded.");
PrefStore.setLastSync(SmsSyncService.this);
updateState(SmsSyncState.IDLE);
folder.close(true);
break;
}
Log.d(Consts.TAG, "Sending " + messages.size() + " messages to server.");
folder.appendMessages(messages.toArray(new Message[messages.size()]));
sCurrentSyncedItems += messages.size();
updateState(SmsSyncState.SYNC);
updateMaxSyncedDate(result.maxDate);
result = null;
messages = null;
}
} catch (MessagingException e) {
throw new GeneralErrorException(this, R.string.err_communication_error, e);
} finally {
items.close();
}
}
|
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapPackerTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapPackerTest.java
index d4f936c4c..549ebf786 100644
--- a/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapPackerTest.java
+++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/PixmapPackerTest.java
@@ -1,53 +1,53 @@
package com.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.PixmapPacker;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.tests.utils.GdxTest;
public class PixmapPackerTest extends GdxTest {
OrthographicCamera camera;
SpriteBatch batch;
Texture texture;
TextureAtlas atlas;
@Override
public void create () {
batch = new SpriteBatch();
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
camera.update();
Pixmap pixmap1 = new Pixmap(Gdx.files.internal("data/badlogic.jpg"));
Pixmap pixmap2 = new Pixmap(Gdx.files.internal("data/wheel.png"));
Pixmap pixmap3 = new Pixmap(Gdx.files.internal("data/egg.png"));
- PixmapPacker packer = new PixmapPacker(512, 512, Format.RGBA8888, 2, true);
+ PixmapPacker packer = new PixmapPacker(1024, 1024, Format.RGBA8888, 2, true);
packer.pack("badlogic", pixmap1);
packer.pack("wheel", pixmap1);
packer.pack("egg", pixmap1);
atlas = packer.generateTextureAtlas(TextureFilter.Nearest, TextureFilter.Nearest, false);
Gdx.app.log("PixmaPackerTest", "Number of textures: " + atlas.getTextures().size());
}
@Override
public void render () {
}
@Override
public void dispose () {
}
}
| true | true | public void create () {
batch = new SpriteBatch();
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
camera.update();
Pixmap pixmap1 = new Pixmap(Gdx.files.internal("data/badlogic.jpg"));
Pixmap pixmap2 = new Pixmap(Gdx.files.internal("data/wheel.png"));
Pixmap pixmap3 = new Pixmap(Gdx.files.internal("data/egg.png"));
PixmapPacker packer = new PixmapPacker(512, 512, Format.RGBA8888, 2, true);
packer.pack("badlogic", pixmap1);
packer.pack("wheel", pixmap1);
packer.pack("egg", pixmap1);
atlas = packer.generateTextureAtlas(TextureFilter.Nearest, TextureFilter.Nearest, false);
Gdx.app.log("PixmaPackerTest", "Number of textures: " + atlas.getTextures().size());
}
| public void create () {
batch = new SpriteBatch();
camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
camera.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2, 0);
camera.update();
Pixmap pixmap1 = new Pixmap(Gdx.files.internal("data/badlogic.jpg"));
Pixmap pixmap2 = new Pixmap(Gdx.files.internal("data/wheel.png"));
Pixmap pixmap3 = new Pixmap(Gdx.files.internal("data/egg.png"));
PixmapPacker packer = new PixmapPacker(1024, 1024, Format.RGBA8888, 2, true);
packer.pack("badlogic", pixmap1);
packer.pack("wheel", pixmap1);
packer.pack("egg", pixmap1);
atlas = packer.generateTextureAtlas(TextureFilter.Nearest, TextureFilter.Nearest, false);
Gdx.app.log("PixmaPackerTest", "Number of textures: " + atlas.getTextures().size());
}
|
diff --git a/support/src/main/java/org/ibeans/impl/LogResponsesInterceptor.java b/support/src/main/java/org/ibeans/impl/LogResponsesInterceptor.java
index bacb8eb..ec2875c 100644
--- a/support/src/main/java/org/ibeans/impl/LogResponsesInterceptor.java
+++ b/support/src/main/java/org/ibeans/impl/LogResponsesInterceptor.java
@@ -1,203 +1,217 @@
/*
* $Id$
* -------------------------------------------------------------------------------------
* Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.ibeans.impl;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.ibeans.api.channel.MimeType;
import org.ibeans.api.AbstractCallInterceptor;
import org.ibeans.api.InvocationContext;
import org.ibeans.api.Response;
import org.ibeans.api.channel.MimeTypes;
/**
* Logs responses from iBean invocations to a directory. Files are stored using the pattern -
* [Test class Name]-[Test method name]-response[count].[json/xml/rss/atom/txt/html/data]
*
* This is useful for tracking responses for different methods which can be used to create mock test cases
*
* This interceptor can be enabled by setting the VM property 'ibeans.log.responses' to the directory path where the files
* should be stored.
*/
public class LogResponsesInterceptor extends AbstractCallInterceptor
{
private File logDirectory;
public LogResponsesInterceptor(String logDirectory)
{
this(new File(logDirectory));
}
public LogResponsesInterceptor(File logDirectory)
{
if(!logDirectory.exists())
{
throw new IllegalArgumentException("Log directory does not exist: " + logDirectory);
}
if(!logDirectory.isDirectory())
{
throw new IllegalArgumentException("Log directory is not a directory: " + logDirectory);
}
this.logDirectory = logDirectory;
}
@Override
public void afterCall(InvocationContext invocationContext) throws Throwable
{
Response msg = invocationContext.getResponse();
boolean isStream = InputStream.class.isAssignableFrom(msg.getPayload().getClass());
String response = msg.getPayload().toString();
//Set the result on the invocationContext in case we got back a stream, this avoids StreamAlreadyClosed exceptions
if(isStream)
{
//wrap it back up as a ByteArray so that transformers do no need to handle the new String payload
invocationContext.setResult(new ByteArrayInputStream(response.getBytes()));
}
else
{
invocationContext.setResult(response);
}
String type = (String)msg.getHeader("Content-Type");
String testMethod = getTestMethod(invocationContext.getMethod().getName());
String ext = getFileExtension(new MimeType(type));
int i = 1;
String filename = testMethod + "-response" + (i++) + ext;
File responseFile = new File(logDirectory, filename);
//make sure we have a unique file name since the same ibeans method may be called more than once from a test method
while(responseFile.exists())
{
filename = testMethod + "-response" + i++ + ext;
responseFile = new File(logDirectory, filename);
}
FileOutputStream fos = openOutputStream(responseFile);
try
{
- fos.write(response.getBytes());
+ if(isStream)
+ {
+ byte buf[] = new byte[1024];
+ int len;
+ InputStream is = msg.getPayloadAsStream();
+ while((len=is.read(buf))>0)
+ {
+ fos.write(buf, 0, len);
+ }
+ is.close();
+ }
+ else
+ {
+ fos.write(response.getBytes());
+ }
}
finally
{
try
{
fos.close();
}
catch (IOException e)
{
//ignore
}
}
}
protected String getFileExtension(MimeType mimeType)
{
if(mimeType==null){
return ".data";
}
if(mimeType.equals(MimeTypes.ATOM))
{
return ".atom";
}
else if(mimeType.equals(MimeTypes.RSS))
{
return ".rss";
}
else if(mimeType.equals(MimeTypes.XML) || mimeType.equals(MimeTypes.APPLICATION_XML))
{
return ".xml";
}
else if(mimeType.equals(MimeTypes.JSON))
{
return ".json";
}
else if(mimeType.equals(MimeTypes.TEXT))
{
return ".txt";
}
else if(mimeType.equals(MimeTypes.HTML))
{
return ".html";
}
else
{
return ".data";
}
}
private String getTestMethod(String name)
{
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (int i = 0; i < stack.length; i++)
{
StackTraceElement element = stack[i];
if(element.getMethodName().equals(name))
{
//This assume that the ibean was called from the current method, not a method called by the test method
//This should be fine for almot all if not all ibeans test cases
String className = stack[i+1].getClassName();
int x = className.lastIndexOf(".");
if(x > -1)
{
className = className.substring(x+1);
}
return className + "-" + stack[i+1].getMethodName();
}
}
throw new IllegalStateException("Method not found in call stack");
}
/**
* Opens a {@link java.io.FileOutputStream} for the specified file, checking and
* creating the parent directory if it does not exist.
* <p>
* At the end of the method either the stream will be successfully opened,
* or an exception will have been thrown.
* <p>
* The parent directory will be created if it does not exist.
* The file will be created if it does not exist.
* An exception is thrown if the file object exists but is a directory.
* An exception is thrown if the file exists but cannot be written to.
* An exception is thrown if the parent directory cannot be created.
*
* @param file the file to open for output, must not be <code>null</code>
* @return a new {@link java.io.FileOutputStream} for the specified file
* @throws java.io.IOException if the file object is a directory, if the file cannot be written to,
* if a parent directory needs creating but that fails
*/
public static FileOutputStream openOutputStream(File file) throws IOException
{
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (!file.canWrite()) {
throw new IOException("File '" + file + "' cannot be written to");
}
} else {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
if (!parent.mkdirs()) {
throw new IOException("File '" + file + "' could not be created");
}
}
}
return new FileOutputStream(file);
}
}
| true | true | public void afterCall(InvocationContext invocationContext) throws Throwable
{
Response msg = invocationContext.getResponse();
boolean isStream = InputStream.class.isAssignableFrom(msg.getPayload().getClass());
String response = msg.getPayload().toString();
//Set the result on the invocationContext in case we got back a stream, this avoids StreamAlreadyClosed exceptions
if(isStream)
{
//wrap it back up as a ByteArray so that transformers do no need to handle the new String payload
invocationContext.setResult(new ByteArrayInputStream(response.getBytes()));
}
else
{
invocationContext.setResult(response);
}
String type = (String)msg.getHeader("Content-Type");
String testMethod = getTestMethod(invocationContext.getMethod().getName());
String ext = getFileExtension(new MimeType(type));
int i = 1;
String filename = testMethod + "-response" + (i++) + ext;
File responseFile = new File(logDirectory, filename);
//make sure we have a unique file name since the same ibeans method may be called more than once from a test method
while(responseFile.exists())
{
filename = testMethod + "-response" + i++ + ext;
responseFile = new File(logDirectory, filename);
}
FileOutputStream fos = openOutputStream(responseFile);
try
{
fos.write(response.getBytes());
}
finally
{
try
{
fos.close();
}
catch (IOException e)
{
//ignore
}
}
}
| public void afterCall(InvocationContext invocationContext) throws Throwable
{
Response msg = invocationContext.getResponse();
boolean isStream = InputStream.class.isAssignableFrom(msg.getPayload().getClass());
String response = msg.getPayload().toString();
//Set the result on the invocationContext in case we got back a stream, this avoids StreamAlreadyClosed exceptions
if(isStream)
{
//wrap it back up as a ByteArray so that transformers do no need to handle the new String payload
invocationContext.setResult(new ByteArrayInputStream(response.getBytes()));
}
else
{
invocationContext.setResult(response);
}
String type = (String)msg.getHeader("Content-Type");
String testMethod = getTestMethod(invocationContext.getMethod().getName());
String ext = getFileExtension(new MimeType(type));
int i = 1;
String filename = testMethod + "-response" + (i++) + ext;
File responseFile = new File(logDirectory, filename);
//make sure we have a unique file name since the same ibeans method may be called more than once from a test method
while(responseFile.exists())
{
filename = testMethod + "-response" + i++ + ext;
responseFile = new File(logDirectory, filename);
}
FileOutputStream fos = openOutputStream(responseFile);
try
{
if(isStream)
{
byte buf[] = new byte[1024];
int len;
InputStream is = msg.getPayloadAsStream();
while((len=is.read(buf))>0)
{
fos.write(buf, 0, len);
}
is.close();
}
else
{
fos.write(response.getBytes());
}
}
finally
{
try
{
fos.close();
}
catch (IOException e)
{
//ignore
}
}
}
|
diff --git a/BerlinCurator/src/com/alvarosantisteban/berlincurator/ListAdapter.java b/BerlinCurator/src/com/alvarosantisteban/berlincurator/ListAdapter.java
index 077f189..e8ebb9e 100644
--- a/BerlinCurator/src/com/alvarosantisteban/berlincurator/ListAdapter.java
+++ b/BerlinCurator/src/com/alvarosantisteban/berlincurator/ListAdapter.java
@@ -1,177 +1,178 @@
package com.alvarosantisteban.berlincurator;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
/**
* An adapter for the ExpandableList that enables the population through an ArrayList
*
* @author Alvaro Santisteban 2013 - [email protected]
*
*/
public class ListAdapter extends BaseExpandableListAdapter {
private Context context;
/**
* The ArrayList used to get the information
*/
private ArrayList<HeaderInfo> websitesList;
public ListAdapter(Context context, ArrayList<HeaderInfo> websiteList) {
this.context = context;
this.websitesList = websiteList;
}
/**
* Gets the event from the given position within the given group (site)
*
* @param groupPosition the position of the group that the event resides in
* @param childPosition the position of the event with respect to other events in the group
*
* @return the event
*/
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Event> eventsList = websitesList.get(groupPosition).getEventsList();
return eventsList.get(childPosition);
}
/**
* Gets the id of the event, which is its position
*
* @param groupPosition the position of the group that the event resides in
* @param childPosition the position of the event with respect to other events in the group
*
* @return the id of the event, which is its position
*/
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
/**
* Gets a View that displays the data for the given event within the given group.
*
* @param groupPosition the position of the group that the event resides in
* @param childPosition the position of the event with respect to other events in the group
* @param isLastChild Whether the event is the last event within the group
* @param convertView the old view to reuse, if possible.
* @param parent the parent that this view will eventually be attached to
*
* @return the View corresponding to the event at the specified position
*/
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Event detailInfo = (Event) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child_row, null);
}
// Write the information of the event in the way we want
TextView sequence = (TextView) convertView.findViewById(R.id.sequence);
sequence.setText(detailInfo.getSequence().trim() + ") ");
TextView childItem = (TextView) convertView.findViewById(R.id.childItem);
childItem.setText(Html.fromHtml(detailInfo.getName().trim())); // <------------------------ CAMBIADO
return convertView;
}
/**
* Gets the number of events in a specified group.
*
* @param groupPosition the position of the group for which the events count should be returned
*
* @return the number of events in the specified group
*/
public int getChildrenCount(int groupPosition) {
ArrayList<Event> eventsList = websitesList.get(groupPosition).getEventsList();
return eventsList.size();
}
/**
* Gets the data associated with the given group.
*
* @param the position of the group
*
* @return the ArrayList of HeaderInfo for the specified group
*/
public Object getGroup(int groupPosition) {
return websitesList.get(groupPosition);
}
/**
* Gets the number of groups
*
* @return the number of groups
*/
public int getGroupCount() {
return websitesList.size();
}
/**
* Gets the ID for the group at the given position. The ID is the position itself.
*
* @param groupPosition the position of the group for which the ID is wanted
*
* @return the ID associated with the group. It is the position itself.
*/
public long getGroupId(int groupPosition) {
return groupPosition;
}
/**
* Gets a View that displays the given group.
*
* @param groupPosition the position of the group for which the View is returned
* @param isExpanded whether the group is expanded or collapsed
* @param convertView the old view to reuse, if possible.
* @param parent the parent that this view will eventually be attached to
*
* @return the View corresponding to the group at the specified position
*/
- public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
+ public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
HeaderInfo headerInfo = (HeaderInfo) getGroup(groupPosition);
- if (convertView == null) {
+ // I had to comment it, because it creates problems with the views
+ //if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.group_heading, null);
- }
+ //}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
String singPl = " events";
if (headerInfo.getEventsNumber() == 1){
singPl =" event";
}
heading.setText(headerInfo.getName().trim() +" - " +headerInfo.getEventsNumber() +singPl);
// If there are no events, make the header's color gray
if(headerInfo.getEventsNumber() == 0){
heading.setTextColor(Color.GRAY);
}
return convertView;
}
/**
* Indicates whether the child and group IDs are stable across changes to the underlying data.
*
* @return always true
*/
public boolean hasStableIds() {
return true;
}
/**
* Whether the child at the specified position is selectable.
*
* @return always true
*/
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
| false | true | public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
HeaderInfo headerInfo = (HeaderInfo) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.group_heading, null);
}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
String singPl = " events";
if (headerInfo.getEventsNumber() == 1){
singPl =" event";
}
heading.setText(headerInfo.getName().trim() +" - " +headerInfo.getEventsNumber() +singPl);
// If there are no events, make the header's color gray
if(headerInfo.getEventsNumber() == 0){
heading.setTextColor(Color.GRAY);
}
return convertView;
}
| public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
HeaderInfo headerInfo = (HeaderInfo) getGroup(groupPosition);
// I had to comment it, because it creates problems with the views
//if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.group_heading, null);
//}
TextView heading = (TextView) convertView.findViewById(R.id.heading);
String singPl = " events";
if (headerInfo.getEventsNumber() == 1){
singPl =" event";
}
heading.setText(headerInfo.getName().trim() +" - " +headerInfo.getEventsNumber() +singPl);
// If there are no events, make the header's color gray
if(headerInfo.getEventsNumber() == 0){
heading.setTextColor(Color.GRAY);
}
return convertView;
}
|
diff --git a/h2/src/main/org/h2/table/RegularTable.java b/h2/src/main/org/h2/table/RegularTable.java
index 3a1d0fcb3..b73d13e39 100644
--- a/h2/src/main/org/h2/table/RegularTable.java
+++ b/h2/src/main/org/h2/table/RegularTable.java
@@ -1,782 +1,782 @@
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.table;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import org.h2.api.DatabaseEventListener;
import org.h2.command.ddl.Analyze;
import org.h2.command.ddl.CreateTableData;
import org.h2.constant.ErrorCode;
import org.h2.constant.SysProperties;
import org.h2.constraint.Constraint;
import org.h2.constraint.ConstraintReferential;
import org.h2.engine.Constants;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.index.Cursor;
import org.h2.index.HashIndex;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.index.MultiVersionIndex;
import org.h2.index.NonUniqueHashIndex;
import org.h2.index.PageBtreeIndex;
import org.h2.index.PageDataIndex;
import org.h2.index.PageDelegateIndex;
import org.h2.index.ScanIndex;
import org.h2.index.SpatialTreeIndex;
import org.h2.index.TreeIndex;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.Row;
import org.h2.result.SortOrder;
import org.h2.schema.SchemaObject;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.value.CompareMode;
import org.h2.value.DataType;
import org.h2.value.Value;
/**
* Most tables are an instance of this class. For this table, the data is stored
* in the database. The actual data is not kept here, instead it is kept in the
* indexes. There is at least one index, the scan index.
*/
public class RegularTable extends TableBase {
private Index scanIndex;
private long rowCount;
private volatile Session lockExclusive;
private HashSet<Session> lockShared = New.hashSet();
private final Trace traceLock;
private final ArrayList<Index> indexes = New.arrayList();
private long lastModificationId;
private boolean containsLargeObject;
private final PageDataIndex mainIndex;
private int changesSinceAnalyze;
private int nextAnalyze;
private Column rowIdColumn;
/**
* True if one thread ever was waiting to lock this table. This is to avoid
* calling notifyAll if no session was ever waiting to lock this table. If
* set, the flag stays. In theory, it could be reset, however not sure when.
*/
private boolean waitForLock;
public RegularTable(CreateTableData data) {
super(data);
nextAnalyze = database.getSettings().analyzeAuto;
this.isHidden = data.isHidden;
for (Column col : getColumns()) {
if (DataType.isLargeObject(col.getType())) {
containsLargeObject = true;
}
}
if (data.persistData && database.isPersistent()) {
mainIndex = new PageDataIndex(this, data.id,
IndexColumn.wrap(getColumns()),
IndexType.createScan(data.persistData),
data.create, data.session);
scanIndex = mainIndex;
} else {
mainIndex = null;
scanIndex = new ScanIndex(this, data.id, IndexColumn.wrap(getColumns()), IndexType.createScan(data.persistData));
}
indexes.add(scanIndex);
traceLock = database.getTrace(Trace.LOCK);
}
@Override
public void close(Session session) {
for (Index index : indexes) {
index.close(session);
}
}
/**
* Read the given row.
*
* @param session the session
* @param key unique key
* @return the row
*/
public Row getRow(Session session, long key) {
return scanIndex.getRow(session, key);
}
@Override
public void addRow(Session session, Row row) {
lastModificationId = database.getNextModificationDataId();
if (database.isMultiVersion()) {
row.setSessionId(session.getId());
}
int i = 0;
try {
for (int size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
index.add(session, row);
checkRowCount(session, index, 1);
}
rowCount++;
} catch (Throwable e) {
try {
while (--i >= 0) {
Index index = indexes.get(i);
index.remove(session, row);
checkRowCount(session, index, 0);
}
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means there is something wrong
// with the database
trace.error(e2, "could not undo operation");
throw e2;
}
DbException de = DbException.convert(e);
if (de.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
for (int j = 0; j < indexes.size(); j++) {
Index index = indexes.get(j);
if (index.getIndexType().isUnique() && index instanceof MultiVersionIndex) {
MultiVersionIndex mv = (MultiVersionIndex) index;
if (mv.isUncommittedFromOtherSession(session, row)) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, index.getName());
}
}
}
}
throw de;
}
analyzeIfRequired(session);
}
@Override
public void commit(short operation, Row row) {
lastModificationId = database.getNextModificationDataId();
for (int i = 0, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
index.commit(operation, row);
}
}
private void checkRowCount(Session session, Index index, int offset) {
if (SysProperties.CHECK && !database.isMultiVersion()) {
if (!(index instanceof PageDelegateIndex)) {
long rc = index.getRowCount(session);
if (rc != rowCount + offset) {
DbException.throwInternalError(
"rowCount expected " + (rowCount + offset) +
" got " + rc + " " + getName() + "." + index.getName());
}
}
}
}
@Override
public Index getScanIndex(Session session) {
return indexes.get(0);
}
@Override
public Index getUniqueIndex() {
for (Index idx : indexes) {
if (idx.getIndexType().isUnique()) {
return idx;
}
}
return null;
}
@Override
public ArrayList<Index> getIndexes() {
return indexes;
}
@Override
public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
boolean create, String indexComment) {
if (indexType.isPrimaryKey()) {
for (IndexColumn c : cols) {
Column column = c.column;
if (column.isNullable()) {
throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName());
}
column.setPrimaryKey(true);
}
}
boolean isSessionTemporary = isTemporary() && !isGlobalTemporary();
if (!isSessionTemporary) {
database.lockMeta(session);
}
Index index;
if (isPersistIndexes() && indexType.isPersistent()) {
int mainIndexColumn;
if (database.isStarting() && database.getPageStore().getRootPageId(indexId) != 0) {
mainIndexColumn = -1;
} else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) {
mainIndexColumn = -1;
} else {
mainIndexColumn = getMainIndexColumn(indexType, cols);
}
if (mainIndexColumn != -1) {
mainIndex.setMainIndexColumn(mainIndexColumn);
index = new PageDelegateIndex(this, indexId, indexName, indexType, mainIndex, create, session);
} else if (!indexType.isSpatial()) {
index = new PageBtreeIndex(this, indexId, indexName, cols, indexType, create, session);
} else {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Spatial index only supported with the MVStore");
}
} else {
if (indexType.isHash() && cols.length <= 1) {
if (indexType.isUnique()) {
index = new HashIndex(this, indexId, indexName, cols, indexType);
} else {
index = new NonUniqueHashIndex(this, indexId, indexName, cols, indexType);
}
} else if (!indexType.isSpatial()) {
index = new TreeIndex(this, indexId, indexName, cols, indexType);
} else {
index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType);
}
}
if (database.isMultiVersion()) {
index = new MultiVersionIndex(index, this);
}
if (index.needRebuild() && rowCount > 0) {
try {
Index scan = getScanIndex(session);
long remaining = scan.getRowCount(session);
long total = remaining;
Cursor cursor = scan.find(session, null, null);
long i = 0;
int bufferSize = (int) Math.min(rowCount, Constants.DEFAULT_MAX_MEMORY_ROWS);
ArrayList<Row> buffer = New.arrayList(bufferSize);
String n = getName() + ":" + index.getName();
int t = MathUtils.convertLongToInt(total);
while (cursor.next()) {
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n,
MathUtils.convertLongToInt(i++), t);
Row row = cursor.get();
buffer.add(row);
if (buffer.size() >= bufferSize) {
addRowsToIndex(session, buffer, index);
}
remaining--;
}
addRowsToIndex(session, buffer, index);
if (SysProperties.CHECK && remaining != 0) {
DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName());
}
} catch (DbException e) {
getSchema().freeUniqueName(indexName);
try {
index.remove(session);
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means
// there is something wrong with the database
trace.error(e2, "could not remove index");
throw e2;
}
throw e;
}
}
index.setTemporary(isTemporary());
if (index.getCreateSQL() != null) {
index.setComment(indexComment);
if (isSessionTemporary) {
session.addLocalTempTableIndex(index);
} else {
database.addSchemaObject(session, index);
}
}
indexes.add(index);
setModified();
return index;
}
private int getMainIndexColumn(IndexType indexType, IndexColumn[] cols) {
if (mainIndex.getMainIndexColumn() != -1) {
return -1;
}
if (!indexType.isPrimaryKey() || cols.length != 1) {
return -1;
}
IndexColumn first = cols[0];
if (first.sortType != SortOrder.ASCENDING) {
return -1;
}
switch(first.column.getType()) {
case Value.BYTE:
case Value.SHORT:
case Value.INT:
case Value.LONG:
break;
default:
return -1;
}
return first.column.getColumnId();
}
@Override
public boolean canGetRowCount() {
return true;
}
private static void addRowsToIndex(Session session, ArrayList<Row> list, Index index) {
final Index idx = index;
Collections.sort(list, new Comparator<Row>() {
@Override
public int compare(Row r1, Row r2) {
return idx.compareRows(r1, r2);
}
});
for (Row row : list) {
index.add(session, row);
}
list.clear();
}
@Override
public boolean canDrop() {
return true;
}
@Override
public long getRowCount(Session session) {
if (database.isMultiVersion()) {
return getScanIndex(session).getRowCount(session);
}
return rowCount;
}
@Override
public void removeRow(Session session, Row row) {
if (database.isMultiVersion()) {
if (row.isDeleted()) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, getName());
}
int old = row.getSessionId();
int newId = session.getId();
if (old == 0) {
row.setSessionId(newId);
} else if (old != newId) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, getName());
}
}
lastModificationId = database.getNextModificationDataId();
int i = indexes.size() - 1;
try {
for (; i >= 0; i--) {
Index index = indexes.get(i);
index.remove(session, row);
checkRowCount(session, index, -1);
}
rowCount--;
} catch (Throwable e) {
try {
while (++i < indexes.size()) {
Index index = indexes.get(i);
index.add(session, row);
checkRowCount(session, index, 0);
}
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means there is something wrong
// with the database
trace.error(e2, "could not undo operation");
throw e2;
}
throw DbException.convert(e);
}
analyzeIfRequired(session);
}
@Override
public void truncate(Session session) {
lastModificationId = database.getNextModificationDataId();
for (int i = indexes.size() - 1; i >= 0; i--) {
Index index = indexes.get(i);
index.truncate(session);
}
rowCount = 0;
changesSinceAnalyze = 0;
}
private void analyzeIfRequired(Session session) {
if (nextAnalyze == 0 || nextAnalyze > changesSinceAnalyze++) {
return;
}
changesSinceAnalyze = 0;
int n = 2 * nextAnalyze;
if (n > 0) {
nextAnalyze = n;
}
int rows = session.getDatabase().getSettings().analyzeSample / 10;
Analyze.analyzeTable(session, this, rows, false);
}
@Override
public boolean isLockedExclusivelyBy(Session session) {
return lockExclusive == session;
}
@Override
public void lock(Session session, boolean exclusive, boolean force) {
int lockMode = database.getLockMode();
if (lockMode == Constants.LOCK_MODE_OFF) {
return;
}
if (!force && database.isMultiVersion()) {
// MVCC: update, delete, and insert use a shared lock.
// Select doesn't lock except when using FOR UPDATE and
// the system property h2.selectForUpdateMvcc
// is not enabled
if (exclusive) {
exclusive = false;
} else {
if (lockExclusive == null) {
return;
}
}
}
if (lockExclusive == session) {
return;
}
synchronized (database) {
try {
doLock(session, lockMode, exclusive);
} finally {
session.setWaitForLock(null);
}
}
}
private void doLock(Session session, int lockMode, boolean exclusive) {
traceLock(session, exclusive, "requesting for");
// don't get the current time unless necessary
long max = 0;
boolean checkDeadlock = false;
while (true) {
if (lockExclusive == session) {
return;
}
if (exclusive) {
if (lockExclusive == null) {
if (lockShared.isEmpty()) {
traceLock(session, exclusive, "added for");
session.addLock(this);
lockExclusive = session;
return;
} else if (lockShared.size() == 1 && lockShared.contains(session)) {
traceLock(session, exclusive, "add (upgraded) for ");
lockExclusive = session;
return;
}
}
} else {
if (lockExclusive == null) {
if (lockMode == Constants.LOCK_MODE_READ_COMMITTED) {
if (!database.isMultiThreaded() && !database.isMultiVersion()) {
// READ_COMMITTED: a read lock is acquired,
// but released immediately after the operation
// is complete.
// When allowing only one thread, no lock is
// required.
// Row level locks work like read committed.
return;
}
}
if (!lockShared.contains(session)) {
traceLock(session, exclusive, "ok");
session.addLock(this);
lockShared.add(session);
}
return;
}
}
session.setWaitForLock(this);
if (checkDeadlock) {
ArrayList<Session> sessions = checkDeadlock(session, null, null);
if (sessions != null) {
throw DbException.get(ErrorCode.DEADLOCK_1, getDeadlockDetails(sessions));
}
} else {
// check for deadlocks from now on
checkDeadlock = true;
}
long now = System.currentTimeMillis();
if (max == 0) {
// try at least one more time
max = now + session.getLockTimeout();
} else if (now >= max) {
traceLock(session, exclusive, "timeout after " + session.getLockTimeout());
throw DbException.get(ErrorCode.LOCK_TIMEOUT_1, getName());
}
try {
traceLock(session, exclusive, "waiting for");
if (database.getLockMode() == Constants.LOCK_MODE_TABLE_GC) {
for (int i = 0; i < 20; i++) {
long free = Runtime.getRuntime().freeMemory();
System.gc();
long free2 = Runtime.getRuntime().freeMemory();
if (free == free2) {
break;
}
}
}
// don't wait too long so that deadlocks are detected early
long sleep = Math.min(Constants.DEADLOCK_CHECK, max - now);
if (sleep == 0) {
sleep = 1;
}
waitForLock = true;
database.wait(sleep);
} catch (InterruptedException e) {
// ignore
}
}
}
private static String getDeadlockDetails(ArrayList<Session> sessions) {
StringBuilder buff = new StringBuilder();
for (Session s : sessions) {
Table lock = s.getWaitForLock();
buff.append("\nSession ").
append(s.toString()).
append(" is waiting to lock ").
append(lock.toString()).
append(" while locking ");
int i = 0;
for (Table t : s.getLocks()) {
if (i++ > 0) {
buff.append(", ");
}
buff.append(t.toString());
if (t instanceof RegularTable) {
if (((RegularTable) t).lockExclusive == s) {
buff.append(" (exclusive)");
} else {
buff.append(" (shared)");
}
}
}
buff.append('.');
}
return buff.toString();
}
@Override
public ArrayList<Session> checkDeadlock(Session session, Session clash, Set<Session> visited) {
// only one deadlock check at any given time
synchronized (RegularTable.class) {
if (clash == null) {
// verification is started
clash = session;
visited = New.hashSet();
} else if (clash == session) {
// we found a circle where this session is involved
return New.arrayList();
} else if (visited.contains(session)) {
// we have already checked this session.
// there is a circle, but the sessions in the circle need to
// find it out themselves
return null;
}
visited.add(session);
ArrayList<Session> error = null;
for (Session s : lockShared) {
if (s == session) {
// it doesn't matter if we have locked the object already
continue;
}
Table t = s.getWaitForLock();
if (t != null) {
error = t.checkDeadlock(s, clash, visited);
if (error != null) {
error.add(session);
break;
}
}
}
if (error == null && lockExclusive != null) {
Table t = lockExclusive.getWaitForLock();
if (t != null) {
error = t.checkDeadlock(lockExclusive, clash, visited);
if (error != null) {
error.add(session);
}
}
}
return error;
}
}
private void traceLock(Session session, boolean exclusive, String s) {
if (traceLock.isDebugEnabled()) {
traceLock.debug("{0} {1} {2} {3}", session.getId(),
exclusive ? "exclusive write lock" : "shared read lock", s, getName());
}
}
@Override
public boolean isLockedExclusively() {
return lockExclusive != null;
}
@Override
public void unlock(Session s) {
if (database != null) {
traceLock(s, lockExclusive == s, "unlock");
if (lockExclusive == s) {
lockExclusive = null;
}
if (lockShared.size() > 0) {
lockShared.remove(s);
}
// TODO lock: maybe we need we fifo-queue to make sure nobody
// starves. check what other databases do
synchronized (database) {
if (database.getSessionCount() > 1 && waitForLock) {
database.notifyAll();
}
}
}
}
/**
* Create a row from the values.
*
* @param data the value list
* @return the row
*/
public static Row createRow(Value[] data) {
return new Row(data, Row.MEMORY_CALCULATE);
}
/**
* Set the row count of this table.
*
* @param count the row count
*/
public void setRowCount(long count) {
this.rowCount = count;
}
@Override
public void removeChildrenAndResources(Session session) {
if (containsLargeObject) {
// unfortunately, the data is gone on rollback
truncate(session);
database.getLobStorage().removeAllForTable(getId());
database.lockMeta(session);
}
super.removeChildrenAndResources(session);
// go backwards because database.removeIndex will call table.removeIndex
while (indexes.size() > 1) {
Index index = indexes.get(1);
if (index.getName() != null) {
database.removeSchemaObject(session, index);
}
}
if (SysProperties.CHECK) {
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.INDEX)) {
Index index = (Index) obj;
if (index.getTable() == this) {
DbException.throwInternalError("index not dropped: " + index.getName());
}
}
}
scanIndex.remove(session);
database.removeMeta(session, getId());
scanIndex = null;
lockExclusive = null;
lockShared = null;
invalidate();
}
@Override
public String toString() {
return getSQL();
}
@Override
public void checkRename() {
// ok
}
@Override
public void checkSupportAlter() {
// ok
}
@Override
public boolean canTruncate() {
if (getCheckForeignKeyConstraints() && database.getReferentialIntegrity()) {
ArrayList<Constraint> constraints = getConstraints();
if (constraints != null) {
for (int i = 0, size = constraints.size(); i < size; i++) {
Constraint c = constraints.get(i);
if (!(c.getConstraintType().equals(Constraint.REFERENTIAL))) {
continue;
}
ConstraintReferential ref = (ConstraintReferential) c;
if (ref.getRefTable() == this) {
return false;
}
}
}
}
return true;
}
@Override
public String getTableType() {
return Table.TABLE;
}
@Override
public long getMaxDataModificationId() {
return lastModificationId;
}
public boolean getContainsLargeObject() {
return containsLargeObject;
}
@Override
public long getRowCountApproximation() {
return scanIndex.getRowCountApproximation();
}
@Override
public long getDiskSpaceUsed() {
return scanIndex.getDiskSpaceUsed();
}
public void setCompareMode(CompareMode compareMode) {
this.compareMode = compareMode;
}
@Override
public boolean isDeterministic() {
return true;
}
@Override
public Column getRowIdColumn() {
if (rowIdColumn == null) {
rowIdColumn = new Column(Column.ROWID, Value.LONG);
rowIdColumn.setTable(this, -1);
}
return rowIdColumn;
}
}
| true | true | public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
boolean create, String indexComment) {
if (indexType.isPrimaryKey()) {
for (IndexColumn c : cols) {
Column column = c.column;
if (column.isNullable()) {
throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName());
}
column.setPrimaryKey(true);
}
}
boolean isSessionTemporary = isTemporary() && !isGlobalTemporary();
if (!isSessionTemporary) {
database.lockMeta(session);
}
Index index;
if (isPersistIndexes() && indexType.isPersistent()) {
int mainIndexColumn;
if (database.isStarting() && database.getPageStore().getRootPageId(indexId) != 0) {
mainIndexColumn = -1;
} else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) {
mainIndexColumn = -1;
} else {
mainIndexColumn = getMainIndexColumn(indexType, cols);
}
if (mainIndexColumn != -1) {
mainIndex.setMainIndexColumn(mainIndexColumn);
index = new PageDelegateIndex(this, indexId, indexName, indexType, mainIndex, create, session);
} else if (!indexType.isSpatial()) {
index = new PageBtreeIndex(this, indexId, indexName, cols, indexType, create, session);
} else {
throw new UnsupportedOperationException();
}
} else {
if (indexType.isHash() && cols.length <= 1) {
if (indexType.isUnique()) {
index = new HashIndex(this, indexId, indexName, cols, indexType);
} else {
index = new NonUniqueHashIndex(this, indexId, indexName, cols, indexType);
}
} else if (!indexType.isSpatial()) {
index = new TreeIndex(this, indexId, indexName, cols, indexType);
} else {
index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType);
}
}
if (database.isMultiVersion()) {
index = new MultiVersionIndex(index, this);
}
if (index.needRebuild() && rowCount > 0) {
try {
Index scan = getScanIndex(session);
long remaining = scan.getRowCount(session);
long total = remaining;
Cursor cursor = scan.find(session, null, null);
long i = 0;
int bufferSize = (int) Math.min(rowCount, Constants.DEFAULT_MAX_MEMORY_ROWS);
ArrayList<Row> buffer = New.arrayList(bufferSize);
String n = getName() + ":" + index.getName();
int t = MathUtils.convertLongToInt(total);
while (cursor.next()) {
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n,
MathUtils.convertLongToInt(i++), t);
Row row = cursor.get();
buffer.add(row);
if (buffer.size() >= bufferSize) {
addRowsToIndex(session, buffer, index);
}
remaining--;
}
addRowsToIndex(session, buffer, index);
if (SysProperties.CHECK && remaining != 0) {
DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName());
}
} catch (DbException e) {
getSchema().freeUniqueName(indexName);
try {
index.remove(session);
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means
// there is something wrong with the database
trace.error(e2, "could not remove index");
throw e2;
}
throw e;
}
}
index.setTemporary(isTemporary());
if (index.getCreateSQL() != null) {
index.setComment(indexComment);
if (isSessionTemporary) {
session.addLocalTempTableIndex(index);
} else {
database.addSchemaObject(session, index);
}
}
indexes.add(index);
setModified();
return index;
}
| public Index addIndex(Session session, String indexName, int indexId, IndexColumn[] cols, IndexType indexType,
boolean create, String indexComment) {
if (indexType.isPrimaryKey()) {
for (IndexColumn c : cols) {
Column column = c.column;
if (column.isNullable()) {
throw DbException.get(ErrorCode.COLUMN_MUST_NOT_BE_NULLABLE_1, column.getName());
}
column.setPrimaryKey(true);
}
}
boolean isSessionTemporary = isTemporary() && !isGlobalTemporary();
if (!isSessionTemporary) {
database.lockMeta(session);
}
Index index;
if (isPersistIndexes() && indexType.isPersistent()) {
int mainIndexColumn;
if (database.isStarting() && database.getPageStore().getRootPageId(indexId) != 0) {
mainIndexColumn = -1;
} else if (!database.isStarting() && mainIndex.getRowCount(session) != 0) {
mainIndexColumn = -1;
} else {
mainIndexColumn = getMainIndexColumn(indexType, cols);
}
if (mainIndexColumn != -1) {
mainIndex.setMainIndexColumn(mainIndexColumn);
index = new PageDelegateIndex(this, indexId, indexName, indexType, mainIndex, create, session);
} else if (!indexType.isSpatial()) {
index = new PageBtreeIndex(this, indexId, indexName, cols, indexType, create, session);
} else {
throw new UnsupportedOperationException("Spatial index only supported with the MVStore");
}
} else {
if (indexType.isHash() && cols.length <= 1) {
if (indexType.isUnique()) {
index = new HashIndex(this, indexId, indexName, cols, indexType);
} else {
index = new NonUniqueHashIndex(this, indexId, indexName, cols, indexType);
}
} else if (!indexType.isSpatial()) {
index = new TreeIndex(this, indexId, indexName, cols, indexType);
} else {
index = new SpatialTreeIndex(this, indexId, indexName, cols, indexType);
}
}
if (database.isMultiVersion()) {
index = new MultiVersionIndex(index, this);
}
if (index.needRebuild() && rowCount > 0) {
try {
Index scan = getScanIndex(session);
long remaining = scan.getRowCount(session);
long total = remaining;
Cursor cursor = scan.find(session, null, null);
long i = 0;
int bufferSize = (int) Math.min(rowCount, Constants.DEFAULT_MAX_MEMORY_ROWS);
ArrayList<Row> buffer = New.arrayList(bufferSize);
String n = getName() + ":" + index.getName();
int t = MathUtils.convertLongToInt(total);
while (cursor.next()) {
database.setProgress(DatabaseEventListener.STATE_CREATE_INDEX, n,
MathUtils.convertLongToInt(i++), t);
Row row = cursor.get();
buffer.add(row);
if (buffer.size() >= bufferSize) {
addRowsToIndex(session, buffer, index);
}
remaining--;
}
addRowsToIndex(session, buffer, index);
if (SysProperties.CHECK && remaining != 0) {
DbException.throwInternalError("rowcount remaining=" + remaining + " " + getName());
}
} catch (DbException e) {
getSchema().freeUniqueName(indexName);
try {
index.remove(session);
} catch (DbException e2) {
// this could happen, for example on failure in the storage
// but if that is not the case it means
// there is something wrong with the database
trace.error(e2, "could not remove index");
throw e2;
}
throw e;
}
}
index.setTemporary(isTemporary());
if (index.getCreateSQL() != null) {
index.setComment(indexComment);
if (isSessionTemporary) {
session.addLocalTempTableIndex(index);
} else {
database.addSchemaObject(session, index);
}
}
indexes.add(index);
setModified();
return index;
}
|
diff --git a/modules/org.restlet/src/org/restlet/service/MetadataService.java b/modules/org.restlet/src/org/restlet/service/MetadataService.java
index e90e6d43a..9e096f721 100644
--- a/modules/org.restlet/src/org/restlet/service/MetadataService.java
+++ b/modules/org.restlet/src/org/restlet/service/MetadataService.java
@@ -1,732 +1,734 @@
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Metadata;
import org.restlet.engine.application.MetadataExtension;
/**
* Application service providing access to metadata and their associated
* extension names. The list of default mappings is documented in the
* {@link #addCommonExtensions()} method.<br>
* <br>
* Internally, the mappings are stored as a list of "extension, metadata" pairs.
*
* @author Jerome Louvel
*/
public class MetadataService extends Service {
/** The default character set for textual representations. */
private volatile CharacterSet defaultCharacterSet;
/** The default encoding for representations. */
private volatile Encoding defaultEncoding;
/** The default language for representations. */
private volatile Language defaultLanguage;
/** The default media type for representations. */
private volatile MediaType defaultMediaType;
/** The list of mappings between extension names and metadata. */
private final List<MetadataExtension> mappings;
/**
* Constructor. Sets the default language to {@link Language#ENGLISH_US},
* the default encoding to {@link Encoding#IDENTITY} (no encoding) and the
* default media type to {@link MediaType#APPLICATION_OCTET_STREAM}. It also
* calls the {@link #addCommonExtensions()} method.
*/
public MetadataService() {
this.defaultCharacterSet = CharacterSet.DEFAULT;
this.defaultEncoding = Encoding.IDENTITY;
this.defaultLanguage = Language.DEFAULT;
this.defaultMediaType = MediaType.APPLICATION_OCTET_STREAM;
this.mappings = new CopyOnWriteArrayList<MetadataExtension>();
addCommonExtensions();
}
/**
* Adds a common list of associations from extensions to metadata. The list
* of languages extensions:<br>
* <ul>
* <li>en: English</li>
* <li>es: Spanish</li>
* <li>fr: French</li>
* </ul>
* <br>
* The list of media type extensions:<br>
* <ul>
* <li>ai: PostScript document</li>
* <li>atom: Atom syndication document</li>
* <li>au: AU audio file</li>
* <li>bin: Binary file</li>
* <li>bmp: Bitmap graphics</li>
* <li>class: Java bytecode</li>
* <li>css: CSS stylesheet</li>
* <li>csv: Comma-separated Values</li>
* <li>dat: Fixed-width Values</li>
* <li>dib: Device-Independent Bitmap Graphics</li>
* <li>doc: Microsoft Word document</li>
* <li>docx: Microsoft Office Word 2007 document</li>
* <li>docm: Office Word 2007 macro-enabled document</li>
* <li>dotx: Office Word 2007 template</li>
* <li>dotm: Office Word 2007 macro-enabled document template</li>
* <li>dtd: XML Document Type Definition</li>
* <li>eps: Encapsulated PostScript</li>
* <li>exe: Executable File (Microsoft Corporation)</li>
* <li>fmt: FreeMarker encoding</li>
* <li>form: Web forms (URL encoded)</li>
* <li>ftl: FreeMarker encoding</li>
* <li>gif: GIF image</li>
* <li>hqx: BinHex 4 Compressed Archive (Macintosh)</li>
* <li>htm, html: HTML document</li>
* <li>ico: Windows icon (Favicon)</li>
* <li>jad: Java Application Descriptor file</li>
* <li>jar: Java Archive</li>
* <li>java: Java source code</li>
* <li>jnlp: Java Web start launch file</li>
* <li>jpe, jpeg, jpg: JPEG image</li>
* <li>js: JavaScript document</li>
* <li>jsf: Java Server Faces file</li>
* <li>json: JavaScript Object Notation document</li>
* <li>kar: Karaoke MIDI file</li>
* <li>latex: LaTeX document</li>
* <li>man: Manual file</li>
* <li>mathml: Mathml XML document</li>
* <li>mid, midi: MIDI Audio</li>
* <li>mov, qt: QuickTime video clip (Apple Computer, Inc.)</li>
* <li>mp2, mp3: MPEG Audio Stream file</li>
* <li>mp4: MPEG-4 video file</li>
* <li>mpe, mpeg, mpg: MPEG video clip</li>
* <li>n3: RDF N3 document</li>
* <li>nt: RDF N-Triples document</li>
* <li>odb: OpenDocument Database</li>
* <li>odc: OpenDocument Chart</li>
* <li>odf: OpenDocument Formula</li>
* <li>odg: OpenDocument Drawing</li>
* <li>odi: OpenDocument Image</li>
* <li>odm: OpenDocument Master Document</li>
* <li>odp: OpenDocument Presentation</li>
* <li>ods: OpenDocument Spreadsheet</li>
* <li>odt: OpenDocument Text</li>
* <li>onetoc: Microsoft Office OneNote 2007 TOC</li>
* <li>onetoc2: Office OneNote 2007 TOC</li>
* <li>otg: OpenDocument Drawing Template</li>
* <li>oth: HTML Document Template</li>
* <li>otp: OpenDocument Presentation Template</li>
* <li>ots: OpenDocument Spreadsheet Template</li>
* <li>ott: OpenDocument Text Template</li>
* <li>oxt: OpenOffice.org extension</li>
* <li>pdf: Adobe PDF document</li>
* <li>png: PNG image</li>
* <li>potm: Office PowerPoint 2007 macro-enabled presentation template</li>
* <li>potx: Office PowerPoint 2007 template</li>
* <li>ppam: Office PowerPoint 2007 add-in</li>
* <li>pps, ppt: Microsoft Powerpoint document</li>
* <li>ppsm: Office PowerPoint 2007 macro-enabled slide show</li>
* <li>ppsx: Office PowerPoint 2007 slide show</li>
* <li>pptm: Office PowerPoint 2007 macro-enabled presentation</li>
* <li>pptx: Microsoft Office PowerPoint 2007 presentation</li>
* <li>ps: PostScript document</li>
* <li>rdf: Description Framework document</li>
* <li>rnc: Relax NG Schema document, Compact syntax</li>
* <li>rng: Relax NG Schema document, XML syntax</li>
* <li>rss: RSS file</li>
* <li>rtf: Rich Text Format document</li>
* <li>sav: SPSS Data</li>
* <li>sit: StuffIt compressed archive file</li>
* <li>sldm: Office PowerPoint 2007 macro-enabled slide</li>
* <li>sldx: Office PowerPoint 2007 slide</li>
* <li>snd: Amiga sound</li>
* <li>sps: SPSS Script Syntax</li>
* <li>sta: Stata data file</li>
* <li>svg: Scalable Vector Graphics file</li>
* <li>swf: Adobe Flash file</li>
* <li>tar: Tape Archive file</li>
* <li>tex: Tex file</li>
* <li>tif, tiff: Tagged Image Format File</li>
* <li>tsv: Tab-separated Values</li>
* <li>txt: Plain text</li>
* <li>ulw: MU-LAW (US telephony format)</li>
* <li>vm: Velocity encoding</li>
* <li>vrml: Virtual Reality Modeling Language file</li>
* <li>vxml: VoiceXML source file</li>
* <li>wadl: Web Application Description Language document</li>
* <li>wav: Waveform audio</li>
* <li>wrl: Plain text VRML file</li>
* <li>xht, xhtml: XHTML document</li>
* <li>xlam: Office Excel 2007 add-in</li>
* <li>xls: Microsoft Excel document</li>
* <li>xlsb: Office Excel 2007 binary workbook</li>
* <li>xlsm: Office Excel 2007 macro-enabled workbook</li>
* <li>xlsx: Microsoft Office Excel 2007 workbook</li>
* <li>xltm: Office Excel 2007 macro-enabled workbook template</li>
* <li>xltx: Office Excel 2007 template</li>
* <li>xmi: XMI document</li>
* <li>xml: XML document</li>
* <li>xsd: W3C XML Schema document</li>
* <li>xsl, xslt: XSL Transform file</li>
* <li>xul: XML User Interface Language file</li>
* <li>z: UNIX compressed archive file</li>
* <li>zip: Zip archive</li>
* </ul>
*/
public void addCommonExtensions() {
List<MetadataExtension> dm = new ArrayList<MetadataExtension>();
ext(dm, "en", Language.ENGLISH);
ext(dm, "es", Language.SPANISH);
ext(dm, "fr", Language.FRENCH);
+ // [ifndef gwt]
ext(dm, "ai", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "ascii", CharacterSet.US_ASCII);
ext(dm, "atom", MediaType.APPLICATION_ATOM);
ext(dm, "atomcat", MediaType.APPLICATION_ATOMPUB_CATEGORY);
ext(dm, "atomsvc", MediaType.APPLICATION_ATOMPUB_SERVICE);
ext(dm, "au", MediaType.AUDIO_BASIC);
ext(dm, "bin", MediaType.APPLICATION_OCTET_STREAM);
ext(dm, "bmp", MediaType.IMAGE_BMP);
ext(dm, "class", MediaType.APPLICATION_JAVA);
ext(dm, "css", MediaType.TEXT_CSS);
ext(dm, "csv", MediaType.TEXT_CSV);
ext(dm, "dat", MediaType.TEXT_DAT);
ext(dm, "dib", MediaType.IMAGE_BMP);
ext(dm, "doc", MediaType.APPLICATION_WORD);
ext(dm, "docm", MediaType.APPLICATION_MSOFFICE_DOCM);
ext(dm, "docx", MediaType.APPLICATION_MSOFFICE_DOCX);
ext(dm, "dotm", MediaType.APPLICATION_MSOFFICE_DOTM);
ext(dm, "dotx", MediaType.APPLICATION_MSOFFICE_DOTX);
ext(dm, "dtd", MediaType.APPLICATION_XML_DTD);
ext(dm, "eps", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "exe", MediaType.APPLICATION_OCTET_STREAM);
ext(dm, "fmt", Encoding.FREEMARKER);
ext(dm, "form", MediaType.APPLICATION_WWW_FORM);
ext(dm, "ftl", Encoding.FREEMARKER, true);
ext(dm, "gif", MediaType.IMAGE_GIF);
ext(dm, "hqx", MediaType.APPLICATION_MAC_BINHEX40);
- ext(dm, "htm", MediaType.TEXT_HTML);
- ext(dm, "html", MediaType.TEXT_HTML);
ext(dm, "ico", MediaType.IMAGE_ICON);
ext(dm, "jad", MediaType.TEXT_J2ME_APP_DESCRIPTOR);
ext(dm, "jar", MediaType.APPLICATION_JAVA_ARCHIVE);
ext(dm, "java", MediaType.TEXT_PLAIN);
ext(dm, "jnlp", MediaType.APPLICATION_JNLP);
ext(dm, "jpe", MediaType.IMAGE_JPEG);
ext(dm, "jpeg", MediaType.IMAGE_JPEG);
ext(dm, "jpg", MediaType.IMAGE_JPEG);
ext(dm, "js", MediaType.APPLICATION_JAVASCRIPT);
ext(dm, "jsf", MediaType.TEXT_PLAIN);
- ext(dm, "json", MediaType.APPLICATION_JSON);
ext(dm, "kar", MediaType.AUDIO_MIDI);
ext(dm, "latex", MediaType.APPLICATION_LATEX);
ext(dm, "latin1", CharacterSet.ISO_8859_1);
ext(dm, "mac", CharacterSet.MACINTOSH);
ext(dm, "man", MediaType.APPLICATION_TROFF_MAN);
ext(dm, "mathml", MediaType.APPLICATION_MATHML);
ext(dm, "mid", MediaType.AUDIO_MIDI);
ext(dm, "midi", MediaType.AUDIO_MIDI);
ext(dm, "mov", MediaType.VIDEO_QUICKTIME);
ext(dm, "mp2", MediaType.AUDIO_MPEG);
ext(dm, "mp3", MediaType.AUDIO_MPEG);
ext(dm, "mp4", MediaType.VIDEO_MP4);
ext(dm, "mpe", MediaType.VIDEO_MPEG);
ext(dm, "mpeg", MediaType.VIDEO_MPEG);
ext(dm, "mpg", MediaType.VIDEO_MPEG);
ext(dm, "n3", MediaType.TEXT_RDF_N3);
ext(dm, "nt", MediaType.TEXT_PLAIN);
ext(dm, "odb", MediaType.APPLICATION_OPENOFFICE_ODB);
ext(dm, "odc", MediaType.APPLICATION_OPENOFFICE_ODC);
ext(dm, "odf", MediaType.APPLICATION_OPENOFFICE_ODF);
ext(dm, "odi", MediaType.APPLICATION_OPENOFFICE_ODI);
ext(dm, "odm", MediaType.APPLICATION_OPENOFFICE_ODM);
ext(dm, "odg", MediaType.APPLICATION_OPENOFFICE_ODG);
ext(dm, "odp", MediaType.APPLICATION_OPENOFFICE_ODP);
ext(dm, "ods", MediaType.APPLICATION_OPENOFFICE_ODS);
ext(dm, "odt", MediaType.APPLICATION_OPENOFFICE_ODT);
ext(dm, "onetoc", MediaType.APPLICATION_MSOFFICE_ONETOC);
ext(dm, "onetoc2", MediaType.APPLICATION_MSOFFICE_ONETOC2);
ext(dm, "otg", MediaType.APPLICATION_OPENOFFICE_OTG);
ext(dm, "oth", MediaType.APPLICATION_OPENOFFICE_OTH);
ext(dm, "otp", MediaType.APPLICATION_OPENOFFICE_OTP);
ext(dm, "ots", MediaType.APPLICATION_OPENOFFICE_OTS);
ext(dm, "ott", MediaType.APPLICATION_OPENOFFICE_OTT);
ext(dm, "oxt", MediaType.APPLICATION_OPENOFFICE_OXT);
ext(dm, "pdf", MediaType.APPLICATION_PDF);
ext(dm, "png", MediaType.IMAGE_PNG);
ext(dm, "potx", MediaType.APPLICATION_MSOFFICE_POTX);
ext(dm, "potm", MediaType.APPLICATION_MSOFFICE_POTM);
ext(dm, "ppam", MediaType.APPLICATION_MSOFFICE_PPAM);
ext(dm, "pps", MediaType.APPLICATION_POWERPOINT);
ext(dm, "ppsm", MediaType.APPLICATION_MSOFFICE_PPSM);
ext(dm, "ppsx", MediaType.APPLICATION_MSOFFICE_PPSX);
ext(dm, "ppt", MediaType.APPLICATION_POWERPOINT);
ext(dm, "pptm", MediaType.APPLICATION_MSOFFICE_PPTM);
ext(dm, "pptx", MediaType.APPLICATION_MSOFFICE_PPTX);
ext(dm, "ps", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "qt", MediaType.VIDEO_QUICKTIME);
ext(dm, "rdf", MediaType.APPLICATION_RDF_XML);
ext(dm, "rnc", MediaType.APPLICATION_RELAXNG_COMPACT);
ext(dm, "rng", MediaType.APPLICATION_RELAXNG_XML);
ext(dm, "rss", MediaType.APPLICATION_RSS);
ext(dm, "rtf", MediaType.APPLICATION_RTF);
ext(dm, "sav", MediaType.APPLICATION_SPSS_SAV);
ext(dm, "sit", MediaType.APPLICATION_STUFFIT);
ext(dm, "sldm", MediaType.APPLICATION_MSOFFICE_SLDM);
ext(dm, "sldx", MediaType.APPLICATION_MSOFFICE_SLDX);
ext(dm, "snd", MediaType.AUDIO_BASIC);
ext(dm, "sps", MediaType.APPLICATION_SPSS_SPS);
ext(dm, "sta", MediaType.APPLICATION_STATA_STA);
ext(dm, "svg", MediaType.IMAGE_SVG);
ext(dm, "swf", MediaType.APPLICATION_FLASH);
ext(dm, "tar", MediaType.APPLICATION_TAR);
ext(dm, "tex", MediaType.APPLICATION_TEX);
ext(dm, "tif", MediaType.IMAGE_TIFF);
ext(dm, "tiff", MediaType.IMAGE_TIFF);
ext(dm, "tsv", MediaType.TEXT_TSV);
- ext(dm, "txt", MediaType.TEXT_PLAIN, true);
ext(dm, "ulw", MediaType.AUDIO_BASIC);
ext(dm, "utf16", CharacterSet.UTF_16);
ext(dm, "utf8", CharacterSet.UTF_8);
ext(dm, "vm", Encoding.VELOCITY);
ext(dm, "vrml", MediaType.MODEL_VRML);
ext(dm, "vxml", MediaType.APPLICATION_VOICEXML);
ext(dm, "wadl", MediaType.APPLICATION_WADL);
ext(dm, "wav", MediaType.AUDIO_WAV);
ext(dm, "win", CharacterSet.WINDOWS_1252);
ext(dm, "wrl", MediaType.MODEL_VRML);
ext(dm, "xht", MediaType.APPLICATION_XHTML);
- ext(dm, "xhtml", MediaType.APPLICATION_XHTML);
ext(dm, "xls", MediaType.APPLICATION_EXCEL);
ext(dm, "xlsx", MediaType.APPLICATION_MSOFFICE_XLSX);
ext(dm, "xlsm", MediaType.APPLICATION_MSOFFICE_XLSM);
ext(dm, "xltx", MediaType.APPLICATION_MSOFFICE_XLTX);
ext(dm, "xltm", MediaType.APPLICATION_MSOFFICE_XLTM);
ext(dm, "xlsb", MediaType.APPLICATION_MSOFFICE_XLSB);
ext(dm, "xlam", MediaType.APPLICATION_MSOFFICE_XLAM);
ext(dm, "xmi", MediaType.APPLICATION_XMI_XML);
- ext(dm, "xml", MediaType.TEXT_XML);
- ext(dm, "xml", MediaType.APPLICATION_XML);
ext(dm, "xsd", MediaType.APPLICATION_W3C_SCHEMA);
ext(dm, "xsl", MediaType.APPLICATION_W3C_XSLT);
ext(dm, "xslt", MediaType.APPLICATION_W3C_XSLT);
ext(dm, "xul", MediaType.APPLICATION_XUL);
ext(dm, "z", MediaType.APPLICATION_COMPRESS);
ext(dm, "zip", MediaType.APPLICATION_ZIP);
+ // [enddef]
+ ext(dm, "htm", MediaType.TEXT_HTML);
+ ext(dm, "html", MediaType.TEXT_HTML);
+ ext(dm, "json", MediaType.APPLICATION_JSON);
+ ext(dm, "txt", MediaType.TEXT_PLAIN, true);
+ ext(dm, "xhtml", MediaType.APPLICATION_XHTML);
+ ext(dm, "xml", MediaType.TEXT_XML);
+ ext(dm, "xml", MediaType.APPLICATION_XML);
// Add all those mappings
this.mappings.addAll(dm);
}
/**
* Maps an extension to some metadata (media type, language or character
* set) to an extension.
*
* @param extension
* The extension name.
* @param metadata
* The metadata to map.
*/
public void addExtension(String extension, Metadata metadata) {
addExtension(extension, metadata, false);
}
/**
* Maps an extension to some metadata (media type, language or character
* set) to an extension.
*
* @param extension
* The extension name.
* @param metadata
* The metadata to map.
* @param preferred
* indicates if this mapping is the preferred one.
*/
public void addExtension(String extension, Metadata metadata,
boolean preferred) {
if (preferred) {
// Add the mapping at the beginning of the list
this.mappings.add(0, new MetadataExtension(extension, metadata));
} else {
// Add the mapping at the end of the list
this.mappings.add(new MetadataExtension(extension, metadata));
}
}
/**
* clears the mappings for all extensions.
*/
public void clearExtensions() {
this.mappings.clear();
}
/**
* Creates a new extension mapping.
*
* @param extensions
* The extensions list to update.
* @param extension
* The extension name.
* @param metadata
* The associated metadata.
* @param preferred
* indicates if this mapping is the preferred one.
* @return The new extension mapping.
*/
private void ext(List<MetadataExtension> extensions, String extension,
Metadata metadata) {
ext(extensions, extension, metadata, false);
}
/**
* Creates a new extension mapping.
*
* @param extensions
* The extensions list to update.
* @param extension
* The extension name.
* @param metadata
* The associated metadata.
* @param preferred
* indicates if this mapping is the preferred one.
* @return The new extension mapping.
*/
private void ext(List<MetadataExtension> extensions, String extension,
Metadata metadata, boolean preferred) {
if (preferred) {
// Add the mapping at the beginning of the list
extensions.add(0, new MetadataExtension(extension, metadata));
} else {
// Add the mapping at the end of the list
extensions.add(new MetadataExtension(extension, metadata));
}
}
/**
* Returns all the media types associated to this extension. It returns null
* if the extension was not declared.
*
* @param extension
* The extension name without any delimiter.
* @return The list of media type associated to this extension.
*/
public List<MediaType> getAllMediaTypes(String extension) {
List<MediaType> result = null;
if (extension != null) {
// Look for all registered convenient mapping.
for (final MetadataExtension metadataExtension : this.mappings) {
if (extension.equals(metadataExtension.getName())
&& (metadataExtension.getMetadata() instanceof MediaType)) {
if (result == null) {
result = new ArrayList<MediaType>();
}
result.add(metadataExtension.getMediaType());
}
}
}
return result;
}
/**
* Returns all the metadata associated to this extension. It returns null if
* the extension was not declared.
*
* @param extension
* The extension name without any delimiter.
* @return The list of metadata associated to this extension.
*/
public List<Metadata> getAllMetadata(String extension) {
List<Metadata> result = null;
if (extension != null) {
// Look for all registered convenient mapping.
for (final MetadataExtension metadataExtension : this.mappings) {
if (extension.equals(metadataExtension.getName())) {
if (result == null) {
result = new ArrayList<Metadata>();
}
result.add(metadataExtension.getMetadata());
}
}
}
return result;
}
/**
* Returns the character set associated to this extension. It returns null
* if the extension was not declared of it is corresponds to another type of
* medatata such as a media type. If several metadata are associated to the
* same extension then only the first matching metadata is returned.
*
*
* @param extension
* The extension name without any delimiter.
* @return The character set associated to this extension.
*/
public CharacterSet getCharacterSet(String extension) {
// [ifndef gwt] instruction
return getMetadata(extension, CharacterSet.class);
// [ifdef gwt] uncomment
// Metadata metadata = getMetadata(extension);
// if (metadata instanceof CharacterSet) {
// return (CharacterSet) metadata;
// } else {
// return null;
// }
// [enddef]
}
/**
* Returns the default character set for textual representations.
*
* @return The default character set for textual representations.
*/
public CharacterSet getDefaultCharacterSet() {
return this.defaultCharacterSet;
}
/**
* Returns the default encoding for representations.
*
* @return The default encoding for representations.
*/
public Encoding getDefaultEncoding() {
return this.defaultEncoding;
}
/**
* Returns the default language for representations.
*
* @return The default language for representations.
*/
public Language getDefaultLanguage() {
return this.defaultLanguage;
}
/**
* Returns the default media type for representations.
*
* @return The default media type for representations.
*/
public MediaType getDefaultMediaType() {
return this.defaultMediaType;
}
/**
* Returns the encoding associated to this extension. It returns null if the
* extension was not declared of it is corresponds to another type of
* medatata such as a media type. If several metadata are associated to the
* same extension then only the first matching metadata is returned.
*
* @param extension
* The extension name without any delimiter.
* @return The encoding associated to this extension.
*/
public Encoding getEncoding(String extension) {
// [ifndef gwt] instruction
return getMetadata(extension, Encoding.class);
// [ifdef gwt] uncomment
// Metadata metadata = getMetadata(extension);
// if (metadata instanceof Encoding) {
// return (Encoding) metadata;
// } else {
// return null;
// }
// [enddef]
}
/**
* Returns the first extension mapping to this metadata.
*
* @param metadata
* The metadata to find.
* @return The first extension mapping to this metadata.
*/
public String getExtension(Metadata metadata) {
if (metadata != null) {
// Look for the first registered convenient mapping.
for (final MetadataExtension metadataExtension : this.mappings) {
if (metadata.equals(metadataExtension.getMetadata())) {
return metadataExtension.getName();
}
}
}
return null;
}
/**
* Returns the language associated to this extension. It returns null if the
* extension was not declared of it is corresponds to another type of
* medatata such as a media type. If several metadata are associated to the
* same extension then only the first matching metadata is returned.
*
* @param extension
* The extension name without any delimiter.
* @return The language associated to this extension.
*/
public Language getLanguage(String extension) {
// [ifndef gwt] instruction
return getMetadata(extension, Language.class);
// [ifdef gwt] uncomment
// Metadata metadata = getMetadata(extension);
// if (metadata instanceof Language) {
// return (Language) metadata;
// } else {
// return null;
// }
// [enddef]
}
/**
* Returns the mediatype associated to this extension. It returns null if
* the extension was not declared of it is corresponds to another type of
* medatata such as a language. If several metadata are associated to the
* same extension (ex: 'xml' for both 'text/xml' and 'application/xml') then
* only the first matching metadata is returned.
*
*
* @param extension
* The extension name without any delimiter.
* @return The media type associated to this extension.
*/
public MediaType getMediaType(String extension) {
// [ifndef gwt] instruction
return getMetadata(extension, MediaType.class);
// [ifdef gwt] uncomment
// Metadata metadata = getMetadata(extension);
// if (metadata instanceof MediaType) {
// return (MediaType) metadata;
// } else {
// return null;
// }
// [enddef]
}
/**
* Returns the metadata associated to this extension. It returns null if the
* extension was not declared. If several metadata are associated to the
* same extension (ex: 'xml' for both 'text/xml' and 'application/xml') then
* only the first matching metadata is returned.
*
* @param extension
* The extension name without any delimiter.
* @return The metadata associated to this extension.
*/
public Metadata getMetadata(String extension) {
if (extension != null) {
// Look for the first registered convenient mapping.
for (final MetadataExtension metadataExtension : this.mappings) {
if (extension.equals(metadataExtension.getName())) {
return metadataExtension.getMetadata();
}
}
}
return null;
}
// [ifndef gwt] method
/**
* Returns the metadata associated to this extension. It returns null if the
* extension was not declared or is not of the target metadata type.
*
* @param <T>
* @param extension
* The extension name without any delimiter.
* @param metadataType
* The target metadata type.
* @return The metadata associated to this extension.
*/
public <T extends Metadata> T getMetadata(String extension,
Class<T> metadataType) {
Metadata metadata = getMetadata(extension);
if (metadata != null
&& metadataType.isAssignableFrom(metadata.getClass())) {
return metadataType.cast(metadata);
}
return null;
}
/**
* Sets the default character set for local representations.
*
* @param defaultCharacterSet
* The default character set for local representations.
*/
public void setDefaultCharacterSet(CharacterSet defaultCharacterSet) {
this.defaultCharacterSet = defaultCharacterSet;
}
/**
* Sets the default encoding for local representations.
*
* @param defaultEncoding
* The default encoding for local representations.
*/
public void setDefaultEncoding(Encoding defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
/**
* Sets the default language for local representations.
*
* @param defaultLanguage
* The default language for local representations.
*/
public void setDefaultLanguage(Language defaultLanguage) {
this.defaultLanguage = defaultLanguage;
}
/**
* Sets the default media type for local representations.
*
* @param defaultMediaType
* The default media type for local representations.
*/
public void setDefaultMediaType(MediaType defaultMediaType) {
this.defaultMediaType = defaultMediaType;
}
}
| false | true | public void addCommonExtensions() {
List<MetadataExtension> dm = new ArrayList<MetadataExtension>();
ext(dm, "en", Language.ENGLISH);
ext(dm, "es", Language.SPANISH);
ext(dm, "fr", Language.FRENCH);
ext(dm, "ai", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "ascii", CharacterSet.US_ASCII);
ext(dm, "atom", MediaType.APPLICATION_ATOM);
ext(dm, "atomcat", MediaType.APPLICATION_ATOMPUB_CATEGORY);
ext(dm, "atomsvc", MediaType.APPLICATION_ATOMPUB_SERVICE);
ext(dm, "au", MediaType.AUDIO_BASIC);
ext(dm, "bin", MediaType.APPLICATION_OCTET_STREAM);
ext(dm, "bmp", MediaType.IMAGE_BMP);
ext(dm, "class", MediaType.APPLICATION_JAVA);
ext(dm, "css", MediaType.TEXT_CSS);
ext(dm, "csv", MediaType.TEXT_CSV);
ext(dm, "dat", MediaType.TEXT_DAT);
ext(dm, "dib", MediaType.IMAGE_BMP);
ext(dm, "doc", MediaType.APPLICATION_WORD);
ext(dm, "docm", MediaType.APPLICATION_MSOFFICE_DOCM);
ext(dm, "docx", MediaType.APPLICATION_MSOFFICE_DOCX);
ext(dm, "dotm", MediaType.APPLICATION_MSOFFICE_DOTM);
ext(dm, "dotx", MediaType.APPLICATION_MSOFFICE_DOTX);
ext(dm, "dtd", MediaType.APPLICATION_XML_DTD);
ext(dm, "eps", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "exe", MediaType.APPLICATION_OCTET_STREAM);
ext(dm, "fmt", Encoding.FREEMARKER);
ext(dm, "form", MediaType.APPLICATION_WWW_FORM);
ext(dm, "ftl", Encoding.FREEMARKER, true);
ext(dm, "gif", MediaType.IMAGE_GIF);
ext(dm, "hqx", MediaType.APPLICATION_MAC_BINHEX40);
ext(dm, "htm", MediaType.TEXT_HTML);
ext(dm, "html", MediaType.TEXT_HTML);
ext(dm, "ico", MediaType.IMAGE_ICON);
ext(dm, "jad", MediaType.TEXT_J2ME_APP_DESCRIPTOR);
ext(dm, "jar", MediaType.APPLICATION_JAVA_ARCHIVE);
ext(dm, "java", MediaType.TEXT_PLAIN);
ext(dm, "jnlp", MediaType.APPLICATION_JNLP);
ext(dm, "jpe", MediaType.IMAGE_JPEG);
ext(dm, "jpeg", MediaType.IMAGE_JPEG);
ext(dm, "jpg", MediaType.IMAGE_JPEG);
ext(dm, "js", MediaType.APPLICATION_JAVASCRIPT);
ext(dm, "jsf", MediaType.TEXT_PLAIN);
ext(dm, "json", MediaType.APPLICATION_JSON);
ext(dm, "kar", MediaType.AUDIO_MIDI);
ext(dm, "latex", MediaType.APPLICATION_LATEX);
ext(dm, "latin1", CharacterSet.ISO_8859_1);
ext(dm, "mac", CharacterSet.MACINTOSH);
ext(dm, "man", MediaType.APPLICATION_TROFF_MAN);
ext(dm, "mathml", MediaType.APPLICATION_MATHML);
ext(dm, "mid", MediaType.AUDIO_MIDI);
ext(dm, "midi", MediaType.AUDIO_MIDI);
ext(dm, "mov", MediaType.VIDEO_QUICKTIME);
ext(dm, "mp2", MediaType.AUDIO_MPEG);
ext(dm, "mp3", MediaType.AUDIO_MPEG);
ext(dm, "mp4", MediaType.VIDEO_MP4);
ext(dm, "mpe", MediaType.VIDEO_MPEG);
ext(dm, "mpeg", MediaType.VIDEO_MPEG);
ext(dm, "mpg", MediaType.VIDEO_MPEG);
ext(dm, "n3", MediaType.TEXT_RDF_N3);
ext(dm, "nt", MediaType.TEXT_PLAIN);
ext(dm, "odb", MediaType.APPLICATION_OPENOFFICE_ODB);
ext(dm, "odc", MediaType.APPLICATION_OPENOFFICE_ODC);
ext(dm, "odf", MediaType.APPLICATION_OPENOFFICE_ODF);
ext(dm, "odi", MediaType.APPLICATION_OPENOFFICE_ODI);
ext(dm, "odm", MediaType.APPLICATION_OPENOFFICE_ODM);
ext(dm, "odg", MediaType.APPLICATION_OPENOFFICE_ODG);
ext(dm, "odp", MediaType.APPLICATION_OPENOFFICE_ODP);
ext(dm, "ods", MediaType.APPLICATION_OPENOFFICE_ODS);
ext(dm, "odt", MediaType.APPLICATION_OPENOFFICE_ODT);
ext(dm, "onetoc", MediaType.APPLICATION_MSOFFICE_ONETOC);
ext(dm, "onetoc2", MediaType.APPLICATION_MSOFFICE_ONETOC2);
ext(dm, "otg", MediaType.APPLICATION_OPENOFFICE_OTG);
ext(dm, "oth", MediaType.APPLICATION_OPENOFFICE_OTH);
ext(dm, "otp", MediaType.APPLICATION_OPENOFFICE_OTP);
ext(dm, "ots", MediaType.APPLICATION_OPENOFFICE_OTS);
ext(dm, "ott", MediaType.APPLICATION_OPENOFFICE_OTT);
ext(dm, "oxt", MediaType.APPLICATION_OPENOFFICE_OXT);
ext(dm, "pdf", MediaType.APPLICATION_PDF);
ext(dm, "png", MediaType.IMAGE_PNG);
ext(dm, "potx", MediaType.APPLICATION_MSOFFICE_POTX);
ext(dm, "potm", MediaType.APPLICATION_MSOFFICE_POTM);
ext(dm, "ppam", MediaType.APPLICATION_MSOFFICE_PPAM);
ext(dm, "pps", MediaType.APPLICATION_POWERPOINT);
ext(dm, "ppsm", MediaType.APPLICATION_MSOFFICE_PPSM);
ext(dm, "ppsx", MediaType.APPLICATION_MSOFFICE_PPSX);
ext(dm, "ppt", MediaType.APPLICATION_POWERPOINT);
ext(dm, "pptm", MediaType.APPLICATION_MSOFFICE_PPTM);
ext(dm, "pptx", MediaType.APPLICATION_MSOFFICE_PPTX);
ext(dm, "ps", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "qt", MediaType.VIDEO_QUICKTIME);
ext(dm, "rdf", MediaType.APPLICATION_RDF_XML);
ext(dm, "rnc", MediaType.APPLICATION_RELAXNG_COMPACT);
ext(dm, "rng", MediaType.APPLICATION_RELAXNG_XML);
ext(dm, "rss", MediaType.APPLICATION_RSS);
ext(dm, "rtf", MediaType.APPLICATION_RTF);
ext(dm, "sav", MediaType.APPLICATION_SPSS_SAV);
ext(dm, "sit", MediaType.APPLICATION_STUFFIT);
ext(dm, "sldm", MediaType.APPLICATION_MSOFFICE_SLDM);
ext(dm, "sldx", MediaType.APPLICATION_MSOFFICE_SLDX);
ext(dm, "snd", MediaType.AUDIO_BASIC);
ext(dm, "sps", MediaType.APPLICATION_SPSS_SPS);
ext(dm, "sta", MediaType.APPLICATION_STATA_STA);
ext(dm, "svg", MediaType.IMAGE_SVG);
ext(dm, "swf", MediaType.APPLICATION_FLASH);
ext(dm, "tar", MediaType.APPLICATION_TAR);
ext(dm, "tex", MediaType.APPLICATION_TEX);
ext(dm, "tif", MediaType.IMAGE_TIFF);
ext(dm, "tiff", MediaType.IMAGE_TIFF);
ext(dm, "tsv", MediaType.TEXT_TSV);
ext(dm, "txt", MediaType.TEXT_PLAIN, true);
ext(dm, "ulw", MediaType.AUDIO_BASIC);
ext(dm, "utf16", CharacterSet.UTF_16);
ext(dm, "utf8", CharacterSet.UTF_8);
ext(dm, "vm", Encoding.VELOCITY);
ext(dm, "vrml", MediaType.MODEL_VRML);
ext(dm, "vxml", MediaType.APPLICATION_VOICEXML);
ext(dm, "wadl", MediaType.APPLICATION_WADL);
ext(dm, "wav", MediaType.AUDIO_WAV);
ext(dm, "win", CharacterSet.WINDOWS_1252);
ext(dm, "wrl", MediaType.MODEL_VRML);
ext(dm, "xht", MediaType.APPLICATION_XHTML);
ext(dm, "xhtml", MediaType.APPLICATION_XHTML);
ext(dm, "xls", MediaType.APPLICATION_EXCEL);
ext(dm, "xlsx", MediaType.APPLICATION_MSOFFICE_XLSX);
ext(dm, "xlsm", MediaType.APPLICATION_MSOFFICE_XLSM);
ext(dm, "xltx", MediaType.APPLICATION_MSOFFICE_XLTX);
ext(dm, "xltm", MediaType.APPLICATION_MSOFFICE_XLTM);
ext(dm, "xlsb", MediaType.APPLICATION_MSOFFICE_XLSB);
ext(dm, "xlam", MediaType.APPLICATION_MSOFFICE_XLAM);
ext(dm, "xmi", MediaType.APPLICATION_XMI_XML);
ext(dm, "xml", MediaType.TEXT_XML);
ext(dm, "xml", MediaType.APPLICATION_XML);
ext(dm, "xsd", MediaType.APPLICATION_W3C_SCHEMA);
ext(dm, "xsl", MediaType.APPLICATION_W3C_XSLT);
ext(dm, "xslt", MediaType.APPLICATION_W3C_XSLT);
ext(dm, "xul", MediaType.APPLICATION_XUL);
ext(dm, "z", MediaType.APPLICATION_COMPRESS);
ext(dm, "zip", MediaType.APPLICATION_ZIP);
// Add all those mappings
this.mappings.addAll(dm);
}
| public void addCommonExtensions() {
List<MetadataExtension> dm = new ArrayList<MetadataExtension>();
ext(dm, "en", Language.ENGLISH);
ext(dm, "es", Language.SPANISH);
ext(dm, "fr", Language.FRENCH);
// [ifndef gwt]
ext(dm, "ai", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "ascii", CharacterSet.US_ASCII);
ext(dm, "atom", MediaType.APPLICATION_ATOM);
ext(dm, "atomcat", MediaType.APPLICATION_ATOMPUB_CATEGORY);
ext(dm, "atomsvc", MediaType.APPLICATION_ATOMPUB_SERVICE);
ext(dm, "au", MediaType.AUDIO_BASIC);
ext(dm, "bin", MediaType.APPLICATION_OCTET_STREAM);
ext(dm, "bmp", MediaType.IMAGE_BMP);
ext(dm, "class", MediaType.APPLICATION_JAVA);
ext(dm, "css", MediaType.TEXT_CSS);
ext(dm, "csv", MediaType.TEXT_CSV);
ext(dm, "dat", MediaType.TEXT_DAT);
ext(dm, "dib", MediaType.IMAGE_BMP);
ext(dm, "doc", MediaType.APPLICATION_WORD);
ext(dm, "docm", MediaType.APPLICATION_MSOFFICE_DOCM);
ext(dm, "docx", MediaType.APPLICATION_MSOFFICE_DOCX);
ext(dm, "dotm", MediaType.APPLICATION_MSOFFICE_DOTM);
ext(dm, "dotx", MediaType.APPLICATION_MSOFFICE_DOTX);
ext(dm, "dtd", MediaType.APPLICATION_XML_DTD);
ext(dm, "eps", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "exe", MediaType.APPLICATION_OCTET_STREAM);
ext(dm, "fmt", Encoding.FREEMARKER);
ext(dm, "form", MediaType.APPLICATION_WWW_FORM);
ext(dm, "ftl", Encoding.FREEMARKER, true);
ext(dm, "gif", MediaType.IMAGE_GIF);
ext(dm, "hqx", MediaType.APPLICATION_MAC_BINHEX40);
ext(dm, "ico", MediaType.IMAGE_ICON);
ext(dm, "jad", MediaType.TEXT_J2ME_APP_DESCRIPTOR);
ext(dm, "jar", MediaType.APPLICATION_JAVA_ARCHIVE);
ext(dm, "java", MediaType.TEXT_PLAIN);
ext(dm, "jnlp", MediaType.APPLICATION_JNLP);
ext(dm, "jpe", MediaType.IMAGE_JPEG);
ext(dm, "jpeg", MediaType.IMAGE_JPEG);
ext(dm, "jpg", MediaType.IMAGE_JPEG);
ext(dm, "js", MediaType.APPLICATION_JAVASCRIPT);
ext(dm, "jsf", MediaType.TEXT_PLAIN);
ext(dm, "kar", MediaType.AUDIO_MIDI);
ext(dm, "latex", MediaType.APPLICATION_LATEX);
ext(dm, "latin1", CharacterSet.ISO_8859_1);
ext(dm, "mac", CharacterSet.MACINTOSH);
ext(dm, "man", MediaType.APPLICATION_TROFF_MAN);
ext(dm, "mathml", MediaType.APPLICATION_MATHML);
ext(dm, "mid", MediaType.AUDIO_MIDI);
ext(dm, "midi", MediaType.AUDIO_MIDI);
ext(dm, "mov", MediaType.VIDEO_QUICKTIME);
ext(dm, "mp2", MediaType.AUDIO_MPEG);
ext(dm, "mp3", MediaType.AUDIO_MPEG);
ext(dm, "mp4", MediaType.VIDEO_MP4);
ext(dm, "mpe", MediaType.VIDEO_MPEG);
ext(dm, "mpeg", MediaType.VIDEO_MPEG);
ext(dm, "mpg", MediaType.VIDEO_MPEG);
ext(dm, "n3", MediaType.TEXT_RDF_N3);
ext(dm, "nt", MediaType.TEXT_PLAIN);
ext(dm, "odb", MediaType.APPLICATION_OPENOFFICE_ODB);
ext(dm, "odc", MediaType.APPLICATION_OPENOFFICE_ODC);
ext(dm, "odf", MediaType.APPLICATION_OPENOFFICE_ODF);
ext(dm, "odi", MediaType.APPLICATION_OPENOFFICE_ODI);
ext(dm, "odm", MediaType.APPLICATION_OPENOFFICE_ODM);
ext(dm, "odg", MediaType.APPLICATION_OPENOFFICE_ODG);
ext(dm, "odp", MediaType.APPLICATION_OPENOFFICE_ODP);
ext(dm, "ods", MediaType.APPLICATION_OPENOFFICE_ODS);
ext(dm, "odt", MediaType.APPLICATION_OPENOFFICE_ODT);
ext(dm, "onetoc", MediaType.APPLICATION_MSOFFICE_ONETOC);
ext(dm, "onetoc2", MediaType.APPLICATION_MSOFFICE_ONETOC2);
ext(dm, "otg", MediaType.APPLICATION_OPENOFFICE_OTG);
ext(dm, "oth", MediaType.APPLICATION_OPENOFFICE_OTH);
ext(dm, "otp", MediaType.APPLICATION_OPENOFFICE_OTP);
ext(dm, "ots", MediaType.APPLICATION_OPENOFFICE_OTS);
ext(dm, "ott", MediaType.APPLICATION_OPENOFFICE_OTT);
ext(dm, "oxt", MediaType.APPLICATION_OPENOFFICE_OXT);
ext(dm, "pdf", MediaType.APPLICATION_PDF);
ext(dm, "png", MediaType.IMAGE_PNG);
ext(dm, "potx", MediaType.APPLICATION_MSOFFICE_POTX);
ext(dm, "potm", MediaType.APPLICATION_MSOFFICE_POTM);
ext(dm, "ppam", MediaType.APPLICATION_MSOFFICE_PPAM);
ext(dm, "pps", MediaType.APPLICATION_POWERPOINT);
ext(dm, "ppsm", MediaType.APPLICATION_MSOFFICE_PPSM);
ext(dm, "ppsx", MediaType.APPLICATION_MSOFFICE_PPSX);
ext(dm, "ppt", MediaType.APPLICATION_POWERPOINT);
ext(dm, "pptm", MediaType.APPLICATION_MSOFFICE_PPTM);
ext(dm, "pptx", MediaType.APPLICATION_MSOFFICE_PPTX);
ext(dm, "ps", MediaType.APPLICATION_POSTSCRIPT);
ext(dm, "qt", MediaType.VIDEO_QUICKTIME);
ext(dm, "rdf", MediaType.APPLICATION_RDF_XML);
ext(dm, "rnc", MediaType.APPLICATION_RELAXNG_COMPACT);
ext(dm, "rng", MediaType.APPLICATION_RELAXNG_XML);
ext(dm, "rss", MediaType.APPLICATION_RSS);
ext(dm, "rtf", MediaType.APPLICATION_RTF);
ext(dm, "sav", MediaType.APPLICATION_SPSS_SAV);
ext(dm, "sit", MediaType.APPLICATION_STUFFIT);
ext(dm, "sldm", MediaType.APPLICATION_MSOFFICE_SLDM);
ext(dm, "sldx", MediaType.APPLICATION_MSOFFICE_SLDX);
ext(dm, "snd", MediaType.AUDIO_BASIC);
ext(dm, "sps", MediaType.APPLICATION_SPSS_SPS);
ext(dm, "sta", MediaType.APPLICATION_STATA_STA);
ext(dm, "svg", MediaType.IMAGE_SVG);
ext(dm, "swf", MediaType.APPLICATION_FLASH);
ext(dm, "tar", MediaType.APPLICATION_TAR);
ext(dm, "tex", MediaType.APPLICATION_TEX);
ext(dm, "tif", MediaType.IMAGE_TIFF);
ext(dm, "tiff", MediaType.IMAGE_TIFF);
ext(dm, "tsv", MediaType.TEXT_TSV);
ext(dm, "ulw", MediaType.AUDIO_BASIC);
ext(dm, "utf16", CharacterSet.UTF_16);
ext(dm, "utf8", CharacterSet.UTF_8);
ext(dm, "vm", Encoding.VELOCITY);
ext(dm, "vrml", MediaType.MODEL_VRML);
ext(dm, "vxml", MediaType.APPLICATION_VOICEXML);
ext(dm, "wadl", MediaType.APPLICATION_WADL);
ext(dm, "wav", MediaType.AUDIO_WAV);
ext(dm, "win", CharacterSet.WINDOWS_1252);
ext(dm, "wrl", MediaType.MODEL_VRML);
ext(dm, "xht", MediaType.APPLICATION_XHTML);
ext(dm, "xls", MediaType.APPLICATION_EXCEL);
ext(dm, "xlsx", MediaType.APPLICATION_MSOFFICE_XLSX);
ext(dm, "xlsm", MediaType.APPLICATION_MSOFFICE_XLSM);
ext(dm, "xltx", MediaType.APPLICATION_MSOFFICE_XLTX);
ext(dm, "xltm", MediaType.APPLICATION_MSOFFICE_XLTM);
ext(dm, "xlsb", MediaType.APPLICATION_MSOFFICE_XLSB);
ext(dm, "xlam", MediaType.APPLICATION_MSOFFICE_XLAM);
ext(dm, "xmi", MediaType.APPLICATION_XMI_XML);
ext(dm, "xsd", MediaType.APPLICATION_W3C_SCHEMA);
ext(dm, "xsl", MediaType.APPLICATION_W3C_XSLT);
ext(dm, "xslt", MediaType.APPLICATION_W3C_XSLT);
ext(dm, "xul", MediaType.APPLICATION_XUL);
ext(dm, "z", MediaType.APPLICATION_COMPRESS);
ext(dm, "zip", MediaType.APPLICATION_ZIP);
// [enddef]
ext(dm, "htm", MediaType.TEXT_HTML);
ext(dm, "html", MediaType.TEXT_HTML);
ext(dm, "json", MediaType.APPLICATION_JSON);
ext(dm, "txt", MediaType.TEXT_PLAIN, true);
ext(dm, "xhtml", MediaType.APPLICATION_XHTML);
ext(dm, "xml", MediaType.TEXT_XML);
ext(dm, "xml", MediaType.APPLICATION_XML);
// Add all those mappings
this.mappings.addAll(dm);
}
|
diff --git a/src/java/no/schibstedsok/front/searchportal/query/transform/TvQueryTransformer.java b/src/java/no/schibstedsok/front/searchportal/query/transform/TvQueryTransformer.java
index 1af96d14c..4bb9c907c 100644
--- a/src/java/no/schibstedsok/front/searchportal/query/transform/TvQueryTransformer.java
+++ b/src/java/no/schibstedsok/front/searchportal/query/transform/TvQueryTransformer.java
@@ -1,67 +1,67 @@
// Copyright (2006) Schibsted Søk AS
package no.schibstedsok.front.searchportal.query.transform;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* TvQueryTransformer is part of no.schibstedsok.front.searchportal.query
*
* @author Ola Marius Sagli <a href="[email protected]">ola at schibstedsok</a>
* @version $Id$
*/
public final class TvQueryTransformer extends AbstractQueryTransformer {
private static final Log LOG = LogFactory.getLog(TvQueryTransformer.class);
private static final int REG_EXP_OPTIONS = Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
private static final Pattern TV_PATTERNS
= Pattern.compile("((p(å|aa?)\\s+)?tv(\\s+i\\s?dag)?|(tv(-|\\s+))?program(oversikt)?|fjernsyn)(\\s*\\:)?",
REG_EXP_OPTIONS);
/**
* Add keywords to query to get better searchresults
*
* @param originalQuery
* @return
*/
public String getTransformedQuery() {
// If a channel has been chosen using tv_ syntax. Query should be empty
// to return everything.
if (getContext().getQuery().getQueryString().startsWith("tv_")) {
return "";
}
final String transformedQuery = getContext().getTransformedQuery();
return TV_PATTERNS.matcher(transformedQuery).replaceAll("");
}
/**
* Set docdatetime > current date
* @return docdatetime:>[FORMATTED DATE]
*/
public String getFilter() {
final String origQuery = getContext().getQuery().getQueryString();
final StringBuilder filter = new StringBuilder();
// Special case to choose channel.
if (origQuery.startsWith("tv_")) {
- filter.append("+wpfornavn:^");
+ filter.append("+sgeneric11:'");
filter.append(origQuery.substring(3));
- filter.append("$ ");
+ filter.append("' ");
}
filter.append("+starttime:>");
filter.append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
return filter.toString();
}
}
| false | true | public String getFilter() {
final String origQuery = getContext().getQuery().getQueryString();
final StringBuilder filter = new StringBuilder();
// Special case to choose channel.
if (origQuery.startsWith("tv_")) {
filter.append("+wpfornavn:^");
filter.append(origQuery.substring(3));
filter.append("$ ");
}
filter.append("+starttime:>");
filter.append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
return filter.toString();
}
| public String getFilter() {
final String origQuery = getContext().getQuery().getQueryString();
final StringBuilder filter = new StringBuilder();
// Special case to choose channel.
if (origQuery.startsWith("tv_")) {
filter.append("+sgeneric11:'");
filter.append(origQuery.substring(3));
filter.append("' ");
}
filter.append("+starttime:>");
filter.append(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(new Date()));
return filter.toString();
}
|
diff --git a/Dubsar/src/com/dubsar_dictionary/Dubsar/DubsarService.java b/Dubsar/src/com/dubsar_dictionary/Dubsar/DubsarService.java
index 86686b7..e4cf7ad 100644
--- a/Dubsar/src/com/dubsar_dictionary/Dubsar/DubsarService.java
+++ b/Dubsar/src/com/dubsar_dictionary/Dubsar/DubsarService.java
@@ -1,292 +1,293 @@
/*
Dubsar Dictionary Project
Copyright (C) 2010-11 Jimmy Dee
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.dubsar_dictionary.Dubsar;
import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.IBinder;
import android.provider.BaseColumns;
import android.util.Log;
public class DubsarService extends Service {
public static final int WOTD_ID=1;
public static final int MILLIS_PER_DAY=86400000;
public static final String ACTION_WOTD = "action_wotd";
public static final String WOTD_TEXT = "wotd_text";
public static final String ERROR_MESSAGE = "error_message";
private Timer mTimer=new Timer(true);
private NotificationManager mNotificationMgr = null;
private ConnectivityManager mConnectivityMgr=null;
private long mNextWotdTime=0;
private int mWotdId=0;
private String mWotdText=null;
private String mWotdNameAndPos=null;
private boolean mHasError=false;
@Override
public void onCreate() {
super.onCreate();
Log.i(getString(R.string.app_name), "DubsarService created");
mNotificationMgr =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mConnectivityMgr =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
computeNextWotdTime();
if (mNextWotdTime - System.currentTimeMillis() > 2000) {
/*
* If it's more than 2 seconds till the next WOTD,
* request the last one immediately and set the time to
* the (approximate) time it was generated.
*/
requestNow();
}
requestDaily();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(getString(R.string.app_name), "DubsarService destroyed");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i(getString(R.string.app_name),
"DubsarService received start command, intent action = " +
intent.getAction());
if (ACTION_WOTD.equals(intent.getAction())) {
generateBroadcast(hasError() ? getString(R.string.no_network) : null);
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public boolean hasError() {
return mHasError;
}
protected void clearError() {
resetTimer();
mHasError = false;
}
protected void resetTimer() {
mTimer.cancel();
mTimer = new Timer(true);
}
/**
* Determine whether the network is currently available. There must
* be a better way to do this.
* @return true if the network is available; false otherwise
*/
protected boolean isNetworkAvailable() {
NetworkInfo wifiInfo = mConnectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileInfo = mConnectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return wifiInfo.isConnected() || mobileInfo.isConnected();
}
protected void saveResults(Cursor cursor) {
if (cursor == null) return;
int idColumn = cursor.getColumnIndex(BaseColumns._ID);
int nameAndPosColumn = cursor.getColumnIndex(DubsarContentProvider.WORD_NAME_AND_POS);
int freqCntColumn = cursor.getColumnIndex(DubsarContentProvider.WORD_FREQ_CNT);
cursor.moveToFirst();
mWotdId = cursor.getInt(idColumn);
mWotdNameAndPos = cursor.getString(nameAndPosColumn);
int freqCnt = cursor.getInt(freqCntColumn);
mWotdText = mWotdNameAndPos;
if (freqCnt > 0) {
mWotdText += " freq. cnt.:" + freqCnt;
}
}
protected void generateNotification(long time) {
Notification notification = new Notification(R.drawable.ic_dubsar_rounded,
getString(R.string.dubsar_wotd), time);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent wordIntent = new Intent(this, WordActivity.class);
wordIntent.putExtra(DubsarContentProvider.WORD_NAME_AND_POS, mWotdText);
Uri uri = Uri.withAppendedPath(DubsarContentProvider.CONTENT_URI,
DubsarContentProvider.WORDS_URI_PATH + "/" + mWotdId);
wordIntent.setData(uri);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, wordIntent, 0);
notification.setLatestEventInfo(this, getString(R.string.dubsar_wotd),
getString(R.string.dubsar_wotd) + ": " + mWotdText, contentIntent);
mNotificationMgr.notify(WOTD_ID, notification);
generateBroadcast(null);
computeNextWotdTime();
}
protected void generateBroadcast(String error) {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ACTION_WOTD);
if (error == null) {
broadcastIntent.putExtra(BaseColumns._ID, mWotdId);
broadcastIntent.putExtra(WOTD_TEXT, mWotdText);
broadcastIntent.putExtra(DubsarContentProvider.WORD_NAME_AND_POS,
mWotdNameAndPos);
}
else {
broadcastIntent.putExtra(ERROR_MESSAGE, error);
}
sendStickyBroadcast(broadcastIntent);
}
protected void computeNextWotdTime() {
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
int _amPm = now.get(Calendar.AM_PM);
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
if (_amPm == Calendar.PM) hour += 12;
int secondsTillNext = (23-hour)*3600 + (59-minute)*60 + 60 - second;
// add a 30-second pad
secondsTillNext += 30;
mNextWotdTime = now.getTimeInMillis() + secondsTillNext*1000;
}
protected void requestNow() {
long lastWotdTime = mNextWotdTime - MILLIS_PER_DAY;
mTimer.schedule(new WotdTimer(this, lastWotdTime), 0);
}
protected void requestDaily() {
/* schedule requests for WOTD once a day */
mTimer.scheduleAtFixedRate(new WotdTimer(this),
mNextWotdTime - System.currentTimeMillis(),
MILLIS_PER_DAY);
}
protected void startRerequesting() {
Log.d(getString(R.string.app_name), "network out, polling...");
resetTimer();
// begin rechecking every 5 seconds
mTimer.scheduleAtFixedRate(new WotdTimer(this), 5000, 5000);
}
protected void noNetworkError() {
Log.d(getString(R.string.app_name), getString(R.string.no_network));
if (!hasError()) generateBroadcast(getString(R.string.no_network));
startRerequesting();
mHasError = true;
}
static class WotdTimer extends TimerTask {
private final WeakReference<DubsarService> mServiceReference;
private long mWotdTime=0;
public WotdTimer(DubsarService service) {
mServiceReference = new WeakReference<DubsarService>(service);
}
public WotdTimer(DubsarService service, long wotdTime) {
mServiceReference = new WeakReference<DubsarService>(service);
mWotdTime = wotdTime;
}
public DubsarService getService() {
return mServiceReference != null ? mServiceReference.get() : null;
}
@Override
public void run() {
if (getService() == null) return;
if (!getService().isNetworkAvailable()) {
getService().noNetworkError();
return;
}
else if (getService().hasError()) {
getService().clearError();
getService().requestNow();
getService().requestDaily();
+ return;
}
Uri uri = Uri.withAppendedPath(DubsarContentProvider.CONTENT_URI,
DubsarContentProvider.WOTD_URI_PATH);
ContentResolver resolver = getService().getContentResolver();
Cursor cursor = resolver.query(uri, null, null, null, null);
// the request should not take long, but since we have a weak
// reference:
if (getService() == null) return;
long notificationTime = mWotdTime != 0 ? mWotdTime : System.currentTimeMillis();
getService().saveResults(cursor);
getService().generateNotification(notificationTime);
cursor.close();
}
}
}
| true | true | public void run() {
if (getService() == null) return;
if (!getService().isNetworkAvailable()) {
getService().noNetworkError();
return;
}
else if (getService().hasError()) {
getService().clearError();
getService().requestNow();
getService().requestDaily();
}
Uri uri = Uri.withAppendedPath(DubsarContentProvider.CONTENT_URI,
DubsarContentProvider.WOTD_URI_PATH);
ContentResolver resolver = getService().getContentResolver();
Cursor cursor = resolver.query(uri, null, null, null, null);
// the request should not take long, but since we have a weak
// reference:
if (getService() == null) return;
long notificationTime = mWotdTime != 0 ? mWotdTime : System.currentTimeMillis();
getService().saveResults(cursor);
getService().generateNotification(notificationTime);
cursor.close();
}
| public void run() {
if (getService() == null) return;
if (!getService().isNetworkAvailable()) {
getService().noNetworkError();
return;
}
else if (getService().hasError()) {
getService().clearError();
getService().requestNow();
getService().requestDaily();
return;
}
Uri uri = Uri.withAppendedPath(DubsarContentProvider.CONTENT_URI,
DubsarContentProvider.WOTD_URI_PATH);
ContentResolver resolver = getService().getContentResolver();
Cursor cursor = resolver.query(uri, null, null, null, null);
// the request should not take long, but since we have a weak
// reference:
if (getService() == null) return;
long notificationTime = mWotdTime != 0 ? mWotdTime : System.currentTimeMillis();
getService().saveResults(cursor);
getService().generateNotification(notificationTime);
cursor.close();
}
|
diff --git a/cyklotron-core/src/main/java/net/cyklotron/cms/sitemap/internal/SitemapServiceImpl.java b/cyklotron-core/src/main/java/net/cyklotron/cms/sitemap/internal/SitemapServiceImpl.java
index 2cededa4c..c5d2523ae 100644
--- a/cyklotron-core/src/main/java/net/cyklotron/cms/sitemap/internal/SitemapServiceImpl.java
+++ b/cyklotron-core/src/main/java/net/cyklotron/cms/sitemap/internal/SitemapServiceImpl.java
@@ -1,192 +1,192 @@
package net.cyklotron.cms.sitemap.internal;
import static java.lang.String.format;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.jcontainer.dna.ConfigurationException;
import org.jcontainer.dna.Logger;
import org.objectledge.coral.entity.AmbigousEntityNameException;
import org.objectledge.coral.entity.EntityDoesNotExistException;
import org.objectledge.coral.session.CoralSession;
import org.objectledge.coral.session.CoralSessionFactory;
import org.objectledge.filesystem.FileSystem;
import org.objectledge.parameters.DefaultParameters;
import org.objectledge.parameters.Parameters;
import net.cyklotron.cms.integration.ApplicationResource;
import net.cyklotron.cms.integration.IntegrationService;
import net.cyklotron.cms.site.SiteResource;
import net.cyklotron.cms.site.SiteService;
import net.cyklotron.cms.sitemap.SitemapGenerationParticipant;
import net.cyklotron.cms.sitemap.SitemapItem;
import net.cyklotron.cms.sitemap.SitemapService;
public class SitemapServiceImpl
implements SitemapService
{
private static final String CONFIGURATION_PATH = "/cms/sitemaps";
private static final String APPLICATION_NAME = "sitemap";
private final List<SitemapGenerationParticipant> participants;
private final CoralSessionFactory coralSessionFactory;
private final IntegrationService integrationService;
private final SiteService siteService;
private final Logger logger;
private final FileSystem fileSystem;
public SitemapServiceImpl(SitemapGenerationParticipant[] participants, FileSystem fileSystem,
SiteService siteService, IntegrationService integrationService,
CoralSessionFactory coralSessionFactory, Logger logger)
throws ConfigurationException
{
this.participants = Arrays.asList(participants);
this.fileSystem = fileSystem;
this.siteService = siteService;
this.integrationService = integrationService;
this.coralSessionFactory = coralSessionFactory;
this.logger = logger;
}
@Override
public SitemapConfiguration configuration()
{
try(CoralSession coralSession = coralSessionFactory.getRootSession())
{
return (SitemapConfiguration)coralSession.getStore().getUniqueResourceByPath(
CONFIGURATION_PATH);
}
catch(EntityDoesNotExistException | AmbigousEntityNameException e)
{
throw new IllegalStateException("unable to access sitemap application configuration", e);
}
}
@Override
public List<SitemapGenerationParticipant> participants()
{
return Collections.unmodifiableList(participants);
}
public void generateSitemaps()
{
try(CoralSession coralSession = coralSessionFactory.getRootSession())
{
SitemapConfiguration config = (SitemapConfiguration)coralSession.getStore()
.getUniqueResourceByPath(CONFIGURATION_PATH);
final String basePath = config.getBasePath();
if(basePath != null)
{
ApplicationResource app = integrationService.getApplication(coralSession,
APPLICATION_NAME);
for(SiteResource site : siteService.getSites(coralSession))
{
if(integrationService.isApplicationEnabled(coralSession, site, app))
{
try
{
String domain = siteService.getPrimaryMapping(coralSession, site);
if(domain == null)
{
logger
.error(format(
"unable to generate site map for site %s because primary virtual host is not set",
site.getName()));
}
else
{
SitemapWriter sw = new SitemapWriter(fileSystem, basePath, domain,
config.getCompress());
sw.write(itemIterator(site, domain, config.getParticipantsConfig(),
coralSession));
}
}
catch(Exception e)
{
logger.error(
format("unable to generate site map for site %s", site.getName()),
e);
}
}
}
}
else
{
logger.error("unable to generate site maps, base path is not set in configuration");
}
}
catch(EntityDoesNotExistException | AmbigousEntityNameException e)
{
logger.error("unable to access sitemap application configuration");
}
}
private Iterator<SitemapItem> itemIterator(final SiteResource site, final String domain,
final Parameters participantsConfig, final CoralSession coralSession)
{
return new Iterator<SitemapItem>()
{
private final Iterator<SitemapGenerationParticipant> outer = participants
.iterator();
private Iterator<SitemapItem> inner = null;
private Iterator<SitemapItem> nextInner()
{
final SitemapGenerationParticipant participant = outer.next();
if(participant.supportsConfiguration())
{
return participant.items(site, domain,
participantsConfig.getChild(participant.name() + "."), coralSession);
}
else
{
return participant.items(site, domain, new DefaultParameters(),
coralSession);
}
}
@Override
public boolean hasNext()
{
- if(inner == null)
+ if(inner == null || !inner.hasNext())
{
if(outer.hasNext())
{
inner = nextInner();
}
else
{
return false;
}
}
return inner.hasNext();
}
@Override
public SitemapItem next()
{
if(inner == null || !inner.hasNext())
{
inner = nextInner();
}
return inner.next();
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
}
| true | true | private Iterator<SitemapItem> itemIterator(final SiteResource site, final String domain,
final Parameters participantsConfig, final CoralSession coralSession)
{
return new Iterator<SitemapItem>()
{
private final Iterator<SitemapGenerationParticipant> outer = participants
.iterator();
private Iterator<SitemapItem> inner = null;
private Iterator<SitemapItem> nextInner()
{
final SitemapGenerationParticipant participant = outer.next();
if(participant.supportsConfiguration())
{
return participant.items(site, domain,
participantsConfig.getChild(participant.name() + "."), coralSession);
}
else
{
return participant.items(site, domain, new DefaultParameters(),
coralSession);
}
}
@Override
public boolean hasNext()
{
if(inner == null)
{
if(outer.hasNext())
{
inner = nextInner();
}
else
{
return false;
}
}
return inner.hasNext();
}
@Override
public SitemapItem next()
{
if(inner == null || !inner.hasNext())
{
inner = nextInner();
}
return inner.next();
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
| private Iterator<SitemapItem> itemIterator(final SiteResource site, final String domain,
final Parameters participantsConfig, final CoralSession coralSession)
{
return new Iterator<SitemapItem>()
{
private final Iterator<SitemapGenerationParticipant> outer = participants
.iterator();
private Iterator<SitemapItem> inner = null;
private Iterator<SitemapItem> nextInner()
{
final SitemapGenerationParticipant participant = outer.next();
if(participant.supportsConfiguration())
{
return participant.items(site, domain,
participantsConfig.getChild(participant.name() + "."), coralSession);
}
else
{
return participant.items(site, domain, new DefaultParameters(),
coralSession);
}
}
@Override
public boolean hasNext()
{
if(inner == null || !inner.hasNext())
{
if(outer.hasNext())
{
inner = nextInner();
}
else
{
return false;
}
}
return inner.hasNext();
}
@Override
public SitemapItem next()
{
if(inner == null || !inner.hasNext())
{
inner = nextInner();
}
return inner.next();
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
|
diff --git a/src/main/java/org/mctourney/AutoReferee/listeners/TeamListener.java b/src/main/java/org/mctourney/AutoReferee/listeners/TeamListener.java
index c06c355..56271dc 100644
--- a/src/main/java/org/mctourney/AutoReferee/listeners/TeamListener.java
+++ b/src/main/java/org/mctourney/AutoReferee/listeners/TeamListener.java
@@ -1,246 +1,251 @@
package org.mctourney.AutoReferee.listeners;
import java.util.Iterator;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.block.Sign;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.plugin.Plugin;
import org.mctourney.AutoReferee.AutoRefMap;
import org.mctourney.AutoReferee.AutoRefMatch;
import org.mctourney.AutoReferee.AutoRefMatch.Role;
import org.mctourney.AutoReferee.AutoRefPlayer;
import org.mctourney.AutoReferee.AutoRefTeam;
import org.mctourney.AutoReferee.AutoReferee;
import com.google.common.collect.Maps;
public class TeamListener implements Listener
{
AutoReferee plugin = null;
// mapping spectators to the matches they died in
Map<String, AutoRefMatch> deadSpectators = Maps.newHashMap();
public TeamListener(Plugin p)
{ plugin = (AutoReferee) p; }
@EventHandler(priority=EventPriority.HIGHEST)
public void chatMessage(AsyncPlayerChatEvent event)
{
// typical chat message format, swap out with colored version
Player speaker = event.getPlayer();
AutoRefMatch match = plugin.getMatch(speaker.getWorld());
// restrict listeners to being in the same match (not world).
// this should avoid messing up multi-world chat on multipurpose servers
Iterator<Player> iter = event.getRecipients().iterator();
while (iter.hasNext())
{
Player listener = iter.next();
if (plugin.getMatch(listener.getWorld()) != match)
{ iter.remove(); continue; }
}
// if the speaker isn't in a match, that's all we can do
if (match == null) return;
AutoRefTeam speakerTeam = match.getPlayerTeam(speaker);
Role speakerRole = match.getRole(speaker);
- event.setFormat("<" + match.getDisplayName(speaker) + "> " + event.getMessage());
+ if (speakerTeam != null)
+ {
+ ChatColor teamColor = speakerTeam.getColor();
+ event.setFormat("<" + teamColor + "%s" + ChatColor.RESET + "> %s");
+ }
+ else event.setFormat("<%s> %s");
iter = event.getRecipients().iterator();
if (!match.getCurrentState().isBeforeMatch()) while (iter.hasNext())
{
Player listener = iter.next();
// if listener is a streamer and the speaker is a non-streamer spectator, hide it
if (match.isStreamer(listener) && speakerTeam == null && speakerRole != Role.STREAMER)
{ iter.remove(); continue; }
// if listener is on a team, and speaker is a spectator, hide message
if (speakerTeam == null && match.getPlayerTeam(listener) != null)
{ iter.remove(); continue; }
}
}
@EventHandler(priority=EventPriority.MONITOR)
public void spectatorDeath(PlayerDeathEvent event)
{
World world = event.getEntity().getWorld();
AutoRefMatch match = plugin.getMatch(world);
if (match != null && !match.isPlayer(event.getEntity()))
{
deadSpectators.put(event.getEntity().getName(), match);
event.getDrops().clear();
}
}
@EventHandler(priority=EventPriority.MONITOR)
public void spectatorDeath(EntityDamageEvent event)
{
World world = event.getEntity().getWorld();
AutoRefMatch match = plugin.getMatch(world);
if (event.getEntityType() != EntityType.PLAYER) return;
Player player = (Player) event.getEntity();
if (match != null && match.getCurrentState().inProgress() &&
!match.isPlayer(player))
{
event.setCancelled(true);
if (player.getLocation().getY() < -64)
player.teleport(match.getPlayerSpawn(player));
player.setFallDistance(0);
}
}
@EventHandler
public void playerRespawn(PlayerRespawnEvent event)
{
String name = event.getPlayer().getName();
if (deadSpectators.containsKey(name))
{
AutoRefMatch match = deadSpectators.get(name);
if (match != null) event.setRespawnLocation(match.getWorldSpawn());
deadSpectators.remove(name); return;
}
World world = event.getPlayer().getWorld();
AutoRefMatch match = plugin.getMatch(world);
if (match != null && match.isPlayer(event.getPlayer()))
{
// does this player have a bed spawn?
boolean hasBed = event.getPlayer().getBedSpawnLocation() != null;
// if the player attempts to respawn in a different world, bring them back
if (!hasBed || event.getRespawnLocation().getWorld() != match.getWorld())
event.setRespawnLocation(match.getPlayerSpawn(event.getPlayer()));
// setup respawn for the player
match.getPlayer(event.getPlayer()).respawn();
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void playerLogin(PlayerLoginEvent event)
{
Player player = event.getPlayer();
if (plugin.isAutoMode())
{
// if they should be whitelisted, let them in, otherwise, block them
if (plugin.playerWhitelisted(player)) event.allow();
else
{
event.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, AutoReferee.NO_LOGIN_MESSAGE);
return;
}
}
// if this player needs to be in a specific world, put them there
AutoRefTeam team = plugin.getExpectedTeam(player);
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (team != null) { team.join(player); match = team.getMatch(); }
if (match != null && match.isPlayer(player))
match.messageReferees("player", player.getName(), "login");
}
@EventHandler(priority=EventPriority.MONITOR)
public void playerQuit(PlayerQuitEvent event)
{
Player player = event.getPlayer();
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (match == null) return;
// leave the team, if necessary
AutoRefTeam team = plugin.getTeam(player);
if (team != null) match.messageReferees("player", player.getName(), "logout");
if (team != null && !match.getCurrentState().inProgress()) team.leave(player);
AutoRefPlayer apl = match.getPlayer(player);
if (apl != null && player.getLocation() != null)
apl.setLastLogoutLocation(player.getLocation());
// if this player was damaged recently (during the match), notify
if (match.getCurrentState().inProgress() && apl != null && !apl.isDead() && apl.wasDamagedRecently())
{
String message = apl.getDisplayName() + ChatColor.GRAY + " logged out during combat " +
String.format("with %2.1f hearts remaining", apl.getPlayer().getHealth() / 2.0);
for (Player ref : match.getReferees(true)) ref.sendMessage(message);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void signCommand(PlayerInteractEvent event)
{
Player player = event.getPlayer();
AutoRefMatch match = plugin.getMatch(player.getWorld());
if (event.hasBlock() && event.getClickedBlock().getState() instanceof Sign)
{
String[] lines = ((Sign) event.getClickedBlock().getState()).getLines();
if (lines[0] == null || !"[AutoReferee]".equals(lines[0])) return;
if (match != null && match.getCurrentState().isBeforeMatch() &&
match.inStartRegion(event.getClickedBlock().getLocation()))
{
// execute the command on the sign (and hope like hell that AutoReferee picks it up)
if (event.getAction() == Action.RIGHT_CLICK_BLOCK)
player.performCommand(ChatColor.stripColor(lines[1] + " " + lines[2]).trim());
event.setCancelled(true);
}
else if (player.getWorld() == plugin.getLobbyWorld())
{
// load the world named on the sign
if (event.getAction() == Action.RIGHT_CLICK_BLOCK)
{
// cancel the event only if its a right click
event.setCancelled(true);
player.sendMessage(ChatColor.GREEN + "Please wait...");
String mapName = lines[1] + " " + lines[2] + " " + lines[3];
AutoRefMap.loadMap(player, mapName.trim(), null);
}
}
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void changeGamemode(PlayerGameModeChangeEvent event)
{
Player player = event.getPlayer();
AutoRefMatch match = plugin.getMatch(player.getWorld());
// if there is a match currently in progress on this world...
if (match != null && plugin.isAutoMode() &&
match.getCurrentState().inProgress())
{
// cancel the gamemode change if the player is a participant
if (event.getNewGameMode() == GameMode.CREATIVE &&
match.isPlayer(player)) event.setCancelled(true);
}
}
}
| true | true | public void chatMessage(AsyncPlayerChatEvent event)
{
// typical chat message format, swap out with colored version
Player speaker = event.getPlayer();
AutoRefMatch match = plugin.getMatch(speaker.getWorld());
// restrict listeners to being in the same match (not world).
// this should avoid messing up multi-world chat on multipurpose servers
Iterator<Player> iter = event.getRecipients().iterator();
while (iter.hasNext())
{
Player listener = iter.next();
if (plugin.getMatch(listener.getWorld()) != match)
{ iter.remove(); continue; }
}
// if the speaker isn't in a match, that's all we can do
if (match == null) return;
AutoRefTeam speakerTeam = match.getPlayerTeam(speaker);
Role speakerRole = match.getRole(speaker);
event.setFormat("<" + match.getDisplayName(speaker) + "> " + event.getMessage());
iter = event.getRecipients().iterator();
if (!match.getCurrentState().isBeforeMatch()) while (iter.hasNext())
{
Player listener = iter.next();
// if listener is a streamer and the speaker is a non-streamer spectator, hide it
if (match.isStreamer(listener) && speakerTeam == null && speakerRole != Role.STREAMER)
{ iter.remove(); continue; }
// if listener is on a team, and speaker is a spectator, hide message
if (speakerTeam == null && match.getPlayerTeam(listener) != null)
{ iter.remove(); continue; }
}
}
| public void chatMessage(AsyncPlayerChatEvent event)
{
// typical chat message format, swap out with colored version
Player speaker = event.getPlayer();
AutoRefMatch match = plugin.getMatch(speaker.getWorld());
// restrict listeners to being in the same match (not world).
// this should avoid messing up multi-world chat on multipurpose servers
Iterator<Player> iter = event.getRecipients().iterator();
while (iter.hasNext())
{
Player listener = iter.next();
if (plugin.getMatch(listener.getWorld()) != match)
{ iter.remove(); continue; }
}
// if the speaker isn't in a match, that's all we can do
if (match == null) return;
AutoRefTeam speakerTeam = match.getPlayerTeam(speaker);
Role speakerRole = match.getRole(speaker);
if (speakerTeam != null)
{
ChatColor teamColor = speakerTeam.getColor();
event.setFormat("<" + teamColor + "%s" + ChatColor.RESET + "> %s");
}
else event.setFormat("<%s> %s");
iter = event.getRecipients().iterator();
if (!match.getCurrentState().isBeforeMatch()) while (iter.hasNext())
{
Player listener = iter.next();
// if listener is a streamer and the speaker is a non-streamer spectator, hide it
if (match.isStreamer(listener) && speakerTeam == null && speakerRole != Role.STREAMER)
{ iter.remove(); continue; }
// if listener is on a team, and speaker is a spectator, hide message
if (speakerTeam == null && match.getPlayerTeam(listener) != null)
{ iter.remove(); continue; }
}
}
|
diff --git a/miiflipper/src/MiiLayer.java b/miiflipper/src/MiiLayer.java
index fed135c..a982b2d 100644
--- a/miiflipper/src/MiiLayer.java
+++ b/miiflipper/src/MiiLayer.java
@@ -1,334 +1,335 @@
import com.jtattoo.plaf.noire.NoireLookAndFeel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.Properties;
public class MiiLayer extends JFrame implements ActionListener {
private MiicraftImager miicraft = new MiicraftImager(null);
private MiicraftModel miimodel = new MiicraftModel();
private String path;
public MiiLayer() {
try {
- Properties props = new Properties();
- props.put("logoString", "miiImager");
- props.put("licenseKey", "39q5-dpgu-fat5-xz81");
- NoireLookAndFeel.setCurrentTheme(props);
- com.jtattoo.plaf.noire.NoireLookAndFeel.setTheme("Noire");
- UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
+ //Properties props = new Properties();
+ //props.put("logoString", "miiImager");
+ //props.put("licenseKey", "39q5-dpgu-fat5-xz81");
+ //NoireLookAndFeel.setCurrentTheme(props);
+ //com.jtattoo.plaf.noire.NoireLookAndFeel.setTheme("Noire");
+ //UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
+ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
BorderLayout bl = new BorderLayout();
setName("miilayer");
setLayout(bl);
setBounds(0, 0, 1000, 800);
setVisible(true);
// text output
JTextPane messages = new JTextPane();
messages.setBackground(Color.DARK_GRAY);
messages.setForeground(Color.white);
messages.setPreferredSize(new Dimension(350, 480));
messages.setEditable(false);
JScrollPane messageScroller = new JScrollPane(messages);
messageScroller.setAutoscrolls(true);
messageScroller.setWheelScrollingEnabled(true);
///
//text pan
JTextPane messagesx = new JTextPane();
messagesx.setBackground(Color.BLUE);
messagesx.setForeground(Color.yellow);
messagesx.setPreferredSize(new Dimension(350, 480));
messagesx.setEditable(false);
JScrollPane messageScrollerx = new JScrollPane(messagesx);
messageScrollerx.setAutoscrolls(true);
messageScrollerx.setWheelScrollingEnabled(true);
///
miicraft.setMessages(messages);
miicraft.setVisible(true);
miicraft.setSize(768, 480);
miimodel.setMessages(messagesx);
miimodel.setVisible(true);
miimodel.setSize(768, 480);
//menue
JMenuBar menubar = new JMenuBar();
JMenu a = new JMenu("Files");
a.add(menuitem("Open"));
a.addSeparator();
a.add(menuitem("Save Layer"));
a.addSeparator();
a.add(menuitem("Travel UP"));
a.add(menuitem("Travel DOWN"));
a.addSeparator();
a.add(menuitem("Generate Structure"));
a.add(menuitem("Generate Structure Steps"));
a.addSeparator();
a.add(menuitem("Calculate and Generate"));
menubar.add(a);
JMenu b = new JMenu("Model");
b.add(menuitem("Reconstruct Model"));
menubar.add(b);
JMenu c = new JMenu("Tools");
c.add(menuitem("Toggle FloodFill"));
menubar.add(c);
JButton up = new JButton("up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.up();
miicraft.repaint();
}
});
JButton down = new JButton("down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.down();
miicraft.repaint();
}
});
JButton black = new JButton("black");
black.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.setBlack();
}
});
JButton white = new JButton("white");
white.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.setWhite();
}
});
// save a single layer
JButton save = new JButton("save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.save();
}
});
// save a single layer
JButton clearAllPoints = new JButton("clearPoints");
clearAllPoints.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.clearPoints();
}
});
// save a single layer
JButton clearAllStrokes = new JButton("clearStrokes");
clearAllStrokes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.clearStrokes();
}
});
// orbit 3d
JButton orbitX = new JButton("orbitX");
orbitX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.orbitX(miimodel.getVoxels());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
}
});
JButton orbitY = new JButton("orbitY");
orbitY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.orbitY(miimodel.getVoxels());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
}
});
JPanel controllButtonsA = new JPanel();
controllButtonsA.add(up);
controllButtonsA.add(down);
controllButtonsA.add(white);
controllButtonsA.add(black);
controllButtonsA.add(save);
controllButtonsA.add(clearAllPoints);
controllButtonsA.add(clearAllStrokes);
JPanel controllButtonsB = new JPanel();
controllButtonsB.add(orbitX);
controllButtonsB.add(orbitY);
JPanel layers = new JPanel(new BorderLayout());
layers.add(BorderLayout.PAGE_END, controllButtonsA);
layers.add(BorderLayout.CENTER, miicraft);
layers.add(BorderLayout.LINE_START, messageScroller);
JPanel threedee = new JPanel(new BorderLayout());
threedee.add(BorderLayout.PAGE_END, controllButtonsB);
threedee.add(BorderLayout.CENTER, miimodel);
threedee.add(BorderLayout.LINE_START, messageScrollerx);
JTabbedPane tabs = new JTabbedPane();
tabs.add("layers", layers);
tabs.add("model", threedee);
setJMenuBar(menubar);
add(tabs);
miicraft.insertMessage("miiLayer designer ready ...");
setVisible(true);
//layers.setVisible(true);
//messages.setVisible(true);
//messagesx.setVisible(true);
//miicraft.setVisible(true);
//controllButtonsA.setVisible(true);
//threedee.setVisible(true);
repaint();
}
public JMenuItem menuitem(String itemName) {
JMenuItem item = new JMenuItem(itemName);
item.addActionListener(this);
return item;
}
public static void main(String[] params) {
new MiiLayer();
}
public void actionPerformed(ActionEvent event) {
if (event == null) {
return;
}
if (event.getActionCommand().equals("Open")) {
System.out.println("user.home = " + System.getProperty("user.home"));
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select Image Folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setCurrentDirectory(new File(System.getProperty("user.home")));
chooser.showOpenDialog(this);
try {
miicraft.setDirectory(chooser.getSelectedFile().getPath());
miicraft.initiateImage();
miimodel.setDirectory(chooser.getSelectedFile().getPath());
miimodel.initiateImage();
} catch (Exception e) {
System.out.println("no file set ...");
}
} else if (event.getActionCommand().equals("Save Layer")) {
if (miicraft == null) {
return;
}
miicraft.save();
} else if (event.getActionCommand().equals("Travel UP")) {
Thread t = new Thread(new TravelUp(miicraft));
t.start();
} else if (event.getActionCommand().equals("Travel DOWN")) {
Thread t = new Thread(new TravelDown(miicraft));
t.start();
} else if (event.getActionCommand().equals("Generate Structure")) {
Thread t = new Thread(new Generator(miicraft));
t.start();
} else if (event.getActionCommand().equals("Generate Structure Steps")) {
Thread t = new Thread(new GeneratorStep(miicraft));
t.start();
} else if (event.getActionCommand().equals("Calculate and Generate")) {
Thread t = new Thread(new GenerateStructure(miicraft));
t.start();
} else if (event.getActionCommand().equals("Reconstruct Model")) {
Thread t = new Thread(new Reconstruct(miimodel));
t.start();
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
} else if (event.getActionCommand().equals("Toggle FloodFill")) {
if (miicraft.isFloodFill()) {
miicraft.setFloodFill(false);
} else {
miicraft.setFloodFill(true);
}
miicraft.repaint();
}
}
}
| true | true | public MiiLayer() {
try {
Properties props = new Properties();
props.put("logoString", "miiImager");
props.put("licenseKey", "39q5-dpgu-fat5-xz81");
NoireLookAndFeel.setCurrentTheme(props);
com.jtattoo.plaf.noire.NoireLookAndFeel.setTheme("Noire");
UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
} catch (Exception ex) {
ex.printStackTrace();
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
BorderLayout bl = new BorderLayout();
setName("miilayer");
setLayout(bl);
setBounds(0, 0, 1000, 800);
setVisible(true);
// text output
JTextPane messages = new JTextPane();
messages.setBackground(Color.DARK_GRAY);
messages.setForeground(Color.white);
messages.setPreferredSize(new Dimension(350, 480));
messages.setEditable(false);
JScrollPane messageScroller = new JScrollPane(messages);
messageScroller.setAutoscrolls(true);
messageScroller.setWheelScrollingEnabled(true);
///
//text pan
JTextPane messagesx = new JTextPane();
messagesx.setBackground(Color.BLUE);
messagesx.setForeground(Color.yellow);
messagesx.setPreferredSize(new Dimension(350, 480));
messagesx.setEditable(false);
JScrollPane messageScrollerx = new JScrollPane(messagesx);
messageScrollerx.setAutoscrolls(true);
messageScrollerx.setWheelScrollingEnabled(true);
///
miicraft.setMessages(messages);
miicraft.setVisible(true);
miicraft.setSize(768, 480);
miimodel.setMessages(messagesx);
miimodel.setVisible(true);
miimodel.setSize(768, 480);
//menue
JMenuBar menubar = new JMenuBar();
JMenu a = new JMenu("Files");
a.add(menuitem("Open"));
a.addSeparator();
a.add(menuitem("Save Layer"));
a.addSeparator();
a.add(menuitem("Travel UP"));
a.add(menuitem("Travel DOWN"));
a.addSeparator();
a.add(menuitem("Generate Structure"));
a.add(menuitem("Generate Structure Steps"));
a.addSeparator();
a.add(menuitem("Calculate and Generate"));
menubar.add(a);
JMenu b = new JMenu("Model");
b.add(menuitem("Reconstruct Model"));
menubar.add(b);
JMenu c = new JMenu("Tools");
c.add(menuitem("Toggle FloodFill"));
menubar.add(c);
JButton up = new JButton("up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.up();
miicraft.repaint();
}
});
JButton down = new JButton("down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.down();
miicraft.repaint();
}
});
JButton black = new JButton("black");
black.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.setBlack();
}
});
JButton white = new JButton("white");
white.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.setWhite();
}
});
// save a single layer
JButton save = new JButton("save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.save();
}
});
// save a single layer
JButton clearAllPoints = new JButton("clearPoints");
clearAllPoints.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.clearPoints();
}
});
// save a single layer
JButton clearAllStrokes = new JButton("clearStrokes");
clearAllStrokes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.clearStrokes();
}
});
// orbit 3d
JButton orbitX = new JButton("orbitX");
orbitX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.orbitX(miimodel.getVoxels());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
}
});
JButton orbitY = new JButton("orbitY");
orbitY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.orbitY(miimodel.getVoxels());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
}
});
JPanel controllButtonsA = new JPanel();
controllButtonsA.add(up);
controllButtonsA.add(down);
controllButtonsA.add(white);
controllButtonsA.add(black);
controllButtonsA.add(save);
controllButtonsA.add(clearAllPoints);
controllButtonsA.add(clearAllStrokes);
JPanel controllButtonsB = new JPanel();
controllButtonsB.add(orbitX);
controllButtonsB.add(orbitY);
JPanel layers = new JPanel(new BorderLayout());
layers.add(BorderLayout.PAGE_END, controllButtonsA);
layers.add(BorderLayout.CENTER, miicraft);
layers.add(BorderLayout.LINE_START, messageScroller);
JPanel threedee = new JPanel(new BorderLayout());
threedee.add(BorderLayout.PAGE_END, controllButtonsB);
threedee.add(BorderLayout.CENTER, miimodel);
threedee.add(BorderLayout.LINE_START, messageScrollerx);
JTabbedPane tabs = new JTabbedPane();
tabs.add("layers", layers);
tabs.add("model", threedee);
setJMenuBar(menubar);
add(tabs);
miicraft.insertMessage("miiLayer designer ready ...");
setVisible(true);
//layers.setVisible(true);
//messages.setVisible(true);
//messagesx.setVisible(true);
//miicraft.setVisible(true);
//controllButtonsA.setVisible(true);
//threedee.setVisible(true);
repaint();
}
| public MiiLayer() {
try {
//Properties props = new Properties();
//props.put("logoString", "miiImager");
//props.put("licenseKey", "39q5-dpgu-fat5-xz81");
//NoireLookAndFeel.setCurrentTheme(props);
//com.jtattoo.plaf.noire.NoireLookAndFeel.setTheme("Noire");
//UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
ex.printStackTrace();
}
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
BorderLayout bl = new BorderLayout();
setName("miilayer");
setLayout(bl);
setBounds(0, 0, 1000, 800);
setVisible(true);
// text output
JTextPane messages = new JTextPane();
messages.setBackground(Color.DARK_GRAY);
messages.setForeground(Color.white);
messages.setPreferredSize(new Dimension(350, 480));
messages.setEditable(false);
JScrollPane messageScroller = new JScrollPane(messages);
messageScroller.setAutoscrolls(true);
messageScroller.setWheelScrollingEnabled(true);
///
//text pan
JTextPane messagesx = new JTextPane();
messagesx.setBackground(Color.BLUE);
messagesx.setForeground(Color.yellow);
messagesx.setPreferredSize(new Dimension(350, 480));
messagesx.setEditable(false);
JScrollPane messageScrollerx = new JScrollPane(messagesx);
messageScrollerx.setAutoscrolls(true);
messageScrollerx.setWheelScrollingEnabled(true);
///
miicraft.setMessages(messages);
miicraft.setVisible(true);
miicraft.setSize(768, 480);
miimodel.setMessages(messagesx);
miimodel.setVisible(true);
miimodel.setSize(768, 480);
//menue
JMenuBar menubar = new JMenuBar();
JMenu a = new JMenu("Files");
a.add(menuitem("Open"));
a.addSeparator();
a.add(menuitem("Save Layer"));
a.addSeparator();
a.add(menuitem("Travel UP"));
a.add(menuitem("Travel DOWN"));
a.addSeparator();
a.add(menuitem("Generate Structure"));
a.add(menuitem("Generate Structure Steps"));
a.addSeparator();
a.add(menuitem("Calculate and Generate"));
menubar.add(a);
JMenu b = new JMenu("Model");
b.add(menuitem("Reconstruct Model"));
menubar.add(b);
JMenu c = new JMenu("Tools");
c.add(menuitem("Toggle FloodFill"));
menubar.add(c);
JButton up = new JButton("up");
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.up();
miicraft.repaint();
}
});
JButton down = new JButton("down");
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.down();
miicraft.repaint();
}
});
JButton black = new JButton("black");
black.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.setBlack();
}
});
JButton white = new JButton("white");
white.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.setWhite();
}
});
// save a single layer
JButton save = new JButton("save");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.save();
}
});
// save a single layer
JButton clearAllPoints = new JButton("clearPoints");
clearAllPoints.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.clearPoints();
}
});
// save a single layer
JButton clearAllStrokes = new JButton("clearStrokes");
clearAllStrokes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miicraft.clearStrokes();
}
});
// orbit 3d
JButton orbitX = new JButton("orbitX");
orbitX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.orbitX(miimodel.getVoxels());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
}
});
JButton orbitY = new JButton("orbitY");
orbitY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
miimodel.getCurrentImage().getGraphics().clearRect(0, 0, miimodel.getCurrentImage().getWidth(), miimodel.getCurrentImage().getHeight());
Reconstruct.orbitY(miimodel.getVoxels());
Reconstruct.project(miimodel.getCurrentImage(), miimodel.getVoxels());
miimodel.repaint();
}
});
JPanel controllButtonsA = new JPanel();
controllButtonsA.add(up);
controllButtonsA.add(down);
controllButtonsA.add(white);
controllButtonsA.add(black);
controllButtonsA.add(save);
controllButtonsA.add(clearAllPoints);
controllButtonsA.add(clearAllStrokes);
JPanel controllButtonsB = new JPanel();
controllButtonsB.add(orbitX);
controllButtonsB.add(orbitY);
JPanel layers = new JPanel(new BorderLayout());
layers.add(BorderLayout.PAGE_END, controllButtonsA);
layers.add(BorderLayout.CENTER, miicraft);
layers.add(BorderLayout.LINE_START, messageScroller);
JPanel threedee = new JPanel(new BorderLayout());
threedee.add(BorderLayout.PAGE_END, controllButtonsB);
threedee.add(BorderLayout.CENTER, miimodel);
threedee.add(BorderLayout.LINE_START, messageScrollerx);
JTabbedPane tabs = new JTabbedPane();
tabs.add("layers", layers);
tabs.add("model", threedee);
setJMenuBar(menubar);
add(tabs);
miicraft.insertMessage("miiLayer designer ready ...");
setVisible(true);
//layers.setVisible(true);
//messages.setVisible(true);
//messagesx.setVisible(true);
//miicraft.setVisible(true);
//controllButtonsA.setVisible(true);
//threedee.setVisible(true);
repaint();
}
|
diff --git a/tests/src/org/jboss/test/messaging/util/VeryBasicValveTest.java b/tests/src/org/jboss/test/messaging/util/VeryBasicValveTest.java
index 920f94766..add6b0bd8 100644
--- a/tests/src/org/jboss/test/messaging/util/VeryBasicValveTest.java
+++ b/tests/src/org/jboss/test/messaging/util/VeryBasicValveTest.java
@@ -1,132 +1,132 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.messaging.util;
import junit.framework.TestCase;
import org.jboss.logging.Logger;
import org.jboss.jms.util.Valve;
/**
* This verifies the very basic functionality of ConnectionState.Valve.
* Two functions can't enter at the same time, and this will test that routine
* @author <a href="mailto:[email protected]">Clebert Suconic</a>
* @version <tt>$Revision:$</tt>
* <p/>
* $Id:$
*/
public class VeryBasicValveTest extends TestCase
{
private static Logger log = Logger.getLogger(VeryBasicValveTest.class);
static int counter = 0;
static int counterWait = 0;
static boolean started=false;
static Object startSemaphore = new Object();
static Valve valve = new Valve();
// multiple threads opening/closing a thread.
// only one should be able to open it
public static class SomeThread extends Thread
{
int threadId;
public SomeThread(int threadId)
{
this.threadId = threadId;
}
public void run()
{
try
{
log.info("Starting Thread " + threadId);
synchronized (startSemaphore)
{
if (!started)
{
startSemaphore.wait();
}
}
//log.info("Thread " + threadId + "Opening valve");
if (!valve.open())
{
//log.info("Valve couldn't be opened at thread " + threadId);
synchronized (VeryBasicValveTest.class)
{
counterWait ++;
}
} else
{
//log.info("Thread " + threadId + " could open the valve");
//Thread.sleep(1000);
synchronized (VeryBasicValveTest.class)
{
counter ++;
}
+ valve.close();
}
//log.info("Thread " + threadId + " is now closing the valve");
- valve.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void testValve() throws Exception
{
SomeThread thread[] = new SomeThread[2500];
for (int i=0; i<thread.length; i++)
{
thread[i] = new SomeThread(i);
}
for (int i=0; i<thread.length; i++)
{
thread[i].start();
}
synchronized (startSemaphore)
{
started=true;
startSemaphore.notifyAll();
}
for (int i = 0; i < thread.length; i++)
{
thread[i].join();
}
assertEquals(1, counter);
assertEquals(thread.length-1, counterWait);
}
}
| false | true | public void run()
{
try
{
log.info("Starting Thread " + threadId);
synchronized (startSemaphore)
{
if (!started)
{
startSemaphore.wait();
}
}
//log.info("Thread " + threadId + "Opening valve");
if (!valve.open())
{
//log.info("Valve couldn't be opened at thread " + threadId);
synchronized (VeryBasicValveTest.class)
{
counterWait ++;
}
} else
{
//log.info("Thread " + threadId + " could open the valve");
//Thread.sleep(1000);
synchronized (VeryBasicValveTest.class)
{
counter ++;
}
}
//log.info("Thread " + threadId + " is now closing the valve");
valve.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
| public void run()
{
try
{
log.info("Starting Thread " + threadId);
synchronized (startSemaphore)
{
if (!started)
{
startSemaphore.wait();
}
}
//log.info("Thread " + threadId + "Opening valve");
if (!valve.open())
{
//log.info("Valve couldn't be opened at thread " + threadId);
synchronized (VeryBasicValveTest.class)
{
counterWait ++;
}
} else
{
//log.info("Thread " + threadId + " could open the valve");
//Thread.sleep(1000);
synchronized (VeryBasicValveTest.class)
{
counter ++;
}
valve.close();
}
//log.info("Thread " + threadId + " is now closing the valve");
}
catch (Exception e)
{
e.printStackTrace();
}
}
|
diff --git a/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java b/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java
index b5b7650..c661735 100644
--- a/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java
+++ b/src/main/java/plugins/WebOfTrust/fcp/GetIdentitiesByPartialNickname.java
@@ -1,106 +1,106 @@
package plugins.WebOfTrust.fcp;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.index.lucene.QueryContext;
import plugins.WebOfTrust.WebOfTrust;
import plugins.WebOfTrust.datamodel.IContext;
import plugins.WebOfTrust.datamodel.IVertex;
import plugins.WebOfTrust.datamodel.Rel;
import plugins.WebOfTrust.exceptions.UnknownIdentityException;
import freenet.node.FSParseException;
import freenet.support.SimpleFieldSet;
public class GetIdentitiesByPartialNickname extends GetIdentity {
public GetIdentitiesByPartialNickname(GraphDatabaseService db) {
super(db);
}
@Override
public SimpleFieldSet handle(SimpleFieldSet input) throws UnknownIdentityException {
final String trusterID = input.get("Truster");
final String partialNickname = input.get("PartialNickname").trim();
final String partialID = input.get("PartialID").trim();
final String context = input.get("Context");
int maxIdentities = 0;
try {
maxIdentities = input.getInt("MaxIdentities");
} catch (FSParseException e) {
throw new IllegalArgumentException("MaxIdentities has an incorrect value");
}
//find all identities for given context
reply.putSingle("Message", "Identities");
int numIdentities = 0;
//find trusterID
final Node treeOwnerNode = nodeIndex.get(IVertex.ID, trusterID).getSingle();
if (treeOwnerNode == null) throw new UnknownIdentityException("No such local identity '" + trusterID + "'.");
final String treeOwnerTrustProperty = IVertex.TRUST+"_"+treeOwnerNode.getProperty(IVertex.ID);
final Node contextNode = nodeIndex.get(IContext.NAME, context).getSingle();
//get all identities with a specific context
if (nodeIndex.get(IContext.NAME, context).hasNext()) //the context exists in the graph
{
for(Node identity : nodeIndex.query(new QueryContext( IVertex.NAME + ":" + partialNickname)))
{
//check if identity has the context
boolean has_context = false;
for(Relationship contextRel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT))
{
if (contextRel.getEndNode().equals(contextNode))
{
has_context = true;
break;
}
}
if (has_context)
{
//check whether keypart matches as well
if (((String) identity.getProperty(IVertex.ID)).startsWith(partialID))
{
//find the score relation if present
Relationship directScore = null;
for(Relationship rel : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS))
{
if (rel.getStartNode().getProperty(IVertex.ID).equals(trusterID))
{
directScore = rel;
break;
}
}
//check whether the trust is >= 0 before including
if (identity.hasProperty(treeOwnerTrustProperty))
{
if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0)
{
addIdentityReplyFields(directScore, identity, Integer.toString(numIdentities), true, trusterID);
numIdentities += 1;
}
}
}
}
- if (numIdentities > maxIdentities) continue;
+ if (numIdentities > maxIdentities) break;
}
}
reply.put("IdentitiesMatched", numIdentities);
if (WebOfTrust.DEBUG) System.out.println("GetIdentitiesByPartialNickname returned " + numIdentities + " identities for the context: " + context);
return reply;
}
}
| true | true | public SimpleFieldSet handle(SimpleFieldSet input) throws UnknownIdentityException {
final String trusterID = input.get("Truster");
final String partialNickname = input.get("PartialNickname").trim();
final String partialID = input.get("PartialID").trim();
final String context = input.get("Context");
int maxIdentities = 0;
try {
maxIdentities = input.getInt("MaxIdentities");
} catch (FSParseException e) {
throw new IllegalArgumentException("MaxIdentities has an incorrect value");
}
//find all identities for given context
reply.putSingle("Message", "Identities");
int numIdentities = 0;
//find trusterID
final Node treeOwnerNode = nodeIndex.get(IVertex.ID, trusterID).getSingle();
if (treeOwnerNode == null) throw new UnknownIdentityException("No such local identity '" + trusterID + "'.");
final String treeOwnerTrustProperty = IVertex.TRUST+"_"+treeOwnerNode.getProperty(IVertex.ID);
final Node contextNode = nodeIndex.get(IContext.NAME, context).getSingle();
//get all identities with a specific context
if (nodeIndex.get(IContext.NAME, context).hasNext()) //the context exists in the graph
{
for(Node identity : nodeIndex.query(new QueryContext( IVertex.NAME + ":" + partialNickname)))
{
//check if identity has the context
boolean has_context = false;
for(Relationship contextRel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT))
{
if (contextRel.getEndNode().equals(contextNode))
{
has_context = true;
break;
}
}
if (has_context)
{
//check whether keypart matches as well
if (((String) identity.getProperty(IVertex.ID)).startsWith(partialID))
{
//find the score relation if present
Relationship directScore = null;
for(Relationship rel : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS))
{
if (rel.getStartNode().getProperty(IVertex.ID).equals(trusterID))
{
directScore = rel;
break;
}
}
//check whether the trust is >= 0 before including
if (identity.hasProperty(treeOwnerTrustProperty))
{
if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0)
{
addIdentityReplyFields(directScore, identity, Integer.toString(numIdentities), true, trusterID);
numIdentities += 1;
}
}
}
}
if (numIdentities > maxIdentities) continue;
}
}
reply.put("IdentitiesMatched", numIdentities);
if (WebOfTrust.DEBUG) System.out.println("GetIdentitiesByPartialNickname returned " + numIdentities + " identities for the context: " + context);
return reply;
}
| public SimpleFieldSet handle(SimpleFieldSet input) throws UnknownIdentityException {
final String trusterID = input.get("Truster");
final String partialNickname = input.get("PartialNickname").trim();
final String partialID = input.get("PartialID").trim();
final String context = input.get("Context");
int maxIdentities = 0;
try {
maxIdentities = input.getInt("MaxIdentities");
} catch (FSParseException e) {
throw new IllegalArgumentException("MaxIdentities has an incorrect value");
}
//find all identities for given context
reply.putSingle("Message", "Identities");
int numIdentities = 0;
//find trusterID
final Node treeOwnerNode = nodeIndex.get(IVertex.ID, trusterID).getSingle();
if (treeOwnerNode == null) throw new UnknownIdentityException("No such local identity '" + trusterID + "'.");
final String treeOwnerTrustProperty = IVertex.TRUST+"_"+treeOwnerNode.getProperty(IVertex.ID);
final Node contextNode = nodeIndex.get(IContext.NAME, context).getSingle();
//get all identities with a specific context
if (nodeIndex.get(IContext.NAME, context).hasNext()) //the context exists in the graph
{
for(Node identity : nodeIndex.query(new QueryContext( IVertex.NAME + ":" + partialNickname)))
{
//check if identity has the context
boolean has_context = false;
for(Relationship contextRel : identity.getRelationships(Direction.OUTGOING, Rel.HAS_CONTEXT))
{
if (contextRel.getEndNode().equals(contextNode))
{
has_context = true;
break;
}
}
if (has_context)
{
//check whether keypart matches as well
if (((String) identity.getProperty(IVertex.ID)).startsWith(partialID))
{
//find the score relation if present
Relationship directScore = null;
for(Relationship rel : identity.getRelationships(Direction.INCOMING, Rel.TRUSTS))
{
if (rel.getStartNode().getProperty(IVertex.ID).equals(trusterID))
{
directScore = rel;
break;
}
}
//check whether the trust is >= 0 before including
if (identity.hasProperty(treeOwnerTrustProperty))
{
if (((Integer) identity.getProperty(treeOwnerTrustProperty)) >= 0)
{
addIdentityReplyFields(directScore, identity, Integer.toString(numIdentities), true, trusterID);
numIdentities += 1;
}
}
}
}
if (numIdentities > maxIdentities) break;
}
}
reply.put("IdentitiesMatched", numIdentities);
if (WebOfTrust.DEBUG) System.out.println("GetIdentitiesByPartialNickname returned " + numIdentities + " identities for the context: " + context);
return reply;
}
|
diff --git a/application/src/com.phdroid/smsb/filter/WhiteListSpamFilter.java b/application/src/com.phdroid/smsb/filter/WhiteListSpamFilter.java
index cc38ec8..e9cebbd 100644
--- a/application/src/com.phdroid/smsb/filter/WhiteListSpamFilter.java
+++ b/application/src/com.phdroid/smsb/filter/WhiteListSpamFilter.java
@@ -1,22 +1,22 @@
package com.phdroid.smsb.filter;
import com.phdroid.smsb.SmsPojo;
import com.phdroid.smsb.storage.dao.Session;
import com.phdroid.smsb.storage.dao.SmsMessageSenderEntry;
/**
* Spam Filter taking into consideration only white list of senders.
*/
public class WhiteListSpamFilter implements ISpamFilter {
Session session;
public WhiteListSpamFilter(Session session) {
this.session = session;
}
@Override
public boolean isSpam(SmsPojo message) {
SmsMessageSenderEntry sender = this.session.getSenderById(message.getSenderId());
- return sender.isInWhiteList();
+ return !sender.isInWhiteList();
}
}
| true | true | public boolean isSpam(SmsPojo message) {
SmsMessageSenderEntry sender = this.session.getSenderById(message.getSenderId());
return sender.isInWhiteList();
}
| public boolean isSpam(SmsPojo message) {
SmsMessageSenderEntry sender = this.session.getSenderById(message.getSenderId());
return !sender.isInWhiteList();
}
|
diff --git a/jsf-ri/src/com/sun/faces/el/CompositeComponentAttributesELResolver.java b/jsf-ri/src/com/sun/faces/el/CompositeComponentAttributesELResolver.java
index 20f82df76..c5f4958c8 100644
--- a/jsf-ri/src/com/sun/faces/el/CompositeComponentAttributesELResolver.java
+++ b/jsf-ri/src/com/sun/faces/el/CompositeComponentAttributesELResolver.java
@@ -1,422 +1,422 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.el;
import java.beans.FeatureDescriptor;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Collection;
import java.util.HashMap;
import javax.el.ELResolver;
import javax.el.ELContext;
import javax.el.ValueExpression;
import javax.el.MethodExpression;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.el.CompositeComponentExpressionHolder;
import com.sun.faces.util.Util;
import com.sun.faces.component.CompositeComponentStackManager;
import static com.sun.faces.component.CompositeComponentStackManager.StackType.TreeCreation;
import static com.sun.faces.component.CompositeComponentStackManager.StackType.Evaluation;
import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
/**
* <p>
* This {@link ELResolver} will handle the resolution of <code>attrs</code>
* when processing a composite component instance.
* </p>
*/
public class CompositeComponentAttributesELResolver extends ELResolver {
/**
* Implicit object related only to the cc implicitObject.
*/
private static final String COMPOSITE_COMPONENT_ATTRIBUTES_NAME = "attrs";
/**
* Implicit object related only to the cc implicit object
* and refers to the composite component parent (if any).
*/
private static final String COMPOSITE_COMPONENT_PARENT_NAME = "parent";
/**
* Key to which we store the mappings between composite component instances
* and their ExpressionEvalMap.
*/
private static final String EVAL_MAP_KEY =
CompositeComponentAttributesELResolver.class.getName() + "_EVAL_MAP";
// ------------------------------------------------- Methods from ELResolver
/**
* <p>
* If <code>base</code> is a composite component and <code>property</code>
* is <code>attrs</code>, return a new <code>ExpressionEvalMap</code>
* which wraps the composite component's attributes map.
* </p>
*
* <p>
* The <code>ExpressionEvalMap</code> simple evaluates any {@link ValueExpression}
* instances stored in the composite component's attribute map and returns
* the result.
* </p>
*
* <p>
* If <code>base</code> is a composite component and <code>property</code>
* is <code>parent</code> attempt to resolve the composite componet parent
* of the current composite component by calling
* {@link UIComponent#getCompositeComponentParent(javax.faces.component.UIComponent)})
* and returning that value.
* </p>
*
* @see javax.el.ELResolver#getValue(javax.el.ELContext, Object, Object)
* @see com.sun.faces.el.CompositeComponentAttributesELResolver.ExpressionEvalMap
*/
public Object getValue(ELContext context, Object base, Object property) {
Util.notNull("context", context);
if (base != null
&& (base instanceof UIComponent)
&& UIComponent.isCompositeComponent((UIComponent) base)
&& property != null) {
String propertyName = property.toString();
if (COMPOSITE_COMPONENT_ATTRIBUTES_NAME.equals(propertyName)) {
UIComponent c = (UIComponent) base;
context.setPropertyResolved(true);
FacesContext ctx = (FacesContext)
context.getContext(FacesContext.class);
return getEvalMapFor(c, ctx);
}
if (COMPOSITE_COMPONENT_PARENT_NAME.equals(propertyName)) {
UIComponent c = (UIComponent) base;
context.setPropertyResolved(true);
FacesContext ctx = (FacesContext)
context.getContext(FacesContext.class);
CompositeComponentStackManager m =
CompositeComponentStackManager.getManager(ctx);
UIComponent ccp = m.getParentCompositeComponent(TreeCreation,
ctx,
c);
if (ccp == null) {
- m.getParentCompositeComponent(Evaluation,
- ctx,
- c);
+ ccp = m.getParentCompositeComponent(Evaluation,
+ ctx,
+ c);
}
return ccp;
}
}
return null;
}
/**
* <p>
* Readonly, so return <code>null</code>.
* </p>
*
* @see ELResolver#getType(javax.el.ELContext, Object, Object)
*/
public Class<?> getType(ELContext context, Object base, Object property) {
Util.notNull("context", context);
return null;
}
/**
* <p>
* This is a no-op.
* </p>
*
* @see ELResolver#setValue(javax.el.ELContext, Object, Object, Object)
*/
public void setValue(ELContext context,
Object base,
Object property,
Object value) {
Util.notNull("context", context);
}
/**
* <p>
* Readonly, so return <code>true</code>
* </p>
*
* @see javax.el.ELResolver#isReadOnly(javax.el.ELContext, Object, Object)
*/
public boolean isReadOnly(ELContext context, Object base, Object property) {
Util.notNull("context", context);
return true;
}
/**
* <p>
* This <code>ELResolver</code> currently returns no feature descriptors
* as we have no way to effectively iterate over the UIComponent
* attributes Map.
* </p>
*
* @see javax.el.ELResolver#getFeatureDescriptors(javax.el.ELContext, Object)
*/
public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context,
Object base) {
Util.notNull("context", context);
return null;
}
/**
* <p>
* <code>attrs<code> is considered a <code>String</code> property.
* </p>
*
* @see javax.el.ELResolver#getCommonPropertyType(javax.el.ELContext, Object)
*/
public Class<?> getCommonPropertyType(ELContext context, Object base) {
Util.notNull("context", context);
return String.class;
}
// --------------------------------------------------------- Private Methods
/**
* <p>
* Creates (if necessary) and caches an <code>ExpressionEvalMap</code>
* instance associated with the owning {@link UIComponent}
* </p>
*
* @param c the owning {@link UIComponent}
* @param ctx the {@link FacesContext} for the current request
* @return an <code>ExpressionEvalMap</code> for the specified component
*/
public Map<String,Object> getEvalMapFor(UIComponent c, FacesContext ctx) {
Map<Object, Object> ctxAttributes = ctx.getAttributes();
//noinspection unchecked
Map<UIComponent,Map<String,Object>> topMap =
(Map<UIComponent,Map<String,Object>>) ctxAttributes.get(EVAL_MAP_KEY);
Map<String,Object> evalMap = null;
if (topMap == null) {
topMap = new HashMap<UIComponent,Map<String,Object>>();
ctxAttributes.put(EVAL_MAP_KEY, topMap);
evalMap = new ExpressionEvalMap(ctx, c);
topMap.put(c, evalMap);
}
if (evalMap == null) {
evalMap = topMap.get(c);
if (evalMap == null) {
evalMap = new ExpressionEvalMap(ctx, c);
topMap.put(c, evalMap);
}
}
return evalMap;
}
// ---------------------------------------------------------- Nested Classes
/**
* Simple Map implementation to evaluate any <code>ValueExpression</code>
* stored directly within the provided attributes map.
*/
private static final class ExpressionEvalMap
implements Map<String,Object>, CompositeComponentExpressionHolder {
private Map<String,Object> attributesMap;
private PropertyDescriptor[] declaredAttributes;
private Map<Object, Object> declaredDefaultValues;
private FacesContext ctx;
private UIComponent cc;
// -------------------------------------------------------- Constructors
ExpressionEvalMap(FacesContext ctx, UIComponent cc) {
this.cc = cc;
this.attributesMap = cc.getAttributes();
BeanInfo metadata = (BeanInfo) this.attributesMap.get(UIComponent.BEANINFO_KEY);
if (null != metadata) {
this.declaredAttributes = metadata.getPropertyDescriptors();
this.declaredDefaultValues = new HashMap<Object, Object>(5);
}
this.ctx = ctx;
}
// --------------------- Methods from CompositeComponentExpressionHolder
public ValueExpression getExpression(String name) {
Object ve = cc.getValueExpression(name);
return ((ve instanceof ValueExpression) ? (ValueExpression) ve : null);
}
// ---------------------------------------------------- Methods from Map
public int size() {
throw new UnsupportedOperationException();
}
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key) {
throw new UnsupportedOperationException();
}
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
public Object get(Object key) {
Object v = attributesMap.get(key);
if (v == null) {
v = getDeclaredDefaultValue(key);
if (v != null) {
return ((ValueExpression) v).getValue(ctx.getELContext());
}
}
if (v != null && v instanceof MethodExpression) {
return v;
}
return v;
}
public Object put(String key, Object value) {
// Unlinke AttributesMap.get() which will obtain a value from
// a ValueExpression, AttributesMap.put(), when passed a value,
// will never call ValueExpression.setValue(), so we have to take
// matters into our own hands...
ValueExpression ve = cc.getValueExpression(key);
if (ve != null) {
ve.setValue(ctx.getELContext(), value);
} else {
attributesMap.put(key, value);
}
return null;
}
public Object remove(Object key) {
throw new UnsupportedOperationException();
}
public void putAll(Map<? extends String,?> t) {
throw new UnsupportedOperationException();
}
public void clear() {
throw new UnsupportedOperationException();
}
public Set<String> keySet() {
throw new UnsupportedOperationException();
}
public Collection<Object> values() {
throw new UnsupportedOperationException();
}
public Set<Map.Entry<String,Object>> entrySet() {
throw new UnsupportedOperationException();
}
private Object getDeclaredDefaultValue(Object key) {
Object result = null;
// If it's not in the cache...
if (!declaredDefaultValues.containsKey(key)) {
// iterate through the property descriptors...
boolean found = false;
for (PropertyDescriptor cur : declaredAttributes) {
// and if you find a match...
if (cur.getName().equals(key)) {
found = true;
// put it in the cache, returning the value.
declaredDefaultValues.put(key, result = cur.getValue("default"));
break;
}
}
// Otherwise, if no attribute was declared
if (!found) {
// put null into the cache for future lookups.
declaredDefaultValues.put(key, null);
}
} else {
// It's in the cache, just return the value.
result = declaredDefaultValues.get(key);
}
return result;
}
}
}
| true | true | public Object getValue(ELContext context, Object base, Object property) {
Util.notNull("context", context);
if (base != null
&& (base instanceof UIComponent)
&& UIComponent.isCompositeComponent((UIComponent) base)
&& property != null) {
String propertyName = property.toString();
if (COMPOSITE_COMPONENT_ATTRIBUTES_NAME.equals(propertyName)) {
UIComponent c = (UIComponent) base;
context.setPropertyResolved(true);
FacesContext ctx = (FacesContext)
context.getContext(FacesContext.class);
return getEvalMapFor(c, ctx);
}
if (COMPOSITE_COMPONENT_PARENT_NAME.equals(propertyName)) {
UIComponent c = (UIComponent) base;
context.setPropertyResolved(true);
FacesContext ctx = (FacesContext)
context.getContext(FacesContext.class);
CompositeComponentStackManager m =
CompositeComponentStackManager.getManager(ctx);
UIComponent ccp = m.getParentCompositeComponent(TreeCreation,
ctx,
c);
if (ccp == null) {
m.getParentCompositeComponent(Evaluation,
ctx,
c);
}
return ccp;
}
}
return null;
}
| public Object getValue(ELContext context, Object base, Object property) {
Util.notNull("context", context);
if (base != null
&& (base instanceof UIComponent)
&& UIComponent.isCompositeComponent((UIComponent) base)
&& property != null) {
String propertyName = property.toString();
if (COMPOSITE_COMPONENT_ATTRIBUTES_NAME.equals(propertyName)) {
UIComponent c = (UIComponent) base;
context.setPropertyResolved(true);
FacesContext ctx = (FacesContext)
context.getContext(FacesContext.class);
return getEvalMapFor(c, ctx);
}
if (COMPOSITE_COMPONENT_PARENT_NAME.equals(propertyName)) {
UIComponent c = (UIComponent) base;
context.setPropertyResolved(true);
FacesContext ctx = (FacesContext)
context.getContext(FacesContext.class);
CompositeComponentStackManager m =
CompositeComponentStackManager.getManager(ctx);
UIComponent ccp = m.getParentCompositeComponent(TreeCreation,
ctx,
c);
if (ccp == null) {
ccp = m.getParentCompositeComponent(Evaluation,
ctx,
c);
}
return ccp;
}
}
return null;
}
|
diff --git a/src/net/sourceforge/cilib/pso/niching/FitnessDeviationCreationStrategy.java b/src/net/sourceforge/cilib/pso/niching/FitnessDeviationCreationStrategy.java
index 3a031a81..821d4fcf 100644
--- a/src/net/sourceforge/cilib/pso/niching/FitnessDeviationCreationStrategy.java
+++ b/src/net/sourceforge/cilib/pso/niching/FitnessDeviationCreationStrategy.java
@@ -1,14 +1,14 @@
package net.sourceforge.cilib.pso.niching;
import java.util.Collection;
import net.sourceforge.cilib.algorithm.PopulationBasedAlgorithm;
public class FitnessDeviationCreationStrategy<E extends PopulationBasedAlgorithm> implements SwarmCreationStrategy<E> {
- public Collection<E> create(E mainSwarm, Collection<? extends E> subSwarms) {
+ public Collection<E> create(E mainSwarm, Collection<E> subSwarms) {
// TODO Auto-generated method stub
return null;
}
}
| true | true | public Collection<E> create(E mainSwarm, Collection<? extends E> subSwarms) {
// TODO Auto-generated method stub
return null;
}
| public Collection<E> create(E mainSwarm, Collection<E> subSwarms) {
// TODO Auto-generated method stub
return null;
}
|
diff --git a/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardEntityListener.java b/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardEntityListener.java
index 76d5a4b6..2c2165ce 100644
--- a/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardEntityListener.java
+++ b/src/main/java/com/sk89q/worldguard/bukkit/WorldGuardEntityListener.java
@@ -1,882 +1,882 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
import java.util.Set;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.LocalPlayer;
import com.sk89q.worldguard.protection.GlobalRegionManager;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Creature;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.EnderDragon;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Fireball;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Painting;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.entity.Tameable;
import org.bukkit.entity.Wolf;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingBreakEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.inventory.ItemStack;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.blacklist.events.BlockBreakBlacklistEvent;
import com.sk89q.worldguard.blacklist.events.ItemUseBlacklistEvent;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.events.DisallowedPVPEvent;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
/**
* Listener for entity related events.
*
* @author sk89q
*/
public class WorldGuardEntityListener implements Listener {
private WorldGuardPlugin plugin;
/**
* Construct the object;
*
* @param plugin The plugin instance
*/
public WorldGuardEntityListener(WorldGuardPlugin plugin) {
this.plugin = plugin;
}
/**
* Register events.
*/
public void registerEvents() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityInteract(EntityInteractEvent event) {
Entity entity = event.getEntity();
Block block = event.getBlock();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (block.getTypeId() == BlockID.SOIL) {
if (entity instanceof Creature && wcfg.disableCreatureCropTrampling) {
event.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onEntityDeath(EntityDeathEvent event) {
WorldConfiguration wcfg = plugin.getGlobalStateManager().get(event.getEntity().getWorld());
if (wcfg.disableExpDrops || !plugin.getGlobalRegionManager().allows(DefaultFlag.EXP_DROPS,
event.getEntity().getLocation())) {
event.setDroppedExp(0);
}
if (event instanceof PlayerDeathEvent && wcfg.disableDeathMessages) {
((PlayerDeathEvent) event).setDeathMessage("");
}
}
private void onEntityDamageByBlock(EntityDamageByBlockEvent event) {
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness && !(type == DamageCause.VOID)) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
if (wcfg.disableLavaDamage && type == DamageCause.LAVA) {
event.setCancelled(true);
player.setFireTicks(0);
return;
}
if (wcfg.disableContactDamage && type == DamageCause.CONTACT) {
event.setCancelled(true);
return;
}
if (wcfg.teleportOnVoid && type == DamageCause.VOID) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableVoidDamage && type == DamageCause.VOID) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && type == DamageCause.BLOCK_EXPLOSION) {
event.setCancelled(true);
return;
}
}
}
private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
- if (event.getCause() == DamageCause.PROJECTILE) {
+ if (event.getDamager() instanceof Projectile) {
onEntityDamageByProjectile(event);
return;
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), held.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
if (wcfg.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
}
event.setCancelled(true);
return;
}
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.ENTITY_EXPLOSION) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof TNTPrimed) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.TNT, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Fireball) {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Fireball fireball = (Fireball) attacker;
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
private void onEntityDamageByProjectile(EntityDamageByEntityEvent event) {
Entity defender = event.getEntity();
Entity attacker = ((Projectile) event.getDamager()).getShooter();
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof Skeleton) {
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityDamage(EntityDamageEvent event) {
if (event instanceof EntityDamageByEntityEvent) {
this.onEntityDamageByEntity((EntityDamageByEntityEvent) event);
return;
} else if (event instanceof EntityDamageByBlockEvent) {
this.onEntityDamageByBlock((EntityDamageByBlockEvent) event);
return;
}
Entity defender = event.getEntity();
DamageCause type = event.getCause();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(defender.getWorld());
if (defender instanceof Wolf && ((Wolf) defender).isTamed()) {
if (wcfg.antiWolfDumbness) {
event.setCancelled(true);
return;
}
} else if (defender instanceof Player) {
Player player = (Player) defender;
if (isInvincible(player)) {
event.setCancelled(true);
player.setFireTicks(0);
return;
}
if (type == DamageCause.DROWNING && cfg.hasAmphibiousMode(player)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
ItemStack helmet = player.getInventory().getHelmet();
if (type == DamageCause.DROWNING && wcfg.pumpkinScuba
&& helmet != null
&& (helmet.getTypeId() == BlockID.PUMPKIN
|| helmet.getTypeId() == BlockID.JACKOLANTERN)) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (wcfg.disableFallDamage && type == DamageCause.FALL) {
event.setCancelled(true);
return;
}
if (wcfg.disableFireDamage && (type == DamageCause.FIRE
|| type == DamageCause.FIRE_TICK)) {
event.setCancelled(true);
return;
}
if (wcfg.disableDrowningDamage && type == DamageCause.DROWNING) {
player.setRemainingAir(player.getMaximumAir());
event.setCancelled(true);
return;
}
if (wcfg.teleportOnSuffocation && type == DamageCause.SUFFOCATION) {
BukkitUtil.findFreePosition(player);
event.setCancelled(true);
return;
}
if (wcfg.disableSuffocationDamage && type == DamageCause.SUFFOCATION) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityCombust(EntityCombustEvent event) {
Entity entity = event.getEntity();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(entity.getWorld());
if (entity instanceof Player) {
Player player = (Player) entity;
if (cfg.hasGodMode(player) || (wcfg.useRegions && RegionQueryUtil.isInvincible(plugin, player))) {
event.setCancelled(true);
return;
}
}
}
/*
* Called on entity explode.
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
Location l = event.getLocation();
World world = l.getWorld();
WorldConfiguration wcfg = cfg.get(world);
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
ent.remove();
event.setCancelled(true);
return;
}
if (ent instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.CREEPER_EXPLOSION)) {
event.blockList().clear();
return;
}
}
}
}
} else if (ent instanceof EnderDragon) {
if (wcfg.blockEnderDragonBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.ENDERDRAGON_BLOCK_DAMAGE)) {
event.blockList().clear();
return;
}
}
}
} else if (ent instanceof TNTPrimed) {
if (wcfg.blockTNTBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.TNT)) {
event.blockList().clear();
return;
}
}
}
} else if (ent instanceof Fireball) {
if (wcfg.blockFireballBlockDamage) {
event.blockList().clear();
return;
}
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
RegionManager mgr = plugin.getGlobalRegionManager().get(world);
for (Block block : event.blockList()) {
if (!mgr.getApplicableRegions(toVector(block)).allows(DefaultFlag.GHAST_FIREBALL)) {
event.blockList().clear();
return;
}
}
}
}
if (wcfg.signChestProtection) {
for (Block block : event.blockList()) {
if (wcfg.isChestProtected(block)) {
event.blockList().clear();
return;
}
}
}
}
/*
* Called on explosion prime
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onExplosionPrime(ExplosionPrimeEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
Entity ent = event.getEntity();
if (cfg.activityHaltToggle) {
ent.remove();
event.setCancelled(true);
return;
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
if (cfg.activityHaltToggle) {
event.setCancelled(true);
return;
}
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
// allow spawning of creatures from plugins
if (!wcfg.blockPluginSpawning && event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM)
return;
EntityType entityType = event.getEntityType();
if (wcfg.blockCreatureSpawn.contains(entityType)) {
event.setCancelled(true);
return;
}
Location eventLoc = event.getLocation();
if (wcfg.useRegions && cfg.useRegionsCreatureSpawnEvent) {
Vector pt = toVector(eventLoc);
RegionManager mgr = plugin.getGlobalRegionManager().get(eventLoc.getWorld());
// @TODO get victims' stacktraces and find out why it's null anyway
if (mgr == null) return;
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_SPAWNING)) {
event.setCancelled(true);
return;
}
Set<EntityType> entityTypes = set.getFlag(DefaultFlag.DENY_SPAWN);
if (entityTypes != null && entityTypes.contains(entityType)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPigZap(PigZapEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disablePigZap) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreeperPower(CreeperPowerEvent event) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld());
if (wcfg.disableCreeperPower) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingBreak(PaintingBreakEvent breakEvent) {
if (!(breakEvent instanceof PaintingBreakByEntityEvent)) {
return;
}
PaintingBreakByEntityEvent event = (PaintingBreakByEntityEvent) breakEvent;
Painting painting = event.getPainting();
World world = painting.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (event.getRemover() instanceof Player) {
Player player = (Player) event.getRemover();
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new BlockBreakBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, painting.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
} else {
if (event.getRemover() instanceof Creeper) {
if (wcfg.blockCreeperBlockDamage || wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.CREEPER_EXPLOSION, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
if (wcfg.blockEntityPaintingDestroy) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions && !plugin.getGlobalRegionManager().allows(DefaultFlag.ENTITY_PAINTING_DESTROY, painting.getLocation())) {
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onPaintingPlace(PaintingPlaceEvent event) {
Block placedOn = event.getBlock();
Player player = event.getPlayer();
World world = placedOn.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), ItemID.PAINTING), false, false)) {
event.setCancelled(true);
return;
}
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().canBuild(player, placedOn.getLocation())) {
player.sendMessage(ChatColor.DARK_RED + "You don't have permission for this area.");
event.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity ent = event.getEntity();
World world = ent.getWorld();
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(world);
if (wcfg.disableHealthRegain) {
event.setCancelled(true);
return;
}
}
/**
* Called when an enderman picks up or puts down a block and some other cases.
*
* @param event Relevant event details
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onEndermanPickup(EntityChangeBlockEvent event) {
Entity ent = event.getEntity();
Block block = event.getBlock();
Location location = block.getLocation();
if (ent instanceof Enderman) {
if (event.getTo() == Material.AIR) {
// pickup
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
} else {
// place
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(ent.getWorld());
if (wcfg.disableEndermanGriefing) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
if (!plugin.getGlobalRegionManager().allows(DefaultFlag.ENDER_BUILD, location)) {
event.setCancelled(true);
return;
}
}
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onFoodLevelChange(FoodLevelChangeEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (event.getFoodLevel() < player.getFoodLevel() && isInvincible(player)) {
event.setCancelled(true);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
GlobalRegionManager global = plugin.getGlobalRegionManager();
int blockedEntities = 0;
for (LivingEntity e : event.getAffectedEntities()) {
if (!global.allows(DefaultFlag.POTION_SPLASH, e.getLocation(), e instanceof Player ? plugin.wrapPlayer((Player) e) : null)) {
event.setIntensity(e, 0);
++blockedEntities;
}
}
if (blockedEntities == event.getAffectedEntities().size()) {
event.setCancelled(true);
}
}
/**
* Check if a player is invincible, via either god mode or region flag. If
* the region denies invincibility, the player must have an extra permission
* to override it. (worldguard.god.override-regions)
*
* @param player The player to check
* @return Whether {@code player} is invincible
*/
private boolean isInvincible(Player player) {
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
boolean god = cfg.hasGodMode(player);
if (wcfg.useRegions) {
Boolean flag = RegionQueryUtil.isAllowedInvinciblity(plugin, player);
boolean allowed = flag == null || flag;
boolean invincible = RegionQueryUtil.isInvincible(plugin, player);
if (allowed) {
return god || invincible;
} else {
return (god && plugin.hasPermission(player, "worldguard.god.override-regions"))
|| invincible;
}
} else {
return god;
}
}
/**
* Using a DisallowedPVPEvent, notifies other plugins that WorldGuard
* wants to cancel a PvP damage event.<br />
* If this event is not cancelled, the attacking player is notified that
* PvP is disabled and WorldGuard cancels the damage event.
*
* @param attackingPlayer The attacker
* @param defendingPlayer The defender
* @param event The event that caused WorldGuard to act
*/
public void tryCancelPVPEvent(final Player attackingPlayer, final Player defendingPlayer, EntityDamageByEntityEvent event) {
final DisallowedPVPEvent disallowedPVPEvent = new DisallowedPVPEvent(attackingPlayer, defendingPlayer, event);
plugin.getServer().getPluginManager().callEvent(disallowedPVPEvent);
if (!disallowedPVPEvent.isCancelled()) {
attackingPlayer.sendMessage(ChatColor.DARK_RED + "You are in a no-PvP area.");
event.setCancelled(true);
}
}
}
| true | true | private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getCause() == DamageCause.PROJECTILE) {
onEntityDamageByProjectile(event);
return;
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), held.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
if (wcfg.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
}
event.setCancelled(true);
return;
}
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.ENTITY_EXPLOSION) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof TNTPrimed) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.TNT, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Fireball) {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Fireball fireball = (Fireball) attacker;
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
| private void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Projectile) {
onEntityDamageByProjectile(event);
return;
}
Entity attacker = event.getDamager();
Entity defender = event.getEntity();
if (attacker instanceof Player) {
Player player = (Player) attacker;
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
ItemStack held = player.getInventory().getItemInHand();
if (held != null) {
if (wcfg.getBlacklist() != null) {
if (!wcfg.getBlacklist().check(
new ItemUseBlacklistEvent(plugin.wrapPlayer(player),
toVector(player.getLocation()), held.getTypeId()), false, false)) {
event.setCancelled(true);
return;
}
}
}
}
if (defender instanceof Player) {
Player player = (Player) defender;
LocalPlayer localPlayer = plugin.wrapPlayer(player);
ConfigurationManager cfg = plugin.getGlobalStateManager();
WorldConfiguration wcfg = cfg.get(player.getWorld());
if (isInvincible(player)) {
if (wcfg.regionInvinciblityRemovesMobs
&& attacker instanceof LivingEntity && !(attacker instanceof Player)
&& !(attacker instanceof Tameable && ((Tameable) attacker).isTamed())) {
attacker.remove();
}
event.setCancelled(true);
return;
}
if (wcfg.disableLightningDamage && event.getCause() == DamageCause.LIGHTNING) {
event.setCancelled(true);
return;
}
if (wcfg.disableExplosionDamage && event.getCause() == DamageCause.ENTITY_EXPLOSION) {
event.setCancelled(true);
return;
}
if (attacker != null && attacker instanceof Player) {
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
Vector pt2 = toVector(attacker.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
if (!mgr.getApplicableRegions(pt).allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) attacker))) {
tryCancelPVPEvent((Player) attacker, player, event);
return;
}
}
}
if (attacker != null && attacker instanceof TNTPrimed) {
if (wcfg.blockTNTExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.TNT, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
if (attacker != null && attacker instanceof Fireball) {
if (wcfg.blockFireballExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Fireball fireball = (Fireball) attacker;
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (fireball.getShooter() instanceof Player) {
Vector pt2 = toVector(fireball.getShooter().getLocation());
if (!set.allows(DefaultFlag.PVP, localPlayer)
|| !mgr.getApplicableRegions(pt2).allows(DefaultFlag.PVP, plugin.wrapPlayer((Player) fireball.getShooter()))) {
tryCancelPVPEvent((Player) fireball.getShooter(), player, event);
return;
}
} else {
if (!set.allows(DefaultFlag.GHAST_FIREBALL, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
if (attacker != null && attacker instanceof LivingEntity
&& !(attacker instanceof Player)) {
if (attacker instanceof Creeper && wcfg.blockCreeperExplosions) {
event.setCancelled(true);
return;
}
if (wcfg.disableMobDamage) {
event.setCancelled(true);
return;
}
if (wcfg.useRegions) {
Vector pt = toVector(defender.getLocation());
RegionManager mgr = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet set = mgr.getApplicableRegions(pt);
if (!set.allows(DefaultFlag.MOB_DAMAGE, localPlayer)) {
event.setCancelled(true);
return;
}
if (attacker instanceof Creeper) {
if (!set.allows(DefaultFlag.CREEPER_EXPLOSION, localPlayer)) {
event.setCancelled(true);
return;
}
}
}
}
}
}
|
diff --git a/GQ_Android/src/com/qeevee/gq/rules/act/ShowAlert.java b/GQ_Android/src/com/qeevee/gq/rules/act/ShowAlert.java
index c083c8c..55b7852 100644
--- a/GQ_Android/src/com/qeevee/gq/rules/act/ShowAlert.java
+++ b/GQ_Android/src/com/qeevee/gq/rules/act/ShowAlert.java
@@ -1,38 +1,38 @@
package com.qeevee.gq.rules.act;
import com.qeevee.ui.BitmapUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import edu.bonn.mobilegaming.geoquest.GeoQuestApp;
import edu.bonn.mobilegaming.geoquest.R;
public class ShowAlert extends Action {
@Override
protected boolean checkInitialization() {
return params.containsKey("message");
}
@Override
public void execute() {
AlertDialog.Builder builder = new AlertDialog.Builder(
- (Context) GeoQuestApp.getCurrentActivity()).setMessage(
+ (Context) GeoQuestApp.getCurrentActivity()).setTitle(
(params.get("message"))).setPositiveButton(R.string.ok,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
- if (params.containsKey("icon")) {
- Bitmap bitmap = BitmapUtil.loadBitmap(params.get("icon"), false);
+ if (params.containsKey("image")) {
+ Bitmap bitmap = BitmapUtil.loadBitmap(params.get("image"), false);
builder.setIcon(new BitmapDrawable(bitmap));
}
builder.show();
}
}
| false | true | public void execute() {
AlertDialog.Builder builder = new AlertDialog.Builder(
(Context) GeoQuestApp.getCurrentActivity()).setMessage(
(params.get("message"))).setPositiveButton(R.string.ok,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
if (params.containsKey("icon")) {
Bitmap bitmap = BitmapUtil.loadBitmap(params.get("icon"), false);
builder.setIcon(new BitmapDrawable(bitmap));
}
builder.show();
}
| public void execute() {
AlertDialog.Builder builder = new AlertDialog.Builder(
(Context) GeoQuestApp.getCurrentActivity()).setTitle(
(params.get("message"))).setPositiveButton(R.string.ok,
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
if (params.containsKey("image")) {
Bitmap bitmap = BitmapUtil.loadBitmap(params.get("image"), false);
builder.setIcon(new BitmapDrawable(bitmap));
}
builder.show();
}
|
diff --git a/PARQme/src/com/test/HelpActivity.java b/PARQme/src/com/test/HelpActivity.java
index 4fad208..ac54070 100644
--- a/PARQme/src/com/test/HelpActivity.java
+++ b/PARQme/src/com/test/HelpActivity.java
@@ -1,77 +1,75 @@
package com.test;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import com.quietlycoding.android.picker.NumberPickerDialog;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class HelpActivity extends Activity {
private Button testphp;
public static final String SAVED_INFO = "ParqMeInfo";
private TextView phpre;
public String time;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myhelp);
testphp = (Button) findViewById(R.id.testbutton);
phpre = (TextView) findViewById(R.id.phpresponse);
testphp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
- Intent myIntent = new Intent(HelpActivity.this, TestMap.class);
- startActivity(myIntent);
}
});
new CountDownTimer(minToMil(120), 1000){
@Override
public void onFinish() {
//unparq
}
@Override
public void onTick(long arg0) {
int seconds = (int)arg0/1000;
phpre.setText(formatMe(seconds));
}
}.start();
}
public static String formatMe(int seconds){
SimpleDateFormat sdf = new SimpleDateFormat("H:mm:ss");
try {
Date x = sdf.parse("00:00:00");
x.setSeconds(seconds);
return (sdf.format(x));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "BADBADBAD";
}
public static long minToMil(int minutes){
return minutes*60000;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myhelp);
testphp = (Button) findViewById(R.id.testbutton);
phpre = (TextView) findViewById(R.id.phpresponse);
testphp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(HelpActivity.this, TestMap.class);
startActivity(myIntent);
}
});
new CountDownTimer(minToMil(120), 1000){
@Override
public void onFinish() {
//unparq
}
@Override
public void onTick(long arg0) {
int seconds = (int)arg0/1000;
phpre.setText(formatMe(seconds));
}
}.start();
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myhelp);
testphp = (Button) findViewById(R.id.testbutton);
phpre = (TextView) findViewById(R.id.phpresponse);
testphp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
new CountDownTimer(minToMil(120), 1000){
@Override
public void onFinish() {
//unparq
}
@Override
public void onTick(long arg0) {
int seconds = (int)arg0/1000;
phpre.setText(formatMe(seconds));
}
}.start();
}
|
diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/content/DescriptionGeneratorImplTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/content/DescriptionGeneratorImplTest.java
index 5b1ef264..245e5f3b 100644
--- a/MyTracksTest/src/com/google/android/apps/mytracks/content/DescriptionGeneratorImplTest.java
+++ b/MyTracksTest/src/com/google/android/apps/mytracks/content/DescriptionGeneratorImplTest.java
@@ -1,214 +1,214 @@
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import android.util.Pair;
/**
* Tests for {@link DescriptionGeneratorImpl}.
*
* @author Jimmy Shih
*/
public class DescriptionGeneratorImplTest extends AndroidTestCase {
private static final long START_TIME = 1288721514000L;
private DescriptionGeneratorImpl descriptionGenerator;
@Override
protected void setUp() throws Exception {
descriptionGenerator = new DescriptionGeneratorImpl(getContext());
}
/**
* Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track,
* java.util.Vector, java.util.Vector, boolean)}.
*/
public void testGenerateTrackDescription() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(START_TIME);
track.setTripStatistics(stats);
track.setCategory("hiking");
String expected = "Created by"
- + " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>"
+ + " <a href='http://www.google.com/mobile/mytracks'>Google My Tracks</a> on Android.<p>"
+ "Name: -<br>"
+ "Activity type: hiking<br>"
+ "Description: -<br>"
+ "Total distance: 20.00 km (12.4 mi)<br>"
+ "Total time: 10:00<br>"
+ "Moving time: 05:00<br>"
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
+ "Fastest pace: 0.17 min/km (0.3 min/mi)<br>"
+ "Max elevation: 550 m (1804 ft)<br>"
+ "Min elevation: -500 m (-1640 ft)<br>"
+ "Elevation gain: 6000 m (19685 ft)<br>"
+ "Max grade: 42 %<br>"
+ "Min grade: 11 %<br>"
+ "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "<br>";
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null, true));
}
/**
* Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(TripStatistics)}.
*/
public void testGenerateWaypointDescription() {
Waypoint waypoint = new Waypoint();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(START_TIME);
waypoint.setTripStatistics(stats);
String expected = "Total distance: 20.00 km (12.4 mi)\n"
+ "Total time: 10:00\n"
+ "Moving time: 05:00\n"
+ "Average speed: 120.00 km/h (74.6 mi/h)\n"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)\n"
+ "Max speed: 360.00 km/h (223.7 mi/h)\n"
+ "Average pace: 0.50 min/km (0.8 min/mi)\n"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)\n"
+ "Fastest pace: 0.17 min/km (0.3 min/mi)\n"
+ "Max elevation: 550 m (1804 ft)\n"
+ "Min elevation: -500 m (-1640 ft)\n"
+ "Elevation gain: 6000 m (19685 ft)\n"
+ "Max grade: 42 %\n"
+ "Min grade: 11 %\n"
+ "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "\n";
assertEquals(
expected, descriptionGenerator.generateWaypointDescription(waypoint.getTripStatistics()));
}
/**
* Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder,
* int, String)}.
*/
public void testWriteDistance() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "<br>");
assertEquals("Total distance: 1.10 km (0.7 mi)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int,
* String)}.
*/
public void testWriteTime() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "<br>");
assertEquals("Total time: 00:01<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder,
* int, String)}.
*/
public void testWriteSpeed() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeSpeed(1.1, builder, R.string.description_average_speed, "\n");
assertEquals("Average speed: 3.96 km/h (2.5 mi/h)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder,
* int, String)}.
*/
public void testWriteElevation() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "<br>");
assertEquals("Min elevation: 4 m (14 ft)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writePace(Pair, StringBuilder, int,
* String)}.
*/
public void testWritePace() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writePace(
new Pair<Double, Double>(1.1, 2.2), builder, R.string.description_average_pace, "\n");
assertEquals("Average pace: 54.55 min/km (27.3 min/mi)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)}.
*/
public void testWriteGrade() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 4 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with a NaN.
*/
public void testWriteGrade_nan() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with an infinite number.
*/
public void testWriteGrade_infinite() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(
Double.POSITIVE_INFINITY, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)}.
*/
public void testGetPace() {
assertEquals(12.0, descriptionGenerator.getPace(5));
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)} with zero speed.
*/
public void testGetPace_zero() {
assertEquals(0.0, descriptionGenerator.getPace(0));
}
}
| true | true | public void testGenerateTrackDescription() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(START_TIME);
track.setTripStatistics(stats);
track.setCategory("hiking");
String expected = "Created by"
+ " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>"
+ "Name: -<br>"
+ "Activity type: hiking<br>"
+ "Description: -<br>"
+ "Total distance: 20.00 km (12.4 mi)<br>"
+ "Total time: 10:00<br>"
+ "Moving time: 05:00<br>"
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
+ "Fastest pace: 0.17 min/km (0.3 min/mi)<br>"
+ "Max elevation: 550 m (1804 ft)<br>"
+ "Min elevation: -500 m (-1640 ft)<br>"
+ "Elevation gain: 6000 m (19685 ft)<br>"
+ "Max grade: 42 %<br>"
+ "Min grade: 11 %<br>"
+ "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "<br>";
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null, true));
}
| public void testGenerateTrackDescription() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(START_TIME);
track.setTripStatistics(stats);
track.setCategory("hiking");
String expected = "Created by"
+ " <a href='http://www.google.com/mobile/mytracks'>Google My Tracks</a> on Android.<p>"
+ "Name: -<br>"
+ "Activity type: hiking<br>"
+ "Description: -<br>"
+ "Total distance: 20.00 km (12.4 mi)<br>"
+ "Total time: 10:00<br>"
+ "Moving time: 05:00<br>"
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
+ "Fastest pace: 0.17 min/km (0.3 min/mi)<br>"
+ "Max elevation: 550 m (1804 ft)<br>"
+ "Min elevation: -500 m (-1640 ft)<br>"
+ "Elevation gain: 6000 m (19685 ft)<br>"
+ "Max grade: 42 %<br>"
+ "Min grade: 11 %<br>"
+ "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "<br>";
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null, true));
}
|
diff --git a/core/src/main/java/com/findwise/hydra/StageRunner.java b/core/src/main/java/com/findwise/hydra/StageRunner.java
index 4f5f8cf..e44a723 100644
--- a/core/src/main/java/com/findwise/hydra/StageRunner.java
+++ b/core/src/main/java/com/findwise/hydra/StageRunner.java
@@ -1,367 +1,367 @@
package com.findwise.hydra;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.ProcessDestroyer;
import org.apache.commons.exec.launcher.CommandLauncher;
import org.apache.commons.exec.launcher.CommandLauncherFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.findwise.hydra.stage.GroupStarter;
public class StageRunner extends Thread {
private StageGroup stageGroup;
private Logger logger = LoggerFactory.getLogger(getClass());
private StageDestroyer stageDestroyer;
private boolean prepared = false;
private int timesToRetry = -1;
private int timesStarted;
private int pipelinePort;
private List<File> files = null;
private String jvmParameters = null;
private String startupArgsString = null;
private String classPathString = null;
private String java = "java";
private boolean hasQueried = false;
private File targetDirectory;
private File baseDirectory;
private boolean performanceLogging = false;
private int loggingPort;
private boolean started;
private boolean wasKilled = false;
private ShutdownHandler shutdownHandler;
public synchronized void setHasQueried() {
hasQueried = true;
}
public synchronized boolean hasQueried() {
return hasQueried;
}
public StageRunner(StageGroup stageGroup, File baseDirectory, int pipelinePort, boolean performanceLogging, int loggingPort, ShutdownHandler shutdownHandler) {
this.stageGroup = stageGroup;
this.baseDirectory = baseDirectory;
this.targetDirectory = new File(baseDirectory, stageGroup.getName());
this.pipelinePort = pipelinePort;
this.performanceLogging = performanceLogging;
this.loggingPort = loggingPort;
this.shutdownHandler = shutdownHandler;
timesStarted = 0;
}
/**
* This method must be called prior to a call to start()
*
* @throws IOException
*/
public void prepare() throws IOException {
files = new ArrayList<File>();
if ((!baseDirectory.isDirectory() && !baseDirectory.mkdir()) ||
(!targetDirectory.isDirectory() && !targetDirectory.mkdir())) {
throw new IOException("Unable to write files, target (" + targetDirectory.getAbsolutePath() + ") is not a directory");
}
for (DatabaseFile df : stageGroup.getDatabaseFiles()) {
File f = new File(targetDirectory, df.getFilename());
files.add(f);
InputStream dfis = df.getInputStream();
assert(dfis != null);
FileOutputStream fos = new FileOutputStream(f);
assert(fos != null);
try {
IOUtils.copy(dfis, fos);
} finally {
IOUtils.closeQuietly(dfis);
IOUtils.closeQuietly(fos);
}
}
stageDestroyer = new StageDestroyer();
setParameters(stageGroup.toPropertiesMap());
if (stageGroup.getSize() == 1) {
//If there is only a single stage in this group, it's configuration takes precedent
setParameters(stageGroup.getStages().iterator().next().getProperties());
}
prepared = true;
}
public final void setParameters(Map<String, Object> conf) {
if (conf.containsKey(StageGroup.JVM_PARAMETERS_KEY) && conf.get(StageGroup.JVM_PARAMETERS_KEY) != null) {
jvmParameters = (String) conf.get(StageGroup.JVM_PARAMETERS_KEY);
} else {
jvmParameters = null;
}
if (conf.containsKey(StageGroup.JAVA_LOCATION_KEY) && conf.get(StageGroup.JAVA_LOCATION_KEY) != null) {
java = (String) conf.get(StageGroup.JAVA_LOCATION_KEY);
} else {
java = "java";
}
if (conf.containsKey(StageGroup.RETRIES_KEY) && conf.get(StageGroup.RETRIES_KEY) != null) {
timesToRetry = (Integer) conf.get(StageGroup.RETRIES_KEY);
} else {
timesToRetry = -1;
}
}
public void run() {
started = true;
if (!prepared) {
logger.error("The StageRunner was not prepared prior to being started. Aborting!");
return;
}
if (stageGroup.isEmpty()) {
logger.info("Stage group " + stageGroup.getName() + " has no stages, and can not be started.");
return;
}
do {
logger.info("Starting stage group " + stageGroup.getName()
+ ". Times started so far: " + timesStarted);
timesStarted++;
boolean cleanShutdown = runGroup();
if (cleanShutdown) {
return;
}
if (!hasQueried()) {
logger.error("The stage group " + stageGroup.getName() + " did not start. It will not be restarted until configuration changes.");
return;
}
} while ((timesToRetry == -1 || timesToRetry >= timesStarted) && !shutdownHandler.isShuttingDown());
logger.error("Stage group " + stageGroup.getName()
+ " has failed and cannot be restarted. ");
}
public void printJavaVersion() {
CommandLine cmdLine = new CommandLine("java");
cmdLine.addArgument("-version");
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
Executor executor = new DefaultExecutor();
try {
executor.execute(cmdLine, resultHandler);
} catch (ExecuteException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Launches this stage and waits for process termination.
*
* @return true if the stage was killed by a call to the destroy()-method. false otherwise.
*/
private boolean runGroup() {
CommandLine cmdLine = new CommandLine(java);
cmdLine.addArgument(jvmParameters, false);
String cp = getClassPath();
cmdLine.addArgument("-cp");
- cmdLine.addArgument("${classpath}");
+ cmdLine.addArgument("${classpath}", false);
cmdLine.addArgument(GroupStarter.class.getCanonicalName());
cmdLine.addArgument(stageGroup.getName());
cmdLine.addArgument("localhost");
cmdLine.addArgument("" + pipelinePort);
cmdLine.addArgument("" + performanceLogging);
cmdLine.addArgument("" + loggingPort);
cmdLine.addArgument(startupArgsString);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("classpath", cp);
cmdLine.setSubstitutionMap(map);
logger.info("Launching with command " + cmdLine.toString());
CommandLauncher cl = CommandLauncherFactory.createVMLauncher();
int exitValue = 0;
try {
Process p = cl.exec(cmdLine, null);
new StreamLogger(
String.format("%s (stdout)", stageGroup.getName()),
p.getInputStream()
).start();
new StreamLogger(
String.format("%s (stderr)", stageGroup.getName()),
p.getErrorStream()
).start();
stageDestroyer.add(p);
exitValue = p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException("Caught Interrupt while waiting for process exit", e);
} catch (IOException e) {
logger.error("Caught IOException while running command", e);
return false;
}
if (!wasKilled) {
logger.error("Stage group " + stageGroup.getName()
+ " terminated unexpectedly with exit value " + exitValue);
return false;
}
return true;
}
private String getClassPath() {
if (classPathString == null) {
return getAllJars();
} else {
return classPathString + File.pathSeparator + getAllJars();
}
}
private String getAllJars() {
String jars = "";
for (String s : targetDirectory.list()) {
jars += targetDirectory.getAbsolutePath() + File.separator + s + File.pathSeparator;
}
return jars.substring(0, jars.length() - 1);
}
/**
* Destroys the JVM running this stage and removes it's working files.
* Should a JVM shutdown fail, it will throw an IllegalStateException.
*/
public void destroy() {
logger.debug("Attempting to destroy JVM running stage group "
+ stageGroup.getName());
boolean success = stageDestroyer.killAll();
if (success) {
logger.debug("... destruction successful");
} else {
logger.error("JVM running stage group " + stageGroup.getName()
+ " was not killed");
throw new IllegalStateException("Orphaned process for "
+ stageGroup.getName());
}
removeFiles();
wasKilled = true;
}
private void removeFiles() {
long start = System.currentTimeMillis();
IOException ex = null;
do {
try {
FileUtils.deleteDirectory(targetDirectory);
return;
} catch (IOException e) {
ex = e;
try {
Thread.sleep(50);
} catch (InterruptedException e1) {
logger.error("Interrupted while waiting on delete");
Thread.currentThread().interrupt();
return;
}
}
} while (start + 5000 > System.currentTimeMillis());
logger.error("Unable to delete the directory "
+ targetDirectory.getAbsolutePath()
+ ", containing Stage Group " + stageGroup.getName(), ex);
}
public StageGroup getStageGroup() {
return stageGroup;
}
public boolean isStarted() {
return started;
}
/**
* Manages the destruction of any Stages launched in this wrapper.
* Automatically binds to the Runtime to shut down along with the master
* JVM.
*
* @author joel.westberg
*/
static class StageDestroyer extends Thread implements ProcessDestroyer {
private final List<Process> processes = new ArrayList<Process>();
public StageDestroyer() {
Runtime.getRuntime().addShutdownHook(this);
}
@Override
public boolean add(Process p) {
/**
* Register this destroyer to Runtime in order to avoid orphaned
* processes if the main JVM dies
*/
processes.add(p);
return true;
}
@Override
public boolean remove(Process p) {
return processes.remove(p);
}
@Override
public int size() {
return processes.size();
}
/**
* Invoked by the runtime ShutdownHook on JVM exit
*/
public void run() {
killAll();
}
public boolean killAll() {
boolean success = true;
synchronized (processes) {
for (Process process : processes) {
try {
process.destroy();
} catch (RuntimeException t) {
success = false;
}
}
}
return success;
}
}
public void setStageDestroyer(StageDestroyer sd) {
stageDestroyer = sd;
}
}
| true | true | private boolean runGroup() {
CommandLine cmdLine = new CommandLine(java);
cmdLine.addArgument(jvmParameters, false);
String cp = getClassPath();
cmdLine.addArgument("-cp");
cmdLine.addArgument("${classpath}");
cmdLine.addArgument(GroupStarter.class.getCanonicalName());
cmdLine.addArgument(stageGroup.getName());
cmdLine.addArgument("localhost");
cmdLine.addArgument("" + pipelinePort);
cmdLine.addArgument("" + performanceLogging);
cmdLine.addArgument("" + loggingPort);
cmdLine.addArgument(startupArgsString);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("classpath", cp);
cmdLine.setSubstitutionMap(map);
logger.info("Launching with command " + cmdLine.toString());
CommandLauncher cl = CommandLauncherFactory.createVMLauncher();
int exitValue = 0;
try {
Process p = cl.exec(cmdLine, null);
new StreamLogger(
String.format("%s (stdout)", stageGroup.getName()),
p.getInputStream()
).start();
new StreamLogger(
String.format("%s (stderr)", stageGroup.getName()),
p.getErrorStream()
).start();
stageDestroyer.add(p);
exitValue = p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException("Caught Interrupt while waiting for process exit", e);
} catch (IOException e) {
logger.error("Caught IOException while running command", e);
return false;
}
if (!wasKilled) {
logger.error("Stage group " + stageGroup.getName()
+ " terminated unexpectedly with exit value " + exitValue);
return false;
}
return true;
}
| private boolean runGroup() {
CommandLine cmdLine = new CommandLine(java);
cmdLine.addArgument(jvmParameters, false);
String cp = getClassPath();
cmdLine.addArgument("-cp");
cmdLine.addArgument("${classpath}", false);
cmdLine.addArgument(GroupStarter.class.getCanonicalName());
cmdLine.addArgument(stageGroup.getName());
cmdLine.addArgument("localhost");
cmdLine.addArgument("" + pipelinePort);
cmdLine.addArgument("" + performanceLogging);
cmdLine.addArgument("" + loggingPort);
cmdLine.addArgument(startupArgsString);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("classpath", cp);
cmdLine.setSubstitutionMap(map);
logger.info("Launching with command " + cmdLine.toString());
CommandLauncher cl = CommandLauncherFactory.createVMLauncher();
int exitValue = 0;
try {
Process p = cl.exec(cmdLine, null);
new StreamLogger(
String.format("%s (stdout)", stageGroup.getName()),
p.getInputStream()
).start();
new StreamLogger(
String.format("%s (stderr)", stageGroup.getName()),
p.getErrorStream()
).start();
stageDestroyer.add(p);
exitValue = p.waitFor();
} catch (InterruptedException e) {
throw new IllegalStateException("Caught Interrupt while waiting for process exit", e);
} catch (IOException e) {
logger.error("Caught IOException while running command", e);
return false;
}
if (!wasKilled) {
logger.error("Stage group " + stageGroup.getName()
+ " terminated unexpectedly with exit value " + exitValue);
return false;
}
return true;
}
|
diff --git a/src/org/linter/LintedPage.java b/src/org/linter/LintedPage.java
index 047bdfc..445b639 100644
--- a/src/org/linter/LintedPage.java
+++ b/src/org/linter/LintedPage.java
@@ -1,259 +1,259 @@
package org.linter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
public class LintedPage {
static private Logger logger = Logger.getLogger(LintedPage.class);
private boolean _parseOk = false;
private String _originalUrl;
private String[] _aliases = {};
private String _destinationUrl;
private String _title;
private String _description;
private String _favIconUrl;
private long _processingTime;
private TagNode _node;
/**
* Create a blank linted page, expects you to call {@link process} at some point
* @param originalUrl - the URL to be processed
*/
public LintedPage(String originalUrl) {
_originalUrl = originalUrl;
}
/***
* Process the original URL, including alias resolution, scraping and metadata extraction
*/
void process() {
final long startTime = System.nanoTime();
final long endTime;
try {
processRunner();
} finally {
endTime = System.nanoTime();
}
_processingTime = endTime - startTime;
}
/***
* Process the original URL associated with this LintedPage
*/
protected void processRunner() {
logger.info("Processing URL: " + _originalUrl);
logger.debug("Expanding any shortened URLs...");
followUrlRedirects();
logger.debug("Scraping & cleaning HTML...");
scrapeMetadata();
}
/***
* Follows the originalUrl to its destination, saving any aliases along the way. This is useful to expand
* URL shortening services.
* @return True if successful, false otherwise
*/
public boolean followUrlRedirects() {
ArrayList<String> aliases = new ArrayList<String>();
String nextLocation = _originalUrl;
String lastLocation = nextLocation;
while (nextLocation != null) {
try {
URL url = new URL(nextLocation);
logger.trace("Following " + nextLocation + "...");
HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("HEAD");
connection.setConnectTimeout(Linter.HTTP_CONNECT_TIMEOUT);
connection.connect();
nextLocation = connection.getHeaderField("Location");
if (nextLocation != null) {
logger.trace("Discovered redirect to " + nextLocation);
aliases.add(lastLocation);
lastLocation = nextLocation;
} else {
logger.trace("URL resolved to its destination");
_destinationUrl = lastLocation;
}
connection.disconnect();
} catch (MalformedURLException ex) {
logger.error("Invalid URL [" + nextLocation + "]: " + ex.getMessage());
return false;
} catch (IOException ioe) {
logger.error("IO Exception [" + nextLocation + "]: " + ioe.getMessage());
return false;
}
}
_aliases = aliases.toArray(new String[0]);
return true;
}
/**
* Scrapes the metadata on this page (can be called separately from {@link process}
*/
public void scrapeMetadata() {
HtmlCleaner cleaner = new HtmlCleaner();
try {
_node = cleaner.clean(new URL(this.getDestinationUrl()));
} catch (MalformedURLException mue) {
logger.error("Invalid URL [" + this.getDestinationUrl() + "]: " + mue.toString());
return;
} catch (Exception ex) {
logger.error("Unable to scrape and clean HTML: " + ex.toString());
return;
}
// Page title
try {
Object[] titleNodes = _node.evaluateXPath("//head/title");
if (titleNodes != null) {
_title = ((TagNode)titleNodes[0]).getText().toString().trim();
}
} catch (Exception e) {
- logger.warn("Error extracting the page title: " + e.toString());
+ logger.trace("[" + this.getDestinationUrl() + "] Could not extract the page title");
}
// Page description
try {
Object[] descNodes = _node.evaluateXPath("//head/meta[@name='description']");
if (descNodes != null) {
_description = ((TagNode)descNodes[0]).getAttributeByName("content").trim();
}
} catch (Exception e) {
- logger.warn("Error extracting the page description: " + e.toString());
+ logger.trace("[" + this.getDestinationUrl() + "] Could not extract the page description");
}
// Fav icon
try {
Object[] favIconNodes = _node.evaluateXPath("//head/link[@rel='icon']");
if (favIconNodes != null) {
_favIconUrl = ((TagNode)favIconNodes[0]).getAttributeByName("href").trim();
}
} catch (Exception e) {
- logger.warn("Error extracting the favicon URL: " + e.toString());
+ logger.trace("[" + this.getDestinationUrl() + "] Could not extract the fav icon URL");
}
_parseOk = true;
}
/***
* Whether or not the parse completed successfully
* @return
*/
public Boolean getParseOk() {
return _parseOk;
}
/***
* Returns the original URL (before any shortened URLs were expanded)
* @return
*/
public String getOriginalUrl() {
return _originalUrl;
}
/***
* Gets any aliases for this URL -- e.g. any redirects between the original URL and its actual destination
* @return
*/
public String[] getAliases() {
return _aliases;
}
/***
* Gets the page title
* @return
*/
public String getTitle() {
return _title;
}
/***
* Gets the final destination, after expanding any shortened URLs starting from the original URL
* @return
*/
public String getDestinationUrl() {
return _destinationUrl;
}
/***
* Gets the page descripton (from <meta name='description'>)
* @return
*/
public String getDescription() {
return _description;
}
/***
* Gets the page's favicon (from <link rel='icon'>)
* @return
*/
public String getFavIconUrl() {
return _favIconUrl;
}
/***
* Gets the processing time in milliseconds
* @return
*/
public long getProcessingTimeMillis() {
return TimeUnit.NANOSECONDS.toMillis(_processingTime);
}
/***
* Gets the processing time in human-readable format
* @return
*/
public String getProcessingTimeForHumans() {
// mm:ss is:
// TimeUnit.NANOSECONDS.toMinutes(_processingTime),
// TimeUnit.NANOSECONDS.toSeconds(_processingTime) -
// TimeUnit.MINUTES.toSeconds(TimeUnit.NANOSECONDS.toMinutes(_processingTime))
Float millis = new Float(getProcessingTimeMillis() / 1000);
return String.format("%.4f", millis);
}
public String toDebugString() {
StringBuilder sb = new StringBuilder(_originalUrl);
sb.append(" {\n");
sb.append("\tPARSE OK:\t\t"); sb.append(this.getParseOk()); sb.append('\n');
sb.append("\tALIASES:");
if (_aliases == null || _aliases.length == 0)
sb.append("\t\tNONE\n");
else {
sb.append('\n');
for (String alias : _aliases) {
sb.append("\t\t"); sb.append(alias); sb.append('\n');
}
}
sb.append("\tDEST URL:\t\t"); sb.append(this.getDestinationUrl()); sb.append('\n');
sb.append("\tPAGE TITLE:\t\t"); sb.append(this.getTitle()); sb.append('\n');
sb.append("\tDESCRIPTION:\t\t"); sb.append(this.getDescription()); sb.append('\n');
sb.append("\tFAV ICON:\t\t"); sb.append(this.getFavIconUrl()); sb.append('\n');
sb.append("} in "); sb.append(this.getProcessingTimeForHumans()); sb.append(" s\n");
return sb.toString();
}
}
| false | true | public void scrapeMetadata() {
HtmlCleaner cleaner = new HtmlCleaner();
try {
_node = cleaner.clean(new URL(this.getDestinationUrl()));
} catch (MalformedURLException mue) {
logger.error("Invalid URL [" + this.getDestinationUrl() + "]: " + mue.toString());
return;
} catch (Exception ex) {
logger.error("Unable to scrape and clean HTML: " + ex.toString());
return;
}
// Page title
try {
Object[] titleNodes = _node.evaluateXPath("//head/title");
if (titleNodes != null) {
_title = ((TagNode)titleNodes[0]).getText().toString().trim();
}
} catch (Exception e) {
logger.warn("Error extracting the page title: " + e.toString());
}
// Page description
try {
Object[] descNodes = _node.evaluateXPath("//head/meta[@name='description']");
if (descNodes != null) {
_description = ((TagNode)descNodes[0]).getAttributeByName("content").trim();
}
} catch (Exception e) {
logger.warn("Error extracting the page description: " + e.toString());
}
// Fav icon
try {
Object[] favIconNodes = _node.evaluateXPath("//head/link[@rel='icon']");
if (favIconNodes != null) {
_favIconUrl = ((TagNode)favIconNodes[0]).getAttributeByName("href").trim();
}
} catch (Exception e) {
logger.warn("Error extracting the favicon URL: " + e.toString());
}
_parseOk = true;
}
| public void scrapeMetadata() {
HtmlCleaner cleaner = new HtmlCleaner();
try {
_node = cleaner.clean(new URL(this.getDestinationUrl()));
} catch (MalformedURLException mue) {
logger.error("Invalid URL [" + this.getDestinationUrl() + "]: " + mue.toString());
return;
} catch (Exception ex) {
logger.error("Unable to scrape and clean HTML: " + ex.toString());
return;
}
// Page title
try {
Object[] titleNodes = _node.evaluateXPath("//head/title");
if (titleNodes != null) {
_title = ((TagNode)titleNodes[0]).getText().toString().trim();
}
} catch (Exception e) {
logger.trace("[" + this.getDestinationUrl() + "] Could not extract the page title");
}
// Page description
try {
Object[] descNodes = _node.evaluateXPath("//head/meta[@name='description']");
if (descNodes != null) {
_description = ((TagNode)descNodes[0]).getAttributeByName("content").trim();
}
} catch (Exception e) {
logger.trace("[" + this.getDestinationUrl() + "] Could not extract the page description");
}
// Fav icon
try {
Object[] favIconNodes = _node.evaluateXPath("//head/link[@rel='icon']");
if (favIconNodes != null) {
_favIconUrl = ((TagNode)favIconNodes[0]).getAttributeByName("href").trim();
}
} catch (Exception e) {
logger.trace("[" + this.getDestinationUrl() + "] Could not extract the fav icon URL");
}
_parseOk = true;
}
|
diff --git a/usage/cli/src/test/java/brooklyn/cli/CliTest.java b/usage/cli/src/test/java/brooklyn/cli/CliTest.java
index e4d8a2ea2..e040a1d82 100644
--- a/usage/cli/src/test/java/brooklyn/cli/CliTest.java
+++ b/usage/cli/src/test/java/brooklyn/cli/CliTest.java
@@ -1,71 +1,71 @@
package brooklyn.cli;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import groovy.lang.GroovyClassLoader;
import org.iq80.cli.Cli;
import org.iq80.cli.ParseException;
import org.testng.annotations.Test;
import brooklyn.cli.Main.BrooklynCommand;
import brooklyn.cli.Main.HelpCommand;
import brooklyn.cli.Main.LaunchCommand;
import brooklyn.entity.basic.AbstractApplication;
import brooklyn.util.ResourceUtils;
public class CliTest {
@Test
public void testLoadApplicationFromClasspath() throws Exception {
LaunchCommand launchCommand = new Main.LaunchCommand();
ResourceUtils resourceUtils = new ResourceUtils(this);
GroovyClassLoader loader = new GroovyClassLoader(CliTest.class.getClassLoader());
String appName = ExampleApp.class.getName();
AbstractApplication app = launchCommand.loadApplicationFromClasspathOrParse(resourceUtils, loader, appName);
assertTrue(app instanceof ExampleApp, "app="+app);
}
@Test
public void testLoadApplicationByParsingFile() throws Exception {
LaunchCommand launchCommand = new Main.LaunchCommand();
ResourceUtils resourceUtils = new ResourceUtils(this);
GroovyClassLoader loader = new GroovyClassLoader(CliTest.class.getClassLoader());
String appName = "ExampleAppInFile.groovy"; // file found in src/test/resources (contains empty app)
AbstractApplication app = launchCommand.loadApplicationFromClasspathOrParse(resourceUtils, loader, appName);
assertTrue(app.getClass().getName().equals("ExampleAppInFile"), "app="+app);
}
@Test
public void testLaunchCommand() throws ParseException {
Cli<BrooklynCommand> cli = Main.buildCli();
BrooklynCommand command = cli.parse("launch", "--app", "my.App", "--location", "localhost");
- assertTrue(command instanceof LaunchCommand);
+ assertTrue(command instanceof LaunchCommand, ""+command);
String details = command.toString();
- assertTrue(details.contains("app=my.App"));
- assertTrue(details.contains("script=null"));
- assertTrue(details.contains("location=[localhost]"));
- assertTrue(details.contains("port=8081"));
- assertTrue(details.contains("noConsole=false"));
- assertTrue(details.contains("noShutdwonOnExit=false"));
+ assertTrue(details.contains("app=my.App"), details);
+ assertTrue(details.contains("script=null"), details);
+ assertTrue(details.contains("location=localhost"), details);
+ assertTrue(details.contains("port=8081"), details);
+ assertTrue(details.contains("noConsole=false"), details);
+ assertTrue(details.contains("noShutdwonOnExit=false"), details);
}
@Test(expectedExceptions = ParseException.class, expectedExceptionsMessageRegExp = "Required option '-a' is missing")
public void testMissingAppOption() throws ParseException {
Cli<BrooklynCommand> cli = Main.buildCli();
cli.parse("launch", "blah", "my.App");
fail("Should throw ParseException");
}
public void testHelpCommand() {
Cli<BrooklynCommand> cli = Main.buildCli();
BrooklynCommand command = cli.parse("help");
assertTrue(command instanceof HelpCommand);
command = cli.parse();
assertTrue(command instanceof HelpCommand);
}
// An empty app to be used for testing
@SuppressWarnings("serial")
public static class ExampleApp extends AbstractApplication { }
}
| false | true | public void testLaunchCommand() throws ParseException {
Cli<BrooklynCommand> cli = Main.buildCli();
BrooklynCommand command = cli.parse("launch", "--app", "my.App", "--location", "localhost");
assertTrue(command instanceof LaunchCommand);
String details = command.toString();
assertTrue(details.contains("app=my.App"));
assertTrue(details.contains("script=null"));
assertTrue(details.contains("location=[localhost]"));
assertTrue(details.contains("port=8081"));
assertTrue(details.contains("noConsole=false"));
assertTrue(details.contains("noShutdwonOnExit=false"));
}
| public void testLaunchCommand() throws ParseException {
Cli<BrooklynCommand> cli = Main.buildCli();
BrooklynCommand command = cli.parse("launch", "--app", "my.App", "--location", "localhost");
assertTrue(command instanceof LaunchCommand, ""+command);
String details = command.toString();
assertTrue(details.contains("app=my.App"), details);
assertTrue(details.contains("script=null"), details);
assertTrue(details.contains("location=localhost"), details);
assertTrue(details.contains("port=8081"), details);
assertTrue(details.contains("noConsole=false"), details);
assertTrue(details.contains("noShutdwonOnExit=false"), details);
}
|
diff --git a/RoboWizards/src/edu/wpi/first/wpilibj/templates/RobotWizards.java b/RoboWizards/src/edu/wpi/first/wpilibj/templates/RobotWizards.java
index 0f93310..4983d84 100644
--- a/RoboWizards/src/edu/wpi/first/wpilibj/templates/RobotWizards.java
+++ b/RoboWizards/src/edu/wpi/first/wpilibj/templates/RobotWizards.java
@@ -1,98 +1,98 @@
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SimpleRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.Watchdog;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class RobotWizards extends SimpleRobot {
public static final String ROTATTION_KEY = "Rotate State: ";
public static final String LIFTING_KEY = "Lift State: ";
private final WizardArmController armController;
private final RobotDrive robotDrive;
private final Joystick joystick1;
private final Joystick joystick2;
private final Joystick joystick3;
public RobotWizards() {
this.armController = new WizardArmController(RobotMap.RAISE_ARM_RELAY,
RobotMap.ROTATE_ARM_RELAY);
this.robotDrive = new RobotDrive(RobotMap.MOTOR_ONE, RobotMap.MOTOR_TWO);
joystick1 = new Joystick(1);
joystick2 = new Joystick(2);
joystick3 = new Joystick(3);
}
public void autonomous() {
Watchdog.getInstance().setEnabled(false);
//Autonomous cod here
Watchdog.getInstance().setEnabled(true);
Watchdog.getInstance().feed();
}
public void operatorControl() {
while(isOperatorControl() && isEnabled()){
Watchdog.getInstance().setEnabled(true);
Watchdog.getInstance().feed();
robotDrive.tankDrive(joystick1, joystick2);
checkRotateJoystick();
checkClimbButtons();
checkAutoClimbButtons();
Timer.delay(0.01);
}
}
private void checkRotateJoystick(){
if(joystick3.getY() > UIMap.JOYSTICK_DEAD_ZONE){
armController.rotateArmsForward();
SmartDashboard.putString(ROTATTION_KEY, "Forwards");
}
- else if(joystick3.getY() < UIMap.JOYSTICK_DEAD_ZONE){
+ else if(joystick3.getY() < -UIMap.JOYSTICK_DEAD_ZONE){
armController.rotateArmsBackward();
SmartDashboard.putString(ROTATTION_KEY, "Backwards");
}
else{
armController.stopArmRotation();
SmartDashboard.putString(ROTATTION_KEY, "Stopped");
}
SmartDashboard.putNumber("Rotatin:", joystick3.getY());
}
private void checkClimbButtons(){
if(joystick3.getRawButton(UIMap.RAISE_ARM_BUTTON)){
armController.lowerClimbArms();
SmartDashboard.putString(LIFTING_KEY, "Lifting");
}
else if(joystick3.getRawButton(UIMap.LOWER_ARM_BUTTON)){
armController.raiseClimbArms();
SmartDashboard.putString(LIFTING_KEY, "Lowering");
}
else{
armController.stopClimbArms();
SmartDashboard.putString(LIFTING_KEY, "Stopped");
}
}
private void checkAutoClimbButtons(){
//To-Do
}
public void test() {
SmartDashboard.putNumber("Test Axis", joystick3.getY());
}
}
| true | true | private void checkRotateJoystick(){
if(joystick3.getY() > UIMap.JOYSTICK_DEAD_ZONE){
armController.rotateArmsForward();
SmartDashboard.putString(ROTATTION_KEY, "Forwards");
}
else if(joystick3.getY() < UIMap.JOYSTICK_DEAD_ZONE){
armController.rotateArmsBackward();
SmartDashboard.putString(ROTATTION_KEY, "Backwards");
}
else{
armController.stopArmRotation();
SmartDashboard.putString(ROTATTION_KEY, "Stopped");
}
SmartDashboard.putNumber("Rotatin:", joystick3.getY());
}
| private void checkRotateJoystick(){
if(joystick3.getY() > UIMap.JOYSTICK_DEAD_ZONE){
armController.rotateArmsForward();
SmartDashboard.putString(ROTATTION_KEY, "Forwards");
}
else if(joystick3.getY() < -UIMap.JOYSTICK_DEAD_ZONE){
armController.rotateArmsBackward();
SmartDashboard.putString(ROTATTION_KEY, "Backwards");
}
else{
armController.stopArmRotation();
SmartDashboard.putString(ROTATTION_KEY, "Stopped");
}
SmartDashboard.putNumber("Rotatin:", joystick3.getY());
}
|
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/tasks/EvictUnusedProxiedItemsTask.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/tasks/EvictUnusedProxiedItemsTask.java
index 8001a5934..809d01906 100644
--- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/tasks/EvictUnusedProxiedItemsTask.java
+++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/tasks/EvictUnusedProxiedItemsTask.java
@@ -1,97 +1,97 @@
/*
* Nexus: Maven Repository Manager
* Copyright (C) 2008 Sonatype Inc.
*
* This file is part of Nexus.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package org.sonatype.nexus.tasks;
import java.util.Collection;
import org.sonatype.nexus.feeds.FeedRecorder;
import org.sonatype.nexus.scheduling.AbstractNexusRepositoriesTask;
/**
* Evicts unused proxied items.
*
* @author cstamas
* @plexus.component role="org.sonatype.scheduling.SchedulerTask"
* role-hint="org.sonatype.nexus.tasks.EvictUnusedProxiedItemsTask"
* instantiation-strategy="per-lookup"
*/
public class EvictUnusedProxiedItemsTask
extends AbstractNexusRepositoriesTask<Collection<String>>
{
public static final String EVICT_OLDER_CACHE_ITEMS_THEN_KEY = "evictOlderCacheItemsThen";
public int getEvictOlderCacheItemsThen()
{
return Integer.parseInt( getParameters().get( EVICT_OLDER_CACHE_ITEMS_THEN_KEY ) );
}
public void setEvictOlderCacheItemsThen( int evictOlderCacheItemsThen )
{
getParameters().put( EVICT_OLDER_CACHE_ITEMS_THEN_KEY, Integer.toString( evictOlderCacheItemsThen ) );
}
@Override
protected Collection<String> doRun()
throws Exception
{
if ( getRepositoryGroupId() != null )
{
return getNexus().evictRepositoryGroupUnusedProxiedItems(
- System.currentTimeMillis() - ( getEvictOlderCacheItemsThen() * 24 * 60 * 60 * 1000 ),
+ System.currentTimeMillis() - ( ( (long) getEvictOlderCacheItemsThen() ) * 24 * 60 * 60 * 1000 ),
getRepositoryGroupId() );
}
else if ( getRepositoryId() != null )
{
return getNexus().evictRepositoryUnusedProxiedItems(
- System.currentTimeMillis() - ( getEvictOlderCacheItemsThen() * 24 * 60 * 60 * 1000 ),
+ System.currentTimeMillis() - ( ( (long) getEvictOlderCacheItemsThen() ) * 24 * 60 * 60 * 1000 ),
getRepositoryId() );
}
else
{
return getNexus().evictAllUnusedProxiedItems(
- System.currentTimeMillis() - ( getEvictOlderCacheItemsThen() * 24 * 60 * 60 * 1000 ) );
+ System.currentTimeMillis() - ( ( (long) getEvictOlderCacheItemsThen() ) * 24 * 60 * 60 * 1000 ) );
}
}
@Override
protected String getAction()
{
return FeedRecorder.SYSTEM_EVICT_UNUSED_PROXIED_ITEMS;
}
@Override
protected String getMessage()
{
if ( getRepositoryGroupId() != null )
{
return "Evicting unused proxied items for repository group with ID=" + getRepositoryGroupId() + ".";
}
else if ( getRepositoryId() != null )
{
return "Evicting unused proxied items for repository with ID=" + getRepositoryId() + ".";
}
else
{
return "Evicting unused proxied items for all registered proxy repositories.";
}
}
}
| false | true | protected Collection<String> doRun()
throws Exception
{
if ( getRepositoryGroupId() != null )
{
return getNexus().evictRepositoryGroupUnusedProxiedItems(
System.currentTimeMillis() - ( getEvictOlderCacheItemsThen() * 24 * 60 * 60 * 1000 ),
getRepositoryGroupId() );
}
else if ( getRepositoryId() != null )
{
return getNexus().evictRepositoryUnusedProxiedItems(
System.currentTimeMillis() - ( getEvictOlderCacheItemsThen() * 24 * 60 * 60 * 1000 ),
getRepositoryId() );
}
else
{
return getNexus().evictAllUnusedProxiedItems(
System.currentTimeMillis() - ( getEvictOlderCacheItemsThen() * 24 * 60 * 60 * 1000 ) );
}
}
| protected Collection<String> doRun()
throws Exception
{
if ( getRepositoryGroupId() != null )
{
return getNexus().evictRepositoryGroupUnusedProxiedItems(
System.currentTimeMillis() - ( ( (long) getEvictOlderCacheItemsThen() ) * 24 * 60 * 60 * 1000 ),
getRepositoryGroupId() );
}
else if ( getRepositoryId() != null )
{
return getNexus().evictRepositoryUnusedProxiedItems(
System.currentTimeMillis() - ( ( (long) getEvictOlderCacheItemsThen() ) * 24 * 60 * 60 * 1000 ),
getRepositoryId() );
}
else
{
return getNexus().evictAllUnusedProxiedItems(
System.currentTimeMillis() - ( ( (long) getEvictOlderCacheItemsThen() ) * 24 * 60 * 60 * 1000 ) );
}
}
|
diff --git a/src/main/java/uk/co/epii/conservatives/williamcavendishbentinck/extensions/DeliveryPointAddressExtensions.java b/src/main/java/uk/co/epii/conservatives/williamcavendishbentinck/extensions/DeliveryPointAddressExtensions.java
index e2034b6..72e059f 100644
--- a/src/main/java/uk/co/epii/conservatives/williamcavendishbentinck/extensions/DeliveryPointAddressExtensions.java
+++ b/src/main/java/uk/co/epii/conservatives/williamcavendishbentinck/extensions/DeliveryPointAddressExtensions.java
@@ -1,35 +1,36 @@
package uk.co.epii.conservatives.williamcavendishbentinck.extensions;
import uk.co.epii.conservatives.williamcavendishbentinck.tables.DeliveryPointAddress;
import java.util.ArrayList;
/**
* User: James Robinson
* Date: 30/09/2013
* Time: 23:45
*/
public class DeliveryPointAddressExtensions {
public static String getAddress(DeliveryPointAddress deliveryPointAddress) {
StringBuilder stringBuilder = new StringBuilder(deliveryPointAddress.getPostcode());
ArrayList<String> addressLines = new ArrayList<String>();
+ addressLines.add(deliveryPointAddress.getPostTown());
addressLines.add(deliveryPointAddress.getDependentLocality());
addressLines.add(deliveryPointAddress.getDoubleDependentLocality());
addressLines.add(deliveryPointAddress.getThoroughfareName());
addressLines.add(deliveryPointAddress.getDependentThoroughfareName());
addressLines.add(deliveryPointAddress.getBuildingNumber() == null ? null : deliveryPointAddress.getBuildingNumber()+ "");
addressLines.add(deliveryPointAddress.getBuildingName());
addressLines.add(deliveryPointAddress.getSubBuildingName());
addressLines.add(deliveryPointAddress.getDepartmentName());
addressLines.add(deliveryPointAddress.getOrganisationName());
for (String addressLine : addressLines) {
if (addressLine != null) {
stringBuilder.insert(0, ", ");
stringBuilder.insert(0, addressLine);
}
}
return stringBuilder.toString();
}
}
| true | true | public static String getAddress(DeliveryPointAddress deliveryPointAddress) {
StringBuilder stringBuilder = new StringBuilder(deliveryPointAddress.getPostcode());
ArrayList<String> addressLines = new ArrayList<String>();
addressLines.add(deliveryPointAddress.getDependentLocality());
addressLines.add(deliveryPointAddress.getDoubleDependentLocality());
addressLines.add(deliveryPointAddress.getThoroughfareName());
addressLines.add(deliveryPointAddress.getDependentThoroughfareName());
addressLines.add(deliveryPointAddress.getBuildingNumber() == null ? null : deliveryPointAddress.getBuildingNumber()+ "");
addressLines.add(deliveryPointAddress.getBuildingName());
addressLines.add(deliveryPointAddress.getSubBuildingName());
addressLines.add(deliveryPointAddress.getDepartmentName());
addressLines.add(deliveryPointAddress.getOrganisationName());
for (String addressLine : addressLines) {
if (addressLine != null) {
stringBuilder.insert(0, ", ");
stringBuilder.insert(0, addressLine);
}
}
return stringBuilder.toString();
}
| public static String getAddress(DeliveryPointAddress deliveryPointAddress) {
StringBuilder stringBuilder = new StringBuilder(deliveryPointAddress.getPostcode());
ArrayList<String> addressLines = new ArrayList<String>();
addressLines.add(deliveryPointAddress.getPostTown());
addressLines.add(deliveryPointAddress.getDependentLocality());
addressLines.add(deliveryPointAddress.getDoubleDependentLocality());
addressLines.add(deliveryPointAddress.getThoroughfareName());
addressLines.add(deliveryPointAddress.getDependentThoroughfareName());
addressLines.add(deliveryPointAddress.getBuildingNumber() == null ? null : deliveryPointAddress.getBuildingNumber()+ "");
addressLines.add(deliveryPointAddress.getBuildingName());
addressLines.add(deliveryPointAddress.getSubBuildingName());
addressLines.add(deliveryPointAddress.getDepartmentName());
addressLines.add(deliveryPointAddress.getOrganisationName());
for (String addressLine : addressLines) {
if (addressLine != null) {
stringBuilder.insert(0, ", ");
stringBuilder.insert(0, addressLine);
}
}
return stringBuilder.toString();
}
|
diff --git a/src/de/ueller/gpsmid/ui/Trace.java b/src/de/ueller/gpsmid/ui/Trace.java
index bcd82781..9ffc2f5c 100644
--- a/src/de/ueller/gpsmid/ui/Trace.java
+++ b/src/de/ueller/gpsmid/ui/Trace.java
@@ -1,3608 +1,3608 @@
/*
* GpsMid - Copyright (c) 2007 Harald Mueller james22 at users dot sourceforge dot net
* See file COPYING.
*/
package de.ueller.gpsmid.ui;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
//#if polish.api.fileconnection
import javax.microedition.io.file.FileConnection;
//#endif
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.List;
//#if polish.android
import android.view.WindowManager;
//#else
import javax.microedition.lcdui.game.GameCanvas;
//#endif
import javax.microedition.midlet.MIDlet;
import de.enough.polish.util.Locale;
import de.ueller.gps.Node;
import de.ueller.gps.Satellite;
import de.ueller.gps.location.CellIdProvider;
import de.ueller.gps.location.Compass;
import de.ueller.gps.location.CompassProducer;
import de.ueller.gps.location.CompassProvider;
import de.ueller.gps.location.CompassReceiver;
import de.ueller.gps.location.GsmCell;
import de.ueller.gps.location.GetCompass;
import de.ueller.gps.location.LocationMsgProducer;
import de.ueller.gps.location.LocationMsgReceiver;
import de.ueller.gps.location.LocationMsgReceiverList;
import de.ueller.gps.location.LocationUpdateListener;
import de.ueller.gps.location.NmeaInput;
import de.ueller.gps.location.SECellId;
import de.ueller.gps.location.SirfInput;
//#if polish.api.osm-editing
import de.ueller.gpsmid.data.EditableWay;
//#endif
import de.ueller.gpsmid.data.Configuration;
import de.ueller.gpsmid.data.Gpx;
import de.ueller.gpsmid.data.Legend;
import de.ueller.gpsmid.data.PaintContext;
import de.ueller.gpsmid.data.Position;
import de.ueller.gpsmid.data.PositionMark;
import de.ueller.gpsmid.data.RoutePositionMark;
import de.ueller.gpsmid.data.SECellLocLogger;
import de.ueller.gpsmid.data.TrackPlayer;
import de.ueller.gpsmid.graphics.ImageCollector;
import de.ueller.gpsmid.graphics.Images;
import de.ueller.gpsmid.graphics.Proj2D;
import de.ueller.gpsmid.graphics.Proj3D;
import de.ueller.gpsmid.graphics.ProjFactory;
import de.ueller.gpsmid.graphics.Projection;
import de.ueller.gpsmid.mapdata.DictReader;
import de.ueller.gpsmid.mapdata.QueueDataReader;
import de.ueller.gpsmid.mapdata.QueueDictReader;
import de.ueller.gpsmid.mapdata.Way;
import de.ueller.gpsmid.names.Names;
import de.ueller.gpsmid.names.Urls;
import de.ueller.gpsmid.routing.RouteInstructions;
import de.ueller.gpsmid.routing.RouteLineProducer;
import de.ueller.gpsmid.routing.RouteNode;
import de.ueller.gpsmid.routing.RouteSyntax;
import de.ueller.gpsmid.routing.Routing;
import de.ueller.gpsmid.tile.Tile;
import de.ueller.midlet.iconmenu.IconActionPerformer;
import de.ueller.midlet.iconmenu.LayoutElement;
import de.ueller.midlet.ui.CompletionListener;
import de.ueller.util.CancelMonitorInterface;
import de.ueller.util.DateTimeTools;
import de.ueller.util.HelperRoutines;
import de.ueller.util.IntPoint;
import de.ueller.util.Logger;
import de.ueller.util.MoreMath;
import de.ueller.util.ProjMath;
//#if polish.android
import de.enough.polish.android.midlet.MidletBridge;
//#endif
/**
* Implements the main "Map" screen which displays the map, offers track recording etc.
* @author Harald Mueller
*
*/
public class Trace extends KeyCommandCanvas implements LocationMsgReceiver,
CompassReceiver, Runnable , GpsMidDisplayable, CompletionListener, IconActionPerformer {
/** Soft button for exiting the map screen */
protected static final int EXIT_CMD = 1;
protected static final int CONNECT_GPS_CMD = 2;
protected static final int DISCONNECT_GPS_CMD = 3;
protected static final int START_RECORD_CMD = 4;
protected static final int STOP_RECORD_CMD = 5;
protected static final int MANAGE_TRACKS_CMD = 6;
protected static final int SAVE_WAYP_CMD = 7;
protected static final int ENTER_WAYP_CMD = 8;
protected static final int MANAGE_WAYP_CMD = 9;
protected static final int ROUTING_TOGGLE_CMD = 10;
protected static final int CAMERA_CMD = 11;
protected static final int CLEAR_DEST_CMD = 12;
protected static final int SET_DEST_CMD = 13;
protected static final int MAPFEATURES_CMD = 14;
protected static final int RECORDINGS_CMD = 16;
protected static final int ROUTINGS_CMD = 17;
protected static final int OK_CMD =18;
protected static final int BACK_CMD = 19;
protected static final int ZOOM_IN_CMD = 20;
protected static final int ZOOM_OUT_CMD = 21;
protected static final int MANUAL_ROTATION_MODE_CMD = 22;
protected static final int TOGGLE_OVERLAY_CMD = 23;
protected static final int TOGGLE_BACKLIGHT_CMD = 24;
protected static final int TOGGLE_FULLSCREEN_CMD = 25;
protected static final int TOGGLE_MAP_PROJ_CMD = 26;
protected static final int TOGGLE_KEY_LOCK_CMD = 27;
protected static final int TOGGLE_RECORDING_CMD = 28;
protected static final int TOGGLE_RECORDING_SUSP_CMD = 29;
protected static final int RECENTER_GPS_CMD = 30;
protected static final int DATASCREEN_CMD = 31;
protected static final int OVERVIEW_MAP_CMD = 32;
protected static final int RETRIEVE_XML = 33;
protected static final int PAN_LEFT25_CMD = 34;
protected static final int PAN_RIGHT25_CMD = 35;
protected static final int PAN_UP25_CMD = 36;
protected static final int PAN_DOWN25_CMD = 37;
protected static final int PAN_LEFT2_CMD = 38;
protected static final int PAN_RIGHT2_CMD = 39;
protected static final int PAN_UP2_CMD = 40;
protected static final int PAN_DOWN2_CMD = 41;
protected static final int REFRESH_CMD = 42;
protected static final int SEARCH_CMD = 43;
protected static final int TOGGLE_AUDIO_REC = 44;
protected static final int ROUTING_START_CMD = 45;
protected static final int ROUTING_STOP_CMD = 46;
protected static final int ONLINE_INFO_CMD = 47;
protected static final int ROUTING_START_WITH_MODE_SELECT_CMD = 48;
protected static final int RETRIEVE_NODE = 49;
protected static final int ICON_MENU = 50;
protected static final int ABOUT_CMD = 51;
protected static final int SETUP_CMD = 52;
protected static final int SEND_MESSAGE_CMD = 53;
protected static final int SHOW_DEST_CMD = 54;
protected static final int EDIT_ADDR_CMD = 55;
protected static final int OPEN_URL_CMD = 56;
protected static final int SHOW_PREVIOUS_POSITION_CMD = 57;
protected static final int TOGGLE_GPS_CMD = 58;
protected static final int CELLID_LOCATION_CMD = 59;
protected static final int MANUAL_LOCATION_CMD = 60;
protected static final int EDIT_ENTITY = 61;
private final Command [] CMDS = new Command[62];
public static final int DATASCREEN_NONE = 0;
public static final int DATASCREEN_TACHO = 1;
public static final int DATASCREEN_TRIP = 2;
public static final int DATASCREEN_SATS = 3;
public final static int DISTANCE_GENERIC = 1;
public final static int DISTANCE_ALTITUDE = 2;
public final static int DISTANCE_ROAD = 3;
public final static int DISTANCE_AIR = 4;
public final static int DISTANCE_UNKNOWN = 5;
// private SirfInput si;
private LocationMsgProducer locationProducer;
private LocationMsgProducer cellIDLocationProducer = null;
private CompassProducer compassProducer = null;
private volatile int compassDirection = 0;
private volatile int compassDeviation = 0;
private volatile int compassDeviated = 0;
public byte solution = LocationMsgReceiver.STATUS_OFF;
public String solutionStr = Locale.get("solution.Off");
/** Flag if the user requested to be centered to the current GPS position (true)
* or if the user moved the map away from this position (false).
*/
public boolean gpsRecenter = true;
/** Flag if the gps position is not yet valid after recenter request
*/
public volatile boolean gpsRecenterInvalid = true;
/** Flag if the gps position is stale (last known position instead of current) after recenter request
*/
public volatile boolean gpsRecenterStale = true;
/** Flag if the map is autoZoomed
*/
public boolean autoZoomed = true;
private Position pos = new Position(0.0f, 0.0f,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis());
/**
* this node contains actually RAD coordinates
* although the constructor for Node(lat, lon) requires parameters in DEC format
* - e. g. "new Node(49.328010f, 11.352556f)"
*/
public Node center = new Node(49.328010f, 11.352556f);
private Node prevPositionNode = null;
// Projection projection;
private final GpsMid parent;
public static TraceLayout tl = null;
private String lastTitleMsg;
private String currentTitleMsg;
private volatile int currentTitleMsgOpenCount = 0;
private volatile int setTitleMsgTimeout = 0;
private String lastTitleMsgClock;
private String currentAlertTitle;
private String currentAlertMessage;
private volatile int currentAlertsOpenCount = 0;
private volatile int setAlertTimeout = 0;
private long lastBackLightOnTime = 0;
private volatile static long lastUserActionTime = 0;
private long collected = 0;
public PaintContext pc;
public float scale = Configuration.getRealBaseScale();
int showAddons = 0;
/** x position display was touched last time (on pointerPressed() ) */
private static int touchX = 0;
/** y position display was touched last time (on pointerPressed() ) */
private static int touchY = 0;
/** x position display was released last time (on pointerReleased() ) */
private static int touchReleaseX = 0;
/** y position display was released last time (on pointerReleased() ) */
private static int touchReleaseY = 0;
/** center when display was touched last time (on pointerReleased() ) */
private static Node centerPointerPressedN = new Node();
private static Node pickPointStart = new Node();
private static Node pickPointEnd = new Node();
/**
* time at which a pointer press occured to determine
* single / double / long taps
*/
private long pressedPointerTime;
/**
* indicates if the next release event is valid or the corresponding pointer pressing has already been handled
*/
private volatile boolean pointerActionDone;
/** timer checking for single tap */
private volatile TimerTask singleTapTimerTask = null;
/** timer checking for long tap */
private volatile TimerTask longTapTimerTask = null;
/** timer for returning to small buttons */
private volatile TimerTask bigButtonTimerTask = null;
/**
* Indicates that there was any drag event since the last pointerPressed
*/
private static volatile boolean pointerDragged = false;
/**
* Indicates that there was a rather far drag event since the last pointerPressed
*/
private static volatile boolean pointerDraggedMuch = false;
/** indicates whether we already are checking for a single tap in the TimerTask */
private static volatile boolean checkingForSingleTap = false;
private final int DOUBLETAP_MAXDELAY = 300;
private final int LONGTAP_DELAY = 1000;
/** Flag if a route is currently being calculated */
public volatile boolean routeCalc = false;
public Tile tiles[] = new Tile[6];
public volatile boolean baseTilesRead = false;
public Way actualSpeedLimitWay;
// this is only for visual debugging of the routing engine
Vector routeNodes = new Vector();
private long oldRecalculationTime;
/** List representing the submenu "Recordings" */
private List recordingsMenu = null;
/** Array of command numbers corresponding to the items in recordingsMenu */
private int[] recordingsMenuCmds = null;
/** List representing the submenu "Routing" */
private List routingsMenu = null;
private GuiTacho guiTacho = null;
private GuiTrip guiTrip = null;
private GuiSatellites guiSatellites = null;
private GuiWaypointSave guiWaypointSave = null;
private final GuiWaypointPredefined guiWaypointPredefined = null;
private static TraceIconMenu traceIconMenu = null;
private final static Logger logger = Logger.getInstance(Trace.class, Logger.DEBUG);
//#mdebug info
public static final String statMsg[] = { "no Start1:", "no Start2:",
"to long :", "interrupt:", "checksum :", "no End1 :",
"no End2 :" };
//#enddebug
/**
* Quality of Bluetooth reception, 0..100.
*/
private byte btquality;
private int[] statRecord;
/**
* Current speed from GPS in km/h.
*/
public volatile int speed;
public volatile float fspeed;
/**
* variables for setting course from GPS movement
* TODO: make speed threshold (currently courseMinSpeed)
* user-settable by transfer mode in the style file
* and/or in user menu
*/
// was three until release 0.7; less than three allows
// for course setting even with slow walking, while
// the heuristics filter away erratic courses
// I've even tested with 0.5f with good results --jkpj
private final float courseMinSpeed = 1.5f;
private volatile int prevCourse = -1;
private volatile int secondPrevCourse = -1;
private volatile int thirdPrevCourse = -1;
/**
* Current altitude from GPS in m.
*/
public volatile int altitude;
/**
* Flag if we're speeding
*/
private volatile boolean speeding = false;
private long lastTimeOfSpeedingSound = 0;
private long startTimeOfSpeedingSign = 0;
private int speedingSpeedLimit = 0;
/**
* Current course from GPS in compass degrees, 0..359.
*/
private int course = 0;
private int coursegps = 0;
public boolean atDest = false;
public boolean movedAwayFromDest = true;
private Names namesThread;
private Urls urlsThread;
private ImageCollector imageCollector;
private QueueDataReader tileReader;
private QueueDictReader dictReader;
private final Runtime runtime = Runtime.getRuntime();
private RoutePositionMark dest = null;
public Vector route = null;
private RouteInstructions ri = null;
private boolean running = false;
private static final int CENTERPOS = Graphics.HCENTER | Graphics.VCENTER;
public Gpx gpx;
public AudioRecorder audioRec;
private static volatile Trace traceInstance = null;
private Routing routeEngine;
/*
private static Font smallBoldFont;
private static int smallBoldFontHeight;
*/
public boolean manualRotationMode = false;
public Vector locationUpdateListeners;
private Projection panProjection;
private Trace() throws Exception {
//#debug
logger.info("init Trace");
this.parent = GpsMid.getInstance();
Configuration.setHasPointerEvents(hasPointerEvents());
CMDS[EXIT_CMD] = new Command(Locale.get("generic.Exit")/*Exit*/, Command.EXIT, 2);
CMDS[REFRESH_CMD] = new Command(Locale.get("trace.Refresh")/*Refresh*/, Command.ITEM, 4);
CMDS[SEARCH_CMD] = new Command(Locale.get("generic.Search")/*Search*/, Command.OK, 1);
CMDS[CONNECT_GPS_CMD] = new Command(Locale.get("trace.StartGPS")/*Start GPS*/,Command.ITEM, 2);
CMDS[DISCONNECT_GPS_CMD] = new Command(Locale.get("trace.StopGPS")/*Stop GPS*/,Command.ITEM, 2);
CMDS[TOGGLE_GPS_CMD] = new Command(Locale.get("trace.ToggleGPS")/*Toggle GPS*/,Command.ITEM, 2);
CMDS[START_RECORD_CMD] = new Command(Locale.get("trace.StartRecord")/*Start record*/,Command.ITEM, 4);
CMDS[STOP_RECORD_CMD] = new Command(Locale.get("trace.StopRecord")/*Stop record*/,Command.ITEM, 4);
CMDS[MANAGE_TRACKS_CMD] = new Command(Locale.get("trace.ManageTracks")/*Manage tracks*/,Command.ITEM, 5);
CMDS[SAVE_WAYP_CMD] = new Command(Locale.get("trace.SaveWaypoint")/*Save waypoint*/,Command.ITEM, 7);
CMDS[ENTER_WAYP_CMD] = new Command(Locale.get("trace.EnterWaypoint")/*Enter waypoint*/,Command.ITEM, 7);
CMDS[MANAGE_WAYP_CMD] = new Command(Locale.get("trace.ManageWaypoints")/*Manage waypoints*/,Command.ITEM, 7);
CMDS[ROUTING_TOGGLE_CMD] = new Command(Locale.get("trace.ToggleRouting")/*Toggle routing*/,Command.ITEM, 3);
CMDS[CAMERA_CMD] = new Command(Locale.get("trace.Camera")/*Camera*/,Command.ITEM, 9);
CMDS[CLEAR_DEST_CMD] = new Command(Locale.get("trace.ClearDestination")/*Clear destination*/,Command.ITEM, 10);
CMDS[SET_DEST_CMD] = new Command(Locale.get("trace.AsDestination")/*As destination*/,Command.ITEM, 11);
CMDS[MAPFEATURES_CMD] = new Command(Locale.get("trace.MapFeatures")/*Map Features*/,Command.ITEM, 12);
CMDS[RECORDINGS_CMD] = new Command(Locale.get("trace.Recordings")/*Recordings...*/,Command.ITEM, 4);
CMDS[ROUTINGS_CMD] = new Command(Locale.get("trace.Routing3")/*Routing...*/,Command.ITEM, 3);
CMDS[OK_CMD] = new Command(Locale.get("generic.OK")/*OK*/,Command.OK, 14);
CMDS[BACK_CMD] = new Command(Locale.get("generic.Back")/*Back*/,Command.BACK, 15);
CMDS[ZOOM_IN_CMD] = new Command(Locale.get("trace.ZoomIn")/*Zoom in*/,Command.ITEM, 100);
CMDS[ZOOM_OUT_CMD] = new Command(Locale.get("trace.ZoomOut")/*Zoom out*/,Command.ITEM, 100);
CMDS[MANUAL_ROTATION_MODE_CMD] = new Command(Locale.get("trace.ManualRotation2")/*Manual rotation mode*/,Command.ITEM, 100);
CMDS[TOGGLE_OVERLAY_CMD] = new Command(Locale.get("trace.NextOverlay")/*Next overlay*/,Command.ITEM, 100);
CMDS[TOGGLE_BACKLIGHT_CMD] = new Command(Locale.get("trace.KeepBacklight")/*Keep backlight on/off*/,Command.ITEM, 100);
CMDS[TOGGLE_FULLSCREEN_CMD] = new Command(Locale.get("trace.SwitchToFullscreen")/*Switch to fullscreen*/,Command.ITEM, 100);
CMDS[TOGGLE_MAP_PROJ_CMD] = new Command(Locale.get("trace.NextMapProjection")/*Next map projection*/,Command.ITEM, 100);
CMDS[TOGGLE_KEY_LOCK_CMD] = new Command(Locale.get("trace.ToggleKeylock")/*(De)Activate Keylock*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_CMD] = new Command(Locale.get("trace.ToggleRecording")/*(De)Activate recording*/,Command.ITEM, 100);
CMDS[TOGGLE_RECORDING_SUSP_CMD] = new Command(Locale.get("trace.SuspendRecording")/*Suspend recording*/,Command.ITEM, 100);
CMDS[RECENTER_GPS_CMD] = new Command(Locale.get("trace.RecenterOnGPS")/*Recenter on GPS*/,Command.ITEM, 100);
CMDS[SHOW_DEST_CMD] = new Command(Locale.get("trace.ShowDestination")/*Show destination*/,Command.ITEM, 100);
CMDS[SHOW_PREVIOUS_POSITION_CMD] = new Command(Locale.get("trace.ShowPreviousPosition")/*Previous position*/,Command.ITEM, 100);
CMDS[DATASCREEN_CMD] = new Command(Locale.get("trace.Tacho")/*Tacho*/, Command.ITEM, 15);
CMDS[OVERVIEW_MAP_CMD] = new Command(Locale.get("trace.OverviewFilterMap")/*Overview/Filter map*/, Command.ITEM, 20);
CMDS[RETRIEVE_XML] = new Command(Locale.get("trace.RetrieveXML")/*Retrieve XML*/,Command.ITEM, 200);
CMDS[EDIT_ENTITY] = new Command(Locale.get("traceiconmenu.EditPOI")/*Edit POI*/,Command.ITEM, 200);
CMDS[PAN_LEFT25_CMD] = new Command(Locale.get("trace.left25")/*left 25%*/,Command.ITEM, 100);
CMDS[PAN_RIGHT25_CMD] = new Command(Locale.get("trace.right25")/*right 25%*/,Command.ITEM, 100);
CMDS[PAN_UP25_CMD] = new Command(Locale.get("trace.up25")/*up 25%*/,Command.ITEM, 100);
CMDS[PAN_DOWN25_CMD] = new Command(Locale.get("trace.down25")/*down 25%*/,Command.ITEM, 100);
CMDS[PAN_LEFT2_CMD] = new Command(Locale.get("trace.left2")/*left 2*/,Command.ITEM, 100);
CMDS[PAN_RIGHT2_CMD] = new Command(Locale.get("trace.right2")/*right 2*/,Command.ITEM, 100);
CMDS[PAN_UP2_CMD] = new Command(Locale.get("trace.up2")/*up 2*/,Command.ITEM, 100);
CMDS[PAN_DOWN2_CMD] = new Command(Locale.get("trace.down2")/*down 2*/,Command.ITEM, 100);
CMDS[TOGGLE_AUDIO_REC] = new Command(Locale.get("trace.AudioRecording")/*Audio recording*/,Command.ITEM, 100);
CMDS[ROUTING_START_CMD] = new Command(Locale.get("trace.CalculateRoute")/*Calculate route*/,Command.ITEM, 100);
CMDS[ROUTING_STOP_CMD] = new Command(Locale.get("trace.StopRouting")/*Stop routing*/,Command.ITEM, 100);
CMDS[ONLINE_INFO_CMD] = new Command(Locale.get("trace.OnlineInfo")/*Online info*/,Command.ITEM, 100);
CMDS[ROUTING_START_WITH_MODE_SELECT_CMD] = new Command(Locale.get("trace.CalculateRoute2")/*Calculate route...*/,Command.ITEM, 100);
CMDS[RETRIEVE_NODE] = new Command(Locale.get("trace.AddPOI")/*Add POI to OSM...*/,Command.ITEM, 100);
CMDS[ICON_MENU] = new Command(Locale.get("trace.Menu")/*Menu*/,Command.OK, 100);
CMDS[SETUP_CMD] = new Command(Locale.get("trace.Setup")/*Setup*/, Command.ITEM, 25);
CMDS[ABOUT_CMD] = new Command(Locale.get("generic.About")/*About*/, Command.ITEM, 30);
//#if polish.api.wmapi
CMDS[SEND_MESSAGE_CMD] = new Command(Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/,Command.ITEM, 20);
//#endif
CMDS[EDIT_ADDR_CMD] = new Command(Locale.get("trace.AddAddrNode")/*Add Addr node*/,Command.ITEM,100);
CMDS[CELLID_LOCATION_CMD] = new Command(Locale.get("trace.CellidLocation")/*Set location from CellID*/,Command.ITEM,100);
CMDS[MANUAL_LOCATION_CMD] = new Command(Locale.get("trace.ManualLocation")/*Set location manually*/,Command.ITEM,100);
addAllCommands();
Configuration.loadKeyShortcuts(gameKeyCommand, singleKeyPressCommand,
repeatableKeyPressCommand, doubleKeyPressCommand, longKeyPressCommand,
nonReleasableKeyPressCommand, CMDS);
if (!Configuration.getCfgBitState(Configuration.CFGBIT_CANVAS_SPECIFIC_DEFAULTS_DONE)) {
if (getWidth() > 219) {
// if the map display is wide enough, show the clock in the map screen by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP, true);
// if the map display is wide enough, use big tab buttons by default
Configuration.setCfgBitSavedState(Configuration.CFGBIT_ICONMENUS_BIG_TAB_BUTTONS, true);
}
if (hasPointerEvents()) {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_LARGE_FONT, true);
}
Configuration.setCfgBitSavedState(Configuration.CFGBIT_CANVAS_SPECIFIC_DEFAULTS_DONE, true);
}
try {
startup();
} catch (Exception e) {
logger.fatal(Locale.get("trace.GotExceptionDuringStartup")/*Got an exception during startup: */ + e.getMessage());
e.printStackTrace();
return;
}
// setTitle("initTrace ready");
locationUpdateListeners = new Vector();
traceInstance = this;
}
public Command getCommand(int command) {
return CMDS[command];
}
/**
* Returns the instance of the map screen. If none exists yet,
* a new instance is generated
* @return Reference to singleton instance
*/
public static synchronized Trace getInstance() {
if (traceInstance == null) {
try {
traceInstance = new Trace();
} catch (Exception e) {
logger.exception(Locale.get("trace.FailedToInitialiseMapScreen")/*Failed to initialise Map screen*/, e);
}
}
return traceInstance;
}
public float getGpsLat() {
return pos.latitude;
}
public float getGpsLon() {
return pos.longitude;
}
public void stopCompass() {
if (compassProducer != null) {
compassProducer.close();
}
compassProducer = null;
}
public void startCompass() {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer == null) {
compassProducer = new GetCompass();
if (!compassProducer.init(this)) {
logger.info("Failed to init compass producer");
compassProducer = null;
} else if (!compassProducer.activate(this)) {
logger.info("Failed to activate compass producer");
compassProducer = null;
}
}
}
/**
* Starts the LocationProvider in the background
*/
public void run() {
try {
if (running) {
receiveMessage(Locale.get("trace.GpsStarterRunning")/*GPS starter already running*/);
return;
}
//#debug info
logger.info("start thread init locationprovider");
if (locationProducer != null) {
receiveMessage(Locale.get("trace.LocProvRunning")/*Location provider already running*/);
return;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_NONE) {
receiveMessage(Locale.get("trace.NoLocProv")/*"No location provider*/);
return;
}
running=true;
startCompass();
int locprov = Configuration.getLocationProvider();
receiveMessage(Locale.get("trace.ConnectTo")/*Connect to */ + Configuration.LOCATIONPROVIDER[locprov]);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_CELLID_STARTUP)) {
// Don't do initial lookup if we're going to start primary cellid location provider anyway
if (Configuration.getLocationProvider() != Configuration.LOCATIONPROVIDER_SECELL || !Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
commandAction(CELLID_LOCATION_CMD);
}
}
switch (locprov) {
case Configuration.LOCATIONPROVIDER_SIRF:
locationProducer = new SirfInput();
break;
case Configuration.LOCATIONPROVIDER_NMEA:
locationProducer = new NmeaInput();
break;
case Configuration.LOCATIONPROVIDER_SECELL:
if (cellIDLocationProducer != null) {
cellIDLocationProducer.close();
}
locationProducer = new SECellId();
break;
case Configuration.LOCATIONPROVIDER_JSR179:
//#if polish.api.locationapi
try {
String jsr179Version = null;
try {
jsr179Version = System.getProperty("microedition.location.version");
} catch (RuntimeException re) {
// Some phones throw exceptions if trying to access properties that don't
// exist, so we have to catch these and just ignore them.
} catch (Exception e) {
// As above
}
//#if polish.android
// FIXME current (2010-06, 2011-07 (2.2.1)) android j2mepolish doesn't give this info
//#else
if (jsr179Version != null && jsr179Version.length() > 0) {
//#endif
Class jsr179Class = Class.forName("de.ueller.gps.location.Jsr179Input");
locationProducer = (LocationMsgProducer) jsr179Class.newInstance();
//#if polish.android
//#else
}
//#endif
} catch (ClassNotFoundException cnfe) {
locationDecoderEnd();
logger.exception(Locale.get("trace.NoJSR179Support")/*Your phone does not support JSR179, please use a different location provider*/, cnfe);
running = false;
return;
}
//#else
// keep Eclipse happy
if (true) {
logger.error(Locale.get("trace.JSR179NotCompiledIn")/*JSR179 is not compiled in this version of GpsMid*/);
running = false;
return;
}
//#endif
break;
}
//#if polish.api.fileconnection
/**
* Allow for logging the raw data coming from the gps
*/
String url = Configuration.getGpsRawLoggerUrl();
//logger.error("Raw logging url: " + url);
if (url != null) {
try {
if (Configuration.getGpsRawLoggerEnable()) {
logger.info("Raw Location logging to: " + url);
url += "rawGpsLog" + HelperRoutines.formatSimpleDateNow() + ".txt";
//#if polish.android
de.enough.polish.android.io.Connection logCon = Connector.open(url);
//#else
javax.microedition.io.Connection logCon = Connector.open(url);
//#endif
if (logCon instanceof FileConnection) {
FileConnection fileCon = (FileConnection)logCon;
if (!fileCon.exists()) {
fileCon.create();
}
locationProducer.enableRawLogging(((FileConnection)logCon).openOutputStream());
} else {
logger.info("Raw logging of NMEA is only to filesystem supported");
}
}
/**
* Help out the OpenCellId.org project by gathering and logging
* data of cell ids together with current Gps location. This information
* can then be uploaded to their web site to determine the position of the
* cell towers. It currently only works for SE phones
*/
if (Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
SECellLocLogger secl = new SECellLocLogger();
if (secl.init()) {
locationProducer.addLocationMsgReceiver(secl);
}
}
} catch (IOException ioe) {
logger.exception(Locale.get("trace.CouldntOpenFileForRawLogging")/*Could not open file for raw logging of Gps data*/,ioe);
} catch (SecurityException se) {
logger.error(Locale.get("trace.PermissionWritingDataDenied")/*Permission to write data for NMEA raw logging was denied*/);
}
}
//#endif
if (locationProducer == null) {
logger.error(Locale.get("trace.ChooseDiffLocMethod")/*Your phone does not seem to support this method of location input, please choose a different one*/);
running = false;
return;
}
if (!locationProducer.init(this)) {
logger.info("Failed to initialise location producer");
running = false;
return;
}
if (!locationProducer.activate(this)) {
logger.info("Failed to activate location producer");
running = false;
return;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_CONNECT)) {
GpsMid.mNoiseMaker.playSound("CONNECT");
}
//#debug debug
logger.debug("rm connect, add disconnect");
removeCommand(CMDS[CONNECT_GPS_CMD]);
addCommand(CMDS[DISCONNECT_GPS_CMD]);
//#debug info
logger.info("end startLocationPovider thread");
// setTitle("lp="+Configuration.getLocationProvider() + " " + Configuration.getBtUrl());
} catch (SecurityException se) {
/**
* The application was not permitted to connect to the required resources
* Not much we can do here other than gracefully shutdown the thread *
*/
} catch (OutOfMemoryError oome) {
logger.fatal(Locale.get("trace.TraceThreadCrashOOM")/*Trace thread crashed as out of memory: */ + oome.getMessage());
oome.printStackTrace();
} catch (Exception e) {
logger.fatal(Locale.get("trace.TraceThreadCrashWith")/*Trace thread crashed unexpectedly with error */ + e.getMessage());
e.printStackTrace();
} finally {
running = false;
}
running = false;
}
// add the command only if icon menus are not used
public void addCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.addCommand(c);
}
}
public RoutePositionMark getDest() {
return dest;
}
// remove the command only if icon menus are not used
public void removeCommand(Command c) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
super.removeCommand(c);
}
}
public synchronized void pause() {
logger.debug("Pausing application");
if (imageCollector != null) {
imageCollector.suspend();
}
if (locationProducer != null) {
locationProducer.close();
} else {
return;
}
int polling = 0;
while ((locationProducer != null) && (polling < 7)) {
polling++;
try {
wait(200);
} catch (InterruptedException e) {
break;
}
}
if (locationProducer != null) {
logger.error(Locale.get("trace.LocationProducerTookTooLong")/*LocationProducer took too long to close, giving up*/);
}
}
public void resumeAfterPause() {
logger.debug("resuming application after pause");
if (imageCollector != null) {
imageCollector.resume();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS) && !running && (locationProducer == null)) {
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
}
public void resume() {
logger.debug("resuming application");
if (imageCollector != null) {
imageCollector.resume();
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
public void autoRouteRecalculate() {
if ( gpsRecenter && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_AUTO_RECALC) ) {
if (Math.abs(System.currentTimeMillis()-oldRecalculationTime) >= 7000 ) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_ROUTINGINSTRUCTIONS)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getRecalculationSound(), (byte) 5, (byte) 1 );
}
//#debug debug
logger.debug("autoRouteRecalculate");
// recalculate route
commandAction(ROUTING_START_CMD);
}
}
}
public boolean isGpsConnected() {
return (locationProducer != null && solution != LocationMsgReceiver.STATUS_OFF);
}
/**
* Adds all commands for a normal menu.
*/
public void addAllCommands() {
addCommand(CMDS[EXIT_CMD]);
addCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
addCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
addCommand(CMDS[CONNECT_GPS_CMD]);
}
//TODO Cleanup addCommand(CMDS[MANAGE_TRACKS_CMD]);
//addCommand(CMDS[MAN_WAYP_CMD]);
addCommand(CMDS[ROUTINGS_CMD]);
addCommand(CMDS[RECORDINGS_CMD]);
addCommand(CMDS[MAPFEATURES_CMD]);
addCommand(CMDS[DATASCREEN_CMD]);
addCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
addCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
addCommand(CMDS[RETRIEVE_XML]);
addCommand(CMDS[EDIT_ENTITY]);
addCommand(CMDS[RETRIEVE_NODE]);
addCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
addCommand(CMDS[SETUP_CMD]);
addCommand(CMDS[ABOUT_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
//#ifndef polish.android
super.addCommand(CMDS[ICON_MENU]);
//#endif
}
}
setCommandListener(this);
}
/**
* This method must remove all commands that were added by addAllCommands().
*/
public void removeAllCommands() {
//setCommandListener(null);
/* Although j2me documentation says removeCommand for a non-attached command is allowed
* this would crash MicroEmulator. Thus we only remove the commands attached.
*/
removeCommand(CMDS[EXIT_CMD]);
removeCommand(CMDS[SEARCH_CMD]);
if (isGpsConnected()) {
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
} else {
removeCommand(CMDS[CONNECT_GPS_CMD]);
}
//TODO Cleanup removeCommand(CMDS[MANAGE_TRACKS_CMD]);
//removeCommand(CMDS[MAN_WAYP_CMD]);
removeCommand(CMDS[MAPFEATURES_CMD]);
removeCommand(CMDS[RECORDINGS_CMD]);
removeCommand(CMDS[ROUTINGS_CMD]);
removeCommand(CMDS[DATASCREEN_CMD]);
removeCommand(CMDS[OVERVIEW_MAP_CMD]);
//#if polish.api.online
removeCommand(CMDS[ONLINE_INFO_CMD]);
//#if polish.api.osm-editing
removeCommand(CMDS[RETRIEVE_XML]);
removeCommand(CMDS[EDIT_ENTITY]);
removeCommand(CMDS[RETRIEVE_NODE]);
removeCommand(CMDS[EDIT_ADDR_CMD]);
//#endif
//#endif
removeCommand(CMDS[SETUP_CMD]);
removeCommand(CMDS[ABOUT_CMD]);
removeCommand(CMDS[CELLID_LOCATION_CMD]);
removeCommand(CMDS[MANUAL_LOCATION_CMD]);
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
if (!Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
//#ifndef polish.android
super.removeCommand(CMDS[ICON_MENU]);
//#endif
}
}
}
/** Sets the Canvas to fullScreen or windowed mode
* when icon menus are active the Menu command gets removed
* so the Canvas will not unhide the menu bar first when pressing fire (e.g. on SE mobiles)
*/
public void setFullScreenMode(boolean fullScreen) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
//#ifndef polish.android
if (fullScreen) {
super.removeCommand(CMDS[ICON_MENU]);
} else
//#endif
{
//#ifndef polish.android
super.addCommand(CMDS[ICON_MENU]);
//#endif
}
}
//#if polish.android
if (fullScreen) {
MidletBridge.instance.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
MidletBridge.instance.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
//#else
super.setFullScreenMode(fullScreen);
//#endif
}
public void commandAction(int actionId) {
// take care we'll update actualWay
if (actionId == RETRIEVE_XML || actionId == EDIT_ADDR_CMD) {
repaint();
}
commandAction(CMDS[actionId], null);
}
public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MANAGE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 5;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements;
if (gpx.isRecordingTrk()) {
noElements++;
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = STOP_RECORD_CMD;
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop GPX tracklog*/;
if (gpx.isRecordingTrkSuspended()) {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.ResumeRecording")/*Resume recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.SuspendRecording")/*Suspend recording*/;
}
} else {
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = START_RECORD_CMD;
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start GPX tracklog*/;
}
recordingsMenuCmds[idx] = SAVE_WAYP_CMD;
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
recordingsMenuCmds[idx] = ENTER_WAYP_CMD;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
recordingsMenuCmds[idx] = MANAGE_TRACKS_CMD;
elements[idx++] = Locale.get("trace.ManageTracks")/*Manage tracks*/;
recordingsMenuCmds[idx] = MANAGE_WAYP_CMD;
elements[idx++] = Locale.get("trace.ManageWaypoints")/*Manage waypoints*/;
//#if polish.api.mmapi
recordingsMenuCmds[idx] = CAMERA_CMD;
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
recordingsMenuCmds[idx] = SEND_MESSAGE_CMD;
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,
Choice.IMPLICIT, elements, null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
int recCmd = recordingsMenu.getSelectedIndex();
if (recCmd >= 0 && recCmd < recordingsMenuCmds.length) {
recCmd = recordingsMenuCmds[recCmd];
if (recCmd == STOP_RECORD_CMD) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else if (recCmd == START_RECORD_CMD) {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
} else if (recCmd == TOGGLE_RECORDING_SUSP_CMD) {
commandAction(TOGGLE_RECORDING_SUSP_CMD);
show();
} else {
commandAction(recCmd);
}
}
} else if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
- Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
+ Class GuiCameraClass = Class.forName("de.ueller.gpsmid.ui.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // Refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
recordingsMenu = null; // Refresh recordings menu
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellId();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GuiOsmWayDisplay guiWay = new GuiOsmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
// FIXME add support for accessing a node
// under cursor
if (Legend.enableEdits) {
GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOsmAddrDisplay guiAddr = new GuiOsmAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
tl.ele[TraceLayout.RECORDINGS].setText("*");
tl.ele[TraceLayout.SEARCH].setText("_");
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GsmCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
//if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
// if (!Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
// updateCourse(compassDeviated);
// }
//repaint();
//}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && !Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
} else if (prevCourse == -1) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} // previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
updateCourse((int) pos.course);
} else {
secondPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
prevCourse = (int) pos.course;
} else {
// speed under the minimum. If it went under the limit now, do a heuristic
// to decide a proper course.
// invalidate all prev courses
if (thirdPrevCourse != -1) {
// speed just went under the threshold
// - if the last readings are not within the 30 degree sector of
// the previous one, restore course to the third previous course,
// it's probable that it's more reliable than the last
// course, as we see that at traffic light stops
// an incorrect course is shown relatively often
if ((Math.abs(prevCourse - secondPrevCourse) < 15 || Math.abs(prevCourse - secondPrevCourse) > 345)
&& (Math.abs(thirdPrevCourse - secondPrevCourse) < 15 || Math.abs(thirdPrevCourse - secondPrevCourse) > 345)) {
// we're OK
} else {
updateCourse(thirdPrevCourse);
}
}
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
// to update e.g. tacho
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
show();
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
}
| true | true | public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MANAGE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 5;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements;
if (gpx.isRecordingTrk()) {
noElements++;
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = STOP_RECORD_CMD;
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop GPX tracklog*/;
if (gpx.isRecordingTrkSuspended()) {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.ResumeRecording")/*Resume recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.SuspendRecording")/*Suspend recording*/;
}
} else {
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = START_RECORD_CMD;
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start GPX tracklog*/;
}
recordingsMenuCmds[idx] = SAVE_WAYP_CMD;
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
recordingsMenuCmds[idx] = ENTER_WAYP_CMD;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
recordingsMenuCmds[idx] = MANAGE_TRACKS_CMD;
elements[idx++] = Locale.get("trace.ManageTracks")/*Manage tracks*/;
recordingsMenuCmds[idx] = MANAGE_WAYP_CMD;
elements[idx++] = Locale.get("trace.ManageWaypoints")/*Manage waypoints*/;
//#if polish.api.mmapi
recordingsMenuCmds[idx] = CAMERA_CMD;
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
recordingsMenuCmds[idx] = SEND_MESSAGE_CMD;
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,
Choice.IMPLICIT, elements, null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
int recCmd = recordingsMenu.getSelectedIndex();
if (recCmd >= 0 && recCmd < recordingsMenuCmds.length) {
recCmd = recordingsMenuCmds[recCmd];
if (recCmd == STOP_RECORD_CMD) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else if (recCmd == START_RECORD_CMD) {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
} else if (recCmd == TOGGLE_RECORDING_SUSP_CMD) {
commandAction(TOGGLE_RECORDING_SUSP_CMD);
show();
} else {
commandAction(recCmd);
}
}
} else if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.midlet.gps.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // Refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
recordingsMenu = null; // Refresh recordings menu
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellId();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GuiOsmWayDisplay guiWay = new GuiOsmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
// FIXME add support for accessing a node
// under cursor
if (Legend.enableEdits) {
GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOsmAddrDisplay guiAddr = new GuiOsmAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
tl.ele[TraceLayout.RECORDINGS].setText("*");
tl.ele[TraceLayout.SEARCH].setText("_");
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GsmCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
//if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
// if (!Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
// updateCourse(compassDeviated);
// }
//repaint();
//}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && !Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
} else if (prevCourse == -1) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} // previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
updateCourse((int) pos.course);
} else {
secondPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
prevCourse = (int) pos.course;
} else {
// speed under the minimum. If it went under the limit now, do a heuristic
// to decide a proper course.
// invalidate all prev courses
if (thirdPrevCourse != -1) {
// speed just went under the threshold
// - if the last readings are not within the 30 degree sector of
// the previous one, restore course to the third previous course,
// it's probable that it's more reliable than the last
// course, as we see that at traffic light stops
// an incorrect course is shown relatively often
if ((Math.abs(prevCourse - secondPrevCourse) < 15 || Math.abs(prevCourse - secondPrevCourse) > 345)
&& (Math.abs(thirdPrevCourse - secondPrevCourse) < 15 || Math.abs(thirdPrevCourse - secondPrevCourse) > 345)) {
// we're OK
} else {
updateCourse(thirdPrevCourse);
}
}
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
// to update e.g. tacho
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
show();
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
}
| public void commandAction(Command c, Displayable d) {
updateLastUserActionTime();
try {
if((keyboardLocked) && (d != null)) {
// show alert in keypressed() that keyboard is locked
keyPressed(0);
return;
}
if ((c == CMDS[PAN_LEFT25_CMD]) || (c == CMDS[PAN_RIGHT25_CMD])
|| (c == CMDS[PAN_UP25_CMD]) || (c == CMDS[PAN_DOWN25_CMD])
|| (c == CMDS[PAN_LEFT2_CMD]) || (c == CMDS[PAN_RIGHT2_CMD])
|| (c == CMDS[PAN_UP2_CMD]) || (c == CMDS[PAN_DOWN2_CMD])) {
int panX = 0; int panY = 0;
int courseDiff = 0;
int backLightLevelDiff = 0;
if (c == CMDS[PAN_LEFT25_CMD]) {
panX = -25;
} else if (c == CMDS[PAN_RIGHT25_CMD]) {
panX = 25;
} else if (c == CMDS[PAN_UP25_CMD]) {
panY = -25;
} else if (c == CMDS[PAN_DOWN25_CMD]) {
panY = 25;
} else if (c == CMDS[PAN_LEFT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.slower();
} else if (manualRotationMode) {
courseDiff=-5;
} else {
panX = -2;
}
backLightLevelDiff = -25;
} else if (c == CMDS[PAN_RIGHT2_CMD]) {
if (TrackPlayer.isPlaying) {
TrackPlayer.faster();
} else if (manualRotationMode) {
courseDiff=5;
} else {
panX = 2;
}
backLightLevelDiff = 25;
} else if (c == CMDS[PAN_UP2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(1);
} else {
panY = -2;
}
} else if (c == CMDS[PAN_DOWN2_CMD]) {
if (route!=null && Configuration.getCfgBitState(Configuration.CFGBIT_ROUTE_BROWSING)) {
RouteInstructions.toNextInstruction(-1);
} else {
panY = 2;
}
}
if (backLightLevelDiff !=0 && System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
// turn backlight always on when dimming
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON, true, false);
lastBackLightOnTime = System.currentTimeMillis();
Configuration.addToBackLightLevel(backLightLevelDiff);
parent.showBackLightLevel();
} else if (imageCollector != null) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
// set compass compassDeviation
if (compassDeviation == 360) {
compassDeviation = 0;
} else {
compassDeviation += courseDiff;
compassDeviation %= 360;
if (course < 0) {
course += 360;
}
}
} else {
// manual rotation
if (courseDiff == 360) {
course = 0; //N
} else {
course += courseDiff;
course %= 360;
if (course < 0) {
course += 360;
}
}
if (panX != 0 || panY != 0) {
gpsRecenter = false;
}
}
imageCollector.getCurrentProjection().pan(center, panX, panY);
}
gpsRecenter = false;
return;
}
if (c == CMDS[EXIT_CMD]) {
// FIXME: This is a workaround. It would be better if recording
// would not be stopped when leaving the map.
if (Legend.isValid && gpx.isRecordingTrk()) {
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.PleaseStopRecording")/*Please stop recording before exit.*/ , 2500);
return;
}
if (Legend.isValid) {
pause();
}
parent.exit();
return;
}
if (c == CMDS[START_RECORD_CMD]) {
try {
gpx.newTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StartingToRecord")/*Starting to record*/, 1250);
} catch (RuntimeException e) {
receiveMessage(e.getMessage());
}
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[STOP_RECORD_CMD]) {
gpx.saveTrk(false);
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.StoppingToRecord")/*Stopping to record*/, 1250);
recordingsMenu = null; // refresh recordings menu
return;
}
if (c == CMDS[MANAGE_TRACKS_CMD]) {
if (gpx.isRecordingTrk() && !gpx.isRecordingTrkSuspended()) {
// FIXME it's not strictly necessary to stop, after there are translation for the pause
// message, change to Locale.get("trace.YouNeedStopPauseRecording")
alert(Locale.get("trace.RecordMode")/*Record Mode*/, Locale.get("trace.YouNeedStopRecording")/*You need to stop recording before managing tracks.*/ , 4000);
return;
}
GuiGpx guiGpx = new GuiGpx(this);
guiGpx.show();
return;
}
if (c == CMDS[REFRESH_CMD]) {
repaint();
return;
}
if (c == CMDS[CONNECT_GPS_CMD]) {
if (locationProducer == null) {
if (TrackPlayer.isPlaying) {
TrackPlayer.getInstance().stop();
alert(Locale.get("trace.Trackplayer")/*Trackplayer*/, Locale.get("trace.PlayingStopped")/*Playing stopped for connecting to GPS*/, 2500);
}
Thread thread = new Thread(this,"LocationProducer init");
thread.start();
}
return;
}
if (c == CMDS[DISCONNECT_GPS_CMD]) {
if (locationProducer != null) {
locationProducer.close();
}
return;
}
if (c == CMDS[TOGGLE_GPS_CMD]) {
if (isGpsConnected()) {
commandAction(DISCONNECT_GPS_CMD);
} else {
commandAction(CONNECT_GPS_CMD);
}
return;
}
if (c == CMDS[SEARCH_CMD]) {
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_DEFAULT);
guiSearch.show();
return;
}
if (c == CMDS[ENTER_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypointEnter gwpe = new GuiWaypointEnter(this);
gwpe.show();
}
return;
}
if (c == CMDS[MANAGE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
GuiWaypoint gwp = new GuiWaypoint(this);
gwp.show();
}
return;
}
if (c == CMDS[MAPFEATURES_CMD]) {
GuiMapFeatures gmf = new GuiMapFeatures(this);
gmf.show();
repaint();
return;
}
if (c == CMDS[OVERVIEW_MAP_CMD]) {
GuiOverviewElements ovEl = new GuiOverviewElements(this);
ovEl.show();
repaint();
return;
}
//#if polish.api.wmapi
if (c == CMDS[SEND_MESSAGE_CMD]) {
GuiSendMessage sendMsg = new GuiSendMessage(this);
sendMsg.show();
repaint();
return;
}
//#endif
if (c == CMDS[RECORDINGS_CMD]) {
if (recordingsMenu == null) {
boolean hasJSR120 = Configuration.hasDeviceJSR120();
int noElements = 5;
//#if polish.api.mmapi
noElements += 2;
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
noElements++;
}
//#endif
int idx = 0;
String[] elements;
if (gpx.isRecordingTrk()) {
noElements++;
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = STOP_RECORD_CMD;
elements[idx++] = Locale.get("trace.StopGpxTracklog")/*Stop GPX tracklog*/;
if (gpx.isRecordingTrkSuspended()) {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.ResumeRecording")/*Resume recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_RECORDING_SUSP_CMD;
elements[idx++] = Locale.get("trace.SuspendRecording")/*Suspend recording*/;
}
} else {
elements = new String[noElements];
recordingsMenuCmds = new int[noElements];
recordingsMenuCmds[idx] = START_RECORD_CMD;
elements[idx++] = Locale.get("trace.StartGpxTracklog")/*Start GPX tracklog*/;
}
recordingsMenuCmds[idx] = SAVE_WAYP_CMD;
elements[idx++] = Locale.get("trace.SaveWaypoint")/*Save waypoint*/;
recordingsMenuCmds[idx] = ENTER_WAYP_CMD;
elements[idx++] = Locale.get("trace.EnterWaypoint")/*Enter waypoint*/;
recordingsMenuCmds[idx] = MANAGE_TRACKS_CMD;
elements[idx++] = Locale.get("trace.ManageTracks")/*Manage tracks*/;
recordingsMenuCmds[idx] = MANAGE_WAYP_CMD;
elements[idx++] = Locale.get("trace.ManageWaypoints")/*Manage waypoints*/;
//#if polish.api.mmapi
recordingsMenuCmds[idx] = CAMERA_CMD;
elements[idx++] = Locale.get("trace.TakePictures")/*Take pictures*/;
if (audioRec.isRecording()) {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StopAudioRecording")/*Stop audio recording*/;
} else {
recordingsMenuCmds[idx] = TOGGLE_AUDIO_REC;
elements[idx++] = Locale.get("trace.StartAudioRecording")/*Start audio recording*/;
}
//#endif
//#if polish.api.wmapi
if (hasJSR120) {
recordingsMenuCmds[idx] = SEND_MESSAGE_CMD;
elements[idx++] = Locale.get("trace.SendSMSMapPos")/*Send SMS (map pos)*/;
}
//#endif
recordingsMenu = new List(Locale.get("trace.Recordings")/*Recordings...*/,
Choice.IMPLICIT, elements, null);
recordingsMenu.addCommand(CMDS[OK_CMD]);
recordingsMenu.addCommand(CMDS[BACK_CMD]);
recordingsMenu.setSelectCommand(CMDS[OK_CMD]);
parent.show(recordingsMenu);
recordingsMenu.setCommandListener(this);
}
if (recordingsMenu != null) {
recordingsMenu.setSelectedIndex(0, true);
parent.show(recordingsMenu);
}
return;
}
if (c == CMDS[ROUTINGS_CMD]) {
if (routingsMenu == null) {
String[] elements = new String[4];
if (routeCalc || route != null) {
elements[0] = Locale.get("trace.StopRouting")/*Stop routing*/;
} else {
elements[0] = Locale.get("trace.CalculateRoute")/*Calculate route*/;
}
elements[1] = Locale.get("trace.SetDestination")/*Set destination*/;
elements[2] = Locale.get("trace.ShowDestination")/*Show destination*/;
elements[3] = Locale.get("trace.ClearDestination")/*Clear destination*/;
routingsMenu = new List(Locale.get("trace.Routing2")/*Routing..*/, Choice.IMPLICIT, elements, null);
routingsMenu.addCommand(CMDS[OK_CMD]);
routingsMenu.addCommand(CMDS[BACK_CMD]);
routingsMenu.setSelectCommand(CMDS[OK_CMD]);
routingsMenu.setCommandListener(this);
}
if (routingsMenu != null) {
routingsMenu.setSelectedIndex(0, true);
parent.show(routingsMenu);
}
return;
}
if (c == CMDS[SAVE_WAYP_CMD]) {
if (gpx.isLoadingWaypoints()) {
showAlertLoadingWpt();
} else {
PositionMark posMark = null;
if (gpsRecenter) {
// TODO: If we lose the fix the old position and height
// will be used silently -> we should inform the user
// here that we have no fix - he may not know what's going on.
posMark = new PositionMark(center.radlat, center.radlon,
(int)pos.altitude, pos.timeMillis,
/* fix */ (byte)-1, /* sats */ (byte)-1,
/* sym */ (byte)-1, /* type */ (byte)-1);
} else {
// Cursor does not point to current position
// -> it does not make sense to add elevation and GPS fix info.
posMark = new PositionMark(center.radlat, center.radlon,
PositionMark.INVALID_ELEVATION,
pos.timeMillis, /* fix */ (byte)-1,
/* sats */ (byte)-1, /* sym */ (byte)-1,
/* type */ (byte)-1);
}
/*
if (Configuration.getCfgBitState(Configuration.CFGBIT_WAYPT_OFFER_PREDEF)) {
if (guiWaypointPredefined == null) {
guiWaypointPredefined = new GuiWaypointPredefined(this);
}
if (guiWaypointPredefined != null) {
guiWaypointPredefined.setData(posMark);
guiWaypointPredefined.show();
}
} else {
*/
showGuiWaypointSave(posMark);
//}
}
return;
}
if (c == CMDS[ONLINE_INFO_CMD]) {
//#if polish.api.online
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
GuiWebInfo gWeb = new GuiWebInfo(this, oPos, pc);
gWeb.show();
//#else
alert(Locale.get("trace.NoOnlineCapa")/*No online capabilites*/,
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
//#endif
}
if (c == CMDS[BACK_CMD]) {
show();
return;
}
if (c == CMDS[OK_CMD]) {
if (d == recordingsMenu) {
int recCmd = recordingsMenu.getSelectedIndex();
if (recCmd >= 0 && recCmd < recordingsMenuCmds.length) {
recCmd = recordingsMenuCmds[recCmd];
if (recCmd == STOP_RECORD_CMD) {
commandAction(STOP_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_STOP)) {
show();
}
} else if (recCmd == START_RECORD_CMD) {
commandAction(START_RECORD_CMD);
if (! Configuration.getCfgBitState(Configuration.CFGBIT_GPX_ASK_TRACKNAME_START)) {
show();
}
} else if (recCmd == TOGGLE_RECORDING_SUSP_CMD) {
commandAction(TOGGLE_RECORDING_SUSP_CMD);
show();
} else {
commandAction(recCmd);
}
}
} else if (d == routingsMenu) {
show();
switch (routingsMenu.getSelectedIndex()) {
case 0: {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
break;
}
case 1: {
commandAction(SET_DEST_CMD);
break;
}
case 2: {
commandAction(SHOW_DEST_CMD);
break;
}
case 3: {
commandAction(CLEAR_DEST_CMD);
break;
}
}
}
return;
}
//#if polish.api.mmapi
if (c == CMDS[CAMERA_CMD]) {
try {
Class GuiCameraClass = Class.forName("de.ueller.gpsmid.ui.GuiCamera");
Object GuiCameraObject = GuiCameraClass.newInstance();
GuiCameraInterface cam = (GuiCameraInterface)GuiCameraObject;
cam.init(this);
cam.show();
} catch (ClassNotFoundException cnfe) {
logger.exception(Locale.get("trace.YourPhoneNoCamSupport")/*Your phone does not support the necessary JSRs to use the camera*/, cnfe);
}
return;
}
if (c == CMDS[TOGGLE_AUDIO_REC]) {
if (audioRec.isRecording()) {
audioRec.stopRecord();
} else {
audioRec.startRecorder();
}
recordingsMenu = null; // Refresh recordings menu
return;
}
//#endif
if (c == CMDS[ROUTING_TOGGLE_CMD]) {
if (routeCalc || route != null) {
commandAction(ROUTING_STOP_CMD);
} else {
commandAction(ROUTING_START_WITH_MODE_SELECT_CMD);
}
return;
}
if (c == CMDS[ROUTING_START_WITH_MODE_SELECT_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
GuiRoute guiRoute = new GuiRoute(this, false);
if (Configuration.getCfgBitSavedState(Configuration.CFGBIT_DONT_ASK_FOR_ROUTING_OPTIONS)) {
commandAction(ROUTING_START_CMD);
} else {
guiRoute.show();
}
return;
}
if (c == CMDS[ROUTING_START_CMD]) {
if (! routeCalc || RouteLineProducer.isRunning()) {
routeCalc = true;
if (Configuration.getContinueMapWhileRouteing() != Configuration.continueMap_Always ) {
stopImageCollector();
}
RouteInstructions.resetOffRoute(route, center);
// center of the map is the route source
RoutePositionMark routeSource = new RoutePositionMark(center.radlat, center.radlon);
logger.info("Routing source: " + routeSource);
routeNodes=new Vector();
routeEngine = new Routing(this);
routeEngine.solve(routeSource, dest);
// resume();
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ROUTING_STOP_CMD]) {
NoiseMaker.stopPlayer();
if (routeCalc) {
if (routeEngine != null) {
routeEngine.cancelRouting();
}
alert(Locale.get("trace.RouteCalculation")/*Route Calculation*/, Locale.get("trace.Cancelled")/*Cancelled*/, 1500);
} else {
alert(Locale.get("trace.Routing")/*Routing*/, Locale.get("generic.Off")/*Off*/, 750);
}
endRouting();
routingsMenu = null; // refresh routingsMenu
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
routingsMenu = null; // refresh routingsMenu
return;
}
if (c == CMDS[ZOOM_IN_CMD]) {
scale = scale / 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[ZOOM_OUT_CMD]) {
scale = scale * 1.5f;
autoZoomed = false;
return;
}
if (c == CMDS[MANUAL_ROTATION_MODE_CMD]) {
manualRotationMode = !manualRotationMode;
if (manualRotationMode) {
if (hasPointerEvents()) {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourse")/*Change course with zoom buttons*/, 3000);
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("trace.ChangeCourseWithLeftRightKeys")/*Change course with left/right keys*/, 3000);
}
} else {
alert(Locale.get("trace.ManualRotation")/*Manual Rotation*/, Locale.get("generic.Off")/*Off*/, 750);
}
return;
}
if (c == CMDS[TOGGLE_OVERLAY_CMD]) {
showAddons++;
repaint();
return;
}
if (c == CMDS[TOGGLE_BACKLIGHT_CMD]) {
// toggle Backlight
Configuration.setCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON,
!(Configuration.getCfgBitState(Configuration.CFGBIT_BACKLIGHT_ON)),
false);
lastBackLightOnTime = System.currentTimeMillis();
parent.showBackLightLevel();
return;
}
if (c == CMDS[TOGGLE_FULLSCREEN_CMD]) {
boolean fullScreen = !Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN);
Configuration.setCfgBitState(Configuration.CFGBIT_FULLSCREEN, fullScreen, false);
setFullScreenMode(fullScreen);
return;
}
if (c == CMDS[TOGGLE_MAP_PROJ_CMD]) {
if (manualRotationMode) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
compassDeviation = 0;
} else {
course = 0;
}
alert(Locale.get("trace.ManualRotation"), Locale.get("trace.ManualToNorth"), 750);
} else {
// FIXME rename string to generic
alert(Locale.get("guidiscover.MapProjection")/*Map Projection*/, ProjFactory.nextProj(), 750);
}
// redraw immediately
synchronized (this) {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
return;
}
if (c == CMDS[TOGGLE_KEY_LOCK_CMD]) {
keyboardLocked = !keyboardLocked;
if (keyboardLocked) {
// show alert that keys are locked
keyPressed(0);
} else {
alert(Locale.get("trace.GpsMid")/*GpsMid*/, hasPointerEvents() ? Locale.get("trace.KeysAndTouchscreenUnlocked")/*Keys and touch screen unlocked*/ : Locale.get("trace.KeysUnlocked")/*Keys unlocked*/, 1000);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_CMD]) {
if ( gpx.isRecordingTrk() ) {
commandAction(STOP_RECORD_CMD);
} else {
commandAction(START_RECORD_CMD);
}
return;
}
if (c == CMDS[TOGGLE_RECORDING_SUSP_CMD]) {
if (gpx.isRecordingTrk()) {
if ( gpx.isRecordingTrkSuspended() ) {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.ResumingRecording")/*Resuming recording*/, 1000);
gpx.resumeTrk();
} else {
alert(Locale.get("trace.GpsRecording")/*Gps track recording*/, Locale.get("trace.SuspendingRecording")/*Suspending recording*/, 1000);
gpx.suspendTrk();
}
}
recordingsMenu = null; // Refresh recordings menu
return;
}
if (c == CMDS[RECENTER_GPS_CMD]) {
gpsRecenter = true;
gpsRecenterInvalid = true;
gpsRecenterStale = true;
autoZoomed = true;
if (pos.latitude != 0.0f) {
receivePosition(pos);
}
newDataReady();
return;
}
if (c == CMDS[SHOW_DEST_CMD]) {
if (dest != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
prevPositionNode = center.copy();
center.setLatLonRad(dest.lat, dest.lon);
movedAwayFromDest = false;
updatePosition();
}
else {
alert(Locale.get("trace.ShowDestination")/*Show destination*/, Locale.get("trace.DestinationNotSpecifiedYet")/*Destination is not specified yet*/, 3000);
}
return;
}
if (c == CMDS[SHOW_PREVIOUS_POSITION_CMD]) {
if (prevPositionNode != null) {
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLon(prevPositionNode);
updatePosition();
}
}
if (c == CMDS[DATASCREEN_CMD]) {
showNextDataScreen(DATASCREEN_NONE);
return;
}
if (c == CMDS[ICON_MENU] && Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS)) {
showIconMenu();
return;
}
if (c == CMDS[SETUP_CMD]) {
new GuiDiscover(parent);
return;
}
if (c == CMDS[ABOUT_CMD]) {
new Splash(parent, GpsMid.initDone);
return;
}
if (c == CMDS[CELLID_LOCATION_CMD]) {
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL && locationProducer != null) {
locationProducer.triggerPositionUpdate();
newDataReady();
} else {
if (cellIDLocationProducer == null) {
// init sleeping cellid location provider if cellid is not primary
cellIDLocationProducer = new SECellId();
if (cellIDLocationProducer != null && !cellIDLocationProducer.init(this)) {
logger.info("Failed to initialise CellID location producer");
}
}
if (cellIDLocationProducer != null) {
cellIDLocationProducer.triggerPositionUpdate();
newDataReady();
}
}
return;
}
if (c == CMDS[MANUAL_LOCATION_CMD]) {
Position setpos = new Position(center.radlat / MoreMath.FAC_DECTORAD,
center.radlon / MoreMath.FAC_DECTORAD,
PositionMark.INVALID_ELEVATION, 0.0f, 0.0f, 1,
System.currentTimeMillis(), Position.TYPE_MANUAL);
// implies center to gps, to give feedback as the gps rectangle
gpsRecenter = true;
// gpsRecenterInvalid = true;
// gpsRecenterStale = true;
autoZoomed = true;
receivePosition(setpos);
receiveStatus(LocationMsgReceiver.STATUS_MANUAL, 0);
newDataReady();
return;
}
if (! routeCalc) {
//#if polish.api.osm-editing
if (c == CMDS[RETRIEVE_XML]) {
if (Legend.enableEdits) {
// -1 alert ("Editing", "Urlidx: " + pc.actualWay.urlIdx, Alert.FOREVER);
if ((pc.actualWay != null) && (getUrl(pc.actualWay.urlIdx) != null)) {
parent.alert ("Url", "Url: " + getUrl(pc.actualWay.urlIdx), Alert.FOREVER);
}
if ((pc.actualWay != null) && (pc.actualWay instanceof EditableWay)) {
EditableWay eway = (EditableWay)pc.actualWay;
GuiOsmWayDisplay guiWay = new GuiOsmWayDisplay(eway, pc.actualSingleTile, this);
guiWay.show();
guiWay.refresh();
}
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[EDIT_ENTITY]) {
if (Legend.enableEdits) {
// FIXME: do the following:
// * set a flag that default operation is OSM edit
// * do a search for nearby POIs, asking for type
// * when the user selects, open OSM editing
GuiSearch guiSearch = new GuiSearch(this, GuiSearch.ACTION_EDIT_ENTITY);
guiSearch.show();
return;
} else {
parent.alert("Editing", "Editing support was not enabled in Osm2GpsMid", Alert.FOREVER);
}
}
if (c == CMDS[RETRIEVE_NODE]) {
// FIXME add support for accessing a node
// under cursor
if (Legend.enableEdits) {
GuiOsmPoiDisplay guiNode = new GuiOsmPoiDisplay(-1, null,
center.radlat, center.radlon, this);
guiNode.show();
guiNode.refresh();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
if (c == CMDS[EDIT_ADDR_CMD]) {
if (Legend.enableEdits) {
String streetName = "";
if ((pc != null) && (pc.actualWay != null)) {
streetName = getName(pc.actualWay.nameIdx);
}
GuiOsmAddrDisplay guiAddr = new GuiOsmAddrDisplay(-1, streetName, null,
center.radlat, center.radlon, this);
guiAddr.show();
} else {
logger.error(Locale.get("trace.EditingIsNotEnabled")/*Editing is not enabled in this map*/);
}
}
//#else
if (c == CMDS[RETRIEVE_XML] || c == CMDS[RETRIEVE_NODE] || c == CMDS[EDIT_ADDR_CMD]) {
alert("No online capabilites",
Locale.get("trace.SetAppGeneric")/*Set app=GpsMid-Generic-editing and enableEditing=true in*/ +
Locale.get("trace.PropertiesFile")/*.properties file and recreate GpsMid with Osm2GpsMid.*/,
Alert.FOREVER);
}
//#endif
if (c == CMDS[SET_DEST_CMD]) {
RoutePositionMark pm1 = new RoutePositionMark(center.radlat, center.radlon);
setDestination(pm1);
return;
}
if (c == CMDS[CLEAR_DEST_CMD]) {
setDestination(null);
return;
}
} else {
alert(Locale.get("trace.Error")/*Error*/, Locale.get("trace.CurrentlyInRouteCalculation")/*Currently in route calculation*/, 2000);
}
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceCommandAction")/*In Trace.commandAction*/, e);
}
}
private void startImageCollector() throws Exception {
//#debug info
logger.info("Starting ImageCollector");
Images images = new Images();
pc = new PaintContext(this, images);
/* move responsibility for overscan to ImageCollector
int w = (this.getWidth() * 125) / 100;
int h = (this.getHeight() * 125) / 100;
*/
imageCollector = new ImageCollector(tiles, this.getWidth(), this.getHeight(), this, images);
// projection = ProjFactory.getInstance(center,course, scale, getWidth(), getHeight());
// pc.setP(projection);
pc.center = center.copy();
pc.scale = scale;
pc.xSize = this.getWidth();
pc.ySize = this.getHeight();
}
private void stopImageCollector(){
//#debug info
logger.info("Stopping ImageCollector");
cleanup();
if (imageCollector != null ) {
imageCollector.stop();
imageCollector=null;
}
System.gc();
}
public void startup() throws Exception {
// logger.info("reading Data ...");
namesThread = new Names();
urlsThread = new Urls();
new DictReader(this);
// wait until base tiles are read; otherwise there's apparently
// a race condition triggered on Symbian s60r3 phones, see
// https://sourceforge.net/support/tracker.php?aid=3284022
if (Legend.isValid) {
while (!baseTilesRead) {
try {
Thread.sleep(250);
} catch (InterruptedException e1) {
// nothing to do in that case
}
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTO_START_GPS)) {
Thread thread = new Thread(this, "Trace");
thread.start();
}
// logger.info("Create queueDataReader");
tileReader = new QueueDataReader(this);
// logger.info("create imageCollector");
dictReader = new QueueDictReader(this);
this.gpx = new Gpx();
this.audioRec = new AudioRecorder();
setDict(gpx, (byte)5);
startImageCollector();
recreateTraceLayout();
}
public void shutdown() {
if (gpx != null) {
// change to "false" to ask for track name if configure to
// currently "true" to not ask for name to ensure fast
// quit & try to avoid loss of data which might result from
// waiting for user to type the name
gpx.saveTrk(true);
}
//#debug debug
logger.debug("Shutdown: stopImageCollector");
stopImageCollector();
if (namesThread != null) {
//#debug debug
logger.debug("Shutdown: namesThread");
namesThread.stop();
namesThread = null;
}
if (urlsThread != null) {
urlsThread.stop();
urlsThread = null;
}
if (dictReader != null) {
//#debug debug
logger.debug("Shutdown: dictReader");
dictReader.shutdown();
dictReader = null;
}
if (tileReader != null) {
//#debug debug
logger.debug("Shutdown: tileReader");
tileReader.shutdown();
tileReader = null;
}
if (locationProducer != null) {
//#debug debug
logger.debug("Shutdown: locationProducer");
locationProducer.close();
}
if (TrackPlayer.isPlaying) {
//#debug debug
logger.debug("Shutdown: TrackPlayer");
TrackPlayer.getInstance().stop();
}
}
public void sizeChanged(int w, int h) {
updateLastUserActionTime();
if (imageCollector != null) {
logger.info("Size of Canvas changed to " + w + "|" + h);
stopImageCollector();
try {
startImageCollector();
imageCollector.resume();
imageCollector.newDataReady();
} catch (Exception e) {
logger.exception(Locale.get("trace.CouldNotReinitialiseImageCollector")/*Could not reinitialise Image Collector after size change*/, e);
}
/**
* Recalculate the projection, as it may depends on the size of the screen
*/
updatePosition();
}
tl = new TraceLayout(0, 0, w, h);
}
protected void paint(Graphics g) {
//#debug debug
logger.debug("Drawing Map screen");
try {
int yc = 1;
int la = 18;
getPC();
// cleans the screen
g.setColor(Legend.COLORS[Legend.COLOR_MAP_BACKGROUND]);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
pc.g = g;
if (imageCollector != null) {
/*
* When painting we receive a copy of the center coordinates
* where the imageCollector has drawn last
* as we need to base the routing instructions on the information
* determined during the way drawing (e.g. the current routePathConnection)
*/
Node drawnCenter = imageCollector.paint(pc);
if (route != null && ri != null && pc.lineP2 != null && pc.getP() != null/*avoids exception at route calc*/) {
pc.getP().forward(drawnCenter.radlat, drawnCenter.radlon, pc.lineP2);
/*
* we also need to make sure the current way for the real position
* has really been detected by the imageCollector which happens when drawing the ways
* So we check if we just painted an image that did not cover
* the center of the display because it was too far painted off from
* the display center position and in this case we don't give route instructions
* Thus e.g. after leaving a long tunnel without gps fix there will not be given an
* obsolete instruction from inside the tunnel
*/
int maxAllowedMapMoveOffs = Math.min(pc.xSize/2, pc.ySize/2);
if ( Math.abs(pc.lineP2.x - pc.getP().getImageCenter().x) < maxAllowedMapMoveOffs
&&
Math.abs(pc.lineP2.y - pc.getP().getImageCenter().y) < maxAllowedMapMoveOffs
) {
/*
* we need to synchronize the route instructions on the informations determined during way painting
* so we give the route instructions right after drawing the image with the map
* and use the center of the last drawn image for the route instructions
*/
ri.showRoute(pc, drawnCenter,imageCollector.xScreenOverscan,imageCollector.yScreenOverscan);
}
}
} else {
// show the way bar even if ImageCollector is not running because it's necessary on touch screens to get to the icon menu
tl.ele[TraceLayout.WAYNAME].setText(" ");
}
/* Beginning of voice instructions started from overlay code (besides showRoute above)
*/
// Determine if we are at the destination
if (dest != null) {
float distance = ProjMath.getDistance(dest.lat, dest.lon, center.radlat, center.radlon);
atDest = (distance < 25);
if (atDest) {
if (movedAwayFromDest && Configuration.getCfgBitState(Configuration.CFGBIT_SND_DESTREACHED)) {
GpsMid.mNoiseMaker.playSound(RouteSyntax.getInstance().getDestReachedSound(), (byte) 7, (byte) 1);
}
} else if (!movedAwayFromDest) {
movedAwayFromDest = true;
}
}
// determine if we are currently speeding
speeding = false;
int maxSpeed = 0;
// only detect speeding when gpsRecentered and there is a current way
if (gpsRecenter && actualSpeedLimitWay != null) {
maxSpeed = actualSpeedLimitWay.getMaxSpeed();
// check for winter speed limit if configured
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAXSPEED_WINTER)
&& (actualSpeedLimitWay.getMaxSpeedWinter() > 0)) {
maxSpeed = actualSpeedLimitWay.getMaxSpeedWinter();
}
if (maxSpeed != 0 && speed > (maxSpeed + Configuration.getSpeedTolerance()) ) {
speeding = true;
}
}
if (speeding && Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_SND)) {
// give speeding alert only every 10 seconds
if ( (System.currentTimeMillis() - lastTimeOfSpeedingSound) > 10000 ) {
lastTimeOfSpeedingSound = System.currentTimeMillis();
GpsMid.mNoiseMaker.immediateSound(RouteSyntax.getInstance().getSpeedLimitSound());
}
}
/*
* end of voice instructions started from overlay code
*/
/*
* the final part of the overlay should not give any voice instructions
*/
g.setColor(Legend.COLOR_MAP_TEXT);
switch (showAddons) {
case 1:
yc = showMemory(g, yc, la);
break;
case 2:
yc = showConnectStatistics(g, yc, la);
break;
default:
showAddons = 0;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SCALE_BAR)) {
if (pc != null) {
tl.calcScaleBarWidth(pc);
tl.ele[TraceLayout.SCALEBAR].setText(" ");
}
}
setPointOfTheCompass();
}
showMovement(g);
// Show gpx track recording status
LayoutElement eSolution = tl.ele[TraceLayout.SOLUTION];
LayoutElement eRecorded = tl.ele[TraceLayout.RECORDED_COUNT];
if (gpx.isRecordingTrk()) {
// we are recording tracklogs
if (gpx.isRecordingTrkSuspended()) {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_SUSPENDED_TEXT]); // blue
} else {
eRecorded.setColor(Legend.COLORS[Legend.COLOR_RECORDING_ON_TEXT]); // red
}
eRecorded.setText(gpx.getTrkPointCount() + Locale.get("trace.r")/*r*/);
}
if (TrackPlayer.isPlaying) {
eSolution.setText(Locale.get("trace.Replay")/*Replay*/);
} else {
if (locationProducer == null && !(solution == LocationMsgReceiver.STATUS_CELLID ||
solution == LocationMsgReceiver.STATUS_MANUAL)) {
eSolution.setText(Locale.get("solution.Off")/*Off*/);
} else {
eSolution.setText(solutionStr);
}
}
LayoutElement e = tl.ele[TraceLayout.CELLID];
// show if we are logging cellIDs
if (SECellLocLogger.isCellIDLogging() > 0) {
if (SECellLocLogger.isCellIDLogging() == 2) {
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_TEXT]); // yellow
} else {
//Attempting to log, but currently no valid info available
e.setColor(Legend.COLORS[Legend.COLOR_CELLID_LOG_ON_ATTEMPTING_TEXT]); // red
}
e.setText(Locale.get("trace.cellIDs")/*cellIDs*/);
}
// show audio recording status
e = tl.ele[TraceLayout.AUDIOREC];
if (audioRec.isRecording()) {
e.setColor(Legend.COLORS[Legend.COLOR_AUDIOREC_TEXT]); // red
e.setText(Locale.get("trace.AudioRec")/*AudioRec*/);
}
if (pc != null) {
showDestination(pc);
}
if (speed > 0 &&
Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_SPEED_IN_MAP)) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString(speed) + Locale.get("guitacho.kmh")/* km/h*/);
} else {
tl.ele[TraceLayout.SPEED_CURRENT].setText(" " + Integer.toString((int)(speed / 1.609344f)) + Locale.get("guitacho.mph"));
}
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_ALTITUDE_IN_MAP)
&& locationProducer != null
&& LocationMsgReceiverList.isPosValid(solution)
) {
tl.ele[TraceLayout.ALTITUDE].setText(showDistance(altitude, DISTANCE_ALTITUDE));
}
if (dest != null && (route == null || (!RouteLineProducer.isRouteLineProduced() && !RouteLineProducer.isRunning()) )
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_AIR_DISTANCE_IN_MAP)) {
e = Trace.tl.ele[TraceLayout.ROUTE_DISTANCE];
e.setBackgroundColor(Legend.COLORS[Legend.COLOR_RI_DISTANCE_BACKGROUND]);
double distLine = ProjMath.getDistance(center.radlat, center.radlon, dest.lat, dest.lon);
e.setText(Locale.get("trace.Air")/*Air:*/ + showDistance((int) distLine, DISTANCE_AIR));
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_CLOCK_IN_MAP)) {
e = tl.ele[TraceLayout.CURRENT_TIME]; // e is used *twice* below (also as vRelative)
e.setText(DateTimeTools.getClock(System.currentTimeMillis(), true));
/*
don't use new Date() - it is very slow on some Nokia devices
currentTime.setTime( new Date( System.currentTimeMillis() ) );
e.setText(
currentTime.get(Calendar.HOUR_OF_DAY) + ":"
+ HelperRoutines.formatInt2(currentTime.get(Calendar.MINUTE)));
*/
// if current time is visible, positioning OFFROUTE above current time will work
tl.ele[TraceLayout.ROUTE_OFFROUTE].setVRelative(e);
}
setSpeedingSign(maxSpeed);
if (hasPointerEvents()) {
tl.ele[TraceLayout.ZOOM_IN].setText("+");
tl.ele[TraceLayout.ZOOM_OUT].setText("-");
tl.ele[TraceLayout.RECENTER_GPS].setText("|");
e = tl.ele[TraceLayout.SHOW_DEST];
if (atDest && prevPositionNode != null) {
e.setText("<");
e.setActionID(SHOW_PREVIOUS_POSITION_CMD);
} else {
e.setText(">");
e.setActionID(SHOW_DEST_CMD + (Trace.SET_DEST_CMD << 16) );
}
tl.ele[TraceLayout.RECORDINGS].setText("*");
tl.ele[TraceLayout.SEARCH].setText("_");
}
e = tl.ele[TraceLayout.TITLEBAR];
if (currentTitleMsgOpenCount != 0) {
e.setText(currentTitleMsg);
// setTitleMsgTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setTitleMsgTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentTitleMsgOpenCount--;
lastTitleMsg = currentTitleMsg;
if (currentTitleMsgOpenCount == 0) {
//#debug debug
logger.debug("clearing title");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setTitleMsgTimeout);
setTitleMsgTimeout = 0;
}
}
}
tl.paint(g);
if (currentAlertsOpenCount > 0) {
showCurrentAlert(g);
}
} catch (Exception e) {
logger.silentexception("Unhandled exception in the paint code", e);
}
}
public void showGuiWaypointSave(PositionMark posMark) {
if (guiWaypointSave == null) {
guiWaypointSave = new GuiWaypointSave(this);
}
if (guiWaypointSave != null) {
guiWaypointSave.setData(posMark);
guiWaypointSave.show();
}
}
/** Show an alert telling the user that waypoints are not ready yet.
*/
private void showAlertLoadingWpt() {
alert("Way points", "Way points are not ready yet.", 3000);
}
private void showCurrentAlert(Graphics g) {
Font font = g.getFont();
// request same font in bold for title
Font titleFont = Font.getFont(font.getFace(), Font.STYLE_BOLD, font.getSize());
int fontHeight = font.getHeight();
// add alert title height plus extra space of one line for calculation of alertHeight
int y = titleFont.getHeight() + 2 + fontHeight;
// extra width for alert
int extraWidth = font.charWidth('W');
// alert is at least as wide as alert title
int alertWidth = titleFont.stringWidth(currentAlertTitle);
// width each alert message line must fit in
int maxWidth = getWidth() - extraWidth;
// Two passes: 1st pass calculates placement and necessary size of alert,
// 2nd pass actually does the drawing
for (int i = 0; i <= 1; i++) {
int nextSpaceAt = 0;
int prevSpaceAt = 0;
int start = 0;
// word wrap
do {
int width = 0;
// add word by word until string part is too wide for screen
while (width < maxWidth && nextSpaceAt <= currentAlertMessage.length() ) {
prevSpaceAt = nextSpaceAt;
nextSpaceAt = currentAlertMessage.indexOf(' ', nextSpaceAt);
if (nextSpaceAt == -1) {
nextSpaceAt = currentAlertMessage.length();
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
nextSpaceAt++;
}
nextSpaceAt--;
// Reduce line word by word or if not possible char by char until the
// remaining string part fits to display width
while (width > maxWidth) {
if (prevSpaceAt > start && nextSpaceAt > prevSpaceAt) {
nextSpaceAt = prevSpaceAt;
} else {
nextSpaceAt--;
}
width = font.substringWidth(currentAlertMessage, start, nextSpaceAt - start);
}
// determine maximum alert width
if (alertWidth < width ) {
alertWidth = width;
}
// during the second pass draw the message text lines
if (i==1) {
g.drawSubstring(currentAlertMessage, start, nextSpaceAt - start,
getWidth()/2, y, Graphics.TOP|Graphics.HCENTER);
}
y += fontHeight;
start = nextSpaceAt;
} while (nextSpaceAt < currentAlertMessage.length() );
// at the end of the first pass draw the alert box and the alert title
if (i == 0) {
alertWidth += extraWidth;
int alertHeight = y;
int alertTop = (getHeight() - alertHeight) /2;
//alertHeight += fontHeight/2;
int alertLeft = (getWidth() - alertWidth) / 2;
// alert background color
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, alertHeight);
// background color for alert title
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TITLE_BACKGROUND]);
g.fillRect(alertLeft, alertTop, alertWidth, fontHeight + 3);
// alert border
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_BORDER]);
g.setStrokeStyle(Graphics.SOLID);
g.drawRect(alertLeft, alertTop, alertWidth, fontHeight + 3); // title border
g.drawRect(alertLeft, alertTop, alertWidth, alertHeight); // alert border
// draw alert title
y = alertTop + 2; // output position of alert title
g.setFont(titleFont);
g.setColor(Legend.COLORS[Legend.COLOR_ALERT_TEXT]);
g.drawString(currentAlertTitle, getWidth()/2, y , Graphics.TOP|Graphics.HCENTER);
g.setFont(font);
// output alert message 1.5 lines below alert title in the next pass
y += (fontHeight * 3 / 2);
}
} // end for
// setAlertTimeOut can be changed in receiveMessage()
synchronized (this) {
if (setAlertTimeout != 0) {
TimerTask timerT = new TimerTask() {
public synchronized void run() {
currentAlertsOpenCount--;
if (currentAlertsOpenCount == 0) {
//#debug debug
logger.debug("clearing alert");
repaint();
}
}
};
GpsMid.getTimer().schedule(timerT, setAlertTimeout);
setAlertTimeout = 0;
}
}
}
private void setSpeedingSign(int maxSpeed) {
// speeding = true;
if (Configuration.getCfgBitState(Configuration.CFGBIT_SPEEDALERT_VISUAL)
&&
(
speeding
||
(System.currentTimeMillis() - startTimeOfSpeedingSign) < 3000
)
) {
if (speeding) {
speedingSpeedLimit = maxSpeed;
startTimeOfSpeedingSign = System.currentTimeMillis();
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString(speedingSpeedLimit));
} else {
tl.ele[TraceLayout.SPEEDING_SIGN].setText(Integer.toString((int)(speedingSpeedLimit / 1.609344f + 0.5f)));
}
} else {
startTimeOfSpeedingSign = 0;
}
}
/**
*
*/
private void getPC() {
pc.course = course;
pc.scale = scale;
pc.center = center.copy();
// pc.setP( projection);
// projection.inverse(pc.xSize, 0, pc.screenRU);
// projection.inverse(0, pc.ySize, pc.screenLD);
pc.dest = dest;
}
public void cleanup() {
namesThread.cleanup();
urlsThread.cleanup();
tileReader.incUnusedCounter();
dictReader.incUnusedCounter();
}
// public void searchElement(PositionMark pm) throws Exception {
// PaintContext pc = new PaintContext(this, null);
// // take a bigger angle for lon because of positions near to the poles.
// Node nld = new Node(pm.lat - 0.0001f, pm.lon - 0.0005f, true);
// Node nru = new Node(pm.lat + 0.0001f, pm.lon + 0.0005f, true);
// pc.searchLD = nld;
// pc.searchRU = nru;
// pc.dest = pm;
// pc.setP(new Proj2D(new Node(pm.lat, pm.lon, true), 5000, 100, 100));
// for (int i = 0; i < 4; i++) {
// tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD);
// }
// }
public void searchNextRoutableWay(RoutePositionMark pm) throws Exception {
PaintContext pc = new PaintContext(this, null);
// take a bigger angle for lon because of positions near to the pols.
// Node nld=new Node(pm.lat - 0.0001f,pm.lon - 0.0005f,true);
// Node nru=new Node(pm.lat + 0.0001f,pm.lon + 0.0005f,true);
// pc.searchLD=nld;
// pc.searchRU=nru;
pc.squareDstWithPenToActualRoutableWay = Float.MAX_VALUE;
pc.xSize = 100;
pc.ySize = 100;
// retry searching an expanding region at the position mark
Projection p;
do {
p = new Proj2D(new Node(pm.lat,pm.lon, true),5000,pc.xSize,pc.ySize);
pc.setP(p);
for (int i=0; i<4; i++) {
tiles[i].walk(pc, Tile.OPT_WAIT_FOR_LOAD | Tile.OPT_FIND_CURRENT);
}
// stop the search when a routable way is found
if (pc.actualRoutableWay != null) {
break;
}
// expand the region that gets searched for a routable way
pc.xSize += 100;
pc.ySize += 100;
// System.out.println(pc.xSize);
} while(MoreMath.dist(p.getMinLat(), p.getMinLon(), p.getMinLat(), p.getMaxLon()) < 500); // until we searched at least 500 m edge length
Way w = pc.actualRoutableWay;
pm.setEntity(w, pc.currentPos.nodeLat, pc.currentPos.nodeLon);
}
private void setPointOfTheCompass() {
String c = "";
if (ProjFactory.getProj() != ProjFactory.NORTH_UP
&& Configuration.getCfgBitState(Configuration.CFGBIT_SHOW_POINT_OF_COMPASS)) {
c = Configuration.getCompassDirection(course);
}
// if tl shows big onscreen buttons add spaces to compass directions consisting of only one char or not shown
if (tl.bigOnScreenButtons && c.length() <= 1) {
if (ProjFactory.getProj() == ProjFactory.NORTH_UP) {
c = "(" + Configuration.getCompassDirection(0) + ")";
} else {
c = " " + c + " ";
}
}
tl.ele[TraceLayout.POINT_OF_COMPASS].setText(c);
}
private int showConnectStatistics(Graphics g, int yc, int la) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_TEXT]);
// only try to show compass id and cell id if user has somehow switched them on
GsmCell cell = null;
if (cellIDLocationProducer != null || Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_SECELL || Configuration.getCfgBitState(Configuration.CFGBIT_CELLID_LOGGING)) {
cell = CellIdProvider.getInstance().obtainCachedCellID();
}
Compass compass = null;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION)) {
compass = CompassProvider.getInstance().obtainCachedCompass();
}
if (cell == null) {
g.drawString("No Cell ID available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Cell: MCC=" + cell.mcc + " MNC=" + cell.mnc, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("LAC=" + cell.lac, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString("cellID=" + cell.cellID, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (compass == null) {
g.drawString("No compass direction available", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
} else {
g.drawString("Compass direction: " + compass.direction, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
if (statRecord == null) {
g.drawString("No stats yet", 0, yc, Graphics.TOP
| Graphics.LEFT);
return yc+la;
}
//#mdebug info
for (byte i = 0; i < LocationMsgReceiver.SIRF_FAIL_COUNT; i++) {
g.drawString(statMsg[i] + statRecord[i], 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
}
//#enddebug
g.drawString("BtQual : " + btquality, 0, yc, Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString("Count : " + collected, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
return yc;
}
public void showDestination(PaintContext pc) {
// Avoid exception after route calculation
if ( pc.getP() == null || imageCollector == null )
return;
try {
if (dest != null) {
pc.getP().forward(dest.lat, dest.lon, pc.lineP2);
// System.out.println(dest.toString());
int x = pc.lineP2.x - imageCollector.xScreenOverscan;
int y = pc.lineP2.y - imageCollector.yScreenOverscan;
pc.g.drawImage(pc.images.IMG_DEST, x, y, CENTERPOS);
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_TEXT]);
if (dest.displayName != null) {
pc.g.drawString(dest.displayName, x, y+8,
Graphics.TOP | Graphics.HCENTER);
}
pc.g.setColor(Legend.COLORS[Legend.COLOR_DEST_LINE]);
pc.g.setStrokeStyle(Graphics.SOLID);
pc.g.drawLine( pc.getP().getImageCenter().x - imageCollector.xScreenOverscan,
pc.getP().getImageCenter().y - imageCollector.yScreenOverscan,x, y);
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
e.printStackTrace();
}
}
/**
* Draws the position square, the movement line and the center cross.
*
* @param g Graphics context for drawing
*/
public void showMovement(Graphics g) {
// Avoid exception after route calculation
if ( pc.getP() == null )
return;
IntPoint centerP = null;
try {
if (imageCollector != null) {
g.setColor(Legend.COLORS[Legend.COLOR_MAP_CURSOR]);
centerP = pc.getP().getImageCenter();
int centerX = centerP.x - imageCollector.xScreenOverscan;
int centerY = centerP.y - imageCollector.yScreenOverscan;
int posX, posY;
if (!gpsRecenter) {
IntPoint p1 = new IntPoint(0, 0);
pc.getP().forward((pos.latitude * MoreMath.FAC_DECTORAD),
(pos.longitude * MoreMath.FAC_DECTORAD), p1);
posX = p1.getX()-imageCollector.xScreenOverscan;
posY = p1.getY()-imageCollector.yScreenOverscan;
} else {
posX = centerX;
posY = centerY;
}
g.setColor(Legend.COLORS[Legend.COLOR_MAP_POSINDICATOR]);
float radc = course * MoreMath.FAC_DECTORAD;
int px = posX + (int) (Math.sin(radc) * 20);
int py = posY - (int) (Math.cos(radc) * 20);
// crosshair center cursor
if (!gpsRecenter || gpsRecenterInvalid) {
g.drawLine(centerX, centerY - 12, centerX, centerY + 12);
g.drawLine(centerX - 12, centerY, centerX + 12, centerY);
g.drawArc(centerX - 5, centerY - 5, 10, 10, 0, 360);
}
if (! gpsRecenterInvalid) {
// gps position spot
pc.g.drawImage(gpsRecenterStale ? pc.images.IMG_POS_BG_STALE : pc.images.IMG_POS_BG, posX, posY, CENTERPOS);
// gps position rectangle
g.drawRect(posX - 4, posY - 4, 8, 8);
g.drawLine(posX, posY, px, py);
}
}
} catch (Exception e) {
if (imageCollector == null) {
logger.silentexception("No ImageCollector", e);
}
if (centerP == null) {
logger.silentexception("No centerP", e);
}
e.printStackTrace();
}
}
/**
* Show next screen in the sequence of data screens
* (tacho, trip, satellites).
* @param currentScreen Data screen currently shown, use the DATASCREEN_XXX
* constants from this class. Use DATASCREEN_NONE if none of them
* is on screen i.e. the first one should be shown.
*/
public void showNextDataScreen(int currentScreen) {
switch (currentScreen)
{
case DATASCREEN_TACHO:
// Tacho is followed by Trip.
if (guiTrip == null) {
guiTrip = new GuiTrip(this);
}
if (guiTrip != null) {
guiTrip.show();
}
break;
case DATASCREEN_TRIP:
// Trip is followed by Satellites.
if (guiSatellites == null) {
guiSatellites = new GuiSatellites(this, locationProducer);
}
if (guiSatellites != null) {
guiSatellites.show();
}
break;
case DATASCREEN_SATS:
// After Satellites, go back to map.
this.show();
break;
case DATASCREEN_NONE:
default:
// Tacho is first data screen
if (guiTacho == null) {
guiTacho = new GuiTacho(this);
}
if (guiTacho != null) {
guiTacho.show();
}
break;
}
}
public int showMemory(Graphics g, int yc, int la) {
g.setColor(0);
g.drawString(Locale.get("trace.Freemem")/*Freemem: */ + runtime.freeMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Totmem")/*Totmem: */ + runtime.totalMemory(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Percent")/*Percent: */
+ (100f * runtime.freeMemory() / runtime.totalMemory()), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.ThreadsRunning")/*Threads running: */
+ Thread.activeCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.Names")/*Names: */ + namesThread.getNameCount(), 0, yc,
Graphics.TOP | Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.SingleT")/*Single T: */ + tileReader.getLivingTilesCount() + "/"
+ tileReader.getRequestQueueSize(), 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.FileT")/*File T: */ + dictReader.getLivingTilesCount() + "/"
+ dictReader.getRequestQueueSize() + " Map: " + ImageCollector.icDuration + " ms", 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString(Locale.get("trace.LastMsg")/*LastMsg: */ + lastTitleMsg, 0, yc, Graphics.TOP
| Graphics.LEFT);
yc += la;
g.drawString( Locale.get("trace.at")/*at */ + lastTitleMsgClock, 0, yc,
Graphics.TOP | Graphics.LEFT );
return (yc);
}
private void updatePosition() {
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course=course;
repaint();
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
}
public synchronized void receivePosition(float lat, float lon, float scale) {
//#debug debug
logger.debug("Now displaying: " + (lat * MoreMath.FAC_RADTODEC) + " | " +
(lon * MoreMath.FAC_RADTODEC));
//We are explicitly setting the map to this position, so we probably don't
//want it to be recentered on the GPS immediately.
gpsRecenter = false;
center.setLatLonRad(lat, lon);
this.scale = scale;
updatePosition();
}
public synchronized void receiveCompassStatus(int status) {
}
public synchronized void receiveCompass(float direction) {
//#debug debug
logger.debug("Got compass reading: " + direction);
compassDirection = (int) direction;
compassDeviated = ((int) direction + compassDeviation + 360) % 360;
// TODO: allow for user to use compass for turning the map in panning mode
// (gpsRenter test below switchable by user setting)
//if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && gpsRecenter) {
// if (!Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
// updateCourse(compassDeviated);
// }
//repaint();
//}
// course = compassDeviated;
//}
}
public static void updateLastUserActionTime() {
lastUserActionTime = System.currentTimeMillis();
}
public static long getDurationSinceLastUserActionTime() {
return System.currentTimeMillis() - lastUserActionTime;
}
public void updateCourse(int newcourse) {
coursegps = newcourse;
/* don't rotate too fast
*/
if ((newcourse - course)> 180) {
course = course + 360;
}
if ((course-newcourse)> 180) {
newcourse = newcourse + 360;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null) {
course = newcourse;
} else {
// FIXME I think this is too slow a turn at least when course is
// of good quality, turning should be faster. This probably alleviates
// the trouble caused by unreliable gps course. However,
// some kind of heuristic, averaging course or evaluating the
// quality of course and fast or instant rotation with a known good GPS fix
// should be implemented instead of assuming course is always unreliable.
// The course fluctuations are lesser in faster speeds, so if we're constantly
// (for three consecutive locations) above say 5 km/h, a reasonable approach
// could be to use direct course change in that case, and for speed below
// 5 km/h use the slow turning below.
// jkpj 2010-01-17
// on 2011-04-11: jkpj switched from 1/4 rotation back to 3/4 rotation,
// returning to what it was supposed to do before 2010-11-30.
course = course + ((newcourse - course)*3)/4 + 360;
}
while (course > 360) {
course -= 360;
}
}
public synchronized void receivePosition(Position pos) {
// FIXME signal on location gained
//#debug info
logger.info("New position: " + pos);
collected++;
if (Configuration.getAutoRecenterToGpsMilliSecs() !=0 &&
getDurationSinceLastUserActionTime() > Configuration.getAutoRecenterToGpsMilliSecs()
&& isShown()
) {
gpsRecenter = true;
//autoZoomed = true;
}
if (Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179) {
if (pos.type == Position.TYPE_GPS_LASTKNOWN) {
// if we have a current cell id fix from cellid location,
// don't overwrite it with a stale GPS location, but ignore the position
// FIXME perhaps compare timestamps here in case the last known gps is later
if (this.pos.type == Position.TYPE_CELLID) {
return;
}
gpsRecenterInvalid = false;
gpsRecenterStale = true;
}
}
this.pos = pos;
if (pos.type == Position.TYPE_GPS || pos.type == Position.TYPE_CELLID || pos.type == Position.TYPE_MANUAL) {
gpsRecenterInvalid = false;
gpsRecenterStale = false;
}
if (gpsRecenter) {
center.setLatLonDeg(pos.latitude, pos.longitude);
speed = (int) (pos.speed * 3.6f);
fspeed = pos.speed * 3.6f;
// auto-fallback mode where course is from GPS at high speeds and from compass
// at low speeds
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_DIRECTION) && compassProducer != null && !Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} else if (fspeed >= courseMinSpeed && pos.course != Float.NaN ) {
// Problem: resolve issue erratic course due to GPS fluctuation
// when GPS reception is poor (maybe 3..7S),
// causes unnecessary and disturbing map rotation when device is in one location
// Heuristic for solving: After being still, require
// three consecutive over-the-limit speed readings with roughly the
// same course
if (thirdPrevCourse != -1) {
// first check for normal flow of things, we've had three valid courses after movement start
updateCourse((int) pos.course);
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
} else if (prevCourse == -1) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
} // previous course was invalid,
// don't set course yet, but set the first tentatively good course
prevCourse = (int) pos.course;
} else if (secondPrevCourse == -1) {
// the previous course was the first good one.
// If this course is in the same 60-degree
// sector as the first course, we have two valid courses
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
secondPrevCourse = prevCourse;
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
} else {
// we have received two previous valid curses, check for this one
if (Math.abs(prevCourse - (int)pos.course) < 30 || Math.abs(prevCourse - (int)pos.course) > 330) {
thirdPrevCourse = secondPrevCourse;
secondPrevCourse = prevCourse;
updateCourse((int) pos.course);
} else {
secondPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
prevCourse = (int) pos.course;
} else {
// speed under the minimum. If it went under the limit now, do a heuristic
// to decide a proper course.
// invalidate all prev courses
if (thirdPrevCourse != -1) {
// speed just went under the threshold
// - if the last readings are not within the 30 degree sector of
// the previous one, restore course to the third previous course,
// it's probable that it's more reliable than the last
// course, as we see that at traffic light stops
// an incorrect course is shown relatively often
if ((Math.abs(prevCourse - secondPrevCourse) < 15 || Math.abs(prevCourse - secondPrevCourse) > 345)
&& (Math.abs(thirdPrevCourse - secondPrevCourse) < 15 || Math.abs(thirdPrevCourse - secondPrevCourse) > 345)) {
// we're OK
} else {
updateCourse(thirdPrevCourse);
}
}
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
if (Configuration.getCfgBitState(Configuration.CFGBIT_COMPASS_AND_MOVEMENT_DIRECTION)) {
updateCourse(compassDeviated);
}
}
}
if (gpx.isRecordingTrk()) {
try {
// don't tracklog manual cellid position or gps start/stop last known position
if ((Configuration.getLocationProvider() == Configuration.LOCATIONPROVIDER_JSR179
&& pos.type == Position.TYPE_CELLID) || pos.type == Position.TYPE_GPS_LASTKNOWN) {
} else {
gpx.addTrkPt(pos);
}
} catch (Exception e) {
receiveMessage(e.getMessage());
}
}
altitude = (int) (pos.altitude);
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOZOOM)
&& gpsRecenter
&& (isGpsConnected() || TrackPlayer.isPlaying)
&& autoZoomed
&& pc.getP() != null
&& pos.speed != Float.NaN // if speed is unknown do not autozoom
&& pos.speed != 0 // if speed is 0 do not autozoom
) {
// the minimumScale at 20km/h and below is equivalent to having zoomed in manually once from the startup zoom level
final float minimumScale = Configuration.getRealBaseScale() / 1.5f;
final int minimumSpeed = 20;
// the maximumScale at 160km/h and above is equivalent to having zoomed out manually once from the startup zoom level
final float maximumScale = Configuration.getRealBaseScale() * 1.5f;
final int maximumSpeed = 160;
int speedForScale = speed;
float newScale = minimumScale + (maximumScale - minimumScale) * (speedForScale - minimumSpeed) / (maximumSpeed - minimumSpeed);
// make sure the new scale is within the minimum / maximum scale values
if (newScale < minimumScale) {
newScale = minimumScale;
} else if (newScale > maximumScale) {
newScale = maximumScale;
}
// autozoom in more at the last 200 m of the route
if (route != null && RouteInstructions.getDstRouteToDestination() <= 200) {
float newScale2 = newScale;
newScale2 = newScale / (1f + (200f - RouteInstructions.getDstRouteToDestination())/ 200f);
// fixed increased zoom for the last 100 m
newScale = Math.max(newScale2, newScale / 1.5f);
}
scale = newScale;
// // calculate meters to top of screen
// float topLat = pc.getP().getMaxLat();
// float topLon = (pc.getP().getMinLon() + pc.getP().getMaxLon()) / 2f;
// float distance = MoreMath.dist(center.radlat, center.radlon, topLat, topLon );
// System.out.println("current distance to top of screen: " + distance);
//
// // avoid zooming in or out too far
// int speedForScale = course;
// if (speedForScale < 30) {
// speedForScale = 30;
// } else if (speedForScale > 160) {
// speedForScale = 160;
// }
//
// final float SECONDS_TO_PREVIEW = 45f;
// float metersToPreview = (float) speedForScale / 3.6f * SECONDS_TO_PREVIEW;
// System.out.println(metersToPreview + "meters to preview at " + speedForScale + "km/h");
//
// if (metersToPreview < 2000) {
// // calculate top position that needs to be visible to preview the metersToPreview
// topLat = center.radlat + (topLat - center.radlat) * metersToPreview / distance;
// topLon = center.radlon + (topLon - center.radlon) * metersToPreview / distance;
// System.out.println("new distance to top:" + MoreMath.dist(center.radlat, center.radlon, topLat, topLon ));
//
// /*
// * calculate scale factor, we multiply this again with 2 * 1.2 = 2.4 to take into account we calculated half the screen height
// * and 1.2f is probably the factor the PaintContext is larger than the display size
// * (new scale is calculated similiar to GuiWaypoint)
// */
// IntPoint intPoint1 = new IntPoint(0, 0);
// IntPoint intPoint2 = new IntPoint(getWidth(), getHeight());
// Node n1 = new Node(center.radlat, center.radlon, true);
// Node n2 = new Node(topLat, topLon, true);
// scale = pc.getP().getScale(n1, n2, intPoint1, intPoint2) * 2.4f;
// }
}
updatePosition();
}
public synchronized Position getCurrentPosition() {
return this.pos;
}
public synchronized void receiveMessage(String s) {
// #debug info
logger.info("Setting title: " + s);
currentTitleMsg = s;
synchronized (this) {
/*
* only increase the number of current title messages
* if the timer already has been set in the display code
*/
if (setTitleMsgTimeout == 0) {
currentTitleMsgOpenCount++;
}
setTitleMsgTimeout = 3000;
}
lastTitleMsgClock = DateTimeTools.getClock(System.currentTimeMillis(), false);
repaint();
}
public void receiveSatellites(Satellite[] sats) {
// Not interested
}
/** Shows an alert message
*
* @param title The title of the alert
* @param message The message text
* @param timeout Timeout in ms. Please reserve enough time so the user can
* actually read the message. Use Alert.FOREVER if you want no timeout.
*/
public synchronized void alert(String title, String message, int timeout) {
// #debug info
logger.info("Showing trace alert: " + title + ": " + message);
if (timeout == Alert.FOREVER) {
timeout = 10000;
}
currentAlertTitle = title;
currentAlertMessage = message;
synchronized (this) {
/*
* only increase the number of current open alerts
* if the timer already has been set in the display code
*/
if (setAlertTimeout == 0) {
currentAlertsOpenCount++;
}
setAlertTimeout = timeout;
}
repaint();
}
public MIDlet getParent() {
return parent;
}
protected void pointerPressed(int x, int y) {
updateLastUserActionTime();
long currTime = System.currentTimeMillis();
pointerDragged = false;
pointerDraggedMuch = false;
pointerActionDone = false;
// remember center when the pointer was pressed for dragging
centerPointerPressedN = center.copy();
if (imageCollector != null) {
panProjection=imageCollector.getCurrentProjection();
pickPointStart=panProjection.inverse(x,y, pickPointStart);
} else {
panProjection = null;
}
// remember the LayoutElement the pointer is pressed down at, this will also highlight it on the display
int touchedElementId = tl.getElementIdAtPointer(x, y);
if (touchedElementId >= 0 && (!keyboardLocked || tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU)
&&
tl.isAnyActionIdAtPointer(x, y)
) {
tl.setTouchedElement((LayoutElement) tl.elementAt(touchedElementId));
repaint();
}
// check for double press
if (!keyboardLocked && currTime - pressedPointerTime < DOUBLETAP_MAXDELAY) {
doubleTap(x, y);
return;
}
// Remember the time and position the pointer was pressed after the check for double tap,
// so the double tap code will check for the position of the first of the two taps
pressedPointerTime = currTime;
Trace.touchX = x;
Trace.touchY = y;
// Give a message if keyboard/user interface is locked.
// This must be done after remembering the touchX/Y positions as they are needed to unlock
if (keyboardLocked) {
keyPressed(0);
return;
}
// // when these statements are reached, no double tap action has been executed,
// // so check here if there's currently already a TimerTask waiting for a single tap.
// // If yes, perform the current single tap action immediately before starting the next TimerTask
// if (checkingForSingleTap && !pointerDraggedMuch) {
// singleTap();
// pointerActionDone = false;
// }
//
longTapTimerTask = new TimerTask() {
public void run() {
// if no action (e.g. from double tap) is already done
// and the pointer did not move or if it was pressed on a control and not moved much
if (!pointerActionDone) {
if (System.currentTimeMillis() - pressedPointerTime >= LONGTAP_DELAY){
longTap();
}
}
}
};
try {
// set timer to continue check if this is a long tap
GpsMid.getTimer().schedule(longTapTimerTask, LONGTAP_DELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoLongTapTimerTask")/*No LongTap TimerTask: */ + e.toString());
}
}
protected void pointerReleased(int x, int y) {
// releasing the pointer cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
// releasing the pointer will clear the highlighting of the touched element
if (tl.getTouchedElement() != null) {
tl.clearTouchedElement();
repaint();
}
if (!pointerActionDone && !keyboardLocked) {
touchReleaseX = x;
touchReleaseY = y;
// check for a single tap in a timer started after the maximum double tap delay
// if the timer will not be cancelled by a double tap, the timer will execute the single tap command
singleTapTimerTask = new TimerTask() {
public void run() {
if (!keyboardLocked) {
singleTap(touchReleaseX, touchReleaseY);
}
}
};
try {
// set timer to check if this is a single tap
GpsMid.getTimer().schedule(singleTapTimerTask, DOUBLETAP_MAXDELAY);
} catch (Exception e) {
logger.error(Locale.get("trace.NoSingleTapTimerTask")/*No SingleTap TimerTask: */ + e.toString());
}
if (pointerDragged) {
pointerDragged(x , y);
return;
}
}
}
protected void pointerDragged (int x, int y) {
updateLastUserActionTime();
LayoutElement e = tl.getElementAtPointer(x, y);
if (tl.getTouchedElement() != e) {
// leaving the touched element cancels the check for long tap
if (longTapTimerTask != null) {
longTapTimerTask.cancel();
}
tl.clearTouchedElement();
repaint();
}
// If the initially touched element is reached again during dragging, highlight it
if (tl.getElementAtPointer(touchX, touchY) == e && tl.isAnyActionIdAtPointer(x, y)) {
tl.setTouchedElement(e);
repaint();
}
if (pointerActionDone) {
return;
}
// check if there's been much movement, do this before the slide lock/unlock
// to avoid a single tap action when not sliding enough
if (Math.abs(x - Trace.touchX) > 8
||
Math.abs(y - Trace.touchY) > 8
) {
pointerDraggedMuch = true;
// avoid double tap triggering on fast consecutive drag actions starting at almost the same position
pressedPointerTime = 0;
}
// slide at least 1/4 display width to lock / unlock GpsMid
if (tl.getActionIdAtPointer(touchX, touchY) == Trace.ICON_MENU) {
if ( tl.getActionIdAtPointer(x, y) == Trace.ICON_MENU
&&
x - touchX > getWidth() / 4
) {
commandAction(TOGGLE_KEY_LOCK_CMD);
pointerActionDone = true;
}
return;
}
if (keyboardLocked) {
return;
}
pointerDragged = true;
// do not start map dragging on a touch control if only dragged slightly
if (!pointerDraggedMuch && tl.getElementIdAtPointer(touchX, touchY) >= 0) {
return;
}
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && imageCollector != null && panProjection != null) {
// difference between where the pointer was pressed and is currently dragged
// int diffX = Trace.touchX - x;
// int diffY = Trace.touchY - y;
//
// IntPoint centerPointerPressedP = new IntPoint();
pickPointEnd=panProjection.inverse(x,y, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
// System.out.println("diff " + diffX + "/" + diffY + " " + (pickPointEnd.radlat-pickPointStart.radlat) + "/" + (pickPointEnd.radlon-pickPointStart.radlon) );
imageCollector.newDataReady();
gpsRecenter = false;
}
}
private void singleTap(int x, int y) {
pointerActionDone = true;
// if not tapping a control, then the map area must be tapped so we set the touchable button sizes
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_SINGLE)) {
// if pointer was dragged much, do not recognize a single tap on the map
if (pointerDraggedMuch) {
return;
}
// #debug debug
logger.debug("single tap map");
if (!tl.bigOnScreenButtons) {
tl.setOnScreenButtonSize(true);
// set timer to continuously check if the last user interaction is old enough to make the buttons small again
final long BIGBUTTON_DURATION = 5000;
bigButtonTimerTask = new TimerTask() {
public void run() {
if (System.currentTimeMillis() - lastUserActionTime > BIGBUTTON_DURATION ) {
// make the on screen touch buttons small again
tl.setOnScreenButtonSize(false);
requestRedraw();
bigButtonTimerTask.cancel();
}
}
};
try {
GpsMid.getTimer().schedule(bigButtonTimerTask, BIGBUTTON_DURATION, 500);
} catch (Exception e) {
logger.error("Error scheduling bigButtonTimerTask: " + e.toString());
}
}
}
repaint();
} else if (tl.getElementIdAtPointer(x, y) == tl.getElementIdAtPointer(touchX, touchY)) {
tl.clearTouchedElement();
int actionId = tl.getActionIdAtPointer(x, y);
if (actionId > 0) {
// #debug debug
logger.debug("single tap button: " + actionId + " x: " + touchX + " y: " + touchY);
if (System.currentTimeMillis() < (lastBackLightOnTime + 2500)) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
} else if (manualRotationMode) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_LEFT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_RIGHT2_CMD;
}
} else if (TrackPlayer.isPlaying) {
if (actionId == ZOOM_IN_CMD) {
actionId = PAN_RIGHT2_CMD;
} else if (actionId == ZOOM_OUT_CMD) {
actionId = PAN_LEFT2_CMD;
}
}
commandAction(actionId);
repaint();
}
}
}
private void doubleTap(int x, int y) {
// if not double tapping a control, then the map area must be double tapped and we zoom in
if (tl.getElementIdAtPointer(touchX, touchY) < 0) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_DOUBLE)) {
// if this is a double press on the map, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
// if pointer was dragged much, do not recognize a double tap on the map
if (pointerDraggedMuch) {
return;
}
//#debug debug
logger.debug("double tap map");
pointerActionDone = true;
commandAction(ZOOM_IN_CMD);
}
repaint();
return;
} else if (tl.getTouchedElement() == tl.getElementAtPointer(x, y) ){
// double tapping a control
int actionId = tl.getActionIdDoubleAtPointer(x, y);
//#debug debug
logger.debug("double tap button: " + actionId + " x: " + x + " y: " + x);
if (actionId > 0) {
// if this is a double press on a control, cancel the timer checking for a single press
if (singleTapTimerTask != null) {
singleTapTimerTask.cancel();
}
pointerActionDone = true;
commandAction(actionId);
tl.clearTouchedElement();
repaint();
return;
} else {
singleTap(x, y);
}
}
}
private void longTap() {
// if not tapping a control, then the map area must be tapped so we do the long tap action for the map area
if (tl.getElementIdAtPointer(touchX, touchY) < 0 && panProjection != null) {
if (!pointerDraggedMuch && Configuration.getCfgBitState(Configuration.CFGBIT_MAPTAP_LONG)) {
pointerActionDone = true;
//#debug debug
logger.debug("long tap map");
//#if polish.api.online
// long tap map to open a place-related menu
// use the place of touch instead of old center as position,
// set as new center
pickPointEnd=panProjection.inverse(touchX,touchY, pickPointEnd);
center.radlat=centerPointerPressedN.radlat-(pickPointEnd.radlat-pickPointStart.radlat);
center.radlon=centerPointerPressedN.radlon-(pickPointEnd.radlon-pickPointStart.radlon);
Position oPos = new Position(center.radlat, center.radlon,
0.0f, 0.0f, 0.0f, 0, 0);
imageCollector.newDataReady();
gpsRecenter = false;
commandAction(ONLINE_INFO_CMD);
//#endif
}
return;
// long tapping a control
} else {
int actionId = tl.getActionIdLongAtPointer(touchX, touchY);
if (actionId > 0 && tl.getElementAtPointer(touchX, touchY) == tl.getTouchedElement()) {
tl.clearTouchedElement();
repaint();
pointerActionDone = true;
//#debug debug
logger.debug("long tap button: " + actionId + " x: " + touchX + " y: " + touchY);
commandAction(actionId);
}
}
}
/**
* Returns the command used to go to the data screens.
* Needed by the data screens so they can find the key codes used for this
* as they have to use them too.
* @return Command
*/
public Command getDataScreenCommand() {
return CMDS[DATASCREEN_CMD];
}
public Tile getDict(byte zl) {
return tiles[zl];
}
public void setDict(Tile dict, byte zl) {
tiles[zl] = dict;
// Tile.trace=this;
//addCommand(REFRESH_CMD);
// if (zl == 3) {
// setTitle(null);
// } else {
// setTitle("dict " + zl + "ready");
// }
if (zl == 0) {
// read saved position from Configuration
Configuration.getStartupPos(center);
if (center.radlat == 0.0f && center.radlon == 0.0f) {
// if no saved position use center of map
dict.getCenter(center);
}
// read saved destination position from Configuration
if (Configuration.getCfgBitState(Configuration.CFGBIT_SAVED_DESTPOS_VALID)) {
Node destNode = new Node();
Configuration.getDestPos(destNode);
setDestination(new RoutePositionMark(destNode.radlat, destNode.radlon));
}
if (pc != null) {
pc.center = center.copy();
pc.scale = scale;
pc.course = course;
}
}
updatePosition();
}
public void setBaseTilesRead(boolean read) {
baseTilesRead = read;
}
public void receiveStatistics(int[] statRecord, byte quality) {
this.btquality = quality;
this.statRecord = statRecord;
repaint();
}
public synchronized void locationDecoderEnd() {
//#debug info
logger.info("enter locationDecoderEnd");
if (Configuration.getCfgBitState(Configuration.CFGBIT_SND_DISCONNECT)) {
// some fault tolerance - will crash without a map
if (Legend.isValid) {
GpsMid.mNoiseMaker.playSound("DISCONNECT");
}
}
//if (gpx != null) {
// /**
// * Close and Save the gpx recording, to ensure we don't loose data
// */
// gpx.saveTrk(false);
//}
removeCommand(CMDS[DISCONNECT_GPS_CMD]);
if (locationProducer == null) {
//#debug info
logger.info("leave locationDecoderEnd no producer");
return;
}
locationProducer = null;
notify();
addCommand(CMDS[CONNECT_GPS_CMD]);
// addCommand(START_RECORD_CMD);
//#debug info
logger.info("end locationDecoderEnd");
}
public void receiveStatus(byte status, int satsReceived) {
if (status != LocationMsgReceiver.STATUS_ON
&& status != LocationMsgReceiver.STATUS_2D
&& status != LocationMsgReceiver.STATUS_3D
&& status != LocationMsgReceiver.STATUS_DGPS) {
// no fix, invalidate speed heuristic
prevCourse = -1;
secondPrevCourse = -1;
thirdPrevCourse = -1;
}
// FIXME signal a sound on location gained or lost
solution = status;
solutionStr = LocationMsgReceiverList.getCurrentStatusString(status, satsReceived);
repaint();
// to update e.g. tacho
if (locationUpdateListeners != null && !TrackPlayer.isPlaying) {
synchronized (locationUpdateListeners) {
for (int i = 0; i < locationUpdateListeners.size(); i++) {
((LocationUpdateListener)locationUpdateListeners.elementAt(i)).loctionUpdated();
}
}
}
}
public String getName(int idx) {
if (idx < 0) {
return null;
}
return namesThread.getName(idx);
}
public String getUrl(int idx) {
if (idx < 0) {
return null;
}
return urlsThread.getUrl(idx);
}
public Vector fulltextSearch (String snippet, CancelMonitorInterface cmi) {
return namesThread.fulltextSearch(snippet, cmi);
}
// this is called by ImageCollector
public void requestRedraw() {
repaint();
}
public void newDataReady() {
if (imageCollector != null) {
imageCollector.newDataReady();
}
}
public void show() {
//Display.getDisplay(parent).setCurrent(this);
Legend.freeDrawnWayAndAreaSearchImages();
GpsMid.getInstance().show(this);
setFullScreenMode(Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN));
updateLastUserActionTime();
repaint();
}
public void recreateTraceLayout() {
tl = new TraceLayout(0, 0, getWidth(), getHeight());
}
public void resetSize() {
sizeChanged(getWidth(), getHeight());
}
public void locationDecoderEnd(String msg) {
receiveMessage(msg);
locationDecoderEnd();
}
public PositionMark getDestination() {
return dest;
}
public void setDestination(RoutePositionMark dest) {
endRouting();
this.dest = dest;
pc.dest = dest;
if (dest != null) {
//#debug info
logger.info("Setting destination to " + dest.toString());
// move map only to the destination, if GUI is not optimized for routing
if (! Configuration.getCfgBitState(Configuration.CFGBIT_ICONMENUS_ROUTING_OPTIMIZED)) {
commandAction(SHOW_DEST_CMD);
}
if (Configuration.getCfgBitState(Configuration.CFGBIT_AUTOSAVE_DESTPOS)) {
Configuration.setDestPos(new Node(dest.lat, dest.lon, true));
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, true);
}
movedAwayFromDest = false;
} else {
Configuration.setCfgBitSavedState(Configuration.CFGBIT_SAVED_DESTPOS_VALID, false);
//#debug info
logger.info("Setting destination to null");
}
}
public void endRouting() {
RouteInstructions.initialRecalcDone = false;
RouteInstructions.icCountOffRouteDetected = 0;
RouteInstructions.routeInstructionsHeight = 0;
RouteInstructions.abortRouteLineProduction();
setRoute(null);
setRouteNodes(null);
}
/**
* This is the callback routine if RouteCalculation is ready
* @param route
*/
public void setRoute(Vector route) {
synchronized(this) {
this.route = route;
}
if (this.route != null) {
// reset off-route as soon as first route connection is known
RouteInstructions.resetOffRoute(this.route, center);
if (ri == null) {
ri = new RouteInstructions(this);
}
// show map during route line production
if (Configuration.getContinueMapWhileRouteing() == Configuration.continueMap_At_Route_Line_Creation) {
resumeImageCollectorAfterRouteCalc();
}
ri.newRoute(this.route);
oldRecalculationTime = System.currentTimeMillis();
}
// show map always after route calculation
resumeImageCollectorAfterRouteCalc();
routeCalc=false;
routeEngine=null;
}
private void resumeImageCollectorAfterRouteCalc() {
try {
if (imageCollector == null) {
startImageCollector();
// imageCollector thread starts up suspended,
// so we need to resume it
imageCollector.resume();
} else if (imageCollector != null) {
imageCollector.newDataReady();
}
repaint();
} catch (Exception e) {
logger.exception(Locale.get("trace.InTraceResumeImageCollector")/*In Trace.resumeImageCollector*/, e);
}
}
/**
* If we are running out of memory, try
* dropping all the caches in order to try
* and recover from out of memory errors.
* Not guaranteed to work, as it needs
* to allocate some memory for dropping
* caches.
*/
public void dropCache() {
tileReader.dropCache();
dictReader.dropCache();
System.gc();
namesThread.dropCache();
urlsThread.dropCache();
System.gc();
if (gpx != null) {
gpx.dropCache();
}
}
public QueueDataReader getDataReader() {
return tileReader;
}
public QueueDictReader getDictReader() {
return dictReader;
}
public Vector getRouteNodes() {
return routeNodes;
}
public void setRouteNodes(Vector routeNodes) {
this.routeNodes = routeNodes;
}
protected void hideNotify() {
//#debug debug
logger.debug("Hide notify has been called, screen will no longer be updated");
if (imageCollector != null) {
imageCollector.suspend();
}
}
protected void showNotify() {
//#debug debug
logger.debug("Show notify has been called, screen will be updated again");
if (imageCollector != null) {
imageCollector.resume();
imageCollector.newDataReady();
}
}
public Vector getRoute() {
return route;
}
public void actionCompleted() {
boolean reAddCommands = true;
if (reAddCommands && Configuration.getCfgBitState(Configuration.CFGBIT_FULLSCREEN)) {
addAllCommands();
}
}
public void showIconMenu() {
if (traceIconMenu == null) {
traceIconMenu = new TraceIconMenu(this, this);
}
traceIconMenu.show();
}
/** uncache the icon menu to reflect changes in the setup or save memory */
public static void uncacheIconMenu() {
//#mdebug trace
if (traceIconMenu != null) {
logger.trace("uncaching TraceIconMenu");
}
//#enddebug
traceIconMenu = null;
}
/** interface for IconMenuWithPages: recreate the icon menu from scratch and show it (introduced for reflecting size change of the Canvas) */
public void recreateAndShowIconMenu() {
uncacheIconMenu();
showIconMenu();
}
/** interface for received actions from the IconMenu GUI */
public void performIconAction(int actionId) {
show();
updateLastUserActionTime();
// when we are low on memory or during route calculation do not cache the icon menu (including scaled images)
if (routeCalc || GpsMid.getInstance().needsFreeingMemory()) {
//#debug info
logger.info("low mem: Uncaching traceIconMenu");
uncacheIconMenu();
}
if (actionId != IconActionPerformer.BACK_ACTIONID) {
commandAction(actionId);
}
}
/** convert distance to string based on user preferences */
// The default way to show a distance is "10km" for
// distances 10km or more, "2,6km" for distances under 10, and
// "600m" for distances under 1km.
public static String showDistance(int meters) {
return showDistance(meters, DISTANCE_GENERIC);
}
public static String showDistance(int meters, int type) {
if (Configuration.getCfgBitState(Configuration.CFGBIT_METRIC)) {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.m");
}
int MajorUnit = meters / 1000;
int MinorUnit = meters % 1000;
// km.mm
//String MinorShort = (MinorUnit / 10 < 10 ? "0" : "") + (MinorUnit / 10);
// km.m
String MinorShort = Integer.toString((int)MinorUnit / 100);
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.km");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.m");
} else {
// FIXME use e.g. getDecimalSeparator() for decimal comma/point selection
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.km");
}
} else {
return Integer.toString(meters) + Locale.get("guitacho.m");
}
} else {
if (type == DISTANCE_UNKNOWN) {
return "???" + Locale.get("guitacho.yd");
}
int MajorUnit = (int)(meters / 1609.344f);
int MinorUnit = (int)(meters % 1609.344f + 0.5f);
// mi.dd
//String MinorShort = (MinorUnit / 16.09344f < 10.0f ? "0" : "") + (int)(MinorUnit / 16.09344f);
// mi.d
String MinorShort = Integer.toString((int)(MinorUnit / 160.9344f));
if (Configuration.getCfgBitState(Configuration.CFGBIT_DISTANCE_VIEW) && (type != DISTANCE_ALTITUDE)) {
//if (MajorUnit >= 10) {
// return Integer.toString(MajorUnit) + Locale.get("guitacho.mi");
//} else
if (MajorUnit == 0) {
return Integer.toString(MinorUnit) + Locale.get("guitacho.yd");
} else {
return Integer.toString(MajorUnit) + "." + MinorShort + Locale.get("guitacho.mi");
}
} else {
return Integer.toString((int)(meters / 0.9144 + 0.5f)) + Locale.get("guitacho.yd");
}
}
}
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/changedetail/AlterTopic.java b/gerrit-server/src/main/java/com/google/gerrit/server/changedetail/AlterTopic.java
index 02e2e2412..29033b35e 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/changedetail/AlterTopic.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/changedetail/AlterTopic.java
@@ -1,135 +1,135 @@
// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.changedetail;
import com.google.gerrit.common.data.ReviewResult;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.ChangeMessage;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.mail.EmailException;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.InvalidChangeOperationException;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gwtorm.server.AtomicUpdate;
import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject;
import java.util.Collections;
import java.util.concurrent.Callable;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
public class AlterTopic implements Callable<ReviewResult> {
private final ChangeControl.Factory changeControlFactory;
private final ReviewDb db;
private final IdentifiedUser currentUser;
@Argument(index = 0, required = true, multiValued = false,
usage = "change with topic to change")
private Change.Id changeId;
public void setChangeId(final Change.Id changeId) {
this.changeId = changeId;
}
@Argument(index = 1, required = true, multiValued = false, usage = "new topic")
private String newTopicName;
public void setTopic(final String topic) {
this.newTopicName = topic.trim();
}
@Option(name = "--message", aliases = {"-m"},
usage = "optional message to append to change")
private String message;
public void setMessage(final String message) {
this.message = message;
}
@Inject
AlterTopic(final ChangeControl.Factory changeControlFactory, final ReviewDb db,
final IdentifiedUser currentUser) {
this.changeControlFactory = changeControlFactory;
this.db = db;
this.currentUser = currentUser;
changeId = null;
newTopicName = null;
message = null;
}
@Override
public ReviewResult call() throws EmailException,
InvalidChangeOperationException, NoSuchChangeException, OrmException {
final ChangeControl control = changeControlFactory.validateFor(changeId);
final ReviewResult result = new ReviewResult();
result.setChangeId(changeId);
if (!control.canAddPatchSet()) {
throw new NoSuchChangeException(changeId);
}
if (!control.canEditTopicName()) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.EDIT_TOPIC_NAME_NOT_PERMITTED));
return result;
}
final Change change = db.changes().get(changeId);
- final String oldTopicName = change.getTopic();
+ final String oldTopicName = change.getTopic() != null ? change.getTopic() : "";
if (!oldTopicName.equals(newTopicName)) {
String summary;
if (oldTopicName.isEmpty()) {
summary = "Topic set to \"" + newTopicName + "\"";
} else if (newTopicName.isEmpty()) {
summary = "Topic \"" + oldTopicName + "\" removed";
} else {
summary = "Topic changed from \"" + oldTopicName //
+ "\" to \"" + newTopicName + "\"";
}
final ChangeMessage cmsg = new ChangeMessage(
new ChangeMessage.Key(changeId, ChangeUtil.messageUUID(db)),
currentUser.getAccountId(), change.currentPatchSetId());
final StringBuilder msgBuf = new StringBuilder(summary);
if (message != null && message.length() > 0) {
msgBuf.append("\n\n");
msgBuf.append(message);
}
cmsg.setMessage(msgBuf.toString());
final Change updatedChange = db.changes().atomicUpdate(changeId,
new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
change.setTopic(newTopicName);
return change;
}
});
if (updatedChange == null) {
String err = "Change is closed, submitted, or patchset is not latest";
throw new InvalidChangeOperationException(err);
}
db.changeMessages().insert(Collections.singleton(cmsg));
}
return result;
}
}
| true | true | public ReviewResult call() throws EmailException,
InvalidChangeOperationException, NoSuchChangeException, OrmException {
final ChangeControl control = changeControlFactory.validateFor(changeId);
final ReviewResult result = new ReviewResult();
result.setChangeId(changeId);
if (!control.canAddPatchSet()) {
throw new NoSuchChangeException(changeId);
}
if (!control.canEditTopicName()) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.EDIT_TOPIC_NAME_NOT_PERMITTED));
return result;
}
final Change change = db.changes().get(changeId);
final String oldTopicName = change.getTopic();
if (!oldTopicName.equals(newTopicName)) {
String summary;
if (oldTopicName.isEmpty()) {
summary = "Topic set to \"" + newTopicName + "\"";
} else if (newTopicName.isEmpty()) {
summary = "Topic \"" + oldTopicName + "\" removed";
} else {
summary = "Topic changed from \"" + oldTopicName //
+ "\" to \"" + newTopicName + "\"";
}
final ChangeMessage cmsg = new ChangeMessage(
new ChangeMessage.Key(changeId, ChangeUtil.messageUUID(db)),
currentUser.getAccountId(), change.currentPatchSetId());
final StringBuilder msgBuf = new StringBuilder(summary);
if (message != null && message.length() > 0) {
msgBuf.append("\n\n");
msgBuf.append(message);
}
cmsg.setMessage(msgBuf.toString());
final Change updatedChange = db.changes().atomicUpdate(changeId,
new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
change.setTopic(newTopicName);
return change;
}
});
if (updatedChange == null) {
String err = "Change is closed, submitted, or patchset is not latest";
throw new InvalidChangeOperationException(err);
}
db.changeMessages().insert(Collections.singleton(cmsg));
}
return result;
}
| public ReviewResult call() throws EmailException,
InvalidChangeOperationException, NoSuchChangeException, OrmException {
final ChangeControl control = changeControlFactory.validateFor(changeId);
final ReviewResult result = new ReviewResult();
result.setChangeId(changeId);
if (!control.canAddPatchSet()) {
throw new NoSuchChangeException(changeId);
}
if (!control.canEditTopicName()) {
result.addError(new ReviewResult.Error(
ReviewResult.Error.Type.EDIT_TOPIC_NAME_NOT_PERMITTED));
return result;
}
final Change change = db.changes().get(changeId);
final String oldTopicName = change.getTopic() != null ? change.getTopic() : "";
if (!oldTopicName.equals(newTopicName)) {
String summary;
if (oldTopicName.isEmpty()) {
summary = "Topic set to \"" + newTopicName + "\"";
} else if (newTopicName.isEmpty()) {
summary = "Topic \"" + oldTopicName + "\" removed";
} else {
summary = "Topic changed from \"" + oldTopicName //
+ "\" to \"" + newTopicName + "\"";
}
final ChangeMessage cmsg = new ChangeMessage(
new ChangeMessage.Key(changeId, ChangeUtil.messageUUID(db)),
currentUser.getAccountId(), change.currentPatchSetId());
final StringBuilder msgBuf = new StringBuilder(summary);
if (message != null && message.length() > 0) {
msgBuf.append("\n\n");
msgBuf.append(message);
}
cmsg.setMessage(msgBuf.toString());
final Change updatedChange = db.changes().atomicUpdate(changeId,
new AtomicUpdate<Change>() {
@Override
public Change update(Change change) {
change.setTopic(newTopicName);
return change;
}
});
if (updatedChange == null) {
String err = "Change is closed, submitted, or patchset is not latest";
throw new InvalidChangeOperationException(err);
}
db.changeMessages().insert(Collections.singleton(cmsg));
}
return result;
}
|
diff --git a/src/shoddybattleclient/UserPanel.java b/src/shoddybattleclient/UserPanel.java
index 4121024..e04dd87 100644
--- a/src/shoddybattleclient/UserPanel.java
+++ b/src/shoddybattleclient/UserPanel.java
@@ -1,391 +1,391 @@
/*
* UserPanel.java
*
* Created on May 12, 2009, 1:48:11 PM
*
* This file is a part of Shoddy Battle.
* Copyright (C) 2009 Catherine Fitzpatrick and Benjamin Gwin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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, visit the Free Software Foundation, Inc.
* online at http://gnu.org.
*/
package shoddybattleclient;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.MediaTracker;
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import shoddybattleclient.ChallengeNotifier.Challenge;
import shoddybattleclient.network.ServerLink;
import shoddybattleclient.network.ServerLink.ChallengeMediator;
import shoddybattleclient.shoddybattle.Pokemon;
import shoddybattleclient.shoddybattle.Pokemon.Gender;
import shoddybattleclient.utils.TeamFileParser;
/**
*
* @author ben
*/
public class UserPanel extends javax.swing.JPanel {
private static class SpritePanel extends JPanel {
private Image m_image;
public SpritePanel(String species, Gender g, boolean shiny, String repository) {
setBorder(BorderFactory.createEtchedBorder());
try {
m_image = GameVisualisation.getSprite(species, true,
g != Gender.GENDER_FEMALE, shiny, repository);
//m_image = m_image.getScaledInstance(32, 32, Image.SCALE_SMOOTH);
} catch (Exception e) {
m_image = null;
}
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(m_image, 0);
try {
tracker.waitForAll();
} catch (Exception e) {
}
setToolTipText(species);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(32, 32);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(m_image, 0, 0, this);
}
}
private final ServerLink m_link;
private String m_opponent;
private int m_idx;
private Pokemon[] m_team;
private boolean m_incoming = false;
private Challenge m_challenge;
/** Creates new form UserPanel */
public UserPanel(String name, ServerLink link, int index) {
initComponents();
lblName.setText(name);
m_opponent = name;
m_link = link;
m_idx = index;
panelSprites.setLayout(new GridLayout(2, 3));
for (int i = 0; i < 6; i++) {
panelSprites.add(new SpritePanel(null, null, false, null));
}
lblMessage.setText("<html>I am a polymath so don't challenge me unless you want to lose</html>");
}
public void setIncoming() {
btnChallenge.setText("Accept");
cmbRules.setEnabled(false);
cmbN.setEnabled(false);
cmbGen.setEnabled(false);
m_incoming = true;
}
public void setOptions(Challenge c) {
cmbN.setSelectedIndex(c.getN() - 1);
cmbGen.setSelectedIndex(c.getGeneration());
m_challenge = c;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblName = new javax.swing.JLabel();
lblMessage = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cmbRules = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
cmbN = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
cmbGen = new javax.swing.JComboBox();
panelSprites = new javax.swing.JPanel();
btnLoad = new javax.swing.JButton();
btnChallenge = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
setOpaque(false);
jPanel1.setOpaque(false);
lblName.setFont(new java.awt.Font("Lucida Grande", 1, 16));
lblName.setText("bearzly");
lblMessage.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel3.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel3.setText("Rankings:");
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(lblMessage, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.add(jLabel3)
.add(lblName))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(lblName)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(lblMessage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 91, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel3)
- .addContainerGap(106, Short.MAX_VALUE))
+ .addContainerGap(110, Short.MAX_VALUE))
);
jPanel2.setOpaque(false);
jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel1.setText("Rules:");
cmbRules.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Standard", "Ubers", "Custom..." }));
jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel2.setText("Pokemon per side:");
cmbN.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6" }));
cmbN.setSelectedIndex(1);
jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel4.setText("Generation:");
cmbGen.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "D/P", "Platinum", "Platinum Fake" }));
panelSprites.setBorder(javax.swing.BorderFactory.createEtchedBorder());
panelSprites.setOpaque(false);
org.jdesktop.layout.GroupLayout panelSpritesLayout = new org.jdesktop.layout.GroupLayout(panelSprites);
panelSprites.setLayout(panelSpritesLayout);
panelSpritesLayout.setHorizontalGroup(
panelSpritesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(0, 184, Short.MAX_VALUE)
+ .add(0, 199, Short.MAX_VALUE)
);
panelSpritesLayout.setVerticalGroup(
panelSpritesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 58, Short.MAX_VALUE)
);
btnLoad.setText("Load");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.setEnabled(false);
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(btnLoad, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
- .add(btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
+ .add(btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))
.add(jPanel2Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, panelSprites, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel4)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(cmbGen, 0, 105, Short.MAX_VALUE))
+ .add(cmbGen, 0, 113, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(cmbRules, 0, 143, Short.MAX_VALUE))
+ .add(cmbRules, 0, 151, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
- .add(cmbN, 0, 59, Short.MAX_VALUE)))))
+ .add(cmbN, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
.add(166, 166, 166))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbRules))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbN, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbGen))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(panelSprites, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(btnLoad)
.add(btnChallenge))
.add(78, 78, 78))
);
jTabbedPane1.addTab("Basic", jPanel2);
jPanel3.setOpaque(false);
org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(0, 237, Short.MAX_VALUE)
+ .add(0, 250, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
- .add(0, 203, Short.MAX_VALUE)
+ .add(0, 214, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Advanced", jPanel3);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 258, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 249, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void btnChallengeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChallengeActionPerformed
if (m_team == null) return;
if (m_incoming) {
m_link.resolveChallenge(m_opponent, true, m_team);
} else {
m_link.postChallenge(new ChallengeMediator() {
public Pokemon[] getTeam() {
return m_team;
}
public void informResolved(boolean accepted) {
if (accepted) {
m_link.postChallengeTeam(m_opponent, m_team);
} else {
// todo: internationalisation
JOptionPane.showMessageDialog(UserPanel.this,
m_opponent + " rejected the challenge.");
}
}
public String getOpponent() {
return m_opponent;
}
public int getGeneration() {
return cmbGen.getSelectedIndex();
}
public int getActivePartySize() {
return Integer.parseInt((String)cmbN.getSelectedItem());
}
});
}
m_link.getLobby().closeTab(m_idx);
}//GEN-LAST:event_btnChallengeActionPerformed
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
FileDialog fd = new FileDialog(m_link.getLobby(), "Choose a team to load", FileDialog.LOAD);
fd.setVisible(true);
if (fd.getFile() == null) return;
String file = fd.getDirectory() + fd.getFile();
TeamFileParser tfp = new TeamFileParser();
m_team = tfp.parseTeam(file);
if (m_team != null) {
panelSprites.removeAll();
panelSprites.repaint();
for (int i = 0; i < m_team.length; i++) {
Pokemon p = m_team[i];
//TODO: repository
SpritePanel panel = new SpritePanel(p.species, p.gender, p.shiny, null);
panelSprites.add(panel);
}
btnChallenge.setEnabled(true);
}
if (m_challenge != null) {
m_challenge.setTeam(m_team);
}
}//GEN-LAST:event_btnLoadActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnChallenge;
private javax.swing.JButton btnLoad;
private javax.swing.JComboBox cmbGen;
private javax.swing.JComboBox cmbN;
private javax.swing.JComboBox cmbRules;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JLabel lblMessage;
private javax.swing.JLabel lblName;
private javax.swing.JPanel panelSprites;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblName = new javax.swing.JLabel();
lblMessage = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cmbRules = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
cmbN = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
cmbGen = new javax.swing.JComboBox();
panelSprites = new javax.swing.JPanel();
btnLoad = new javax.swing.JButton();
btnChallenge = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
setOpaque(false);
jPanel1.setOpaque(false);
lblName.setFont(new java.awt.Font("Lucida Grande", 1, 16));
lblName.setText("bearzly");
lblMessage.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel3.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel3.setText("Rankings:");
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(lblMessage, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.add(jLabel3)
.add(lblName))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(lblName)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(lblMessage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 91, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel3)
.addContainerGap(106, Short.MAX_VALUE))
);
jPanel2.setOpaque(false);
jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel1.setText("Rules:");
cmbRules.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Standard", "Ubers", "Custom..." }));
jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel2.setText("Pokemon per side:");
cmbN.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6" }));
cmbN.setSelectedIndex(1);
jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel4.setText("Generation:");
cmbGen.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "D/P", "Platinum", "Platinum Fake" }));
panelSprites.setBorder(javax.swing.BorderFactory.createEtchedBorder());
panelSprites.setOpaque(false);
org.jdesktop.layout.GroupLayout panelSpritesLayout = new org.jdesktop.layout.GroupLayout(panelSprites);
panelSprites.setLayout(panelSpritesLayout);
panelSpritesLayout.setHorizontalGroup(
panelSpritesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 184, Short.MAX_VALUE)
);
panelSpritesLayout.setVerticalGroup(
panelSpritesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 58, Short.MAX_VALUE)
);
btnLoad.setText("Load");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.setEnabled(false);
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(btnLoad, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
.add(jPanel2Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, panelSprites, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel4)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cmbGen, 0, 105, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cmbRules, 0, 143, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cmbN, 0, 59, Short.MAX_VALUE)))))
.add(166, 166, 166))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbRules))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbN, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbGen))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(panelSprites, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(btnLoad)
.add(btnChallenge))
.add(78, 78, 78))
);
jTabbedPane1.addTab("Basic", jPanel2);
jPanel3.setOpaque(false);
org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 237, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 203, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Advanced", jPanel3);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 258, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 249, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jPanel1 = new javax.swing.JPanel();
lblName = new javax.swing.JLabel();
lblMessage = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel2 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cmbRules = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
cmbN = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
cmbGen = new javax.swing.JComboBox();
panelSprites = new javax.swing.JPanel();
btnLoad = new javax.swing.JButton();
btnChallenge = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
setOpaque(false);
jPanel1.setOpaque(false);
lblName.setFont(new java.awt.Font("Lucida Grande", 1, 16));
lblName.setText("bearzly");
lblMessage.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel3.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel3.setText("Rankings:");
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(lblMessage, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 208, Short.MAX_VALUE)
.add(jLabel3)
.add(lblName))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(lblName)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(lblMessage, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 91, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel3)
.addContainerGap(110, Short.MAX_VALUE))
);
jPanel2.setOpaque(false);
jLabel1.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel1.setText("Rules:");
cmbRules.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Standard", "Ubers", "Custom..." }));
jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel2.setText("Pokemon per side:");
cmbN.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6" }));
cmbN.setSelectedIndex(1);
jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 13));
jLabel4.setText("Generation:");
cmbGen.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "D/P", "Platinum", "Platinum Fake" }));
panelSprites.setBorder(javax.swing.BorderFactory.createEtchedBorder());
panelSprites.setOpaque(false);
org.jdesktop.layout.GroupLayout panelSpritesLayout = new org.jdesktop.layout.GroupLayout(panelSprites);
panelSprites.setLayout(panelSpritesLayout);
panelSpritesLayout.setHorizontalGroup(
panelSpritesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 199, Short.MAX_VALUE)
);
panelSpritesLayout.setVerticalGroup(
panelSpritesLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 58, Short.MAX_VALUE)
);
btnLoad.setText("Load");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
btnChallenge.setText("Challenge");
btnChallenge.setEnabled(false);
btnChallenge.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnChallengeActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(btnLoad, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 84, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(btnChallenge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))
.add(jPanel2Layout.createSequentialGroup()
.add(20, 20, 20)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, panelSprites, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel4)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cmbGen, 0, 113, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cmbRules, 0, 151, Short.MAX_VALUE))
.add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2Layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(cmbN, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 67, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
.add(166, 166, 166))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbRules))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 20, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbN, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 21, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(cmbGen))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(panelSprites, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(btnLoad)
.add(btnChallenge))
.add(78, 78, 78))
);
jTabbedPane1.addTab("Basic", jPanel2);
jPanel3.setOpaque(false);
org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 250, Short.MAX_VALUE)
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 214, Short.MAX_VALUE)
);
jTabbedPane1.addTab("Advanced", jPanel3);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 258, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jTabbedPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 249, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/java/org/apache/cassandra/locator/DatacenterShardStrategy.java b/src/java/org/apache/cassandra/locator/DatacenterShardStrategy.java
index d2c635ee..c563165e 100644
--- a/src/java/org/apache/cassandra/locator/DatacenterShardStrategy.java
+++ b/src/java/org/apache/cassandra/locator/DatacenterShardStrategy.java
@@ -1,217 +1,224 @@
package org.apache.cassandra.locator;
/*
*
* 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.FileReader;
import java.io.IOException;
import java.io.IOError;
import java.net.InetAddress;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
import com.google.common.collect.Multimap;
import org.apache.cassandra.config.ConfigurationException;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.service.*;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.utils.FBUtilities;
/**
* This Replication Strategy takes a property file that gives the intended
* replication factor in each datacenter. The sum total of the datacenter
* replication factor values should be equal to the keyspace replication
* factor.
* <p/>
* So for example, if the keyspace replication factor is 6, the
* datacenter replication factors could be 3, 2, and 1 - so 3 replicas in
* one datacenter, 2 in another, and 1 in another - totalling 6.
* <p/>
* This class also caches the Endpoints and invalidates the cache if there is a
* change in the number of tokens.
*/
public class DatacenterShardStrategy extends AbstractReplicationStrategy
{
private static final String DATACENTER_PROPERTY_FILENAME = "datacenters.properties";
private Map<String, List<Token>> dcTokens;
private AbstractRackAwareSnitch snitch;
private Map<String, Map<String, Integer>> datacenters = new HashMap<String, Map<String, Integer>>();
public DatacenterShardStrategy(TokenMetadata tokenMetadata, IEndpointSnitch snitch) throws ConfigurationException
{
super(tokenMetadata, snitch);
if ((!(snitch instanceof AbstractRackAwareSnitch)))
throw new IllegalArgumentException("DatacenterShardStrategy requires a rack-aware endpointsnitch");
this.snitch = (AbstractRackAwareSnitch)snitch;
ClassLoader loader = PropertyFileSnitch.class.getClassLoader();
URL scpurl = loader.getResource(DATACENTER_PROPERTY_FILENAME);
if (scpurl == null)
{
throw new RuntimeException("unable to locate " + DATACENTER_PROPERTY_FILENAME);
}
String dcPropertyFile = scpurl.getFile();
try
{
Properties props = new Properties();
props.load(new FileReader(dcPropertyFile));
for (Object key : props.keySet())
{
String[] keys = ((String)key).split(":");
Map<String, Integer> map = datacenters.get(keys[0]);
if (null == map)
{
map = new HashMap<String, Integer>();
}
map.put(keys[1], Integer.parseInt((String)props.get(key)));
datacenters.put(keys[0], map);
}
}
catch (IOException ioe)
{
throw new IOError(ioe);
}
loadEndpoints(tokenMetadata);
}
private synchronized void loadEndpoints(TokenMetadata metadata) throws ConfigurationException
{
String localDC = snitch.getDatacenter(DatabaseDescriptor.getListenAddress());
if (localDC == null)
throw new ConfigurationException("Invalid datacenter configuration; couldn't find local host " + FBUtilities.getLocalAddress());
dcTokens = new HashMap<String, List<Token>>();
for (Token token : metadata.sortedTokens())
{
InetAddress endPoint = metadata.getEndpoint(token);
String dataCenter = snitch.getDatacenter(endPoint);
// add tokens to dcmap.
List<Token> lst = dcTokens.get(dataCenter);
if (lst == null)
{
lst = new ArrayList<Token>();
}
lst.add(token);
dcTokens.put(dataCenter, lst);
}
for (Entry<String, List<Token>> entry : dcTokens.entrySet())
{
List<Token> valueList = entry.getValue();
Collections.sort(valueList);
dcTokens.put(entry.getKey(), valueList);
}
// TODO verify that each DC has enough endpoints for the desired RF
}
public ArrayList<InetAddress> getNaturalEndpoints(Token searchToken, TokenMetadata metadata, String table)
{
ArrayList<InetAddress> endpoints = new ArrayList<InetAddress>();
if (metadata.sortedTokens().isEmpty())
return endpoints;
for (String dc : dcTokens.keySet())
{
List<Token> tokens = dcTokens.get(dc);
Set<String> racks = new HashSet<String>();
// Add the node at the index by default
Iterator<Token> iter = TokenMetadata.ringIterator(tokens, searchToken);
InetAddress initialDCHost = metadata.getEndpoint(iter.next());
assert initialDCHost != null;
endpoints.add(initialDCHost);
racks.add(snitch.getRack(initialDCHost));
// find replicas on unique racks
int replicas = getReplicationFactor(dc, table);
- while (endpoints.size() < replicas && iter.hasNext())
+ int localEndpoints = 1;
+ while (localEndpoints < replicas && iter.hasNext())
{
Token t = iter.next();
InetAddress endpoint = metadata.getEndpoint(t);
if (!racks.contains(snitch.getRack(endpoint)))
+ {
endpoints.add(endpoint);
+ localEndpoints++;
+ }
}
- if (endpoints.size() == replicas)
+ if (localEndpoints == replicas)
continue;
// if not enough unique racks were found, re-loop and add other endpoints
iter = TokenMetadata.ringIterator(tokens, searchToken);
iter.next(); // skip the first one since we already know it's used
- while (endpoints.size() < replicas && iter.hasNext())
+ while (localEndpoints < replicas && iter.hasNext())
{
Token t = iter.next();
if (!endpoints.contains(metadata.getEndpoint(t)))
+ {
+ localEndpoints++;
endpoints.add(metadata.getEndpoint(t));
+ }
}
}
return endpoints;
}
public int getReplicationFactor(String dc, String table)
{
return datacenters.get(table).get(dc);
}
public Set<String> getDatacenters(String table)
{
return datacenters.get(table).keySet();
}
/**
* This method will generate the QRH object and returns. If the Consistency
* level is DCQUORUM then it will return a DCQRH with a map of local rep
* factor alone. If the consistency level is DCQUORUMSYNC then it will
* return a DCQRH with a map of all the DC rep factor.
*/
@Override
public AbstractWriteResponseHandler getWriteResponseHandler(Collection<InetAddress> writeEndpoints, Multimap<InetAddress, InetAddress> hintedEndpoints, ConsistencyLevel consistency_level, String table)
{
if (consistency_level == ConsistencyLevel.DCQUORUM)
{
// block for in this context will be localnodes block.
return new DatacenterWriteResponseHandler(writeEndpoints, hintedEndpoints, consistency_level, table);
}
else if (consistency_level == ConsistencyLevel.DCQUORUMSYNC)
{
return new DatacenterSyncWriteResponseHandler(writeEndpoints, hintedEndpoints, consistency_level, table);
}
return super.getWriteResponseHandler(writeEndpoints, hintedEndpoints, consistency_level, table);
}
/**
* This method will generate the WRH object and returns. If the Consistency
* level is DCQUORUM/DCQUORUMSYNC then it will return a DCQRH.
*/
@Override
public QuorumResponseHandler getQuorumResponseHandler(IResponseResolver responseResolver, ConsistencyLevel consistencyLevel, String table)
{
if (consistencyLevel.equals(ConsistencyLevel.DCQUORUM) || consistencyLevel.equals(ConsistencyLevel.DCQUORUMSYNC))
{
return new DatacenterQuorumResponseHandler(responseResolver, consistencyLevel, table);
}
return super.getQuorumResponseHandler(responseResolver, consistencyLevel, table);
}
}
| false | true | public ArrayList<InetAddress> getNaturalEndpoints(Token searchToken, TokenMetadata metadata, String table)
{
ArrayList<InetAddress> endpoints = new ArrayList<InetAddress>();
if (metadata.sortedTokens().isEmpty())
return endpoints;
for (String dc : dcTokens.keySet())
{
List<Token> tokens = dcTokens.get(dc);
Set<String> racks = new HashSet<String>();
// Add the node at the index by default
Iterator<Token> iter = TokenMetadata.ringIterator(tokens, searchToken);
InetAddress initialDCHost = metadata.getEndpoint(iter.next());
assert initialDCHost != null;
endpoints.add(initialDCHost);
racks.add(snitch.getRack(initialDCHost));
// find replicas on unique racks
int replicas = getReplicationFactor(dc, table);
while (endpoints.size() < replicas && iter.hasNext())
{
Token t = iter.next();
InetAddress endpoint = metadata.getEndpoint(t);
if (!racks.contains(snitch.getRack(endpoint)))
endpoints.add(endpoint);
}
if (endpoints.size() == replicas)
continue;
// if not enough unique racks were found, re-loop and add other endpoints
iter = TokenMetadata.ringIterator(tokens, searchToken);
iter.next(); // skip the first one since we already know it's used
while (endpoints.size() < replicas && iter.hasNext())
{
Token t = iter.next();
if (!endpoints.contains(metadata.getEndpoint(t)))
endpoints.add(metadata.getEndpoint(t));
}
}
return endpoints;
}
| public ArrayList<InetAddress> getNaturalEndpoints(Token searchToken, TokenMetadata metadata, String table)
{
ArrayList<InetAddress> endpoints = new ArrayList<InetAddress>();
if (metadata.sortedTokens().isEmpty())
return endpoints;
for (String dc : dcTokens.keySet())
{
List<Token> tokens = dcTokens.get(dc);
Set<String> racks = new HashSet<String>();
// Add the node at the index by default
Iterator<Token> iter = TokenMetadata.ringIterator(tokens, searchToken);
InetAddress initialDCHost = metadata.getEndpoint(iter.next());
assert initialDCHost != null;
endpoints.add(initialDCHost);
racks.add(snitch.getRack(initialDCHost));
// find replicas on unique racks
int replicas = getReplicationFactor(dc, table);
int localEndpoints = 1;
while (localEndpoints < replicas && iter.hasNext())
{
Token t = iter.next();
InetAddress endpoint = metadata.getEndpoint(t);
if (!racks.contains(snitch.getRack(endpoint)))
{
endpoints.add(endpoint);
localEndpoints++;
}
}
if (localEndpoints == replicas)
continue;
// if not enough unique racks were found, re-loop and add other endpoints
iter = TokenMetadata.ringIterator(tokens, searchToken);
iter.next(); // skip the first one since we already know it's used
while (localEndpoints < replicas && iter.hasNext())
{
Token t = iter.next();
if (!endpoints.contains(metadata.getEndpoint(t)))
{
localEndpoints++;
endpoints.add(metadata.getEndpoint(t));
}
}
}
return endpoints;
}
|
diff --git a/test/com/id/app/ControllerTest.java b/test/com/id/app/ControllerTest.java
index 1352f9a..9e9d6bc 100644
--- a/test/com/id/app/ControllerTest.java
+++ b/test/com/id/app/ControllerTest.java
@@ -1,514 +1,514 @@
package com.id.app;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.id.editor.Editor;
import com.id.editor.EditorList;
import com.id.editor.Minibuffer;
import com.id.editor.Point;
import com.id.editor.Register;
import com.id.editor.StackList;
import com.id.events.KeyStroke;
import com.id.file.File;
import com.id.file.ModifiedListener;
import com.id.file.Tombstone;
import com.id.fuzzy.Finder;
import com.id.fuzzy.Finder.Listener;
import com.id.fuzzy.FuzzyFinderDriver;
import com.id.git.Diff;
import com.id.git.FileDelta;
import com.id.git.InMemoryRepository;
import com.id.platform.InMemoryFileSystem;
public class ControllerTest {
private Controller controller;
private EditorList editorList;
private InMemoryFileSystem fileSystem;
private Finder fuzzyFinder;
private Listener fuzzyListener;
private InMemoryRepository repo;
private HighlightState highlightState;
private StackList stackList;
private Minibuffer minibuffer;
private CommandExecutor commandExecutor;
private ViewportTracker viewportTracker;
private FocusManager focusManager;
private MinibufferSubsystem minibufferSubsystem;
private Register register;
private EditorFactory editorFactory;
private EditorOpener editorOpener;
@Before
public void setup() {
File files = new File("a", "b", "src/c.h", "src/c.cc", "src/d.cc");
editorList = new EditorList();
stackList = new StackList();
fileSystem = new InMemoryFileSystem();
fuzzyFinder = new Finder(files);
fuzzyListener = mock(Finder.Listener.class);
repo = new InMemoryRepository();
highlightState = new HighlightState();
minibuffer = new Minibuffer();
focusManager = new FocusManager(editorList, stackList);
- minibufferSubsystem = new MinibufferSubsystem(minibuffer, commandExecutor, focusManager);
viewportTracker = new ViewportTracker(focusManager);
register = new Register();
editorFactory = new EditorFactory(highlightState, register, viewportTracker);
FuzzyFinderDriver fileFinderDriver = new FuzzyFinderDriver(files);
Finder finder = new Finder(files);
editorOpener = new EditorOpener(editorFactory, focusManager, editorList, stackList, fileSystem, finder);
commandExecutor = new CommandExecutor(editorOpener, focusManager);
+ minibufferSubsystem = new MinibufferSubsystem(minibuffer, commandExecutor, focusManager);
controller = new Controller(editorList, fileSystem, fuzzyFinder, repo,
highlightState, stackList, minibufferSubsystem, commandExecutor, null,
fileFinderDriver, focusManager, editorOpener);
fileSystem.insertFile("a", "aaa");
fileSystem.insertFile("b", "bbb");
fileSystem.insertFile("src/c.cc", "ccc");
fileSystem.insertFile("src/c.h", "chc");
fileSystem.insertFile("src/d.cc", "ddd");
}
@Test
public void moveBetweenFilesEditingThem() {
editorOpener.openFile("a");
editorOpener.openFile("b");
assertEquals("aaa", editorList.get(0).getLine(0));
assertEquals("bbb", editorList.get(1).getLine(0));
typeString("SxKx");
type(KeyStroke.escape());
typeString("KSzJz");
assertEquals("zJz", editorList.get(0).getLine(0));
assertEquals("xKx", editorList.get(1).getLine(0));
}
@Test
public void controllerCanBringUpTheFuzzyFinder() {
fuzzyFinder.addListener(fuzzyListener);
controller.showFileFinder();
verify(fuzzyListener).onSetVisible(true);
}
@SuppressWarnings("unchecked")
@Test
public void typingGoesToTheFuzzyFinderWhenItsUp() {
controller.showFileFinder();
fuzzyFinder.addListener(fuzzyListener);
typeString("hi");
verify(fuzzyListener, times(2)).onMatchesChanged(any(List.class));
}
@Test
public void tBringsUpFuzzyFinder() {
typeString("t");
assertTrue(fuzzyFinder.isVisible());
}
@Test
public void escapeQuitsFuzzyFinder() {
typeString("t");
type(KeyStroke.escape());
assertFalse(fuzzyFinder.isVisible());
}
@Test
public void selectFromFuzzyFinderOpensFile() {
typeString("ta<CR>");
assertFalse(fuzzyFinder.isVisible());
assertEquals(1, editorList.size());
assertEquals(0, editorList.getFocusedIndex());
assertEquals("a", editorList.get(0).getFilename());
}
@Test
public void showFuzzyFinderClearsOldQuery() {
typeString("ta");
type(KeyStroke.enter());
typeString("t");
assertEquals("", fuzzyFinder.getCurrentQuery());
}
@Test
public void closeCurrentFile() {
editorOpener.openFile("a");
editorOpener.openFile("b");
controller.closeCurrentFile();
assertEquals(1, editorList.size());
}
@Test
public void canImportDiffsFromGit() {
Map<String, FileDelta> fileDeltas = new HashMap<String, FileDelta>();
FileDelta fileDelta = new FileDelta();
fileDelta.addNewLine(0, "aaa"); // First line of "./a" is new.
fileDelta.addDeletedLine(0, "deleted 1"); // We deleted two lines from the end of a.
fileDelta.addDeletedLine(0, "deleted 2");
fileDeltas.put("a", fileDelta);
Diff diff = new Diff(fileDeltas);
repo.setDiffResult(diff);
controller.importDiffsRelativeTo("HEAD");
assertEquals(Tombstone.Status.NEW, editorList.get(0).getStatus(0));
assertEquals(2, editorList.get(0).getGrave(0).size());
}
@Test
public void openingNonExistentFileShouldntCrash() {
editorOpener.openFile("doesn't exist");
}
@Test
public void filesGetSavedToTheFileSystem() {
Editor editor = editorOpener.openFile("a");
typeString("SXXX");
type(KeyStroke.escape());
assertTrue(editor.isModified());
ModifiedListener listener = mock(ModifiedListener.class);
editor.addFileModifiedListener(listener);
type(KeyStroke.fromChar('w'));
verify(listener).onModifiedStateChanged();
assertFalse(editor.isModified());
assertEquals("XXX", fileSystem.getFile("a").getLine(0));
}
@Test
public void regression_bringUpFuzzyFinderTwice() {
typeString("ta");
type(KeyStroke.enter());
typeString("ta");
}
@Test
public void highlightIsGlobal() {
editorOpener.openFile("a");
typeString("*"); // Sets highlight to 'aaa'.
editorOpener.openFile("b");
typeString("Saaa");
assertEquals("aaa", editorList.get(1).getLine(0));
assertTrue(editorList.get(1).isHighlight(0, 0));
}
@Test
public void openingTheSameFileAgainRefocusesTheSpotlightOntoThatEditor() {
editorOpener.openFile("a");
editorOpener.openFile("b");
editorOpener.openFile("a");
assertEquals(0, editorList.getFocusedIndex());
}
@Test
public void gf() {
editorOpener.openFile("a");
typeString("Ssrc/c.cc<ESC>gf");
assertEquals("src/c.cc", editorList.getFocusedItem().getFilename());
}
@Test
public void gF() {
editorOpener.openFile("a");
typeString("Sd<ESC>gF");
assertEquals("src/d.cc", editorList.getFocusedItem().getFilename());
}
@Test
public void gFOperatesOnWordNotFilename() {
editorOpener.openFile("a");
typeString("Sa.d<ESC>gF");
assertEquals("src/d.cc", editorList.getFocusedItem().getFilename());
}
@Test
public void yankRegisterIsGlobal() {
editorOpener.openFile("a");
typeString("Vy");
Editor b = editorOpener.openFile("b");
typeString("P");
assertEquals("aaa", b.getLine(0));
}
@Test
public void addSnippet() {
editorOpener.openFile("a");
typeString("V;");
assertEquals(1, stackList.size());
}
@Test
public void typeInSnippet() {
editorOpener.openFile("a");
typeString("oabc<CR>abc<ESC>");
assertSpotlightFocused();
typeString("V;"); // Make a snippet out of the last line.
typeString("k"); // Move up a line in the editors.
typeString("L"); // Move focus to stack.
assertStackFocused();
typeString("oend");
assertEquals(4, editorList.get(0).getLineCount());
assertEquals("end", editorList.get(0).getLine(3));
}
@Test
public void moveFocusBetweenSnippets() {
editorOpener.openFile("a");
typeString("V;V;");
assertEquals(2, stackList.getFocusedItem().size());
typeString("L");
assertTrue(stackList.isFocused());
assertEquals(0, stackList.getFocusedItem().getFocusedIndex());
typeString("K");
assertEquals(0, stackList.getFocusedItem().getFocusedIndex());
typeString("J");
assertEquals(1, stackList.getFocusedItem().getFocusedIndex());
}
@Test
public void qClosesSnippetWhenFocused() {
editorOpener.openFile("a");
typeString("V;Lq");
assertEquals(1, editorList.size());
assertEquals(0, stackList.size());
}
@Test
public void focusMovesBackToEditorWhenFinalSnippetClosed() {
editorOpener.openFile("a");
typeString("V;Lq");
assertTrue(editorList.isFocused());
}
@Test
public void cantMoveFocusToEmptyStack() {
editorOpener.openFile("a");
typeString("L");
assertTrue(editorList.isFocused());
}
@Test
public void addSnippetsFromSnippet() {
editorOpener.openFile("a");
createSnippetFromCurrentLine();
typeString("L");
createSnippetFromCurrentLine();
assertEquals(2, stackList.getFocusedItem().size());
}
@Test
public void addingASnippetShouldntFocusTheMostRecentlyAddedOne() {
editorOpener.openFile("a");
createSnippetFromCurrentLine();
typeString("L");
createSnippetFromCurrentLine();
assertEquals(0, stackList.getFocusedIndex());
}
@Test
public void closingASnippetShouldMoveFocusToTheNextOneDown() {
editorOpener.openFile("a");
createSnippetFromCurrentLine();
createSnippetFromCurrentLine();
createSnippetFromCurrentLine();
typeString("Lq");
assertEquals(0, stackList.getFocusedIndex());
}
@Test
public void enterInASnippetShouldJumpToThatPointInTheRealFile() {
editorOpener.openFile("a");
editorOpener.openFile("b");
assertEquals(1, editorList.getFocusedIndex());
createSnippetFromCurrentLine();
typeString("K");
assertEquals(0, editorList.getFocusedIndex());
typeString("L<CR>");
assertEquals(1, editorList.getFocusedIndex());
}
@Test
public void openDeltasAsSnippets() {
editorOpener.openFile("a");
typeString("o<ESC>@");
assertEquals(1, stackList.size());
}
@Test
public void openDeltasAsSnippetsDoesntCreateDupes() {
editorOpener.openFile("a");
typeString("o<ESC>@@");
assertEquals(1, stackList.size());
}
@Test
public void commandsGetExecutedWhenTyped() {
typeString(":e b<CR>");
assertEquals(1, editorList.size());
}
@Test
public void eOpensNewFiles() {
typeString(":e doesnt-exist<CR>");
assertEquals(1, editorList.size());
assertEquals("doesnt-exist", editorList.getFocusedItem().getFilename());
}
@Test
public void ctrlKMovesFileUpInFilelist() {
typeString(":e a<CR>:e b<CR><C-k>");
assertEquals(2, editorList.size());
assertEquals("b", editorList.getFocusedItem().getFilename());
assertEquals(0, editorList.getFocusedIndex());
}
@Test
public void ctrlJMovesFileDownInFilelist() {
typeString(":e a<CR>:e b<CR>K<C-j>");
assertEquals(2, editorList.size());
assertEquals("a", editorList.getFocusedItem().getFilename());
assertEquals(1, editorList.getFocusedIndex());
}
@Test
public void BGoesToTopFileInFileList() {
typeString(":e a<CR>:e b<CR>");
assertEquals(1, editorList.getFocusedIndex());
typeString("B");
assertEquals(0, editorList.getFocusedIndex());
}
@Test
public void QClosesAllSnippets() {
typeString(":e a<CR>ihello<CR>world<ESC>");
typeString("V;kV;");
assertEquals(1, stackList.size());
typeString("Q");
assertEquals(0, stackList.size());
}
@Test
public void QPutsFocusBackOnSpotlight() {
typeString(":e a<CR>ihello<CR>world<ESC>");
typeString("V;LQ");
assertSpotlightFocused();
}
@Test
public void outdentDoesntLeaveCursorPastEndOfLine() {
typeString(":e a<CR>ia<CR>b<CR>c<CR>d<CR><ESC>");
typeString(":3<CR>");
Point cursor = editorList.get(0).getCursorPosition();
assertEquals(2, cursor.getY());
}
@Test
public void gfOpensFilesThatDontExist() {
typeString(":e a<CR>");
typeString("A abc<ESC>gf");
assertEquals(2, editorList.size());
assertEquals("abc", editorList.getFocusedItem().getFilename());
}
@Test
public void newFilesStartModified() {
typeString(":e doesnt-exist<CR>");
assertEquals(1, editorList.size());
assertTrue(editorList.getFocusedItem().isModified());
typeString("w");
assertFalse(editorList.getFocusedItem().isModified());
}
@Test
public void openingAFilePutsItUnderneathTheCurrentOne() {
typeString(":e a<CR>:e b<CR>K");
assertEquals(0, editorList.getFocusedIndex());
typeString(":e c<CR>");
assertEquals(1, editorList.getFocusedIndex());
}
@Test
public void controllerStartsWithStackInvisible() {
assertTrue(stackList.isHidden());
}
@Test
public void creatingASnippetMakesTheStackVisible() {
typeString(":e a<CR>V;");
assertFalse(stackList.isHidden());
}
@Test
public void previousHighlightsAccessibleWithQuestionMark() {
typeString(":e doesnt-exist<CR>");
typeString("ia b b c<ESC>*hh*");
// 'b' should be highlighted, so there should be two matches.
assertEquals(2, editorList.get(0).getHighlightMatchCount());
typeString("?<DOWN><CR>");
// 'c' should be highlighted, so there should be one match.
assertEquals(1, editorList.get(0).getHighlightMatchCount());
}
@Test
public void closingTheFinalSnippetMakesTheStackInvisible() {
typeString(":e a<CR>V;Lq");
assertTrue(stackList.isHidden());
}
@Test
public void ctrl6OpensOtherFilesWithDifferentExtensions() {
typeString(":e src/c.h<CR><C-6>");
assertEquals(2, editorList.size());
}
@Test
public void reloadCurrentFile() {
typeString(":e src/c.h<CR>");
String startContents = editorList.getFocusedItem().getLine(0);
typeString("Stest<ESC>");
assertEquals("test", editorList.getFocusedItem().getLine(0));
typeString(":e<CR>");
String endContents = editorList.getFocusedItem().getLine(0);
assertEquals(startContents, endContents);
}
@Test
public void multipleStacks() {
typeString(":e a<CR>");
typeString("V;]V;");
assertEquals(2, stackList.size());
}
private void createSnippetFromCurrentLine() {
typeString("V;");
}
private void assertSpotlightFocused() {
assertTrue(editorList.isFocused());
assertFalse(stackList.isFocused());
}
private void assertStackFocused() {
assertTrue(stackList.isFocused());
assertFalse(editorList.isFocused());
}
private void type(KeyStroke keyStroke) {
controller.handleKeyStroke(keyStroke);
}
private void typeString(String string) {
for (KeyStroke keyStroke : KeyStroke.fromString(string)) {
type(keyStroke);
}
}
}
| false | true | public void setup() {
File files = new File("a", "b", "src/c.h", "src/c.cc", "src/d.cc");
editorList = new EditorList();
stackList = new StackList();
fileSystem = new InMemoryFileSystem();
fuzzyFinder = new Finder(files);
fuzzyListener = mock(Finder.Listener.class);
repo = new InMemoryRepository();
highlightState = new HighlightState();
minibuffer = new Minibuffer();
focusManager = new FocusManager(editorList, stackList);
minibufferSubsystem = new MinibufferSubsystem(minibuffer, commandExecutor, focusManager);
viewportTracker = new ViewportTracker(focusManager);
register = new Register();
editorFactory = new EditorFactory(highlightState, register, viewportTracker);
FuzzyFinderDriver fileFinderDriver = new FuzzyFinderDriver(files);
Finder finder = new Finder(files);
editorOpener = new EditorOpener(editorFactory, focusManager, editorList, stackList, fileSystem, finder);
commandExecutor = new CommandExecutor(editorOpener, focusManager);
controller = new Controller(editorList, fileSystem, fuzzyFinder, repo,
highlightState, stackList, minibufferSubsystem, commandExecutor, null,
fileFinderDriver, focusManager, editorOpener);
fileSystem.insertFile("a", "aaa");
fileSystem.insertFile("b", "bbb");
fileSystem.insertFile("src/c.cc", "ccc");
fileSystem.insertFile("src/c.h", "chc");
fileSystem.insertFile("src/d.cc", "ddd");
}
| public void setup() {
File files = new File("a", "b", "src/c.h", "src/c.cc", "src/d.cc");
editorList = new EditorList();
stackList = new StackList();
fileSystem = new InMemoryFileSystem();
fuzzyFinder = new Finder(files);
fuzzyListener = mock(Finder.Listener.class);
repo = new InMemoryRepository();
highlightState = new HighlightState();
minibuffer = new Minibuffer();
focusManager = new FocusManager(editorList, stackList);
viewportTracker = new ViewportTracker(focusManager);
register = new Register();
editorFactory = new EditorFactory(highlightState, register, viewportTracker);
FuzzyFinderDriver fileFinderDriver = new FuzzyFinderDriver(files);
Finder finder = new Finder(files);
editorOpener = new EditorOpener(editorFactory, focusManager, editorList, stackList, fileSystem, finder);
commandExecutor = new CommandExecutor(editorOpener, focusManager);
minibufferSubsystem = new MinibufferSubsystem(minibuffer, commandExecutor, focusManager);
controller = new Controller(editorList, fileSystem, fuzzyFinder, repo,
highlightState, stackList, minibufferSubsystem, commandExecutor, null,
fileFinderDriver, focusManager, editorOpener);
fileSystem.insertFile("a", "aaa");
fileSystem.insertFile("b", "bbb");
fileSystem.insertFile("src/c.cc", "ccc");
fileSystem.insertFile("src/c.h", "chc");
fileSystem.insertFile("src/d.cc", "ddd");
}
|
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
index e23350777..0c6ef38e9 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
@@ -1,415 +1,415 @@
/*******************************************************************************
* Copyright (c) 2009 Red Hat, 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
*
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.callgraph.launch;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.linuxtools.callgraph.core.DocWriter;
import org.eclipse.linuxtools.callgraph.core.Helper;
import org.eclipse.linuxtools.callgraph.core.LaunchConfigurationConstants;
import org.eclipse.linuxtools.callgraph.core.PluginConstants;
import org.eclipse.linuxtools.callgraph.core.SystemTapCommandGenerator;
import org.eclipse.linuxtools.callgraph.core.SystemTapErrorHandler;
import org.eclipse.linuxtools.callgraph.core.SystemTapParser;
import org.eclipse.linuxtools.callgraph.core.SystemTapUIErrorMessages;
import org.eclipse.linuxtools.profiling.launch.ProfileLaunchConfigurationDelegate;
import org.eclipse.ui.console.TextConsole;
/**
* Delegate for Stap scripts. The Delegate generates part of the command string
* and schedules a job to finish generation of the command and execute.
*
*/
public class SystemTapLaunchConfigurationDelegate extends
ProfileLaunchConfigurationDelegate {
private static final String TEMP_ERROR_OUTPUT =
PluginConstants.getDefaultOutput() + "stapTempError.error"; //$NON-NLS-1$
private String cmd;
private File temporaryScript = null;
private String arguments = ""; //$NON-NLS-1$
private String scriptPath = ""; //$NON-NLS-1$
private String binaryPath = ""; //$NON-NLS-1$
private String outputPath = ""; //$NON-NLS-1$
private boolean needsBinary = false; // Set to false if we want to use SystemTap
private boolean needsArguments = false;
@SuppressWarnings("unused")
private boolean useColour = false;
private String binaryArguments = ""; //$NON-NLS-1$
@Override
protected String getPluginID() {
return null;
}
/**
* Sets strings to blank, booleans to false and everything else to null
*/
private void initialize() {
temporaryScript = null;
arguments = ""; //$NON-NLS-1$
scriptPath = ""; //$NON-NLS-1$
binaryPath = ""; //$NON-NLS-1$
outputPath = ""; //$NON-NLS-1$
needsBinary = false; // Set to false if we want to use SystemTap
needsArguments = false;
useColour = false;
binaryArguments = ""; //$NON-NLS-1$
}
@Override
public void launch(ILaunchConfiguration config, String mode,
ILaunch launch, IProgressMonitor m) throws CoreException {
if (m == null) {
m = new NullProgressMonitor();
}
SubMonitor monitor = SubMonitor.convert(m,
"SystemTap runtime monitor", 5); //$NON-NLS-1$
initialize();
// check for cancellation
if (monitor.isCanceled()) {
return;
}
/*
* Set variables
*/
if (config.getAttribute(LaunchConfigurationConstants.USE_COLOUR,
LaunchConfigurationConstants.DEFAULT_USE_COLOUR))
useColour = true;
if (!config.getAttribute(LaunchConfigurationConstants.ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_ARGUMENTS).equals(
LaunchConfigurationConstants.DEFAULT_ARGUMENTS)) {
arguments = config.getAttribute(
LaunchConfigurationConstants.ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
needsArguments = true;
}
if (!config.getAttribute(LaunchConfigurationConstants.BINARY_PATH,
LaunchConfigurationConstants.DEFAULT_BINARY_PATH).equals(
LaunchConfigurationConstants.DEFAULT_BINARY_PATH)) {
binaryPath = config.getAttribute(
LaunchConfigurationConstants.BINARY_PATH,
LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
needsBinary = true;
}
if (!config.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS).equals(
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS)) {
binaryArguments = config.getAttribute(
LaunchConfigurationConstants.BINARY_ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
}
if (!config.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH).equals(
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH)) {
scriptPath = config.getAttribute(
LaunchConfigurationConstants.SCRIPT_PATH,
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
}
// Generate script if needed
if (config.getAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,
LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE)) {
temporaryScript = new File(scriptPath);
temporaryScript.delete();
try {
temporaryScript.createNewFile();
FileWriter fstream = new FileWriter(temporaryScript);
BufferedWriter out = new BufferedWriter(fstream);
out.write(config.getAttribute(
LaunchConfigurationConstants.GENERATED_SCRIPT,
LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT));
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* Generate partial command
*/
String partialCommand = ConfigurationOptionsSetter.setOptions(config);
outputPath = config.getAttribute(
LaunchConfigurationConstants.OUTPUT_PATH,
PluginConstants.getDefaultOutput());
partialCommand += "-o " + outputPath; //$NON-NLS-1$
// check for cancellation
if ( !testOutput(outputPath) || monitor.isCanceled() ) {
return;
}
finishLaunch(launch, config, partialCommand, m, true);
}
/**
* Returns the current SystemTap command, or returns an error message.
* @return
*/
public String getCommand() {
if (cmd.length() > 0)
return cmd;
else
return Messages.getString("SystemTapLaunchConfigurationDelegate.0"); //$NON-NLS-1$
}
private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String command,
IProgressMonitor monitor, boolean retry) {
String errorMessage = ""; //$NON-NLS-1$
try {
// Generate the command
cmd = SystemTapCommandGenerator.generateCommand(scriptPath, binaryPath,
command, needsBinary, needsArguments, arguments, binaryArguments);
// Check for cancellation
if (monitor.isCanceled()) {
return;
}
monitor.worked(1);
if (launch == null) {
return;
}
// Not sure if this line is necessary
// set the default source locator if required
setDefaultSourceLocator(launch, config);
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser4") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
IProcess process = createProcess(config, cmd, launch);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
//SystemTap terminated with errors, parse console to figure out which error
IDocument doc = Helper.getConsoleDocumentByName(config.getName());
//Sometimes the console has not been printed to yet, wait for a little while longer
if (doc.get().length() < 1)
Thread.sleep(300);
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorMessage = errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
if (errorHandler.hasMismatchedProbePoints() && retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, command, monitor, false);
return;
}
errorHandler.finishHandling(monitor, scriptPath);
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
- errorMessage = generateErrorMessage(config.getName(), command) + errorMessage;
+ errorMessage = generateErrorMessage(config.getName(), binaryArguments) + errorMessage;
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), errorMessage);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
private String generateErrorMessage(String configName, String binaryCommand) {
String output = ""; //$NON-NLS-1$
if (binaryCommand == null || binaryCommand.length() < 0) {
output = PluginConstants.NEW_LINE +
PluginConstants.NEW_LINE + "-------------" + //$NON-NLS-1$
PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch10") //$NON-NLS-1$
+ configName + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch8") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch9") + //$NON-NLS-1$
"configuration in Profile As --> Profile Configurations." + //$NON-NLS-1$
PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
}
else {
output = PluginConstants.NEW_LINE
+ PluginConstants.NEW_LINE +"-------------" //$NON-NLS-1$
+ PluginConstants.NEW_LINE
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage1") //$NON-NLS-1$
+ configName + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage2") //$NON-NLS-1$
+ binaryCommand + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage4") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage5") + //$NON-NLS-1$
PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
}
return output;
}
private class StreamListener implements IStreamListener{
private Helper h;
private int counter;
public StreamListener() throws IOException {
File file = new File(TEMP_ERROR_OUTPUT);
file.delete();
file.createNewFile();
h = new Helper();
h.setBufferedWriter(TEMP_ERROR_OUTPUT); //$NON-NLS-1$
counter = 0;
}
@Override
public void streamAppended(String text, IStreamMonitor monitor) {
try {
if (text.length() < 1) return;
counter++;
if (counter < PluginConstants.MAX_ERRORS)
h.appendToExistingFile(text);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() throws IOException {
h.closeBufferedWriter();
}
}
}
| true | true | private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String command,
IProgressMonitor monitor, boolean retry) {
String errorMessage = ""; //$NON-NLS-1$
try {
// Generate the command
cmd = SystemTapCommandGenerator.generateCommand(scriptPath, binaryPath,
command, needsBinary, needsArguments, arguments, binaryArguments);
// Check for cancellation
if (monitor.isCanceled()) {
return;
}
monitor.worked(1);
if (launch == null) {
return;
}
// Not sure if this line is necessary
// set the default source locator if required
setDefaultSourceLocator(launch, config);
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser4") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
IProcess process = createProcess(config, cmd, launch);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
//SystemTap terminated with errors, parse console to figure out which error
IDocument doc = Helper.getConsoleDocumentByName(config.getName());
//Sometimes the console has not been printed to yet, wait for a little while longer
if (doc.get().length() < 1)
Thread.sleep(300);
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorMessage = errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
if (errorHandler.hasMismatchedProbePoints() && retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, command, monitor, false);
return;
}
errorHandler.finishHandling(monitor, scriptPath);
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
errorMessage = generateErrorMessage(config.getName(), command) + errorMessage;
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), errorMessage);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
| private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String command,
IProgressMonitor monitor, boolean retry) {
String errorMessage = ""; //$NON-NLS-1$
try {
// Generate the command
cmd = SystemTapCommandGenerator.generateCommand(scriptPath, binaryPath,
command, needsBinary, needsArguments, arguments, binaryArguments);
// Check for cancellation
if (monitor.isCanceled()) {
return;
}
monitor.worked(1);
if (launch == null) {
return;
}
// Not sure if this line is necessary
// set the default source locator if required
setDefaultSourceLocator(launch, config);
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser4") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
IProcess process = createProcess(config, cmd, launch);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
//SystemTap terminated with errors, parse console to figure out which error
IDocument doc = Helper.getConsoleDocumentByName(config.getName());
//Sometimes the console has not been printed to yet, wait for a little while longer
if (doc.get().length() < 1)
Thread.sleep(300);
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorMessage = errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
if (errorHandler.hasMismatchedProbePoints() && retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, command, monitor, false);
return;
}
errorHandler.finishHandling(monitor, scriptPath);
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
errorMessage = generateErrorMessage(config.getName(), binaryArguments) + errorMessage;
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), errorMessage);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
|
diff --git a/src/java/no/schibstedsok/searchportal/util/QueryStringHelper.java b/src/java/no/schibstedsok/searchportal/util/QueryStringHelper.java
index 27084ec7b..db3b51015 100644
--- a/src/java/no/schibstedsok/searchportal/util/QueryStringHelper.java
+++ b/src/java/no/schibstedsok/searchportal/util/QueryStringHelper.java
@@ -1,60 +1,60 @@
// Copyright (2006) Schibsted Søk AS
package no.schibstedsok.searchportal.util;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
/**
* Helper for parsing query string.
*
* @author <a href="mailto:[email protected]">Anders Johan Jamtli</a>
*/
public final class QueryStringHelper {
/** A safer way to get parameters for the query string.
* Handles ISO-8859-1 and UTF-8 URL encodings.
*
* @param req The servlet request we are processing
* @param parameter The parameter to retrieve
* @return The correct decoded parameter
*/
public static String safeGetParameter(HttpServletRequest req, String parameter){
StringTokenizer st = new StringTokenizer(req.getQueryString(), "&");
String reqValue = req.getParameter(parameter);
String queryStringValue = null;
parameter += "=";
while(st.hasMoreTokens()) {
String tmp = st.nextToken();
if (tmp.startsWith(parameter)) {
queryStringValue = tmp.substring(parameter.length());
break;
}
}
if (reqValue == null) {
return null;
}
try {
String encodedReqValue = URLEncoder.encode(reqValue, "UTF-8");
queryStringValue = queryStringValue.replaceAll("[+]", "%20");
queryStringValue = queryStringValue.replaceAll("[*]", "%2A");
encodedReqValue = encodedReqValue.replaceAll("[+]", "%20");
encodedReqValue = encodedReqValue.replaceAll("[*]", "%2A");
- if (!queryStringValue.equals(encodedReqValue)){
+ if (!queryStringValue.equalsIgnoreCase(encodedReqValue)){
reqValue = URLDecoder.decode(queryStringValue, "ISO-8859-1");
}
} catch (UnsupportedEncodingException e) {
/* IGNORED */
}
return reqValue;
}
}
| true | true | public static String safeGetParameter(HttpServletRequest req, String parameter){
StringTokenizer st = new StringTokenizer(req.getQueryString(), "&");
String reqValue = req.getParameter(parameter);
String queryStringValue = null;
parameter += "=";
while(st.hasMoreTokens()) {
String tmp = st.nextToken();
if (tmp.startsWith(parameter)) {
queryStringValue = tmp.substring(parameter.length());
break;
}
}
if (reqValue == null) {
return null;
}
try {
String encodedReqValue = URLEncoder.encode(reqValue, "UTF-8");
queryStringValue = queryStringValue.replaceAll("[+]", "%20");
queryStringValue = queryStringValue.replaceAll("[*]", "%2A");
encodedReqValue = encodedReqValue.replaceAll("[+]", "%20");
encodedReqValue = encodedReqValue.replaceAll("[*]", "%2A");
if (!queryStringValue.equals(encodedReqValue)){
reqValue = URLDecoder.decode(queryStringValue, "ISO-8859-1");
}
} catch (UnsupportedEncodingException e) {
/* IGNORED */
}
return reqValue;
}
| public static String safeGetParameter(HttpServletRequest req, String parameter){
StringTokenizer st = new StringTokenizer(req.getQueryString(), "&");
String reqValue = req.getParameter(parameter);
String queryStringValue = null;
parameter += "=";
while(st.hasMoreTokens()) {
String tmp = st.nextToken();
if (tmp.startsWith(parameter)) {
queryStringValue = tmp.substring(parameter.length());
break;
}
}
if (reqValue == null) {
return null;
}
try {
String encodedReqValue = URLEncoder.encode(reqValue, "UTF-8");
queryStringValue = queryStringValue.replaceAll("[+]", "%20");
queryStringValue = queryStringValue.replaceAll("[*]", "%2A");
encodedReqValue = encodedReqValue.replaceAll("[+]", "%20");
encodedReqValue = encodedReqValue.replaceAll("[*]", "%2A");
if (!queryStringValue.equalsIgnoreCase(encodedReqValue)){
reqValue = URLDecoder.decode(queryStringValue, "ISO-8859-1");
}
} catch (UnsupportedEncodingException e) {
/* IGNORED */
}
return reqValue;
}
|
diff --git a/src/org/jailsframework/generators/ModelGenerator.java b/src/org/jailsframework/generators/ModelGenerator.java
index f96f867..532dbd1 100644
--- a/src/org/jailsframework/generators/ModelGenerator.java
+++ b/src/org/jailsframework/generators/ModelGenerator.java
@@ -1,72 +1,72 @@
package org.jailsframework.generators;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.jailsframework.exceptions.JailsException;
import org.jailsframework.util.FileUtil;
import org.jailsframework.util.StringUtil;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">Sanjeev Mishra</a>
* @version $Revision: 0.1
* Date: May 19, 2010
* Time: 1:41:50 AM
*/
public class ModelGenerator {
private JailsProject project;
public ModelGenerator(JailsProject project) {
this.project = project;
}
public boolean generate(String componentFileName) {
try {
String modelName = new StringUtil(componentFileName).camelize();
File modelFile = new File(project.getModelsPath() + "\\" + modelName + ".java");
if (!FileUtil.createFile(modelFile)) {
throw new JailsException("Could not generate migration");
}
return writeContent(modelFile, getSubstitutions(modelName));
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private boolean writeContent(File file, Map<String, String> substitutions) throws Exception {
VelocityEngine velocityEngine = new VelocityEngine();
- velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
+ velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "src");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
Template template;
try {
template = velocityEngine.getTemplate("model.vm");
} catch (ResourceNotFoundException e) {
throw new RuntimeException("Please make sure that your template file exists in the classpath : " + e);
}
FileWriter fileWriter = new FileWriter(file);
template.merge(new VelocityContext(substitutions), fileWriter);
fileWriter.flush();
fileWriter.close();
return true;
}
private Map<String, String> getSubstitutions(String modelName) {
Map<String, String> substitutions = new HashMap<String, String>();
substitutions.put("modelName", modelName);
substitutions.put("package", project.getModelPackage());
return substitutions;
}
}
| true | true | private boolean writeContent(File file, Map<String, String> substitutions) throws Exception {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
Template template;
try {
template = velocityEngine.getTemplate("model.vm");
} catch (ResourceNotFoundException e) {
throw new RuntimeException("Please make sure that your template file exists in the classpath : " + e);
}
FileWriter fileWriter = new FileWriter(file);
template.merge(new VelocityContext(substitutions), fileWriter);
fileWriter.flush();
fileWriter.close();
return true;
}
| private boolean writeContent(File file, Map<String, String> substitutions) throws Exception {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "src");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
Template template;
try {
template = velocityEngine.getTemplate("model.vm");
} catch (ResourceNotFoundException e) {
throw new RuntimeException("Please make sure that your template file exists in the classpath : " + e);
}
FileWriter fileWriter = new FileWriter(file);
template.merge(new VelocityContext(substitutions), fileWriter);
fileWriter.flush();
fileWriter.close();
return true;
}
|
diff --git a/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/nav/NavigationToolView.java b/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/nav/NavigationToolView.java
index e5618ef38..0715c72f5 100644
--- a/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/nav/NavigationToolView.java
+++ b/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/nav/NavigationToolView.java
@@ -1,753 +1,753 @@
/*
* $Id: NavigationToolView.java,v 1.2 2007/04/23 13:49:34 marcop Exp $
*
* Copyright (C) 2002 by Brockmann Consult ([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. This program is distributed in the hope 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 org.esa.beam.visat.toolviews.nav;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.glayer.swing.LayerCanvasModel;
import com.bc.ceres.grender.AdjustableView;
import com.bc.ceres.grender.Viewport;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductNode;
import org.esa.beam.framework.datamodel.ProductNodeEvent;
import org.esa.beam.framework.datamodel.ProductNodeListener;
import org.esa.beam.framework.datamodel.ProductNodeListenerAdapter;
import org.esa.beam.framework.help.HelpSys;
import org.esa.beam.framework.ui.GridBagUtils;
import org.esa.beam.framework.ui.UIUtils;
import org.esa.beam.framework.ui.application.ApplicationPage;
import org.esa.beam.framework.ui.application.ToolView;
import org.esa.beam.framework.ui.application.support.AbstractToolView;
import org.esa.beam.framework.ui.product.ProductSceneView;
import org.esa.beam.framework.ui.tool.ToolButtonFactory;
import org.esa.beam.util.PropertyMap;
import org.esa.beam.util.math.MathUtils;
import org.esa.beam.visat.VisatApp;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.text.NumberFormatter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import static java.lang.Math.*;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
/**
* A window which displays product spectra.
*/
public class NavigationToolView extends AbstractToolView {
public static final String ID = NavigationToolView.class.getName();
private static final int MIN_SLIDER_VALUE = -100;
private static final int MAX_SLIDER_VALUE = +100;
private LayerCanvasModelChangeHandler layerCanvasModelChangeChangeHandler;
private ProductNodeListener productNodeChangeHandler;
private ProductSceneView currentView;
private NavigationCanvas canvas;
private AbstractButton zoomInButton;
private AbstractButton zoomDefaultButton;
private AbstractButton zoomOutButton;
private AbstractButton zoomAllButton;
private AbstractButton syncViewsButton;
private AbstractButton syncCursorButton;
private JTextField zoomFactorField;
private JFormattedTextField rotationAngleField;
private JSlider zoomSlider;
private boolean inUpdateMode;
private DecimalFormat scaleFormat;
private boolean debug;
private Color zeroRotationAngleBackground;
private final Color positiveRotationAngleBackground = new Color(221, 255, 221); //#ddffdd
private final Color negativeRotationAngleBackground = new Color(255, 221, 221); //#ffdddd
private JSpinner rotationAngleSpinner;
private CursorSynchronizer cursorSynchronizer;
public NavigationToolView() {
}
@Override
public JComponent createControl() {
layerCanvasModelChangeChangeHandler = new LayerCanvasModelChangeHandler();
productNodeChangeHandler = createProductNodeListener();
cursorSynchronizer = new CursorSynchronizer(VisatApp.getApp());
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
scaleFormat = new DecimalFormat("#####.##", decimalFormatSymbols);
scaleFormat.setGroupingUsed(false);
scaleFormat.setDecimalSeparatorAlwaysShown(false);
zoomInButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomIn24.gif"), false);
zoomInButton.setToolTipText("Zoom in."); /*I18N*/
zoomInButton.setName("zoomInButton");
zoomInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoom(getCurrentView().getZoomFactor() * 1.2);
}
});
zoomOutButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomOut24.gif"), false);
zoomOutButton.setName("zoomOutButton");
zoomOutButton.setToolTipText("Zoom out."); /*I18N*/
zoomOutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoom(getCurrentView().getZoomFactor() / 1.2);
}
});
zoomDefaultButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomPixel24.gif"), false);
zoomDefaultButton.setToolTipText("Actual Pixels (image pixel = view pixel)."); /*I18N*/
zoomDefaultButton.setName("zoomDefaultButton");
zoomDefaultButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoomToPixelResolution();
}
});
zoomAllButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomAll24.gif"), false);
zoomAllButton.setName("zoomAllButton");
zoomAllButton.setToolTipText("Zoom all."); /*I18N*/
zoomAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoomAll();
}
});
syncViewsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SyncViews24.png"), true);
- syncViewsButton.setToolTipText("Synchronize compatible product views."); /*I18N*/
+ syncViewsButton.setToolTipText("Synchronise compatible product views."); /*I18N*/
syncViewsButton.setName("syncViewsButton");
syncViewsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
maybeSynchronizeCompatibleProductViews();
}
});
syncCursorButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SyncCursor24.png"), true);
- syncCursorButton.setToolTipText("Synchronize cursor position."); /*I18N*/
+ syncCursorButton.setToolTipText("Synchronise cursor position."); /*I18N*/
syncCursorButton.setName("syncCursorButton");
syncCursorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
cursorSynchronizer.setEnabled(syncCursorButton.isSelected());
}
});
AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help24.gif"), false);
helpButton.setToolTipText("Help."); /*I18N*/
helpButton.setName("helpButton");
final JPanel eastPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.gridy = 0;
eastPane.add(zoomInButton, gbc);
gbc.gridy++;
eastPane.add(zoomOutButton, gbc);
gbc.gridy++;
eastPane.add(zoomDefaultButton, gbc);
gbc.gridy++;
eastPane.add(zoomAllButton, gbc);
gbc.gridy++;
eastPane.add(syncViewsButton, gbc);
gbc.gridy++;
eastPane.add(syncCursorButton, gbc);
gbc.gridy++;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.VERTICAL;
eastPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy++;
eastPane.add(helpButton, gbc);
zoomFactorField = new JTextField();
zoomFactorField.setColumns(8);
zoomFactorField.setHorizontalAlignment(JTextField.CENTER);
zoomFactorField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handleZoomFactorFieldUserInput();
}
});
zoomFactorField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(final FocusEvent e) {
handleZoomFactorFieldUserInput();
}
});
rotationAngleSpinner = new JSpinner(new SpinnerNumberModel(0.0, -1800.0, 1800.0, 5.0));
final JSpinner.NumberEditor editor = (JSpinner.NumberEditor) rotationAngleSpinner.getEditor();
rotationAngleField = editor.getTextField();
final DecimalFormat rotationFormat;
rotationFormat = new DecimalFormat("#####.##°", decimalFormatSymbols);
rotationFormat.setGroupingUsed(false);
rotationFormat.setDecimalSeparatorAlwaysShown(false);
rotationAngleField.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
@Override
public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
return new NumberFormatter(rotationFormat);
}
});
rotationAngleField.setColumns(6);
rotationAngleField.setEditable(true);
rotationAngleField.setHorizontalAlignment(JTextField.CENTER);
rotationAngleField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addPropertyChangeListener("value", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
handleRotationAngleFieldUserInput();
}
});
zoomSlider = new JSlider(JSlider.HORIZONTAL);
zoomSlider.setValue(0);
zoomSlider.setMinimum(MIN_SLIDER_VALUE);
zoomSlider.setMaximum(MAX_SLIDER_VALUE);
zoomSlider.setPaintTicks(false);
zoomSlider.setPaintLabels(false);
zoomSlider.setSnapToTicks(false);
zoomSlider.setPaintTrack(true);
zoomSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
if (!inUpdateMode) {
zoom(sliderValueToZoomFactor(zoomSlider.getValue()));
}
}
});
final JPanel zoomFactorPane = new JPanel(new BorderLayout());
zoomFactorPane.add(zoomFactorField, BorderLayout.WEST);
final JPanel rotationAnglePane = new JPanel(new BorderLayout());
rotationAnglePane.add(rotationAngleSpinner, BorderLayout.EAST);
rotationAnglePane.add(new JLabel(" "), BorderLayout.CENTER);
final JPanel sliderPane = new JPanel(new BorderLayout(2, 2));
sliderPane.add(zoomFactorPane, BorderLayout.WEST);
sliderPane.add(zoomSlider, BorderLayout.CENTER);
sliderPane.add(rotationAnglePane, BorderLayout.EAST);
canvas = createNavigationCanvas();
canvas.setBackground(new Color(138, 133, 128)); // image background
canvas.setForeground(new Color(153, 153, 204)); // slider overlay
final JPanel centerPane = new JPanel(new BorderLayout(4, 4));
centerPane.add(BorderLayout.CENTER, canvas);
centerPane.add(BorderLayout.SOUTH, sliderPane);
final JPanel mainPane = new JPanel(new BorderLayout(8, 8));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(centerPane, BorderLayout.CENTER);
mainPane.add(eastPane, BorderLayout.EAST);
mainPane.setPreferredSize(new Dimension(320, 320));
if (getDescriptor().getHelpId() != null) {
HelpSys.enableHelpOnButton(helpButton, getDescriptor().getHelpId());
HelpSys.enableHelpKey(mainPane, getDescriptor().getHelpId());
}
setCurrentView(VisatApp.getApp().getSelectedProductSceneView());
updateState();
// Add an internal frame listener to VISAT so that we can update our
// navigation window with the information of the currently activated
// product scene view.
//
VisatApp.getApp().addInternalFrameListener(new NavigationIFL());
return mainPane;
}
public ProductSceneView getCurrentView() {
return currentView;
}
public void setCurrentView(final ProductSceneView newView) {
if (currentView != newView) {
final ProductSceneView oldView = currentView;
if (oldView != null) {
oldView.getProduct().removeProductNodeListener(productNodeChangeHandler);
if (oldView.getLayerCanvas() != null) {
oldView.getLayerCanvas().getModel().removeChangeListener(layerCanvasModelChangeChangeHandler);
}
}
currentView = newView;
if (currentView != null) {
currentView.getProduct().addProductNodeListener(productNodeChangeHandler);
if (currentView.getLayerCanvas() != null) {
currentView.getLayerCanvas().getModel().addChangeListener(layerCanvasModelChangeChangeHandler);
}
}
canvas.handleViewChanged(oldView, newView);
updateState();
}
}
NavigationCanvas createNavigationCanvas() {
return new NavigationCanvas(this);
}
private void handleZoomFactorFieldUserInput() {
Double zf = getZoomFactorFieldValue();
if (zf != null) {
updateScaleField(zf);
zoom(zf);
}
}
private void handleRotationAngleFieldUserInput() {
final Double ra = Math.round(getRotationAngleFieldValue() / 5) * 5.0;
updateRotationField(ra);
rotate(ra);
}
private Double getZoomFactorFieldValue() {
final String text = zoomFactorField.getText();
if (text.contains(":")) {
return parseTextualValue(text);
} else {
try {
double v = Double.parseDouble(text);
return v > 0 ? v : null;
} catch (NumberFormatException e) {
return null;
}
}
}
private Double getRotationAngleFieldValue() {
String text = rotationAngleField.getText();
if (text != null) {
while (text.endsWith("°")) {
text = text.substring(0, text.length() - 1);
}
}
try {
final double v = Double.parseDouble(text);
final double max = 360 * 100;
final double negMax = max * -1;
if (v > max || v < negMax) {
return 0.0;
}
return v;
} catch (NumberFormatException e) {
return 0.0;
}
}
private static Double parseTextualValue(String text) {
final String[] numbers = text.split(":");
if (numbers.length == 2) {
double dividend = 0;
double divisor = 0;
try {
dividend = Double.parseDouble(numbers[0]);
divisor = Double.parseDouble(numbers[1]);
} catch (NumberFormatException e) {
return null;
}
if (divisor == 0) {
return null;
}
double factor = dividend / divisor;
return factor > 0 ? factor : null;
} else {
return null;
}
}
public void setModelOffset(final double modelOffsetX, final double modelOffsetY) {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().getViewport().setOffset(modelOffsetX, modelOffsetY);
maybeSynchronizeCompatibleProductViews();
}
}
private void zoomToPixelResolution() {
final ProductSceneView view = getCurrentView();
if (view != null) {
final LayerCanvas layerCanvas = view.getLayerCanvas();
layerCanvas.getViewport().setZoomFactor(layerCanvas.getDefaultZoomFactor());
maybeSynchronizeCompatibleProductViews();
}
}
public void zoom(final double zoomFactor) {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().getViewport().setZoomFactor(zoomFactor);
maybeSynchronizeCompatibleProductViews();
}
}
private void rotate(Double rotationAngle) {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().getViewport().setOrientation(rotationAngle * MathUtils.DTOR);
maybeSynchronizeCompatibleProductViews();
}
}
public void zoomAll() {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().zoomAll();
maybeSynchronizeCompatibleProductViews();
}
}
private void maybeSynchronizeCompatibleProductViews() {
if (syncViewsButton.isSelected()) {
synchronizeCompatibleProductViews();
}
}
private void synchronizeCompatibleProductViews() {
final ProductSceneView currentView = getCurrentView();
if (currentView == null) {
return;
}
final JInternalFrame[] internalFrames = VisatApp.getApp().getAllInternalFrames();
for (final JInternalFrame internalFrame : internalFrames) {
if (internalFrame.getContentPane() instanceof ProductSceneView) {
final ProductSceneView view = (ProductSceneView) internalFrame.getContentPane();
if (view != currentView) {
currentView.synchronizeViewport(view);
}
}
}
}
/**
* @param sv a value between MIN_SLIDER_VALUE and MAX_SLIDER_VALUE
*
* @return a value between min and max zoom factor of the AdjustableView
*/
private double sliderValueToZoomFactor(final int sv) {
AdjustableView adjustableView = getCurrentView().getLayerCanvas();
double f1 = scaleExp2Min(adjustableView);
double f2 = scaleExp2Max(adjustableView);
double s1 = zoomSlider.getMinimum();
double s2 = zoomSlider.getMaximum();
double v1 = (sv - s1) / (s2 - s1);
double v2 = f1 + v1 * (f2 - f1);
double zf = exp2(v2);
if (debug) {
System.out.println("NavigationToolView.sliderValueToZoomFactor:");
System.out.println(" sv = " + sv);
System.out.println(" f1 = " + f1);
System.out.println(" f2 = " + f2);
System.out.println(" v1 = " + v1);
System.out.println(" v2 = " + v2);
System.out.println(" zf = " + zf);
}
return zf;
}
/**
* @param zf a value between min and max zoom factor of the AdjustableView
*
* @return a value between MIN_SLIDER_VALUE and MAX_SLIDER_VALUE
*/
private int zoomFactorToSliderValue(final double zf) {
AdjustableView adjustableView = getCurrentView().getLayerCanvas();
double f1 = scaleExp2Min(adjustableView);
double f2 = scaleExp2Max(adjustableView);
double s1 = zoomSlider.getMinimum();
double s2 = zoomSlider.getMaximum();
double v2 = log2(zf);
double v1 = max(0.0, min(1.0, (v2 - f1) / (f2 - f1)));
int sv = (int) round((s1 + v1 * (s2 - s1)));
if (debug) {
System.out.println("NavigationToolView.zoomFactorToSliderValue:");
System.out.println(" zf = " + zf);
System.out.println(" f1 = " + f1);
System.out.println(" f2 = " + f2);
System.out.println(" v2 = " + v2);
System.out.println(" v1 = " + v1);
System.out.println(" sv = " + sv);
}
return sv;
}
private void updateState() {
final boolean canNavigate = getCurrentView() != null;
zoomInButton.setEnabled(canNavigate);
zoomDefaultButton.setEnabled(canNavigate);
zoomOutButton.setEnabled(canNavigate);
zoomAllButton.setEnabled(canNavigate);
zoomSlider.setEnabled(canNavigate);
syncViewsButton.setEnabled(canNavigate);
syncCursorButton.setEnabled(canNavigate);
zoomFactorField.setEnabled(canNavigate);
rotationAngleSpinner.setEnabled(canNavigate);
updateTitle();
updateValues();
}
private void updateTitle() {
// todo - activate when we can use ToolView.setTitle()
/*
if (currentView != null) {
if (currentView.isRGB()) {
setTitle(getDescriptor().getTitle() + " - " + currentView.getProduct().getProductRefString() + " RGB");
} else {
setTitle(getDescriptor().getTitle() + " - " + currentView.getRaster().getDisplayName());
}
} else {
setTitle(getDescriptor().getTitle());
}
*/
}
private void updateValues() {
final ProductSceneView view = getCurrentView();
if (view != null) {
boolean oldState = inUpdateMode;
inUpdateMode = true;
double zf = view.getZoomFactor();
updateZoomSlider(zf);
updateScaleField(zf);
updateRotationField(view.getOrientation() * MathUtils.RTOD);
inUpdateMode = oldState;
}
}
private void updateZoomSlider(double zf) {
int sv = zoomFactorToSliderValue(zf);
zoomSlider.setValue(sv);
}
private void updateScaleField(double zf) {
String text;
if (zf > 1.0) {
text = scaleFormat.format(roundScale(zf)) + " : 1";
} else if (zf < 1.0) {
text = "1 : " + scaleFormat.format(roundScale(1.0 / zf));
} else {
text = "1 : 1";
}
zoomFactorField.setText(text);
}
private void updateRotationField(Double ra) {
while (ra > 180) {
ra -= 360;
}
while (ra < -180) {
ra += 360;
}
rotationAngleField.setValue(ra);
if (zeroRotationAngleBackground == null) {
zeroRotationAngleBackground = rotationAngleField.getBackground();
}
if (ra > 0) {
rotationAngleField.setBackground(positiveRotationAngleBackground);
} else if (ra < 0) {
rotationAngleField.setBackground(negativeRotationAngleBackground);
} else {
rotationAngleField.setBackground(zeroRotationAngleBackground);
}
}
private static double roundScale(double x) {
double e = floor((log10(x)));
double f = 10.0 * pow(10.0, e);
double fx = x * f;
double rfx = round(fx);
if (abs((rfx + 0.5) - fx) <= abs(rfx - fx)) {
rfx += 0.5;
}
return rfx / f;
}
private static double scaleExp2Min(AdjustableView adjustableView) {
return floor(log2(adjustableView.getMinZoomFactor()));
}
private static double scaleExp2Max(AdjustableView adjustableView) {
return floor(log2(adjustableView.getMaxZoomFactor()) + 1);
}
private static double log2(double x) {
return log(x) / log(2.0);
}
private static double exp2(double x) {
return pow(2.0, x);
}
private ProductNodeListener createProductNodeListener() {
return new ProductNodeListenerAdapter() {
@Override
public void nodeChanged(final ProductNodeEvent event) {
if (event.getPropertyName().equalsIgnoreCase(Product.PROPERTY_NAME_NAME)) {
final ProductNode sourceNode = event.getSourceNode();
if ((currentView.isRGB() && sourceNode == currentView.getProduct())
|| sourceNode == currentView.getRaster()) {
updateTitle();
}
}
}
};
}
private class NavigationIFL extends InternalFrameAdapter {
@Override
public void internalFrameOpened(InternalFrameEvent e) {
final Container contentPane = e.getInternalFrame().getContentPane();
if (contentPane instanceof ProductSceneView) {
PropertyMap preferences = VisatApp.getApp().getPreferences();
final boolean showWindow = preferences.getPropertyBool(VisatApp.PROPERTY_KEY_AUTO_SHOW_NAVIGATION,
true);
if (showWindow) {
ApplicationPage page = VisatApp.getApp().getPage();
ToolView toolView = page.getToolView(NavigationToolView.ID);
if (toolView != null) {
page.showToolView(NavigationToolView.ID);
}
}
}
}
@Override
public void internalFrameActivated(InternalFrameEvent e) {
if (isControlCreated()) {
final Container contentPane = e.getInternalFrame().getContentPane();
if (contentPane instanceof ProductSceneView) {
final ProductSceneView view = (ProductSceneView) contentPane;
setCurrentView(view);
} else {
setCurrentView(null);
}
}
}
@Override
public void internalFrameClosed(InternalFrameEvent e) {
if (isControlCreated()) {
final Container contentPane = e.getInternalFrame().getContentPane();
if (contentPane instanceof ProductSceneView) {
ProductSceneView view = (ProductSceneView) contentPane;
if (getCurrentView() == view) {
setCurrentView(null);
}
}
}
}
}
private class LayerCanvasModelChangeHandler implements LayerCanvasModel.ChangeListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
}
@Override
public void handleLayerDataChanged(Layer layer, Rectangle2D modelRegion) {
}
@Override
public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) {
}
@Override
public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) {
}
@Override
public void handleViewportChanged(Viewport viewport, boolean orientationChanged) {
updateValues();
maybeSynchronizeCompatibleProductViews();
}
}
}
| false | true | public JComponent createControl() {
layerCanvasModelChangeChangeHandler = new LayerCanvasModelChangeHandler();
productNodeChangeHandler = createProductNodeListener();
cursorSynchronizer = new CursorSynchronizer(VisatApp.getApp());
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
scaleFormat = new DecimalFormat("#####.##", decimalFormatSymbols);
scaleFormat.setGroupingUsed(false);
scaleFormat.setDecimalSeparatorAlwaysShown(false);
zoomInButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomIn24.gif"), false);
zoomInButton.setToolTipText("Zoom in."); /*I18N*/
zoomInButton.setName("zoomInButton");
zoomInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoom(getCurrentView().getZoomFactor() * 1.2);
}
});
zoomOutButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomOut24.gif"), false);
zoomOutButton.setName("zoomOutButton");
zoomOutButton.setToolTipText("Zoom out."); /*I18N*/
zoomOutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoom(getCurrentView().getZoomFactor() / 1.2);
}
});
zoomDefaultButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomPixel24.gif"), false);
zoomDefaultButton.setToolTipText("Actual Pixels (image pixel = view pixel)."); /*I18N*/
zoomDefaultButton.setName("zoomDefaultButton");
zoomDefaultButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoomToPixelResolution();
}
});
zoomAllButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomAll24.gif"), false);
zoomAllButton.setName("zoomAllButton");
zoomAllButton.setToolTipText("Zoom all."); /*I18N*/
zoomAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoomAll();
}
});
syncViewsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SyncViews24.png"), true);
syncViewsButton.setToolTipText("Synchronize compatible product views."); /*I18N*/
syncViewsButton.setName("syncViewsButton");
syncViewsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
maybeSynchronizeCompatibleProductViews();
}
});
syncCursorButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SyncCursor24.png"), true);
syncCursorButton.setToolTipText("Synchronize cursor position."); /*I18N*/
syncCursorButton.setName("syncCursorButton");
syncCursorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
cursorSynchronizer.setEnabled(syncCursorButton.isSelected());
}
});
AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help24.gif"), false);
helpButton.setToolTipText("Help."); /*I18N*/
helpButton.setName("helpButton");
final JPanel eastPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.gridy = 0;
eastPane.add(zoomInButton, gbc);
gbc.gridy++;
eastPane.add(zoomOutButton, gbc);
gbc.gridy++;
eastPane.add(zoomDefaultButton, gbc);
gbc.gridy++;
eastPane.add(zoomAllButton, gbc);
gbc.gridy++;
eastPane.add(syncViewsButton, gbc);
gbc.gridy++;
eastPane.add(syncCursorButton, gbc);
gbc.gridy++;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.VERTICAL;
eastPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy++;
eastPane.add(helpButton, gbc);
zoomFactorField = new JTextField();
zoomFactorField.setColumns(8);
zoomFactorField.setHorizontalAlignment(JTextField.CENTER);
zoomFactorField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handleZoomFactorFieldUserInput();
}
});
zoomFactorField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(final FocusEvent e) {
handleZoomFactorFieldUserInput();
}
});
rotationAngleSpinner = new JSpinner(new SpinnerNumberModel(0.0, -1800.0, 1800.0, 5.0));
final JSpinner.NumberEditor editor = (JSpinner.NumberEditor) rotationAngleSpinner.getEditor();
rotationAngleField = editor.getTextField();
final DecimalFormat rotationFormat;
rotationFormat = new DecimalFormat("#####.##°", decimalFormatSymbols);
rotationFormat.setGroupingUsed(false);
rotationFormat.setDecimalSeparatorAlwaysShown(false);
rotationAngleField.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
@Override
public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
return new NumberFormatter(rotationFormat);
}
});
rotationAngleField.setColumns(6);
rotationAngleField.setEditable(true);
rotationAngleField.setHorizontalAlignment(JTextField.CENTER);
rotationAngleField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addPropertyChangeListener("value", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
handleRotationAngleFieldUserInput();
}
});
zoomSlider = new JSlider(JSlider.HORIZONTAL);
zoomSlider.setValue(0);
zoomSlider.setMinimum(MIN_SLIDER_VALUE);
zoomSlider.setMaximum(MAX_SLIDER_VALUE);
zoomSlider.setPaintTicks(false);
zoomSlider.setPaintLabels(false);
zoomSlider.setSnapToTicks(false);
zoomSlider.setPaintTrack(true);
zoomSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
if (!inUpdateMode) {
zoom(sliderValueToZoomFactor(zoomSlider.getValue()));
}
}
});
final JPanel zoomFactorPane = new JPanel(new BorderLayout());
zoomFactorPane.add(zoomFactorField, BorderLayout.WEST);
final JPanel rotationAnglePane = new JPanel(new BorderLayout());
rotationAnglePane.add(rotationAngleSpinner, BorderLayout.EAST);
rotationAnglePane.add(new JLabel(" "), BorderLayout.CENTER);
final JPanel sliderPane = new JPanel(new BorderLayout(2, 2));
sliderPane.add(zoomFactorPane, BorderLayout.WEST);
sliderPane.add(zoomSlider, BorderLayout.CENTER);
sliderPane.add(rotationAnglePane, BorderLayout.EAST);
canvas = createNavigationCanvas();
canvas.setBackground(new Color(138, 133, 128)); // image background
canvas.setForeground(new Color(153, 153, 204)); // slider overlay
final JPanel centerPane = new JPanel(new BorderLayout(4, 4));
centerPane.add(BorderLayout.CENTER, canvas);
centerPane.add(BorderLayout.SOUTH, sliderPane);
final JPanel mainPane = new JPanel(new BorderLayout(8, 8));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(centerPane, BorderLayout.CENTER);
mainPane.add(eastPane, BorderLayout.EAST);
mainPane.setPreferredSize(new Dimension(320, 320));
if (getDescriptor().getHelpId() != null) {
HelpSys.enableHelpOnButton(helpButton, getDescriptor().getHelpId());
HelpSys.enableHelpKey(mainPane, getDescriptor().getHelpId());
}
setCurrentView(VisatApp.getApp().getSelectedProductSceneView());
updateState();
// Add an internal frame listener to VISAT so that we can update our
// navigation window with the information of the currently activated
// product scene view.
//
VisatApp.getApp().addInternalFrameListener(new NavigationIFL());
return mainPane;
}
| public JComponent createControl() {
layerCanvasModelChangeChangeHandler = new LayerCanvasModelChangeHandler();
productNodeChangeHandler = createProductNodeListener();
cursorSynchronizer = new CursorSynchronizer(VisatApp.getApp());
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
scaleFormat = new DecimalFormat("#####.##", decimalFormatSymbols);
scaleFormat.setGroupingUsed(false);
scaleFormat.setDecimalSeparatorAlwaysShown(false);
zoomInButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomIn24.gif"), false);
zoomInButton.setToolTipText("Zoom in."); /*I18N*/
zoomInButton.setName("zoomInButton");
zoomInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoom(getCurrentView().getZoomFactor() * 1.2);
}
});
zoomOutButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomOut24.gif"), false);
zoomOutButton.setName("zoomOutButton");
zoomOutButton.setToolTipText("Zoom out."); /*I18N*/
zoomOutButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoom(getCurrentView().getZoomFactor() / 1.2);
}
});
zoomDefaultButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomPixel24.gif"), false);
zoomDefaultButton.setToolTipText("Actual Pixels (image pixel = view pixel)."); /*I18N*/
zoomDefaultButton.setName("zoomDefaultButton");
zoomDefaultButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoomToPixelResolution();
}
});
zoomAllButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomAll24.gif"), false);
zoomAllButton.setName("zoomAllButton");
zoomAllButton.setToolTipText("Zoom all."); /*I18N*/
zoomAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
zoomAll();
}
});
syncViewsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SyncViews24.png"), true);
syncViewsButton.setToolTipText("Synchronise compatible product views."); /*I18N*/
syncViewsButton.setName("syncViewsButton");
syncViewsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
maybeSynchronizeCompatibleProductViews();
}
});
syncCursorButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SyncCursor24.png"), true);
syncCursorButton.setToolTipText("Synchronise cursor position."); /*I18N*/
syncCursorButton.setName("syncCursorButton");
syncCursorButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
cursorSynchronizer.setEnabled(syncCursorButton.isSelected());
}
});
AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help24.gif"), false);
helpButton.setToolTipText("Help."); /*I18N*/
helpButton.setName("helpButton");
final JPanel eastPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.gridy = 0;
eastPane.add(zoomInButton, gbc);
gbc.gridy++;
eastPane.add(zoomOutButton, gbc);
gbc.gridy++;
eastPane.add(zoomDefaultButton, gbc);
gbc.gridy++;
eastPane.add(zoomAllButton, gbc);
gbc.gridy++;
eastPane.add(syncViewsButton, gbc);
gbc.gridy++;
eastPane.add(syncCursorButton, gbc);
gbc.gridy++;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.VERTICAL;
eastPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy++;
eastPane.add(helpButton, gbc);
zoomFactorField = new JTextField();
zoomFactorField.setColumns(8);
zoomFactorField.setHorizontalAlignment(JTextField.CENTER);
zoomFactorField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
handleZoomFactorFieldUserInput();
}
});
zoomFactorField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(final FocusEvent e) {
handleZoomFactorFieldUserInput();
}
});
rotationAngleSpinner = new JSpinner(new SpinnerNumberModel(0.0, -1800.0, 1800.0, 5.0));
final JSpinner.NumberEditor editor = (JSpinner.NumberEditor) rotationAngleSpinner.getEditor();
rotationAngleField = editor.getTextField();
final DecimalFormat rotationFormat;
rotationFormat = new DecimalFormat("#####.##°", decimalFormatSymbols);
rotationFormat.setGroupingUsed(false);
rotationFormat.setDecimalSeparatorAlwaysShown(false);
rotationAngleField.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
@Override
public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
return new NumberFormatter(rotationFormat);
}
});
rotationAngleField.setColumns(6);
rotationAngleField.setEditable(true);
rotationAngleField.setHorizontalAlignment(JTextField.CENTER);
rotationAngleField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addPropertyChangeListener("value", new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
handleRotationAngleFieldUserInput();
}
});
zoomSlider = new JSlider(JSlider.HORIZONTAL);
zoomSlider.setValue(0);
zoomSlider.setMinimum(MIN_SLIDER_VALUE);
zoomSlider.setMaximum(MAX_SLIDER_VALUE);
zoomSlider.setPaintTicks(false);
zoomSlider.setPaintLabels(false);
zoomSlider.setSnapToTicks(false);
zoomSlider.setPaintTrack(true);
zoomSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
if (!inUpdateMode) {
zoom(sliderValueToZoomFactor(zoomSlider.getValue()));
}
}
});
final JPanel zoomFactorPane = new JPanel(new BorderLayout());
zoomFactorPane.add(zoomFactorField, BorderLayout.WEST);
final JPanel rotationAnglePane = new JPanel(new BorderLayout());
rotationAnglePane.add(rotationAngleSpinner, BorderLayout.EAST);
rotationAnglePane.add(new JLabel(" "), BorderLayout.CENTER);
final JPanel sliderPane = new JPanel(new BorderLayout(2, 2));
sliderPane.add(zoomFactorPane, BorderLayout.WEST);
sliderPane.add(zoomSlider, BorderLayout.CENTER);
sliderPane.add(rotationAnglePane, BorderLayout.EAST);
canvas = createNavigationCanvas();
canvas.setBackground(new Color(138, 133, 128)); // image background
canvas.setForeground(new Color(153, 153, 204)); // slider overlay
final JPanel centerPane = new JPanel(new BorderLayout(4, 4));
centerPane.add(BorderLayout.CENTER, canvas);
centerPane.add(BorderLayout.SOUTH, sliderPane);
final JPanel mainPane = new JPanel(new BorderLayout(8, 8));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(centerPane, BorderLayout.CENTER);
mainPane.add(eastPane, BorderLayout.EAST);
mainPane.setPreferredSize(new Dimension(320, 320));
if (getDescriptor().getHelpId() != null) {
HelpSys.enableHelpOnButton(helpButton, getDescriptor().getHelpId());
HelpSys.enableHelpKey(mainPane, getDescriptor().getHelpId());
}
setCurrentView(VisatApp.getApp().getSelectedProductSceneView());
updateState();
// Add an internal frame listener to VISAT so that we can update our
// navigation window with the information of the currently activated
// product scene view.
//
VisatApp.getApp().addInternalFrameListener(new NavigationIFL());
return mainPane;
}
|
diff --git a/src/test/java/org/scribe/examples/FreelancerExample.java b/src/test/java/org/scribe/examples/FreelancerExample.java
index 11a8973..fb7dbef 100644
--- a/src/test/java/org/scribe/examples/FreelancerExample.java
+++ b/src/test/java/org/scribe/examples/FreelancerExample.java
@@ -1,74 +1,71 @@
package org.scribe.examples;
import java.util.Scanner;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.FreelancerAPI;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.SignatureType;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
public class FreelancerExample
{
private static final String NETWORK_NAME = "Freelancer";
private static final String AUTHORIZE_URL = "http://www.sandbox.freelancer.com/users/api-token/auth.php?oauth_token=";
private static final String PROTECTED_RESOURCE_URL = "http://api.sandbox.freelancer.com/Job/getJobList.json";
private static final String SCOPE = "http://api.sandbox.freelancer.com";
public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(FreelancerAPI.class)
.signatureType(SignatureType.QueryString)
.apiKey("7f5a168a0bfdbd15b4a9ea2a969661c731cdea56")
.apiSecret("7bb8961b94873802f1c5344f671a518e087f5785").scope(SCOPE)
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
- System.out.println("(if your curious it looks like this: " + requestToken
- + " )");
+ System.out.println("(if your curious it looks like this: " + requestToken + " )");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(AUTHORIZE_URL + requestToken.getToken());
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
- System.out.println("(if your curious it looks like this: " + accessToken
- + " )");
+ System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
request.addHeader("GData-Version", "3.0");
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
- System.out
- .println("Thats it man! Go and build something awesome with Scribe! :)");
+ System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
}
| false | true | public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(FreelancerAPI.class)
.signatureType(SignatureType.QueryString)
.apiKey("7f5a168a0bfdbd15b4a9ea2a969661c731cdea56")
.apiSecret("7bb8961b94873802f1c5344f671a518e087f5785").scope(SCOPE)
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println("(if your curious it looks like this: " + requestToken
+ " )");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(AUTHORIZE_URL + requestToken.getToken());
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken
+ " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
request.addHeader("GData-Version", "3.0");
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out
.println("Thats it man! Go and build something awesome with Scribe! :)");
}
| public static void main(String[] args)
{
OAuthService service = new ServiceBuilder()
.provider(FreelancerAPI.class)
.signatureType(SignatureType.QueryString)
.apiKey("7f5a168a0bfdbd15b4a9ea2a969661c731cdea56")
.apiSecret("7bb8961b94873802f1c5344f671a518e087f5785").scope(SCOPE)
.build();
Scanner in = new Scanner(System.in);
System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
Token requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println("(if your curious it looks like this: " + requestToken + " )");
System.out.println();
System.out.println("Now go and authorize Scribe here:");
System.out.println(AUTHORIZE_URL + requestToken.getToken());
System.out.println("And paste the verifier here");
System.out.print(">>");
Verifier verifier = new Verifier(in.nextLine());
System.out.println();
// Trade the Request Token and Verfier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
Token accessToken = service.getAccessToken(requestToken, verifier);
System.out.println("Got the Access Token!");
System.out.println("(if your curious it looks like this: " + accessToken + " )");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
request.addHeader("GData-Version", "3.0");
Response response = request.send();
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getCode());
System.out.println(response.getBody());
System.out.println();
System.out.println("Thats it man! Go and build something awesome with Scribe! :)");
}
|
diff --git a/src/main/java/org/andrill/conop/search/mutators/FooMutator.java b/src/main/java/org/andrill/conop/search/mutators/FooMutator.java
index fc4028a..4e0ee2b 100644
--- a/src/main/java/org/andrill/conop/search/mutators/FooMutator.java
+++ b/src/main/java/org/andrill/conop/search/mutators/FooMutator.java
@@ -1,34 +1,34 @@
package org.andrill.conop.search.mutators;
import java.util.List;
import java.util.Random;
import org.andrill.conop.search.Event;
import org.andrill.conop.search.Solution;
import com.google.common.collect.Lists;
public class FooMutator extends AbstractMutator {
protected int pos = 0;
protected Random random = new Random();
@Override
public Solution internalMutate(final Solution solution) {
List<Event> events = Lists.newArrayList(solution.getEvents());
// pick a random event and calculate the valid position range
pos = (pos + 1) % events.size();
Event e = events.remove(pos);
- int range = solution.getMin(e) - solution.getMax(e) + 5;
+ int range = Math.abs(solution.getMin(e) - solution.getMax(e)) + 5;
int newPos = Math.max(0, Math.min(events.size(), pos + (random.nextInt(range) - range / 2)));
// add in the event at a random valid position
events.add(newPos, e);
return new Solution(solution.getRun(), events);
}
@Override
public String toString() {
return "Foo";
}
}
| true | true | public Solution internalMutate(final Solution solution) {
List<Event> events = Lists.newArrayList(solution.getEvents());
// pick a random event and calculate the valid position range
pos = (pos + 1) % events.size();
Event e = events.remove(pos);
int range = solution.getMin(e) - solution.getMax(e) + 5;
int newPos = Math.max(0, Math.min(events.size(), pos + (random.nextInt(range) - range / 2)));
// add in the event at a random valid position
events.add(newPos, e);
return new Solution(solution.getRun(), events);
}
| public Solution internalMutate(final Solution solution) {
List<Event> events = Lists.newArrayList(solution.getEvents());
// pick a random event and calculate the valid position range
pos = (pos + 1) % events.size();
Event e = events.remove(pos);
int range = Math.abs(solution.getMin(e) - solution.getMax(e)) + 5;
int newPos = Math.max(0, Math.min(events.size(), pos + (random.nextInt(range) - range / 2)));
// add in the event at a random valid position
events.add(newPos, e);
return new Solution(solution.getRun(), events);
}
|
diff --git a/src/com/ontologycentral/ldspider/Crawler.java b/src/com/ontologycentral/ldspider/Crawler.java
index 478da45..a48309d 100644
--- a/src/com/ontologycentral/ldspider/Crawler.java
+++ b/src/com/ontologycentral/ldspider/Crawler.java
@@ -1,276 +1,276 @@
package com.ontologycentral.ldspider;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import com.ontologycentral.ldspider.frontier.Frontier;
import com.ontologycentral.ldspider.hooks.content.ContentHandler;
import com.ontologycentral.ldspider.hooks.content.ContentHandlerRdfXml;
import com.ontologycentral.ldspider.hooks.error.ErrorHandler;
import com.ontologycentral.ldspider.hooks.error.ErrorHandlerDummy;
import com.ontologycentral.ldspider.hooks.fetch.FetchFilter;
import com.ontologycentral.ldspider.hooks.fetch.FetchFilterAllow;
import com.ontologycentral.ldspider.hooks.links.LinkFilter;
import com.ontologycentral.ldspider.hooks.links.LinkFilterDefault;
import com.ontologycentral.ldspider.hooks.sink.Sink;
import com.ontologycentral.ldspider.hooks.sink.SinkDummy;
import com.ontologycentral.ldspider.http.ConnectionManager;
import com.ontologycentral.ldspider.http.LookupThread;
import com.ontologycentral.ldspider.http.robot.Robots;
import com.ontologycentral.ldspider.queue.BreadthFirstQueue;
import com.ontologycentral.ldspider.queue.LoadBalancingQueue;
import com.ontologycentral.ldspider.queue.Redirects;
import com.ontologycentral.ldspider.queue.SpiderQueue;
import com.ontologycentral.ldspider.tld.TldManager;
public class Crawler {
Logger _log = Logger.getLogger(this.getClass().getName());
ContentHandler _contentHandler;
Sink _output;
LinkFilter _links;
ErrorHandler _eh;
FetchFilter _ff, _blacklist;
ConnectionManager _cm;
Robots _robots;
// Sitemaps _sitemaps;
TldManager _tldm;
SpiderQueue _queue = null;
int _threads;
public Crawler() {
this(CrawlerConstants.DEFAULT_NB_THREADS);
}
public Crawler(int threads) {
_threads = threads;
String phost = null;
int pport = 0;
String puser = null;
String ppassword = null;
if (System.getProperties().get("http.proxyHost") != null) {
phost = System.getProperties().get("http.proxyHost").toString();
}
if (System.getProperties().get("http.proxyPort") != null) {
pport = Integer.parseInt(System.getProperties().get("http.proxyPort").toString());
}
if (System.getProperties().get("http.proxyUser") != null) {
puser = System.getProperties().get("http.proxyUser").toString();
}
if (System.getProperties().get("http.proxyPassword") != null) {
ppassword = System.getProperties().get("http.proxyPassword").toString();
}
_cm = new ConnectionManager(phost, pport, puser, ppassword, threads*CrawlerConstants.MAX_CONNECTIONS_PER_THREAD);
_cm.setRetries(CrawlerConstants.RETRIES);
try {
_tldm = new TldManager(_cm);
} catch (Exception e) {
_log.info("cannot get tld file online " + e.getMessage());
try {
_tldm = new TldManager();
} catch (IOException e1) {
_log.info("cannot get tld file locally " + e.getMessage());
}
}
_eh = new ErrorHandlerDummy();
_robots = new Robots(_cm);
_robots.setErrorHandler(_eh);
// _sitemaps = new Sitemaps(_cm);
// _sitemaps.setErrorHandler(_eh);
_contentHandler = new ContentHandlerRdfXml();
_output = new SinkDummy();
_ff = new FetchFilterAllow();
_blacklist = new FetchFilterAllow();
}
public void setContentHandler(ContentHandler h) {
_contentHandler = h;
}
public void setFetchFilter(FetchFilter ff) {
_ff = ff;
}
public void setBlacklistFilter(FetchFilter blacklist) {
_blacklist = blacklist;
}
public void setErrorHandler(ErrorHandler eh) {
_eh = eh;
if (_robots != null) {
_robots.setErrorHandler(eh);
}
// if (_sitemaps != null) {
// _sitemaps.setErrorHandler(eh);
// }
if (_links != null) {
_links.setErrorHandler(eh);
}
}
public void setOutputCallback(Sink cb) {
_output = cb;
}
public void setLinkFilter(LinkFilter links) {
_links = links;
}
public void evaluateBreadthFirst(Frontier frontier, int depth, int maxuris, int maxplds) {
evaluateBreadthFirst(frontier, depth, maxuris, maxplds, true, true);
}
public void evaluateBreadthFirst(Frontier frontier, int depth, int maxuris, int maxplds, boolean followABox, boolean followTBox) {
if (_queue == null || !(_queue instanceof BreadthFirstQueue)) {
- _queue = new BreadthFirstQueue(_tldm, maxplds, maxuris);
+ _queue = new BreadthFirstQueue(_tldm, maxuris, maxplds);
} else {
Redirects r = _queue.getRedirects();
Set<URI> seen = _queue.getSeen();
- _queue = new BreadthFirstQueue(_tldm, maxplds, maxuris);
+ _queue = new BreadthFirstQueue(_tldm, maxuris, maxplds);
_queue.setRedirects(r);
_queue.setSeen(seen);
}
if (_links == null) {
_links = new LinkFilterDefault(frontier);
}
_queue.schedule(frontier);
_links.setFollowABox(followABox);
_links.setFollowTBox(followTBox);
_log.info(_queue.toString());
int rounds = followTBox ? depth + 1 : depth;
for (int curRound = 0; curRound <= rounds; curRound++) {
List<Thread> ts = new ArrayList<Thread>();
//Extra round to get TBox
if(curRound == depth + 1) {
_links.setFollowABox(false);
_links.setFollowTBox(true);
}
for (int j = 0; j < _threads; j++) {
LookupThread lt = new LookupThread(_cm, _queue, _contentHandler, _output, _links, _robots, _eh, _ff, _blacklist);
ts.add(new Thread(lt,"LookupThread-"+j));
}
_log.info("Starting threads round " + curRound + " with " + _queue.size() + " uris");
for (Thread t : ts) {
t.start();
}
for (Thread t : ts) {
try {
t.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
_log.info("ROUND " + curRound + " DONE with " + _queue.size() + " uris remaining in queue");
_log.fine("old queue: \n" + _queue.toString());
_queue.schedule(frontier);
_log.fine("new queue: \n" + _queue.toString());
}
}
public void evaluateLoadBalanced(Frontier frontier, int maxuris) {
if (_queue == null || !(_queue instanceof LoadBalancingQueue)) {
_queue = new LoadBalancingQueue(_tldm);
} else {
Redirects r = _queue.getRedirects();
Set<URI> seen = _queue.getSeen();
_queue = new LoadBalancingQueue(_tldm);
_queue.setRedirects(r);
_queue.setSeen(seen);
}
if (_links == null) {
_links = new LinkFilterDefault(frontier);
}
_queue.schedule(frontier);
_log.fine(_queue.toString());
int i = 0;
int uris = 0;
while (uris < maxuris && _queue.size() > 0) {
int size = _queue.size();
List<Thread> ts = new ArrayList<Thread>();
for (int j = 0; j < _threads; j++) {
LookupThread lt = new LookupThread(_cm, _queue, _contentHandler, _output, _links, _robots, _eh, _ff, _blacklist);
ts.add(new Thread(lt,"LookupThread-"+j));
}
_log.info("Starting threads round " + i++ + " with " + _queue.size() + " uris");
for (Thread t : ts) {
t.start();
}
for (Thread t : ts) {
try {
t.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
uris += size - _queue.size();
_log.info("ROUND " + i + " DONE with " + _queue.size() + " uris remaining in queue");
_log.fine("old queue: \n" + _queue.toString());
_log.fine("frontier" + frontier);
_queue.schedule(frontier);
_log.info("new queue: \n" + _queue.toString());
}
}
/**
* Set the spider queue
* @param queue
*/
public void setQueue(final SpiderQueue queue){
_queue = queue;
}
public SpiderQueue getQueue(){
return _queue;
}
public void close() {
_cm.shutdown();
_eh.close();
}
}
| false | true | public void evaluateBreadthFirst(Frontier frontier, int depth, int maxuris, int maxplds, boolean followABox, boolean followTBox) {
if (_queue == null || !(_queue instanceof BreadthFirstQueue)) {
_queue = new BreadthFirstQueue(_tldm, maxplds, maxuris);
} else {
Redirects r = _queue.getRedirects();
Set<URI> seen = _queue.getSeen();
_queue = new BreadthFirstQueue(_tldm, maxplds, maxuris);
_queue.setRedirects(r);
_queue.setSeen(seen);
}
if (_links == null) {
_links = new LinkFilterDefault(frontier);
}
_queue.schedule(frontier);
_links.setFollowABox(followABox);
_links.setFollowTBox(followTBox);
_log.info(_queue.toString());
int rounds = followTBox ? depth + 1 : depth;
for (int curRound = 0; curRound <= rounds; curRound++) {
List<Thread> ts = new ArrayList<Thread>();
//Extra round to get TBox
if(curRound == depth + 1) {
_links.setFollowABox(false);
_links.setFollowTBox(true);
}
for (int j = 0; j < _threads; j++) {
LookupThread lt = new LookupThread(_cm, _queue, _contentHandler, _output, _links, _robots, _eh, _ff, _blacklist);
ts.add(new Thread(lt,"LookupThread-"+j));
}
_log.info("Starting threads round " + curRound + " with " + _queue.size() + " uris");
for (Thread t : ts) {
t.start();
}
for (Thread t : ts) {
try {
t.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
_log.info("ROUND " + curRound + " DONE with " + _queue.size() + " uris remaining in queue");
_log.fine("old queue: \n" + _queue.toString());
_queue.schedule(frontier);
_log.fine("new queue: \n" + _queue.toString());
}
}
| public void evaluateBreadthFirst(Frontier frontier, int depth, int maxuris, int maxplds, boolean followABox, boolean followTBox) {
if (_queue == null || !(_queue instanceof BreadthFirstQueue)) {
_queue = new BreadthFirstQueue(_tldm, maxuris, maxplds);
} else {
Redirects r = _queue.getRedirects();
Set<URI> seen = _queue.getSeen();
_queue = new BreadthFirstQueue(_tldm, maxuris, maxplds);
_queue.setRedirects(r);
_queue.setSeen(seen);
}
if (_links == null) {
_links = new LinkFilterDefault(frontier);
}
_queue.schedule(frontier);
_links.setFollowABox(followABox);
_links.setFollowTBox(followTBox);
_log.info(_queue.toString());
int rounds = followTBox ? depth + 1 : depth;
for (int curRound = 0; curRound <= rounds; curRound++) {
List<Thread> ts = new ArrayList<Thread>();
//Extra round to get TBox
if(curRound == depth + 1) {
_links.setFollowABox(false);
_links.setFollowTBox(true);
}
for (int j = 0; j < _threads; j++) {
LookupThread lt = new LookupThread(_cm, _queue, _contentHandler, _output, _links, _robots, _eh, _ff, _blacklist);
ts.add(new Thread(lt,"LookupThread-"+j));
}
_log.info("Starting threads round " + curRound + " with " + _queue.size() + " uris");
for (Thread t : ts) {
t.start();
}
for (Thread t : ts) {
try {
t.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
_log.info("ROUND " + curRound + " DONE with " + _queue.size() + " uris remaining in queue");
_log.fine("old queue: \n" + _queue.toString());
_queue.schedule(frontier);
_log.fine("new queue: \n" + _queue.toString());
}
}
|
diff --git a/core/src/visad/trunk/Gridded1DDoubleSet.java b/core/src/visad/trunk/Gridded1DDoubleSet.java
index 9ced725aa..28afdaf98 100644
--- a/core/src/visad/trunk/Gridded1DDoubleSet.java
+++ b/core/src/visad/trunk/Gridded1DDoubleSet.java
@@ -1,761 +1,761 @@
//
// Gridded1DDoubleSet.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2006 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
/**
Gridded1DDoubleSet is a Gridded1DSet with double-precision samples.<P>
*/
public class Gridded1DDoubleSet extends Gridded1DSet
implements GriddedDoubleSet {
double[] Low = new double[1];
double[] Hi = new double[1];
double LowX, HiX;
double[][] Samples;
/**
* A canonicalizing cache of previously-created instances. Because instances
* are immutable, a cache can be used to reduce memory usage by ensuring
* that each instance is truely unique. By implementing the cache using a
* {@link WeakHashMap}, this can be accomplished without the technique itself
* adversely affecting memory usage.
*/
private static final WeakHashMap cache = new WeakHashMap();
// Overridden Gridded1DSet constructors (float[][])
/** a 1-D sequence with no regular interval with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded1DDoubleSet(MathType type, float[][] samples, int lengthX)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX, null, null, null, true);
}
public Gridded1DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, Set.floatToDouble(samples), lengthX,
coord_sys, units, errors, true);
}
/** a 1-D sorted sequence with no regular interval. samples array
is organized float[1][number_of_samples] where lengthX =
number_of_samples. samples must be sorted (either increasing
or decreasing). coordinate_system and units must be compatible
with defaults for type, or may be null. errors may be null */
public Gridded1DDoubleSet(MathType type, float[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
this(type, Set.floatToDouble(samples), lengthX,
coord_sys, units, errors, copy);
}
// Corresponding Gridded1DDoubleSet constructors (double[][])
/** a 1-D sequence with no regular interval with null errors,
CoordinateSystem and Units are defaults from type */
public Gridded1DDoubleSet(MathType type, double[][] samples, int lengthX)
throws VisADException {
this(type, samples, lengthX, null, null, null, true);
}
public Gridded1DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, lengthX, coord_sys, units, errors, true);
}
/** a 1-D sorted sequence with no regular interval. samples array
is organized double[1][number_of_samples] where lengthX =
number_of_samples. samples must be sorted (either increasing
or decreasing). coordinate_system and units must be compatible
with defaults for type, or may be null. errors may be null */
public Gridded1DDoubleSet(MathType type, double[][] samples, int lengthX,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, null, lengthX, coord_sys, units, errors, copy);
if (samples == null) {
throw new SetException("Gridded1DDoubleSet: samples are null");
}
init_doubles(samples, copy);
LowX = Low[0];
HiX = Hi[0];
LengthX = Lengths[0];
if (Samples != null && Lengths[0] > 1) {
// samples consistency test
for (int i=0; i<Length; i++) {
if (Samples[0][i] != Samples[0][i]) {
throw new SetException(
"Gridded1DDoubleSet: samples values may not be missing");
}
}
Ascending = (Samples[0][LengthX-1] > Samples[0][0]);
if (Ascending) {
for (int i=1; i<LengthX; i++) {
if (Samples[0][i] < Samples[0][i-1]) {
throw new SetException(
"Gridded1DDoubleSet: samples do not form a valid grid ("+i+")");
}
}
}
else { // !Ascending
for (int i=1; i<LengthX; i++) {
if (Samples[0][i] > Samples[0][i-1]) {
throw new SetException(
"Gridded1DDoubleSet: samples do not form a valid grid ("+i+")");
}
}
}
}
}
/**
* Returns an instance of this class. This method uses a weak cache of
* previously-created instances to reduce memory usage.
*
* @param type The type of the set. Must be a {@link
* RealType} or a single-component {@link
* RealTupleType} or {@link SetType}.
* @param samples The values in the set.
* <code>samples[i]</code> is the value of
* the ith sample point. Must be sorted (either
* increasing or decreasing). May be
* <code>null</code>. The array is not copied, so
* either don't modify it or clone it first.
* @param coord_sys The coordinate system for this, particular, set.
* Must be compatible with the default coordinate
* system. May be <code>null</code>.
* @param unit The unit for the samples. Must be compatible
* with the default unit. May be
* <code>null</code>.
* @param error The error estimate of the samples. May be
* <code>null</code>.
*/
public static synchronized Gridded1DDoubleSet create(
MathType type,
double[] samples,
CoordinateSystem coordSys,
Unit unit,
ErrorEstimate error)
throws VisADException
{
Gridded1DDoubleSet newSet =
new Gridded1DDoubleSet(
type, new double[][] {samples}, samples.length, coordSys,
new Unit[] {unit}, new ErrorEstimate[] {error}, false);
WeakReference ref = (WeakReference)cache.get(newSet);
if (ref == null)
{
/*
* The new instance is unique (any and all previously-created identical
* instances no longer exist).
*
* A WeakReference is used in the following because values of a
* WeakHashMap aren't "weak" themselves and must not strongly reference
* their associated keys either directly or indirectly.
*/
cache.put(newSet, new WeakReference(newSet));
}
else
{
/*
* The new instance is a duplicate of a previously-created one.
*/
Gridded1DDoubleSet oldSet = (Gridded1DDoubleSet)ref.get();
if (oldSet == null)
{
/* The previous instance no longer exists. Save the new instance. */
cache.put(newSet, new WeakReference(newSet));
}
else
{
/* The previous instance still exists. Reuse it to save memory. */
newSet = oldSet;
}
}
return newSet;
}
// Overridden Gridded1DSet methods (float[][])
public float[][] getSamples() throws VisADException {
return getSamples(true);
}
public float[][] getSamples(boolean copy) throws VisADException {
return Set.doubleToFloat(Samples);
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
return Set.doubleToFloat(indexToDouble(index));
}
/**
* Convert an array of values in R^DomainDimension to an array of
* 1-D indices. This Gridded1DDoubleSet must have at least two points in the
* set.
* @param value An array of coordinates. <code>value[i][j]
* <code> contains the <code>i</code>th component of the
* <code>j</code>th point.
* @return Indices of nearest points. RETURN_VALUE<code>[i]</code>
* will contain the index of the point in the set closest
* to <code>value[][i]</code> or <code>-1</code> if
* <code>value[][i]</code> lies outside the set.
*/
public int[] valueToIndex(float[][] value) throws VisADException {
return doubleToIndex(Set.floatToDouble(value));
}
public float[][] gridToValue(float[][] grid) throws VisADException {
return Set.doubleToFloat(gridToDouble(Set.floatToDouble(grid)));
}
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public float[][] valueToGrid(float[][] value) throws VisADException {
return Set.doubleToFloat(doubleToGrid(Set.floatToDouble(value)));
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void valueToInterp(float[][] value, int[][] indices,
float[][] weights) throws VisADException
{
int len = weights.length;
double[][] w = new double[len][];
doubleToInterp(Set.floatToDouble(value), indices, w);
for (int i=0; i<len; i++) {
if (w[i] != null) {
weights[i] = new float[w[i].length];
for (int j=0; j<w[i].length; j++) {
weights[i][j] = (float) w[i][j];
}
}
}
}
public float getLowX() {
return (float) LowX;
}
public float getHiX() {
return (float) HiX;
}
// Corresponding Gridded1DDoubleSet methods (double[][])
public double[][] getDoubles() throws VisADException {
return getDoubles(true);
}
public double[][] getDoubles(boolean copy) throws VisADException {
return copy ? Set.copyDoubles(Samples) : Samples;
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public double[][] indexToDouble(int[] index) throws VisADException {
int length = index.length;
if (Samples == null) {
// not used - over-ridden by Linear1DSet.indexToValue
double[][] grid = new double[ManifoldDimension][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
grid[0][i] = (double) index[i];
}
else {
grid[0][i] = -1;
}
}
return gridToDouble(grid);
}
else {
double[][] values = new double[1][length];
for (int i=0; i<length; i++) {
if (0 <= index[i] && index[i] < Length) {
values[0][i] = Samples[0][index[i]];
}
else {
values[0][i] = Double.NaN;
}
}
return values;
}
}
public int[] doubleToIndex(double[][] value) throws VisADException {
if (value.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length;
int[] index = new int[length];
double[][] grid = doubleToGrid(value);
double[] grid0 = grid[0];
double g;
for (int i=0; i<length; i++) {
g = grid0[i];
index[i] = Double.isNaN(g) ? -1 : ((int) (g + 0.5));
}
return index;
}
/** transform an array of non-integer grid coordinates to an array
of values in R^DomainDimension */
public double[][] gridToDouble(double[][] grid) throws VisADException {
if (grid.length < DomainDimension) {
throw new SetException("Gridded1DDoubleSet.gridToDouble: grid dimension " +
grid.length + " not equal to Domain dimension " +
DomainDimension);
}
/* remove DRM: 2004-09-14
if (Lengths[0] < 2) {
throw new SetException("Gridded1DDoubleSet.gridToDouble: " +
"requires all grid dimensions to be > 1");
}
*/
int length = grid[0].length;
double[][] value = new double[1][length];
for (int i=0; i<length; i++) {
// let g be the current grid coordinate
double g = grid[0][i];
if ( (g < -0.5) || (g > LengthX-0.5) ) {
value[0][i] = Double.NaN;
} else if (Length == 1) {
value[0][i] = Samples[0][0];
} else {
// calculate closest integer variable
int ig;
if (g < 0) ig = 0;
else if (g >= LengthX-1) ig = LengthX - 2;
else ig = (int) g;
double A = g - ig; // distance variable
// do the linear interpolation
value[0][i] = (1-A)*Samples[0][ig] + A*Samples[0][ig+1];
}
}
return value;
}
// WLH 6 Dec 2001
private int ig = -1;
/** transform an array of values in R^DomainDimension to an array
of non-integer grid coordinates */
public double[][] doubleToGrid(double[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToGrid: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
/*
if (Lengths[0] < 2) {
throw new SetException("Gridded1DDoubleSet.doubleToGrid: " +
"requires all grid dimensions to be > 1");
}
*/
double[] vals = value[0];
int length = vals.length;
double[] samps = Samples[0];
double[][] grid = new double[1][length];
/* WLH 6 Dec 2001
int ig = (LengthX - 1)/2;
*/
// use value from last call as first guess, if reasonable
if (ig < 0 || ig >= LengthX) {
ig = (LengthX - 1)/2;
}
for (int i=0; i<length; i++) {
if (Double.isNaN(vals[i])) {
grid[0][i] = Double.NaN;
} else if (Length == 1) {
grid[0][i] = 0;
} else {
int lower = 0;
int upper = LengthX-1;
while (lower < upper) {
if ((vals[i] - samps[ig]) * (vals[i] - samps[ig+1]) <= 0) break;
if (Ascending ? samps[ig+1] < vals[i] : samps[ig+1] > vals[i]) {
lower = ig+1;
}
else if (Ascending ? samps[ig] > vals[i] : samps[ig] < vals[i]) {
upper = ig;
}
if (lower < upper) ig = (lower + upper) / 2;
}
// Newton's method
double solv = ig + (vals[i] - samps[ig]) / (samps[ig+1] - samps[ig]);
if (solv > -0.5 && solv < LengthX - 0.5) grid[0][i] = solv;
else {
grid[0][i] = Double.NaN;
// next guess should be in the middle if previous value was missing
ig = (LengthX - 1)/2;
}
}
}
return grid;
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if i-th value is outside grid
(i.e., if no interpolation is possible) */
public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
- throw new SetException("Gridded1DDoubleinearLatLonSet.doubleToInterp: indices length " +
+ throw new SetException("Gridded1DDoubleSet.doubleToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
public double getDoubleLowX() {
return LowX;
}
public double getDoubleHiX() {
return HiX;
}
// Miscellaneous Set methods that must be overridden
// (this code is duplicated throughout all *DoubleSet classes)
void init_doubles(double[][] samples, boolean copy)
throws VisADException {
if (samples.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.init_doubles:" +
" samples dimension " + samples.length +
" not equal to Domain dimension " +
DomainDimension);
}
if (Length == 0) {
// Length set in init_lengths, but not called for IrregularSet
Length = samples[0].length;
}
else {
if (Length != samples[0].length) {
throw new SetException("Gridded1DDoubleSet.init_doubles: samples[0] length " +
samples[0].length +
" doesn't match expected length " + Length);
}
}
// MEM
if (copy) {
Samples = new double[DomainDimension][Length];
}
else {
Samples = samples;
}
for (int j=0; j<DomainDimension; j++) {
if (samples[j].length != Length) {
throw new SetException("Gridded1DDoubleSet.init_doubles: samples[" + j +
"] length " + samples[0].length +
" doesn't match expected length " + Length);
}
double[] samplesJ = samples[j];
double[] SamplesJ = Samples[j];
if (copy) {
System.arraycopy(samplesJ, 0, SamplesJ, 0, Length);
}
Low[j] = Double.POSITIVE_INFINITY;
Hi[j] = Double.NEGATIVE_INFINITY;
double sum = 0.0f;
for (int i=0; i<Length; i++) {
if (SamplesJ[i] == SamplesJ[i] && !Double.isInfinite(SamplesJ[i])) {
if (SamplesJ[i] < Low[j]) Low[j] = SamplesJ[i];
if (SamplesJ[i] > Hi[j]) Hi[j] = SamplesJ[i];
}
else {
SamplesJ[i] = Double.NaN;
}
sum += SamplesJ[i];
}
if (SetErrors[j] != null ) {
SetErrors[j] =
new ErrorEstimate(SetErrors[j].getErrorValue(), sum / Length,
Length, SetErrors[j].getUnit());
}
super.Low[j] = (float) Low[j];
super.Hi[j] = (float) Hi[j];
}
}
public void cram_missing(boolean[] range_select) {
int n = Math.min(range_select.length, Samples[0].length);
for (int i=0; i<n; i++) {
if (!range_select[i]) Samples[0][i] = Double.NaN;
}
}
public boolean isMissing() {
return (Samples == null);
}
public boolean equals(Object set) {
if (!(set instanceof Gridded1DDoubleSet) || set == null) return false;
if (this == set) return true;
if (testNotEqualsCache((Set) set)) return false;
if (testEqualsCache((Set) set)) return true;
if (!equalUnitAndCS((Set) set)) return false;
try {
int i, j;
if (DomainDimension != ((Gridded1DDoubleSet) set).getDimension() ||
ManifoldDimension !=
((Gridded1DDoubleSet) set).getManifoldDimension() ||
Length != ((Gridded1DDoubleSet) set).getLength()) return false;
for (j=0; j<ManifoldDimension; j++) {
if (Lengths[j] != ((Gridded1DDoubleSet) set).getLength(j)) {
return false;
}
}
// Sets are immutable, so no need for 'synchronized'
double[][] samples = ((Gridded1DDoubleSet) set).getDoubles(false);
if (Samples != null && samples != null) {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (Samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
else {
double[][] this_samples = getDoubles(false);
if (this_samples == null) {
if (samples != null) {
return false;
}
} else if (samples == null) {
return false;
} else {
for (j=0; j<DomainDimension; j++) {
for (i=0; i<Length; i++) {
if (this_samples[j][i] != samples[j][i]) {
addNotEqualsCache((Set) set);
return false;
}
}
}
}
}
addEqualsCache((Set) set);
return true;
}
catch (VisADException e) {
return false;
}
}
/**
* Returns the hash code of this instance. {@link Object#hashCode()} should be
* overridden whenever {@link Object#equals(Object)} is.
* @return The hash code of this instance (includes the
* values).
*/
public int hashCode()
{
if (!hashCodeSet)
{
hashCode = unitAndCSHashCode();
hashCode ^= DomainDimension ^ ManifoldDimension ^ Length;
for (int j=0; j<ManifoldDimension; j++)
hashCode ^= Lengths[j];
if (Samples != null)
for (int j=0; j<DomainDimension; j++)
for (int i=0; i<Length; i++)
hashCode ^= new Double(Samples[j][i]).hashCode();
hashCodeSet = true;
}
return hashCode;
}
/**
* Clones this instance.
*
* @return A clone of this instance.
*/
public Object clone() {
Gridded1DDoubleSet clone = (Gridded1DDoubleSet)super.clone();
if (Samples != null) {
/*
* The Samples array is cloned because getDoubles(false) allows clients
* to manipulate the array and the general clone() contract forbids
* cross-clone contamination.
*/
clone.Samples = (double[][])Samples.clone();
for (int i = 0; i < Samples.length; i++)
clone.Samples[i] = (double[])Samples[i].clone();
}
return clone;
}
public Object cloneButType(MathType type) throws VisADException {
return new Gridded1DDoubleSet(type, Samples, Length,
DomainCoordinateSystem, SetUnits, SetErrors);
}
}
| true | true | public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
throw new SetException("Gridded1DDoubleinearLatLonSet.doubleToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
| public void doubleToInterp(double[][] value, int[][] indices,
double[][] weights) throws VisADException
{
if (value.length != DomainDimension) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if (indices.length != length) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: indices length " +
indices.length +
" doesn't match value[0] length " +
value[0].length);
}
if (weights.length != length) {
throw new SetException("Gridded1DDoubleSet.doubleToInterp: weights length " +
weights.length +
" doesn't match value[0] length " +
value[0].length);
}
// convert value array to grid coord array
double[][] grid = doubleToGrid(value);
int i, j, k; // loop indices
int lis; // temporary length of is & cs
int length_is; // final length of is & cs, varies by i
int isoff; // offset along one grid dimension
double a, b; // weights along one grid dimension; a + b = 1.0
int[] is; // array of indices, becomes part of indices
double[] cs; // array of coefficients, become part of weights
int base; // base index, as would be returned by valueToIndex
int[] l = new int[ManifoldDimension]; // integer 'factors' of base
// fractions with l; -0.5 <= c <= 0.5
double[] c = new double[ManifoldDimension];
// array of index offsets by grid dimension
int[] off = new int[ManifoldDimension];
off[0] = 1;
for (j=1; j<ManifoldDimension; j++) off[j] = off[j-1] * Lengths[j-1];
for (i=0; i<length; i++) {
// compute length_is, base, l & c
length_is = 1;
if (Double.isNaN(grid[ManifoldDimension-1][i])) {
base = -1;
}
else {
l[ManifoldDimension-1] = (int) (grid[ManifoldDimension-1][i] + 0.5);
// WLH 23 Dec 99
if (l[ManifoldDimension-1] == Lengths[ManifoldDimension-1]) {
l[ManifoldDimension-1]--;
}
c[ManifoldDimension-1] = grid[ManifoldDimension-1][i] -
((double) l[ManifoldDimension-1]);
if (!((l[ManifoldDimension-1] == 0 && c[ManifoldDimension-1] <= 0.0) ||
(l[ManifoldDimension-1] == Lengths[ManifoldDimension-1] - 1 &&
c[ManifoldDimension-1] >= 0.0))) {
// only interp along ManifoldDimension-1
// if between two valid grid coords
length_is *= 2;
}
base = l[ManifoldDimension-1];
}
for (j=ManifoldDimension-2; j>=0 && base>=0; j--) {
if (Double.isNaN(grid[j][i])) {
base = -1;
}
else {
l[j] = (int) (grid[j][i] + 0.5);
if (l[j] == Lengths[j]) l[j]--; // WLH 23 Dec 99
c[j] = grid[j][i] - ((double) l[j]);
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
length_is *= 2;
}
base = l[j] + Lengths[j] * base;
}
}
if (base < 0) {
// value is out of grid so return null
is = null;
cs = null;
}
else {
// create is & cs of proper length, and init first element
is = new int[length_is];
cs = new double[length_is];
is[0] = base;
cs[0] = 1.0f;
lis = 1;
for (j=0; j<ManifoldDimension; j++) {
if (!((l[j] == 0 && c[j] <= 0.0) ||
(l[j] == Lengths[j] - 1 && c[j] >= 0.0))) {
// only interp along dimension j if between two valid grid coords
if (c[j] >= 0.0) {
// grid coord above base
isoff = off[j];
a = 1.0f - c[j];
b = c[j];
}
else {
// grid coord below base
isoff = -off[j];
a = 1.0f + c[j];
b = -c[j];
}
// double is & cs; adjust new offsets; split weights
for (k=0; k<lis; k++) {
is[k+lis] = is[k] + isoff;
cs[k+lis] = cs[k] * b;
cs[k] *= a;
}
lis *= 2;
}
}
}
indices[i] = is;
weights[i] = cs;
}
}
|
diff --git a/src/org/jruby/RubyString.java b/src/org/jruby/RubyString.java
index 81878fd0a..c8bf56feb 100644
--- a/src/org/jruby/RubyString.java
+++ b/src/org/jruby/RubyString.java
@@ -1,3394 +1,3394 @@
/*
**** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2001 Alan Moore <[email protected]>
* Copyright (C) 2001-2002 Benoit Cerrina <[email protected]>
* Copyright (C) 2001-2004 Jan Arne Petersen <[email protected]>
* Copyright (C) 2002-2004 Anders Bengtsson <[email protected]>
* Copyright (C) 2002-2006 Thomas E Enebo <[email protected]>
* Copyright (C) 2004 Stefan Matthias Aust <[email protected]>
* Copyright (C) 2004 David Corbin <[email protected]>
* Copyright (C) 2005 Tim Azzopardi <[email protected]>
* Copyright (C) 2006 Miguel Covarrubias <[email protected]>
* Copyright (C) 2006 Ola Bini <[email protected]>
* Copyright (C) 2007 Nick Sieger <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;
import java.util.Locale;
import org.jruby.anno.JRubyMethod;
import org.jruby.regexp.RegexpMatcher;
import org.jruby.regexp.RegexpPattern;
import org.jruby.runtime.Arity;
import org.jruby.runtime.Block;
import org.jruby.runtime.CallbackFactory;
import org.jruby.runtime.ClassIndex;
import org.jruby.runtime.MethodIndex;
import org.jruby.runtime.ObjectAllocator;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.ByteList;
import org.jruby.util.KCode;
import org.jruby.util.Pack;
import org.jruby.util.Sprintf;
/**
*
* @author jpetersen
*/
public class RubyString extends RubyObject {
// string doesn't have it's own ByteList (values)
private static final int SHARED_BUFFER_STR_F = 1 << 9;
// string has it's own ByteList, but it's pointing to a shared buffer (byte[])
private static final int SHARED_BYTELIST_STR_F = 1 << 10;
// string has either ByteList or buffer shared
private static final int SHARED_STR_F = SHARED_BUFFER_STR_F | SHARED_BYTELIST_STR_F;
private ByteList value;
private static ObjectAllocator STRING_ALLOCATOR = new ObjectAllocator() {
public IRubyObject allocate(Ruby runtime, RubyClass klass) {
RubyString newString = runtime.newString("");
newString.setMetaClass(klass);
return newString;
}
};
public static RubyClass createStringClass(Ruby runtime) {
RubyClass stringClass = runtime.defineClass("String", runtime.getObject(), STRING_ALLOCATOR);
runtime.setString(stringClass);
stringClass.index = ClassIndex.STRING;
stringClass.kindOf = new RubyModule.KindOf() {
public boolean isKindOf(IRubyObject obj, RubyModule type) {
return obj instanceof RubyString;
}
};
CallbackFactory callbackFactory = runtime.callbackFactory(RubyString.class);
stringClass.includeModule(runtime.getComparable());
stringClass.includeModule(runtime.getEnumerable());
stringClass.defineAnnotatedMethods(RubyString.class);
stringClass.dispatcher = callbackFactory.createDispatcher(stringClass);
return stringClass;
}
/** short circuit for String key comparison
*
*/
public final boolean eql(IRubyObject other) {
return other instanceof RubyString && value.equal(((RubyString)other).value);
}
private RubyString(Ruby runtime, RubyClass rubyClass, CharSequence value) {
super(runtime, rubyClass);
assert value != null;
this.value = new ByteList(ByteList.plain(value),false);
}
private RubyString(Ruby runtime, RubyClass rubyClass, byte[] value) {
super(runtime, rubyClass);
assert value != null;
this.value = new ByteList(value);
}
private RubyString(Ruby runtime, RubyClass rubyClass, ByteList value) {
super(runtime, rubyClass);
assert value != null;
this.value = value;
}
private RubyString(Ruby runtime, RubyClass rubyClass, ByteList value, boolean objectSpace) {
super(runtime, rubyClass, objectSpace);
assert value != null;
this.value = value;
}
public int getNativeTypeIndex() {
return ClassIndex.STRING;
}
public Class getJavaClass() {
return String.class;
}
public RubyString convertToString() {
return this;
}
public String toString() {
return value.toString();
}
/** rb_str_dup
*
*/
public final RubyString strDup() {
return strDup(getMetaClass());
}
private final RubyString strDup(RubyClass clazz) {
flags |= SHARED_BYTELIST_STR_F;
RubyString dup = new RubyString(getRuntime(), clazz, value);
dup.flags |= SHARED_BYTELIST_STR_F;
dup.infectBy(this);
return dup;
}
public final RubyString makeShared(int index, int len) {
if (len == 0) return newEmptyString(getRuntime(), getMetaClass());
if ((flags & SHARED_STR_F) == 0) flags |= SHARED_BUFFER_STR_F;
RubyString shared = new RubyString(getRuntime(), getMetaClass(), value.makeShared(index, len));
shared.flags |= SHARED_BUFFER_STR_F;
shared.infectBy(this);
return shared;
}
private final void modifyCheck() {
// TODO: tmp lock here!
testFrozen("string");
if (!isTaint() && getRuntime().getSafeLevel() >= 4) {
throw getRuntime().newSecurityError("Insecure: can't modify string");
}
}
private final void modifyCheck(byte[] b, int len) {
if (value.bytes != b || value.realSize != len) throw getRuntime().newRuntimeError("string modified");
}
private final void frozenCheck() {
if (isFrozen()) throw getRuntime().newRuntimeError("string frozen");
}
/** rb_str_modify
*
*/
public final void modify() {
modifyCheck();
if ((flags & SHARED_STR_F) != 0) {
if ((flags & SHARED_BYTELIST_STR_F) != 0) {
value = value.dup();
} else if ((flags & SHARED_BUFFER_STR_F) != 0) {
value.unshare();
}
flags &= ~SHARED_STR_F;
}
value.invalidate();
}
public final void modify(int length) {
modifyCheck();
if ((flags & SHARED_STR_F) != 0) {
if ((flags & SHARED_BYTELIST_STR_F) != 0) {
value = value.dup(length);
} else if ((flags & SHARED_BUFFER_STR_F) != 0) {
value.unshare(length);
}
flags &= ~SHARED_STR_F;
} else {
value = value.dup(length);
}
value.invalidate();
}
private final void view(ByteList bytes) {
modifyCheck();
value = bytes;
flags &= ~SHARED_STR_F;
}
private final void view(byte[]bytes) {
modifyCheck();
value.replace(bytes);
flags &= ~SHARED_STR_F;
value.invalidate();
}
private final void view(int index, int len) {
modifyCheck();
if ((flags & SHARED_STR_F) != 0) {
if ((flags & SHARED_BYTELIST_STR_F) != 0) {
// if len == 0 then shared empty
value = value.makeShared(index, len);
flags &= ~SHARED_BYTELIST_STR_F;
flags |= SHARED_BUFFER_STR_F;
} else if ((flags & SHARED_BUFFER_STR_F) != 0) {
value.view(index, len);
}
} else {
value.view(index, len);
// FIXME this below is temporary, but its much safer for COW (it prevents not shared Strings with begin != 0)
// this allows now e.g.: ByteList#set not to be begin aware
flags |= SHARED_BUFFER_STR_F;
}
value.invalidate();
}
public static String bytesToString(byte[] bytes, int beg, int len) {
return new String(ByteList.plain(bytes, beg, len));
}
public static String byteListToString(ByteList bytes) {
return bytesToString(bytes.unsafeBytes(), bytes.begin(), bytes.length());
}
public static String bytesToString(byte[] bytes) {
return bytesToString(bytes, 0, bytes.length);
}
public static byte[] stringToBytes(String string) {
return ByteList.plain(string);
}
public static boolean isDigit(int c) {
return c >= '0' && c <= '9';
}
public static boolean isUpper(int c) {
return c >= 'A' && c <= 'Z';
}
public static boolean isLower(int c) {
return c >= 'a' && c <= 'z';
}
public static boolean isLetter(int c) {
return isUpper(c) || isLower(c);
}
public static boolean isAlnum(int c) {
return isUpper(c) || isLower(c) || isDigit(c);
}
public static boolean isPrint(int c) {
return c >= 0x20 && c <= 0x7E;
}
public RubyString asString() {
return this;
}
public IRubyObject checkStringType() {
return this;
}
@JRubyMethod(name = {"to_s", "to_str"})
public IRubyObject to_s() {
if (getMetaClass().getRealClass() != getRuntime().getString()) {
return strDup(getRuntime().getString());
}
return this;
}
/* rb_str_cmp_m */
@JRubyMethod(name = "<=>", required = 1)
public IRubyObject op_cmp(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newFixnum(op_cmp((RubyString)other));
}
return getRuntime().getNil();
}
/**
*
*/
@JRubyMethod(name = "==", required = 1)
public IRubyObject op_equal(IRubyObject other) {
if (this == other) return getRuntime().getTrue();
if (!(other instanceof RubyString)) {
if (!other.respondsTo("to_str")) return getRuntime().getFalse();
Ruby runtime = getRuntime();
return other.callMethod(runtime.getCurrentContext(), MethodIndex.EQUALEQUAL, "==", this).isTrue() ? runtime.getTrue() : runtime.getFalse();
}
return value.equal(((RubyString)other).value) ? getRuntime().getTrue() : getRuntime().getFalse();
}
@JRubyMethod(name = "+", required = 1)
public IRubyObject op_plus(IRubyObject other) {
RubyString str = RubyString.stringValue(other);
ByteList newValue = new ByteList(value.length() + str.value.length());
newValue.append(value);
newValue.append(str.value);
return newString(getRuntime(), newValue).infectBy(other).infectBy(this);
}
@JRubyMethod(name = "*", required = 1)
public IRubyObject op_mul(IRubyObject other) {
RubyInteger otherInteger = (RubyInteger) other.convertToInteger();
long len = otherInteger.getLongValue();
if (len < 0) throw getRuntime().newArgumentError("negative argument");
// we limit to int because ByteBuffer can only allocate int sizes
if (len > 0 && Integer.MAX_VALUE / len < value.length()) {
throw getRuntime().newArgumentError("argument too big");
}
ByteList newBytes = new ByteList(value.length() * (int)len);
for (int i = 0; i < len; i++) {
newBytes.append(value);
}
RubyString newString = newString(getRuntime(), newBytes);
newString.setTaint(isTaint());
return newString;
}
@JRubyMethod(name = "%", required = 1)
public IRubyObject op_format(IRubyObject arg) {
// FIXME: Should we make this work with platform's locale, or continue hardcoding US?
return getRuntime().newString((ByteList)Sprintf.sprintf(Locale.US, value, arg));
}
@JRubyMethod(name = "hash")
public RubyFixnum hash() {
return getRuntime().newFixnum(value.hashCode());
}
public int hashCode() {
return value.hashCode();
}
public boolean equals(Object other) {
if (this == other) return true;
if (other instanceof RubyString) {
RubyString string = (RubyString) other;
if (string.value.equal(value)) return true;
}
return false;
}
/** rb_obj_as_string
*
*/
public static RubyString objAsString(IRubyObject obj) {
if (obj instanceof RubyString) return (RubyString) obj;
IRubyObject str = obj.callMethod(obj.getRuntime().getCurrentContext(), MethodIndex.TO_S, "to_s");
if (!(str instanceof RubyString)) return (RubyString) obj.anyToString();
if (obj.isTaint()) str.setTaint(true);
return (RubyString) str;
}
/** rb_str_cmp
*
*/
public int op_cmp(RubyString other) {
return value.cmp(other.value);
}
/** rb_to_id
*
*/
public String asSymbol() {
// TODO: callers that don't need interned string should be modified
// to call toString, there are just a handful of places this happens.
// this must be interned here - call #toString for non-interned value
return toString().intern();
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
*
*/
public RubyString newString(CharSequence s) {
return new RubyString(getRuntime(), getType(), s);
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
*
*/
public RubyString newString(ByteList s) {
return new RubyString(getRuntime(), getMetaClass(), s);
}
// Methods of the String class (rb_str_*):
/** rb_str_new2
*
*/
public static RubyString newString(Ruby runtime, CharSequence str) {
return new RubyString(runtime, runtime.getString(), str);
}
private static RubyString newEmptyString(Ruby runtime, RubyClass metaClass) {
RubyString empty = new RubyString(runtime, metaClass, ByteList.EMPTY_BYTELIST);
empty.flags |= SHARED_BYTELIST_STR_F;
return empty;
}
public static RubyString newUnicodeString(Ruby runtime, String str) {
try {
return new RubyString(runtime, runtime.getString(), new ByteList(str.getBytes("UTF8"), false));
} catch (UnsupportedEncodingException uee) {
return new RubyString(runtime, runtime.getString(), str);
}
}
public static RubyString newString(Ruby runtime, RubyClass clazz, CharSequence str) {
return new RubyString(runtime, clazz, str);
}
public static RubyString newString(Ruby runtime, byte[] bytes) {
return new RubyString(runtime, runtime.getString(), bytes);
}
public static RubyString newString(Ruby runtime, ByteList bytes) {
return new RubyString(runtime, runtime.getString(), bytes);
}
public static RubyString newStringLight(Ruby runtime, ByteList bytes) {
return new RubyString(runtime, runtime.getString(), bytes, false);
}
public static RubyString newStringShared(Ruby runtime, RubyString orig) {
orig.flags |= SHARED_BYTELIST_STR_F;
RubyString str = new RubyString(runtime, runtime.getString(), orig.value);
str.flags |= SHARED_BYTELIST_STR_F;
return str;
}
public static RubyString newStringShared(Ruby runtime, ByteList bytes) {
return newStringShared(runtime, runtime.getString(), bytes);
}
public static RubyString newStringShared(Ruby runtime, RubyClass clazz, ByteList bytes) {
RubyString str = new RubyString(runtime, clazz, bytes);
str.flags |= SHARED_BYTELIST_STR_F;
return str;
}
public static RubyString newString(Ruby runtime, byte[] bytes, int start, int length) {
byte[] bytes2 = new byte[length];
System.arraycopy(bytes, start, bytes2, 0, length);
return new RubyString(runtime, runtime.getString(), new ByteList(bytes2, false));
}
public IRubyObject doClone(){
return newString(getRuntime(), value.dup());
}
// FIXME: cat methods should be more aware of sharing to prevent unnecessary reallocations in certain situations
public RubyString cat(byte[] str) {
modify();
value.append(str);
return this;
}
public RubyString cat(byte[] str, int beg, int len) {
modify();
value.append(str, beg, len);
return this;
}
public RubyString cat(ByteList str) {
modify();
value.append(str);
return this;
}
public RubyString cat(byte ch) {
modify();
value.append(ch);
return this;
}
/** rb_str_replace_m
*
*/
@JRubyMethod(name = {"replace", "initialize_copy"}, required = 1)
public RubyString replace(IRubyObject other) {
modifyCheck();
if (this == other) return this;
RubyString otherStr = stringValue(other);
flags |= SHARED_BYTELIST_STR_F;
otherStr.flags |= SHARED_BYTELIST_STR_F;
value = otherStr.value;
infectBy(other);
return this;
}
@JRubyMethod(name = "reverse")
public RubyString reverse() {
if (value.length() <= 1) return strDup();
ByteList buf = new ByteList(value.length()+2);
buf.realSize = value.length();
int src = value.length() - 1;
int dst = 0;
while (src >= 0) buf.set(dst++, value.get(src--));
RubyString rev = new RubyString(getRuntime(), getMetaClass(), buf);
rev.infectBy(this);
return rev;
}
@JRubyMethod(name = "reverse!")
public RubyString reverse_bang() {
if (value.length() > 1) {
modify();
for (int i = 0; i < (value.length() / 2); i++) {
byte b = (byte) value.get(i);
value.set(i, value.get(value.length() - i - 1));
value.set(value.length() - i - 1, b);
}
}
return this;
}
/** rb_str_s_new
*
*/
public static RubyString newInstance(IRubyObject recv, IRubyObject[] args, Block block) {
RubyString newString = newString(recv.getRuntime(), "");
newString.setMetaClass((RubyClass) recv);
newString.callInit(args, block);
return newString;
}
@JRubyMethod(name = "initialize", optional = 1, frame = true)
public IRubyObject initialize(IRubyObject[] args, Block unusedBlock) {
if (Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 1) replace(args[0]);
return this;
}
@JRubyMethod(name = "casecmp", required = 1)
public IRubyObject casecmp(IRubyObject other) {
int compare = toString().compareToIgnoreCase(stringValue(other).toString());
return RubyFixnum.newFixnum(getRuntime(), compare == 0 ? 0 : (compare < 0 ? -1 : 1));
}
/** rb_str_match
*
*/
@JRubyMethod(name = "=~", required = 1)
public IRubyObject op_match(IRubyObject other) {
if (other instanceof RubyRegexp) return ((RubyRegexp) other).op_match(this);
if (other instanceof RubyString) {
throw getRuntime().newTypeError("type mismatch: String given");
}
return other.callMethod(getRuntime().getCurrentContext(), "=~", this);
}
/** rb_str_match2
*
*/
@JRubyMethod(name = "~")
public IRubyObject op_match2() {
return RubyRegexp.newRegexp(this, 0, null).op_match2();
}
/**
* String#match(pattern)
*
* @param pattern Regexp or String
*/
@JRubyMethod(name = "match", required = 1)
public IRubyObject match(IRubyObject pattern) {
IRubyObject res = null;
if (pattern instanceof RubyRegexp) {
res = ((RubyRegexp)pattern).search2(toString(), this);
} else if (pattern instanceof RubyString) {
RubyRegexp regexp = RubyRegexp.newRegexp((RubyString) pattern, 0, null);
res = regexp.search2(toString(), this);
} else if (pattern.respondsTo("to_str")) {
// FIXME: is this cast safe?
RubyRegexp regexp = RubyRegexp.newRegexp((RubyString) pattern.callMethod(getRuntime().getCurrentContext(), MethodIndex.TO_STR, "to_str", IRubyObject.NULL_ARRAY), 0, null);
res = regexp.search2(toString(), this);
} else {
// not regexp and not string, can't convert
throw getRuntime().newTypeError("wrong argument type " + pattern.getMetaClass().getBaseName() + " (expected Regexp)");
}
if(res instanceof RubyMatchData) {
((RubyMatchData)res).use();
}
return res;
}
/** rb_str_capitalize
*
*/
@JRubyMethod(name = "capitalize")
public IRubyObject capitalize() {
RubyString str = strDup();
str.capitalize_bang();
return str;
}
/** rb_str_capitalize_bang
*
*/
@JRubyMethod(name = "capitalize!")
public IRubyObject capitalize_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
char c = (char)(buf[s] & 0xff);
if (Character.isLetter(c) && Character.isLowerCase(c)) {
buf[s] = (byte)Character.toUpperCase(c);
modify = true;
}
while (++s < send) {
c = (char)(buf[s] & 0xff);
if (Character.isLetter(c) && Character.isUpperCase(c)) {
buf[s] = (byte)Character.toLowerCase(c);
modify = true;
}
}
if (modify) return this;
return getRuntime().getNil();
}
@JRubyMethod(name = ">=", required = 1)
public IRubyObject op_ge(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) >= 0);
}
return RubyComparable.op_ge(this, other);
}
@JRubyMethod(name = ">", required = 1)
public IRubyObject op_gt(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) > 0);
}
return RubyComparable.op_gt(this, other);
}
@JRubyMethod(name = "<=", required = 1)
public IRubyObject op_le(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) <= 0);
}
return RubyComparable.op_le(this, other);
}
@JRubyMethod(name = "<", required = 1)
public IRubyObject op_lt(IRubyObject other) {
if (other instanceof RubyString) {
return getRuntime().newBoolean(op_cmp((RubyString) other) < 0);
}
return RubyComparable.op_lt(this, other);
}
@JRubyMethod(name = "eql?", required = 1)
public IRubyObject eql_p(IRubyObject other) {
if (!(other instanceof RubyString)) return getRuntime().getFalse();
RubyString otherString = (RubyString)other;
return value.equal(otherString.value) ? getRuntime().getTrue() : getRuntime().getFalse();
}
/** rb_str_upcase
*
*/
@JRubyMethod(name = "upcase")
public RubyString upcase() {
RubyString str = strDup();
str.upcase_bang();
return str;
}
/** rb_str_upcase_bang
*
*/
@JRubyMethod(name = "upcase!")
public IRubyObject upcase_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte []buf = value.bytes;
boolean modify = false;
while (s < send) {
char c = (char)(buf[s] & 0xff);
if (c >= 'a' && c<= 'z') {
buf[s] = (byte)(c-32);
modify = true;
}
s++;
}
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_downcase
*
*/
@JRubyMethod(name = "downcase")
public RubyString downcase() {
RubyString str = strDup();
str.downcase_bang();
return str;
}
/** rb_str_downcase_bang
*
*/
@JRubyMethod(name = "downcase!")
public IRubyObject downcase_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte []buf = value.bytes;
boolean modify = false;
while (s < send) {
char c = (char)(buf[s] & 0xff);
if (c >= 'A' && c <= 'Z') {
buf[s] = (byte)(c+32);
modify = true;
}
s++;
}
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_swapcase
*
*/
@JRubyMethod(name = "swapcase")
public RubyString swapcase() {
RubyString str = strDup();
str.swapcase_bang();
return str;
}
/** rb_str_swapcase_bang
*
*/
@JRubyMethod(name = "swapcase!")
public IRubyObject swapcase_bang() {
if (value.realSize == 0) return getRuntime().getNil();
modify();
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
while (s < send) {
char c = (char)(buf[s] & 0xff);
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
buf[s] = (byte)Character.toLowerCase(c);
modify = true;
} else {
buf[s] = (byte)Character.toUpperCase(c);
modify = true;
}
}
s++;
}
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_dump
*
*/
@JRubyMethod(name = "dump")
public IRubyObject dump() {
return inspect();
}
@JRubyMethod(name = "insert", required = 2)
public IRubyObject insert(IRubyObject indexArg, IRubyObject stringArg) {
int index = (int) indexArg.convertToInteger().getLongValue();
if (index < 0) index += value.length() + 1;
if (index < 0 || index > value.length()) {
throw getRuntime().newIndexError("index " + index + " out of range");
}
modify();
ByteList insert = ((RubyString)stringArg.convertToString()).value;
value.unsafeReplace(index, 0, insert);
return this;
}
/** rb_str_inspect
*
*/
@JRubyMethod(name = "inspect")
public IRubyObject inspect() {
final int length = value.length();
Ruby runtime = getRuntime();
ByteList sb = new ByteList(length + 2 + length / 100);
sb.append('\"');
// FIXME: This may not be unicode-safe
for (int i = 0; i < length; i++) {
int c = value.get(i) & 0xFF;
if (isAlnum(c)) {
sb.append((char)c);
} else if (runtime.getKCode() == KCode.UTF8 && c == 0xEF) {
// don't escape encoded UTF8 characters, leave them as bytes
// append byte order mark plus two character bytes
sb.append((char)c);
sb.append((char)(value.get(++i) & 0xFF));
sb.append((char)(value.get(++i) & 0xFF));
} else if (c == '\"' || c == '\\') {
sb.append('\\').append((char)c);
} else if (c == '#' && isEVStr(i, length)) {
sb.append('\\').append((char)c);
} else if (isPrint(c)) {
sb.append((char)c);
} else if (c == '\n') {
sb.append('\\').append('n');
} else if (c == '\r') {
sb.append('\\').append('r');
} else if (c == '\t') {
sb.append('\\').append('t');
} else if (c == '\f') {
sb.append('\\').append('f');
} else if (c == '\u000B') {
sb.append('\\').append('v');
} else if (c == '\u0007') {
sb.append('\\').append('a');
} else if (c == '\u001B') {
sb.append('\\').append('e');
} else {
sb.append(ByteList.plain(Sprintf.sprintf(runtime,"\\%.3o",c)));
}
}
sb.append('\"');
return getRuntime().newString(sb);
}
private boolean isEVStr(int i, int length) {
if (i+1 >= length) return false;
int c = value.get(i+1) & 0xFF;
return c == '$' || c == '@' || c == '{';
}
/** rb_str_length
*
*/
@JRubyMethod(name = {"length", "size"})
public RubyFixnum length() {
return getRuntime().newFixnum(value.length());
}
/** rb_str_empty
*
*/
@JRubyMethod(name = "empty?")
public RubyBoolean empty_p() {
return isEmpty() ? getRuntime().getTrue() : getRuntime().getFalse();
}
private boolean isEmpty() {
return value.length() == 0;
}
/** rb_str_append
*
*/
public RubyString append(IRubyObject other) {
infectBy(other);
return cat(stringValue(other).value);
}
/** rb_str_concat
*
*/
@JRubyMethod(name = {"concat", "<<"}, required = 1)
public RubyString concat(IRubyObject other) {
if (other instanceof RubyFixnum) {
long value = ((RubyFixnum) other).getLongValue();
if (value >= 0 && value < 256) return cat((byte) value);
}
return append(other);
}
/** rb_str_crypt
*
*/
@JRubyMethod(name = "crypt", required = 1)
public RubyString crypt(IRubyObject other) {
String salt = stringValue(other).getValue().toString();
if (salt.length() < 2) {
throw getRuntime().newArgumentError("salt too short(need >=2 bytes)");
}
salt = salt.substring(0, 2);
return getRuntime().newString(JavaCrypt.crypt(salt, this.toString()));
}
public static class JavaCrypt {
private static java.util.Random r_gen = new java.util.Random();
private static final char theBaseSalts[] = {
'a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'0','1','2','3','4','5','6','7','8','9','/','.'};
private static final int ITERATIONS = 16;
private static final int con_salt[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12,
0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22,
0x23, 0x24, 0x25, 0x20, 0x21, 0x22, 0x23, 0x24,
0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C,
0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34,
0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C,
0x3D, 0x3E, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00,
};
private static final boolean shifts2[] = {
false, false, true, true, true, true, true, true,
false, true, true, true, true, true, true, false };
private static final int skb[][] = {
{
/* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x00000010, 0x20000000, 0x20000010,
0x00010000, 0x00010010, 0x20010000, 0x20010010,
0x00000800, 0x00000810, 0x20000800, 0x20000810,
0x00010800, 0x00010810, 0x20010800, 0x20010810,
0x00000020, 0x00000030, 0x20000020, 0x20000030,
0x00010020, 0x00010030, 0x20010020, 0x20010030,
0x00000820, 0x00000830, 0x20000820, 0x20000830,
0x00010820, 0x00010830, 0x20010820, 0x20010830,
0x00080000, 0x00080010, 0x20080000, 0x20080010,
0x00090000, 0x00090010, 0x20090000, 0x20090010,
0x00080800, 0x00080810, 0x20080800, 0x20080810,
0x00090800, 0x00090810, 0x20090800, 0x20090810,
0x00080020, 0x00080030, 0x20080020, 0x20080030,
0x00090020, 0x00090030, 0x20090020, 0x20090030,
0x00080820, 0x00080830, 0x20080820, 0x20080830,
0x00090820, 0x00090830, 0x20090820, 0x20090830,
},{
/* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */
0x00000000, 0x02000000, 0x00002000, 0x02002000,
0x00200000, 0x02200000, 0x00202000, 0x02202000,
0x00000004, 0x02000004, 0x00002004, 0x02002004,
0x00200004, 0x02200004, 0x00202004, 0x02202004,
0x00000400, 0x02000400, 0x00002400, 0x02002400,
0x00200400, 0x02200400, 0x00202400, 0x02202400,
0x00000404, 0x02000404, 0x00002404, 0x02002404,
0x00200404, 0x02200404, 0x00202404, 0x02202404,
0x10000000, 0x12000000, 0x10002000, 0x12002000,
0x10200000, 0x12200000, 0x10202000, 0x12202000,
0x10000004, 0x12000004, 0x10002004, 0x12002004,
0x10200004, 0x12200004, 0x10202004, 0x12202004,
0x10000400, 0x12000400, 0x10002400, 0x12002400,
0x10200400, 0x12200400, 0x10202400, 0x12202400,
0x10000404, 0x12000404, 0x10002404, 0x12002404,
0x10200404, 0x12200404, 0x10202404, 0x12202404,
},{
/* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */
0x00000000, 0x00000001, 0x00040000, 0x00040001,
0x01000000, 0x01000001, 0x01040000, 0x01040001,
0x00000002, 0x00000003, 0x00040002, 0x00040003,
0x01000002, 0x01000003, 0x01040002, 0x01040003,
0x00000200, 0x00000201, 0x00040200, 0x00040201,
0x01000200, 0x01000201, 0x01040200, 0x01040201,
0x00000202, 0x00000203, 0x00040202, 0x00040203,
0x01000202, 0x01000203, 0x01040202, 0x01040203,
0x08000000, 0x08000001, 0x08040000, 0x08040001,
0x09000000, 0x09000001, 0x09040000, 0x09040001,
0x08000002, 0x08000003, 0x08040002, 0x08040003,
0x09000002, 0x09000003, 0x09040002, 0x09040003,
0x08000200, 0x08000201, 0x08040200, 0x08040201,
0x09000200, 0x09000201, 0x09040200, 0x09040201,
0x08000202, 0x08000203, 0x08040202, 0x08040203,
0x09000202, 0x09000203, 0x09040202, 0x09040203,
},{
/* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */
0x00000000, 0x00100000, 0x00000100, 0x00100100,
0x00000008, 0x00100008, 0x00000108, 0x00100108,
0x00001000, 0x00101000, 0x00001100, 0x00101100,
0x00001008, 0x00101008, 0x00001108, 0x00101108,
0x04000000, 0x04100000, 0x04000100, 0x04100100,
0x04000008, 0x04100008, 0x04000108, 0x04100108,
0x04001000, 0x04101000, 0x04001100, 0x04101100,
0x04001008, 0x04101008, 0x04001108, 0x04101108,
0x00020000, 0x00120000, 0x00020100, 0x00120100,
0x00020008, 0x00120008, 0x00020108, 0x00120108,
0x00021000, 0x00121000, 0x00021100, 0x00121100,
0x00021008, 0x00121008, 0x00021108, 0x00121108,
0x04020000, 0x04120000, 0x04020100, 0x04120100,
0x04020008, 0x04120008, 0x04020108, 0x04120108,
0x04021000, 0x04121000, 0x04021100, 0x04121100,
0x04021008, 0x04121008, 0x04021108, 0x04121108,
},{
/* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */
0x00000000, 0x10000000, 0x00010000, 0x10010000,
0x00000004, 0x10000004, 0x00010004, 0x10010004,
0x20000000, 0x30000000, 0x20010000, 0x30010000,
0x20000004, 0x30000004, 0x20010004, 0x30010004,
0x00100000, 0x10100000, 0x00110000, 0x10110000,
0x00100004, 0x10100004, 0x00110004, 0x10110004,
0x20100000, 0x30100000, 0x20110000, 0x30110000,
0x20100004, 0x30100004, 0x20110004, 0x30110004,
0x00001000, 0x10001000, 0x00011000, 0x10011000,
0x00001004, 0x10001004, 0x00011004, 0x10011004,
0x20001000, 0x30001000, 0x20011000, 0x30011000,
0x20001004, 0x30001004, 0x20011004, 0x30011004,
0x00101000, 0x10101000, 0x00111000, 0x10111000,
0x00101004, 0x10101004, 0x00111004, 0x10111004,
0x20101000, 0x30101000, 0x20111000, 0x30111000,
0x20101004, 0x30101004, 0x20111004, 0x30111004,
},{
/* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */
0x00000000, 0x08000000, 0x00000008, 0x08000008,
0x00000400, 0x08000400, 0x00000408, 0x08000408,
0x00020000, 0x08020000, 0x00020008, 0x08020008,
0x00020400, 0x08020400, 0x00020408, 0x08020408,
0x00000001, 0x08000001, 0x00000009, 0x08000009,
0x00000401, 0x08000401, 0x00000409, 0x08000409,
0x00020001, 0x08020001, 0x00020009, 0x08020009,
0x00020401, 0x08020401, 0x00020409, 0x08020409,
0x02000000, 0x0A000000, 0x02000008, 0x0A000008,
0x02000400, 0x0A000400, 0x02000408, 0x0A000408,
0x02020000, 0x0A020000, 0x02020008, 0x0A020008,
0x02020400, 0x0A020400, 0x02020408, 0x0A020408,
0x02000001, 0x0A000001, 0x02000009, 0x0A000009,
0x02000401, 0x0A000401, 0x02000409, 0x0A000409,
0x02020001, 0x0A020001, 0x02020009, 0x0A020009,
0x02020401, 0x0A020401, 0x02020409, 0x0A020409,
},{
/* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */
0x00000000, 0x00000100, 0x00080000, 0x00080100,
0x01000000, 0x01000100, 0x01080000, 0x01080100,
0x00000010, 0x00000110, 0x00080010, 0x00080110,
0x01000010, 0x01000110, 0x01080010, 0x01080110,
0x00200000, 0x00200100, 0x00280000, 0x00280100,
0x01200000, 0x01200100, 0x01280000, 0x01280100,
0x00200010, 0x00200110, 0x00280010, 0x00280110,
0x01200010, 0x01200110, 0x01280010, 0x01280110,
0x00000200, 0x00000300, 0x00080200, 0x00080300,
0x01000200, 0x01000300, 0x01080200, 0x01080300,
0x00000210, 0x00000310, 0x00080210, 0x00080310,
0x01000210, 0x01000310, 0x01080210, 0x01080310,
0x00200200, 0x00200300, 0x00280200, 0x00280300,
0x01200200, 0x01200300, 0x01280200, 0x01280300,
0x00200210, 0x00200310, 0x00280210, 0x00280310,
0x01200210, 0x01200310, 0x01280210, 0x01280310,
},{
/* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */
0x00000000, 0x04000000, 0x00040000, 0x04040000,
0x00000002, 0x04000002, 0x00040002, 0x04040002,
0x00002000, 0x04002000, 0x00042000, 0x04042000,
0x00002002, 0x04002002, 0x00042002, 0x04042002,
0x00000020, 0x04000020, 0x00040020, 0x04040020,
0x00000022, 0x04000022, 0x00040022, 0x04040022,
0x00002020, 0x04002020, 0x00042020, 0x04042020,
0x00002022, 0x04002022, 0x00042022, 0x04042022,
0x00000800, 0x04000800, 0x00040800, 0x04040800,
0x00000802, 0x04000802, 0x00040802, 0x04040802,
0x00002800, 0x04002800, 0x00042800, 0x04042800,
0x00002802, 0x04002802, 0x00042802, 0x04042802,
0x00000820, 0x04000820, 0x00040820, 0x04040820,
0x00000822, 0x04000822, 0x00040822, 0x04040822,
0x00002820, 0x04002820, 0x00042820, 0x04042820,
0x00002822, 0x04002822, 0x00042822, 0x04042822,
}
};
private static final int SPtrans[][] = {
{
/* nibble 0 */
0x00820200, 0x00020000, 0x80800000, 0x80820200,
0x00800000, 0x80020200, 0x80020000, 0x80800000,
0x80020200, 0x00820200, 0x00820000, 0x80000200,
0x80800200, 0x00800000, 0x00000000, 0x80020000,
0x00020000, 0x80000000, 0x00800200, 0x00020200,
0x80820200, 0x00820000, 0x80000200, 0x00800200,
0x80000000, 0x00000200, 0x00020200, 0x80820000,
0x00000200, 0x80800200, 0x80820000, 0x00000000,
0x00000000, 0x80820200, 0x00800200, 0x80020000,
0x00820200, 0x00020000, 0x80000200, 0x00800200,
0x80820000, 0x00000200, 0x00020200, 0x80800000,
0x80020200, 0x80000000, 0x80800000, 0x00820000,
0x80820200, 0x00020200, 0x00820000, 0x80800200,
0x00800000, 0x80000200, 0x80020000, 0x00000000,
0x00020000, 0x00800000, 0x80800200, 0x00820200,
0x80000000, 0x80820000, 0x00000200, 0x80020200,
},{
/* nibble 1 */
0x10042004, 0x00000000, 0x00042000, 0x10040000,
0x10000004, 0x00002004, 0x10002000, 0x00042000,
0x00002000, 0x10040004, 0x00000004, 0x10002000,
0x00040004, 0x10042000, 0x10040000, 0x00000004,
0x00040000, 0x10002004, 0x10040004, 0x00002000,
0x00042004, 0x10000000, 0x00000000, 0x00040004,
0x10002004, 0x00042004, 0x10042000, 0x10000004,
0x10000000, 0x00040000, 0x00002004, 0x10042004,
0x00040004, 0x10042000, 0x10002000, 0x00042004,
0x10042004, 0x00040004, 0x10000004, 0x00000000,
0x10000000, 0x00002004, 0x00040000, 0x10040004,
0x00002000, 0x10000000, 0x00042004, 0x10002004,
0x10042000, 0x00002000, 0x00000000, 0x10000004,
0x00000004, 0x10042004, 0x00042000, 0x10040000,
0x10040004, 0x00040000, 0x00002004, 0x10002000,
0x10002004, 0x00000004, 0x10040000, 0x00042000,
},{
/* nibble 2 */
0x41000000, 0x01010040, 0x00000040, 0x41000040,
0x40010000, 0x01000000, 0x41000040, 0x00010040,
0x01000040, 0x00010000, 0x01010000, 0x40000000,
0x41010040, 0x40000040, 0x40000000, 0x41010000,
0x00000000, 0x40010000, 0x01010040, 0x00000040,
0x40000040, 0x41010040, 0x00010000, 0x41000000,
0x41010000, 0x01000040, 0x40010040, 0x01010000,
0x00010040, 0x00000000, 0x01000000, 0x40010040,
0x01010040, 0x00000040, 0x40000000, 0x00010000,
0x40000040, 0x40010000, 0x01010000, 0x41000040,
0x00000000, 0x01010040, 0x00010040, 0x41010000,
0x40010000, 0x01000000, 0x41010040, 0x40000000,
0x40010040, 0x41000000, 0x01000000, 0x41010040,
0x00010000, 0x01000040, 0x41000040, 0x00010040,
0x01000040, 0x00000000, 0x41010000, 0x40000040,
0x41000000, 0x40010040, 0x00000040, 0x01010000,
},{
/* nibble 3 */
0x00100402, 0x04000400, 0x00000002, 0x04100402,
0x00000000, 0x04100000, 0x04000402, 0x00100002,
0x04100400, 0x04000002, 0x04000000, 0x00000402,
0x04000002, 0x00100402, 0x00100000, 0x04000000,
0x04100002, 0x00100400, 0x00000400, 0x00000002,
0x00100400, 0x04000402, 0x04100000, 0x00000400,
0x00000402, 0x00000000, 0x00100002, 0x04100400,
0x04000400, 0x04100002, 0x04100402, 0x00100000,
0x04100002, 0x00000402, 0x00100000, 0x04000002,
0x00100400, 0x04000400, 0x00000002, 0x04100000,
0x04000402, 0x00000000, 0x00000400, 0x00100002,
0x00000000, 0x04100002, 0x04100400, 0x00000400,
0x04000000, 0x04100402, 0x00100402, 0x00100000,
0x04100402, 0x00000002, 0x04000400, 0x00100402,
0x00100002, 0x00100400, 0x04100000, 0x04000402,
0x00000402, 0x04000000, 0x04000002, 0x04100400,
},{
/* nibble 4 */
0x02000000, 0x00004000, 0x00000100, 0x02004108,
0x02004008, 0x02000100, 0x00004108, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x00004100,
0x02000108, 0x02004008, 0x02004100, 0x00000000,
0x00004100, 0x02000000, 0x00004008, 0x00000108,
0x02000100, 0x00004108, 0x00000000, 0x02000008,
0x00000008, 0x02000108, 0x02004108, 0x00004008,
0x02004000, 0x00000100, 0x00000108, 0x02004100,
0x02004100, 0x02000108, 0x00004008, 0x02004000,
0x00004000, 0x00000008, 0x02000008, 0x02000100,
0x02000000, 0x00004100, 0x02004108, 0x00000000,
0x00004108, 0x02000000, 0x00000100, 0x00004008,
0x02000108, 0x00000100, 0x00000000, 0x02004108,
0x02004008, 0x02004100, 0x00000108, 0x00004000,
0x00004100, 0x02004008, 0x02000100, 0x00000108,
0x00000008, 0x00004108, 0x02004000, 0x02000008,
},{
/* nibble 5 */
0x20000010, 0x00080010, 0x00000000, 0x20080800,
0x00080010, 0x00000800, 0x20000810, 0x00080000,
0x00000810, 0x20080810, 0x00080800, 0x20000000,
0x20000800, 0x20000010, 0x20080000, 0x00080810,
0x00080000, 0x20000810, 0x20080010, 0x00000000,
0x00000800, 0x00000010, 0x20080800, 0x20080010,
0x20080810, 0x20080000, 0x20000000, 0x00000810,
0x00000010, 0x00080800, 0x00080810, 0x20000800,
0x00000810, 0x20000000, 0x20000800, 0x00080810,
0x20080800, 0x00080010, 0x00000000, 0x20000800,
0x20000000, 0x00000800, 0x20080010, 0x00080000,
0x00080010, 0x20080810, 0x00080800, 0x00000010,
0x20080810, 0x00080800, 0x00080000, 0x20000810,
0x20000010, 0x20080000, 0x00080810, 0x00000000,
0x00000800, 0x20000010, 0x20000810, 0x20080800,
0x20080000, 0x00000810, 0x00000010, 0x20080010,
},{
/* nibble 6 */
0x00001000, 0x00000080, 0x00400080, 0x00400001,
0x00401081, 0x00001001, 0x00001080, 0x00000000,
0x00400000, 0x00400081, 0x00000081, 0x00401000,
0x00000001, 0x00401080, 0x00401000, 0x00000081,
0x00400081, 0x00001000, 0x00001001, 0x00401081,
0x00000000, 0x00400080, 0x00400001, 0x00001080,
0x00401001, 0x00001081, 0x00401080, 0x00000001,
0x00001081, 0x00401001, 0x00000080, 0x00400000,
0x00001081, 0x00401000, 0x00401001, 0x00000081,
0x00001000, 0x00000080, 0x00400000, 0x00401001,
0x00400081, 0x00001081, 0x00001080, 0x00000000,
0x00000080, 0x00400001, 0x00000001, 0x00400080,
0x00000000, 0x00400081, 0x00400080, 0x00001080,
0x00000081, 0x00001000, 0x00401081, 0x00400000,
0x00401080, 0x00000001, 0x00001001, 0x00401081,
0x00400001, 0x00401080, 0x00401000, 0x00001001,
},{
/* nibble 7 */
0x08200020, 0x08208000, 0x00008020, 0x00000000,
0x08008000, 0x00200020, 0x08200000, 0x08208020,
0x00000020, 0x08000000, 0x00208000, 0x00008020,
0x00208020, 0x08008020, 0x08000020, 0x08200000,
0x00008000, 0x00208020, 0x00200020, 0x08008000,
0x08208020, 0x08000020, 0x00000000, 0x00208000,
0x08000000, 0x00200000, 0x08008020, 0x08200020,
0x00200000, 0x00008000, 0x08208000, 0x00000020,
0x00200000, 0x00008000, 0x08000020, 0x08208020,
0x00008020, 0x08000000, 0x00000000, 0x00208000,
0x08200020, 0x08008020, 0x08008000, 0x00200020,
0x08208000, 0x00000020, 0x00200020, 0x08008000,
0x08208020, 0x00200000, 0x08200000, 0x08000020,
0x00208000, 0x00008020, 0x08008020, 0x08200000,
0x00000020, 0x08208000, 0x00208020, 0x00000000,
0x08000000, 0x08200020, 0x00008000, 0x00208020
}
};
private static final int cov_2char[] = {
0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35,
0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44,
0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C,
0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62,
0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A,
0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72,
0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
};
private static final int byteToUnsigned(byte b) {
return b & 0xFF;
}
private static int fourBytesToInt(byte b[], int offset) {
int value;
value = byteToUnsigned(b[offset++]);
value |= (byteToUnsigned(b[offset++]) << 8);
value |= (byteToUnsigned(b[offset++]) << 16);
value |= (byteToUnsigned(b[offset++]) << 24);
return(value);
}
private static final void intToFourBytes(int iValue, byte b[], int offset) {
b[offset++] = (byte)((iValue) & 0xff);
b[offset++] = (byte)((iValue >>> 8 ) & 0xff);
b[offset++] = (byte)((iValue >>> 16) & 0xff);
b[offset++] = (byte)((iValue >>> 24) & 0xff);
}
private static final void PERM_OP(int a, int b, int n, int m, int results[]) {
int t;
t = ((a >>> n) ^ b) & m;
a ^= t << n;
b ^= t;
results[0] = a;
results[1] = b;
}
private static final int HPERM_OP(int a, int n, int m) {
int t;
t = ((a << (16 - n)) ^ a) & m;
a = a ^ t ^ (t >>> (16 - n));
return a;
}
private static int [] des_set_key(byte key[]) {
int schedule[] = new int[ITERATIONS * 2];
int c = fourBytesToInt(key, 0);
int d = fourBytesToInt(key, 4);
int results[] = new int[2];
PERM_OP(d, c, 4, 0x0f0f0f0f, results);
d = results[0]; c = results[1];
c = HPERM_OP(c, -2, 0xcccc0000);
d = HPERM_OP(d, -2, 0xcccc0000);
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
PERM_OP(c, d, 8, 0x00ff00ff, results);
c = results[0]; d = results[1];
PERM_OP(d, c, 1, 0x55555555, results);
d = results[0]; c = results[1];
d = (((d & 0x000000ff) << 16) | (d & 0x0000ff00) |
((d & 0x00ff0000) >>> 16) | ((c & 0xf0000000) >>> 4));
c &= 0x0fffffff;
int s, t;
int j = 0;
for(int i = 0; i < ITERATIONS; i ++) {
if(shifts2[i]) {
c = (c >>> 2) | (c << 26);
d = (d >>> 2) | (d << 26);
} else {
c = (c >>> 1) | (c << 27);
d = (d >>> 1) | (d << 27);
}
c &= 0x0fffffff;
d &= 0x0fffffff;
s = skb[0][ (c ) & 0x3f ]|
skb[1][((c >>> 6) & 0x03) | ((c >>> 7) & 0x3c)]|
skb[2][((c >>> 13) & 0x0f) | ((c >>> 14) & 0x30)]|
skb[3][((c >>> 20) & 0x01) | ((c >>> 21) & 0x06) |
((c >>> 22) & 0x38)];
t = skb[4][ (d ) & 0x3f ]|
skb[5][((d >>> 7) & 0x03) | ((d >>> 8) & 0x3c)]|
skb[6][ (d >>>15) & 0x3f ]|
skb[7][((d >>>21) & 0x0f) | ((d >>> 22) & 0x30)];
schedule[j++] = ((t << 16) | (s & 0x0000ffff)) & 0xffffffff;
s = ((s >>> 16) | (t & 0xffff0000));
s = (s << 4) | (s >>> 28);
schedule[j++] = s & 0xffffffff;
}
return(schedule);
}
private static final int D_ENCRYPT(int L, int R, int S, int E0, int E1, int s[]) {
int t, u, v;
v = R ^ (R >>> 16);
u = v & E0;
v = v & E1;
u = (u ^ (u << 16)) ^ R ^ s[S];
t = (v ^ (v << 16)) ^ R ^ s[S + 1];
t = (t >>> 4) | (t << 28);
L ^= SPtrans[1][(t ) & 0x3f] |
SPtrans[3][(t >>> 8) & 0x3f] |
SPtrans[5][(t >>> 16) & 0x3f] |
SPtrans[7][(t >>> 24) & 0x3f] |
SPtrans[0][(u ) & 0x3f] |
SPtrans[2][(u >>> 8) & 0x3f] |
SPtrans[4][(u >>> 16) & 0x3f] |
SPtrans[6][(u >>> 24) & 0x3f];
return(L);
}
private static final int [] body(int schedule[], int Eswap0, int Eswap1) {
int left = 0;
int right = 0;
int t = 0;
for(int j = 0; j < 25; j ++) {
for(int i = 0; i < ITERATIONS * 2; i += 4) {
left = D_ENCRYPT(left, right, i, Eswap0, Eswap1, schedule);
right = D_ENCRYPT(right, left, i + 2, Eswap0, Eswap1, schedule);
}
t = left;
left = right;
right = t;
}
t = right;
right = (left >>> 1) | (left << 31);
left = (t >>> 1) | (t << 31);
left &= 0xffffffff;
right &= 0xffffffff;
int results[] = new int[2];
PERM_OP(right, left, 1, 0x55555555, results);
right = results[0]; left = results[1];
PERM_OP(left, right, 8, 0x00ff00ff, results);
left = results[0]; right = results[1];
PERM_OP(right, left, 2, 0x33333333, results);
right = results[0]; left = results[1];
PERM_OP(left, right, 16, 0x0000ffff, results);
left = results[0]; right = results[1];
PERM_OP(right, left, 4, 0x0f0f0f0f, results);
right = results[0]; left = results[1];
int out[] = new int[2];
out[0] = left; out[1] = right;
return(out);
}
public static final String crypt(String salt, String original) {
while(salt.length() < 2)
salt += getSaltChar();
StringBuffer buffer = new StringBuffer(" ");
char charZero = salt.charAt(0);
char charOne = salt.charAt(1);
buffer.setCharAt(0, charZero);
buffer.setCharAt(1, charOne);
int Eswap0 = con_salt[(int)charZero];
int Eswap1 = con_salt[(int)charOne] << 4;
byte key[] = new byte[8];
for(int i = 0; i < key.length; i ++) {
key[i] = (byte)0;
}
for(int i = 0; i < key.length && i < original.length(); i ++) {
int iChar = (int)original.charAt(i);
key[i] = (byte)(iChar << 1);
}
int schedule[] = des_set_key(key);
int out[] = body(schedule, Eswap0, Eswap1);
byte b[] = new byte[9];
intToFourBytes(out[0], b, 0);
intToFourBytes(out[1], b, 4);
b[8] = 0;
for(int i = 2, y = 0, u = 0x80; i < 13; i ++) {
for(int j = 0, c = 0; j < 6; j ++) {
c <<= 1;
if(((int)b[y] & u) != 0)
c |= 1;
u >>>= 1;
if(u == 0) {
y++;
u = 0x80;
}
buffer.setCharAt(i, (char)cov_2char[c]);
}
}
return(buffer.toString());
}
private static String getSaltChar() {
return JavaCrypt.getSaltChar(1);
}
private static String getSaltChar(int amount) {
StringBuffer sb = new StringBuffer();
for(int i=amount;i>0;i--) {
sb.append(theBaseSalts[(Math.abs(r_gen.nextInt())%64)]);
}
return sb.toString();
}
public static boolean check(String theClear,String theCrypt) {
String theTest = JavaCrypt.crypt(theCrypt.substring(0,2),theClear);
return theTest.equals(theCrypt);
}
public static String crypt(String theClear) {
return JavaCrypt.crypt(getSaltChar(2),theClear);
}
}
/* RubyString aka rb_string_value */
public static RubyString stringValue(IRubyObject object) {
return (RubyString) (object instanceof RubyString ? object :
object.convertToString());
}
/** rb_str_sub
*
*/
@JRubyMethod(name = "sub", required = 1, optional = 1)
public IRubyObject sub(IRubyObject[] args, Block block) {
RubyString str = strDup();
str.sub_bang(args, block);
return str;
}
/** rb_str_sub_bang
*
*/
@JRubyMethod(name = "sub!", required = 1, optional = 1)
public IRubyObject sub_bang(IRubyObject[] args, Block block) {
boolean iter = false;
IRubyObject repl;
Ruby runtime = getRuntime();
boolean tainted = false;
if (args.length == 1 && block.isGiven()) {
iter = true;
repl = runtime.getNil();
} else if (args.length == 2) {
repl = args[1].convertToString();
tainted = repl.isTaint();
} else {
throw runtime.newArgumentError("wrong number of arguments (" + args.length + "for 2)");
}
RubyRegexp pattern = getPat(args[0], true);
boolean utf8 = pattern.getCode() == KCode.UTF8;
RegexpPattern pat = pattern.getPattern();
String str = toString(utf8);
RegexpMatcher mat = pat.matcher(str);
if (mat.find()) {
ThreadContext context = runtime.getCurrentContext();
RubyMatchData md = matchdata(runtime, str, mat, utf8);
context.getCurrentFrame().setBackRef(md);
if (iter) {
// FIXME: I don't like this setting into the frame directly, but it's necessary since blocks dupe the frame
block.getFrame().setBackRef(md);
int len = value.realSize;
byte[]b = value.bytes;
repl = objAsString(block.yield(context, substr(runtime, str, mat.start(0), mat.length(0), utf8)));
modifyCheck(b, len);
frozenCheck();
} else {
repl = pattern.regsub(repl, this, md);
}
if (repl.isTaint()) tainted = true;
int startZ = mat.start(0);
if(utf8) {
try {
startZ = str.substring(0, startZ).getBytes("UTF8").length;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int plen = mat.end(0) - startZ;
if (utf8) {
try {
plen = mat.group(0).getBytes("UTF8").length;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ByteList replValue = ((RubyString)repl).value;
if (replValue.realSize > plen) { // this might be smarter by being real bytes length aware
modify(value.realSize + replValue.realSize - plen);
} else {
modify();
}
if (replValue.realSize != plen && (value.realSize - startZ - plen) > 0) {
int valueOldStart = value.begin + startZ + plen;
int valueNewStart = value.begin + startZ + replValue.realSize;
int valueLength = value.realSize - startZ - plen;
System.arraycopy(value.bytes, valueOldStart, value.bytes, valueNewStart, valueLength);
}
System.arraycopy(replValue.bytes, replValue.begin, value.bytes, value.begin + startZ, replValue.realSize);
value.realSize += replValue.realSize - plen;
if (tainted) setTaint(true);
return this;
}
return runtime.getNil();
}
/** rb_str_gsub
*
*/
@JRubyMethod(name = "gsub", required = 1, optional = 1, frame = true)
public IRubyObject gsub(IRubyObject[] args, Block block) {
return gsub(args, block, false);
}
/** rb_str_gsub_bang
*
*/
@JRubyMethod(name = "gsub!", required = 1, optional = 1, frame = true)
public IRubyObject gsub_bang(IRubyObject[] args, Block block) {
return gsub(args, block, true);
}
private final IRubyObject gsub(IRubyObject[] args, Block block, boolean bang) {
boolean iter = false;
IRubyObject repl;
Ruby runtime = getRuntime();
boolean tainted = false;
if (args.length == 1 && block.isGiven()) {
iter = true;
repl = runtime.getNil();
} else if (args.length == 2) {
repl = args[1].convertToString();
tainted = repl.isTaint();
} else {
throw runtime.newArgumentError("wrong number of arguments (" + args.length + "for 2)");
}
RubyRegexp pattern = getPat(args[0], true);
boolean utf8 = pattern.getCode() == KCode.UTF8;
RegexpPattern pat = pattern.getPattern();
String str = toString(utf8);
RegexpMatcher mat = pat.matcher(str);
boolean found = mat.find();
if (!found) {
if (bang) return runtime.getNil();
return strDup();
}
int blen = value.realSize + 30;
ByteList dest = new ByteList(blen);
dest.realSize = blen;
int buf = 0, bp = 0;
int cp = value.begin;
// for modifyCheck
byte [] sb = value.bytes;
int slen = value.realSize;
RubyString val;
ThreadContext context = runtime.getCurrentContext();
int offset = 0;
// tmp lock
RubyMatchData md = null;
while (found) {
if (iter) {
md = matchdata(runtime, str, mat, utf8);
context.getPreviousFrame().setBackRef(md);
// FIXME: I don't like this setting into the frame directly, but it's necessary since blocks dupe the
block.getFrame().setBackRef(md);
val = objAsString(block.yield(context, substr(runtime, str, mat.start(0), mat.length(0), utf8)));
modifyCheck(sb, slen);
if (bang) frozenCheck();
// rb_raise(rb_eRuntimeError, "block should not cheat");
} else {
if (md == null) {
md = matchdata(runtime, str, mat, utf8);
context.getPreviousFrame().setBackRef(md);
} else {
md.invalidateRegs();
}
val = pattern.regsub(repl, this, md);
}
if (val.isTaint()) tainted = true;
ByteList vbuf = val.value;
int beg = mat.start();
int len = (bp - buf) + (beg - offset) + vbuf.realSize + 3;
if (blen < len) {
while (blen < len) blen <<= 1;
len = bp - buf;
dest.realloc(blen);
dest.realSize = blen;
bp = buf + len;
}
len = beg - offset;
System.arraycopy(value.bytes, cp, dest.bytes, bp, len);
bp += len;
System.arraycopy(vbuf.bytes, vbuf.begin, dest.bytes, bp, vbuf.realSize);
bp += vbuf.realSize;
int endZ = mat.end(0);
offset = endZ;
if (mat.length(0) == 0) {
if (value.realSize <= endZ) break;
len = 1;
System.arraycopy(value.bytes, value.begin + endZ, dest.bytes, bp, len);
bp += len;
offset = endZ + len;
}
cp = value.begin + offset;
if (offset > value.realSize) break;
mat.setPosition(offset);
found = mat.find();
}
if (value.realSize > offset) {
int len = bp - buf;
if (blen - len < value.realSize - offset) {
blen = len + value.realSize - offset;
dest.realloc(blen);
bp = buf + len;
}
System.arraycopy(value.bytes, cp, dest.bytes, bp, value.realSize - offset);
bp += value.realSize - offset;
}
// match unlock
// tmp unlock;
dest.realSize = bp - buf;
if (bang) {
view(dest);
if (tainted) setTaint(true);
return this;
} else {
RubyString destStr = new RubyString(runtime, getMetaClass(), dest);
destStr.infectBy(this);
if (tainted) destStr.setTaint(true);
return destStr;
}
}
/** rb_str_index_m
*
*/
@JRubyMethod(name = "index", required = 1, optional = 1)
public IRubyObject index(IRubyObject[] args) {
return index(args, false);
}
/** rb_str_rindex_m
*
*/
@JRubyMethod(name = "rindex", required = 1, optional = 1)
public IRubyObject rindex(IRubyObject[] args) {
return index(args, true);
}
/**
* @fixme may be a problem with pos when doing reverse searches
*/
private IRubyObject index(IRubyObject[] args, boolean reverse) {
//FIXME may be a problem with pos when doing reverse searches
int pos;
boolean offset = false;
if (Arity.checkArgumentCount(getRuntime(), args, 1, 2) == 2) {
pos = RubyNumeric.fix2int(args[1]);
if (pos > value.length()) {
if (reverse) {
pos = value.length();
} else {
return getRuntime().getNil();
}
} else {
if (pos < 0) {
pos += value.length();
if (pos < 0) return getRuntime().getNil();
}
}
offset = true;
} else {
pos = !reverse ? 0 : value.length();
}
if (args[0] instanceof RubyRegexp) {
// save position we shouldn't look past
int doNotLookPastIfReverse = pos;
// RubyRegexp doesn't (yet?) support reverse searches, so we
// find all matches and use the last one--very inefficient.
// FIXME: - find a better way
pos = ((RubyRegexp) args[0]).search(toString(), this, reverse ? 0 : pos);
if (reverse) {
if (pos == -1) return getRuntime().getNil();
int dummy = pos;
if (offset) {
pos = doNotLookPastIfReverse;
if (dummy > pos) {
pos = -1;
dummy = -1;
}
}
while (reverse && dummy > -1 && dummy <= doNotLookPastIfReverse) {
pos = dummy;
dummy = ((RubyRegexp) args[0]).search(toString(), this, pos + 1);
}
}
} else if (args[0] instanceof RubyFixnum) {
char c = (char) ((RubyFixnum) args[0]).getLongValue();
pos = reverse ? value.lastIndexOf(c, pos) : value.indexOf(c, pos);
} else {
IRubyObject tmp = args[0].checkStringType();
if (tmp.isNil()) throw getRuntime().newTypeError("type mismatch: " + args[0].getMetaClass().getName() + " given");
ByteList sub = ((RubyString) tmp).value;
if (sub.length() > value.length()) return getRuntime().getNil();
// the empty string is always found at the beginning of a string (or at the end when rindex)
if (sub.realSize == 0) return getRuntime().newFixnum(pos);
pos = reverse ? value.lastIndexOf(sub, pos) : value.indexOf(sub, pos);
}
return pos == -1 ? getRuntime().getNil() : getRuntime().newFixnum(pos);
}
/* rb_str_substr */
public IRubyObject substr(int beg, int len) {
int length = value.length();
if (len < 0 || beg > length) return getRuntime().getNil();
if (beg < 0) {
beg += length;
if (beg < 0) return getRuntime().getNil();
}
int end = Math.min(length, beg + len);
return makeShared(beg, end - beg);
}
/* rb_str_replace */
public IRubyObject replace(int beg, int len, RubyString replaceWith) {
if (beg + len >= value.length()) len = value.length() - beg;
modify();
value.unsafeReplace(beg,len,replaceWith.value);
return infectBy(replaceWith);
}
/** rb_str_aref, rb_str_aref_m
*
*/
@JRubyMethod(name = {"[]", "slice"}, required = 1, optional = 1)
public IRubyObject op_aref(IRubyObject[] args) {
if (Arity.checkArgumentCount(getRuntime(), args, 1, 2) == 2) {
if (args[0] instanceof RubyRegexp) {
IRubyObject match = RubyRegexp.regexpValue(args[0]).match(toString(), this, 0);
long idx = args[1].convertToInteger().getLongValue();
getRuntime().getCurrentContext().getCurrentFrame().setBackRef(match);
return RubyRegexp.nth_match((int) idx, match);
}
return substr(RubyNumeric.fix2int(args[0]), RubyNumeric.fix2int(args[1]));
}
if (args[0] instanceof RubyRegexp) {
return RubyRegexp.regexpValue(args[0]).search(toString(), this, 0) >= 0 ?
RubyRegexp.last_match(getRuntime().getCurrentContext().getCurrentFrame().getBackRef()) :
getRuntime().getNil();
} else if (args[0] instanceof RubyString) {
return toString().indexOf(stringValue(args[0]).toString()) != -1 ?
args[0] : getRuntime().getNil();
} else if (args[0] instanceof RubyRange) {
long[] begLen = ((RubyRange) args[0]).begLen(value.length(), 0);
return begLen == null ? getRuntime().getNil() :
substr((int) begLen[0], (int) begLen[1]);
}
int idx = (int) args[0].convertToInteger().getLongValue();
if (idx < 0) idx += value.length();
if (idx < 0 || idx >= value.length()) return getRuntime().getNil();
return getRuntime().newFixnum(value.get(idx) & 0xFF);
}
/**
* rb_str_subpat_set
*
*/
private void subpatSet(RubyRegexp regexp, int nth, IRubyObject repl) {
int found = regexp.search(this.toString(), this, 0);
if (found == -1) throw getRuntime().newIndexError("regexp not matched");
RubyMatchData match = (RubyMatchData) getRuntime().getCurrentContext().getCurrentFrame().getBackRef();
match.use();
if (nth >= match.getSize()) {
throw getRuntime().newIndexError("index " + nth + " out of regexp");
}
if (nth < 0) {
if (-nth >= match.getSize()) {
throw getRuntime().newIndexError("index " + nth + " out of regexp");
}
nth += match.getSize();
}
IRubyObject group = match.group(nth);
if (getRuntime().getNil().equals(group)) {
throw getRuntime().newIndexError("regexp group " + nth + " not matched");
}
int beg = (int) match.begin(nth);
int len = (int) (match.end(nth) - beg);
replace(beg, len, stringValue(repl));
}
/** rb_str_aset, rb_str_aset_m
*
*/
@JRubyMethod(name = "[]=", required = 2, optional = 1)
public IRubyObject op_aset(IRubyObject[] args) {
int strLen = value.length();
if (Arity.checkArgumentCount(getRuntime(), args, 2, 3) == 3) {
if (args[0] instanceof RubyFixnum) {
RubyString repl = stringValue(args[2]);
int beg = RubyNumeric.fix2int(args[0]);
int len = RubyNumeric.fix2int(args[1]);
if (len < 0) throw getRuntime().newIndexError("negative length");
if (beg < 0) beg += strLen;
if (beg < 0 || (beg > 0 && beg >= strLen)) {
throw getRuntime().newIndexError("string index out of bounds");
}
if (beg + len > strLen) len = strLen - beg;
replace(beg, len, repl);
return repl;
}
if (args[0] instanceof RubyRegexp) {
RubyString repl = stringValue(args[2]);
int nth = RubyNumeric.fix2int(args[1]);
subpatSet((RubyRegexp) args[0], nth, repl);
return repl;
}
}
if (args[0] instanceof RubyFixnum || args[0].respondsTo("to_int")) { // FIXME: RubyNumeric or RubyInteger instead?
int idx = 0;
// FIXME: second instanceof check adds overhead?
if (!(args[0] instanceof RubyFixnum)) {
// FIXME: ok to cast?
idx = (int)args[0].convertToInteger().getLongValue();
} else {
idx = RubyNumeric.fix2int(args[0]); // num2int?
}
if (idx < 0) idx += value.length();
if (idx < 0 || idx >= value.length()) {
throw getRuntime().newIndexError("string index out of bounds");
}
if (args[1] instanceof RubyFixnum) {
modify();
value.set(idx, (byte) RubyNumeric.fix2int(args[1]));
} else {
replace(idx, 1, stringValue(args[1]));
}
return args[1];
}
if (args[0] instanceof RubyRegexp) {
sub_bang(args, null);
return args[1];
}
if (args[0] instanceof RubyString) {
RubyString orig = stringValue(args[0]);
int beg = toString().indexOf(orig.toString());
if (beg != -1) {
replace(beg, orig.value.length(), stringValue(args[1]));
}
return args[1];
}
if (args[0] instanceof RubyRange) {
long[] idxs = ((RubyRange) args[0]).getBeginLength(value.length(), true, true);
replace((int) idxs[0], (int) idxs[1], stringValue(args[1]));
return args[1];
}
throw getRuntime().newTypeError("wrong argument type");
}
/** rb_str_slice_bang
*
*/
@JRubyMethod(name = "slice!", required = 1, optional = 1)
public IRubyObject slice_bang(IRubyObject[] args) {
int argc = Arity.checkArgumentCount(getRuntime(), args, 1, 2);
IRubyObject[] newArgs = new IRubyObject[argc + 1];
newArgs[0] = args[0];
if (argc > 1) newArgs[1] = args[1];
newArgs[argc] = newString("");
IRubyObject result = op_aref(args);
if (result.isNil()) return result;
op_aset(newArgs);
return result;
}
@JRubyMethod(name = {"succ", "next"})
public IRubyObject succ() {
return strDup().succ_bang();
}
@JRubyMethod(name = {"succ!", "next!"})
public IRubyObject succ_bang() {
if (value.length() == 0) return this;
modify();
boolean alnumSeen = false;
int pos = -1;
int c = 0;
int n = 0;
for (int i = value.length() - 1; i >= 0; i--) {
c = value.get(i) & 0xFF;
if (isAlnum(c)) {
alnumSeen = true;
if ((isDigit(c) && c < '9') || (isLower(c) && c < 'z') || (isUpper(c) && c < 'Z')) {
value.set(i, (byte)(c + 1));
pos = -1;
break;
}
pos = i;
n = isDigit(c) ? '1' : (isLower(c) ? 'a' : 'A');
value.set(i, (byte)(isDigit(c) ? '0' : (isLower(c) ? 'a' : 'A')));
}
}
if (!alnumSeen) {
for (int i = value.length() - 1; i >= 0; i--) {
c = value.get(i) & 0xFF;
if (c < 0xff) {
value.set(i, (byte)(c + 1));
pos = -1;
break;
}
pos = i;
n = '\u0001';
value.set(i, 0);
}
}
if (pos > -1) {
// This represents left most digit in a set of incremented
// values? Therefore leftmost numeric must be '1' and not '0'
// 999 -> 1000, not 999 -> 0000. whereas chars should be
// zzz -> aaaa and non-alnum byte values should be "\377" -> "\001\000"
value.prepend((byte) n);
}
return this;
}
/** rb_str_upto_m
*
*/
@JRubyMethod(name = "upto", required = 1, frame = true)
public IRubyObject upto(IRubyObject str, Block block) {
return upto(str, false, block);
}
/* rb_str_upto */
public IRubyObject upto(IRubyObject str, boolean excl, Block block) {
// alias 'this' to 'beg' for ease of comparison with MRI
RubyString beg = this;
RubyString end = stringValue(str);
int n = beg.op_cmp(end);
if (n > 0 || (excl && n == 0)) return beg;
RubyString afterEnd = stringValue(end.succ());
RubyString current = beg;
ThreadContext context = getRuntime().getCurrentContext();
while (!current.equals(afterEnd)) {
block.yield(context, current);
if (!excl && current.equals(end)) break;
current = (RubyString) current.succ();
if (excl && current.equals(end)) break;
if (current.length().getLongValue() > end.length().getLongValue()) break;
}
return beg;
}
/** rb_str_include
*
*/
@JRubyMethod(name = "include?", required = 1)
public RubyBoolean include_p(IRubyObject obj) {
if (obj instanceof RubyFixnum) {
int c = RubyNumeric.fix2int(obj);
for (int i = 0; i < value.length(); i++) {
if (value.get(i) == (byte)c) {
return getRuntime().getTrue();
}
}
return getRuntime().getFalse();
}
ByteList str = stringValue(obj).value;
return getRuntime().newBoolean(value.indexOf(str) != -1);
}
/** rb_str_to_i
*
*/
@JRubyMethod(name = "to_i", optional = 1)
public IRubyObject to_i(IRubyObject[] args) {
long base = Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0 ? 10 : args[0].convertToInteger().getLongValue();
return RubyNumeric.str2inum(getRuntime(), this, (int) base);
}
/** rb_str_oct
*
*/
@JRubyMethod(name = "oct")
public IRubyObject oct() {
if (isEmpty()) {
return getRuntime().newFixnum(0);
}
int base = 8;
String str = toString().trim();
int pos = (str.charAt(0) == '-' || str.charAt(0) == '+') ? 1 : 0;
if (str.indexOf("0x") == pos || str.indexOf("0X") == pos) {
base = 16;
} else if (str.indexOf("0b") == pos || str.indexOf("0B") == pos) {
base = 2;
}
return RubyNumeric.str2inum(getRuntime(), this, base);
}
/** rb_str_hex
*
*/
@JRubyMethod(name = "hex")
public IRubyObject hex() {
return RubyNumeric.str2inum(getRuntime(), this, 16);
}
/** rb_str_to_f
*
*/
@JRubyMethod(name = "to_f")
public IRubyObject to_f() {
return RubyNumeric.str2fnum(getRuntime(), this);
}
/** rb_str_split_m
*
*/
@JRubyMethod(name = "split", optional = 2)
public RubyArray split(IRubyObject[] args) {
int beg, end, i = 0;
int lim = 0;
boolean limit = false;
Ruby runtime = getRuntime();
if (Arity.checkArgumentCount(runtime, args, 0, 2) == 2) {
lim = RubyNumeric.fix2int(args[1]);
if (lim == 1) {
if (value.realSize == 0) return runtime.newArray();
return runtime.newArray(this);
} else if (lim > 0) {
limit = true;
}
if (lim > 0) limit = true;
i = 1;
}
IRubyObject spat = (args.length == 0 || args[0].isNil()) ? null : args[0];
boolean awkSplit = false;
if (spat == null && (spat = runtime.getGlobalVariables().get("$;")).isNil()) {
awkSplit = true;
} else {
if (spat instanceof RubyString && ((RubyString)spat).value.realSize == 1) {
if (((RubyString)spat).value.get(0) == ' ') {
awkSplit = true;
}
}
}
RubyArray result = runtime.newArray();
if (awkSplit) { // awk split
int ptr = value.begin;
int eptr = ptr + value.realSize;
byte[]buff = value.bytes;
boolean skip = true;
for (end = beg = 0; ptr < eptr; ptr++) {
if (skip) {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
result.append(makeShared(beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(beg, value.realSize - beg));
}
}
} else if(spat instanceof RubyString) { // string split
ByteList rsep = ((RubyString)spat).value;
int rslen = rsep.realSize;
int ptr = value.begin;
int pend = ptr + value.realSize;
byte[]buff = value.bytes;
int p = ptr;
- byte lastVal = rsep.bytes[rsep.begin+rslen-1];
+ byte lastVal = rslen == 0 ? 0 : rsep.bytes[rsep.begin+rslen-1];
int s = p;
p+=rslen;
for(; p < pend; p++) {
- if(ptr<p && buff[p-1] == lastVal &&
- (rslen <= 1 ||
- ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)) {
+ if(ptr<p && (rslen ==0 || (buff[p-1] == lastVal &&
+ (rslen <= 1 ||
+ ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)))) {
result.append(makeShared(s-ptr, (p - s) - rslen));
s = p;
if(limit) {
i++;
if(lim<=i) {
p = pend;
break;
}
}
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
if(!(limit && lim<=i) && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
result.append(makeShared(s-ptr, (p - s)-rslen));
if(lim < 0) {
result.append(newEmptyString(runtime, getMetaClass()));
}
} else {
result.append(makeShared(s-ptr, p - s));
}
}
} else { // regexp split
boolean utf8 = false;
String str;
RubyRegexp rr =(RubyRegexp)getPat(spat,true);
if (runtime.getKCode() == KCode.UTF8) {
// We're in UTF8 mode; try to convert the string to UTF8, but fall back on raw bytes if we can't decode
// TODO: all this decoder and charset stuff could be centralized...in KCode perhaps?
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
str = decoder.decode(ByteBuffer.wrap(value.unsafeBytes(), value.begin, value.realSize)).toString();
utf8 = true;
} catch (CharacterCodingException cce) {
// ignore, just use the unencoded string
str = toString();
}
} else {
utf8 = rr.getCode() == KCode.UTF8;
str = toString(utf8);
}
RegexpPattern pat = rr.getPattern();
RegexpMatcher mat = pat.matcher(str);
beg = 0;
boolean lastNull = false;
while (mat.find()) {
end = mat.start();
if (beg == end && mat.length(0) == 0) {
if (value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if (lastNull) {
beg = end;
} else {
lastNull = true;
continue;
}
} else {
result.append(substr(runtime, str, beg, end - beg, utf8));
beg = mat.end(0);
}
lastNull = false;
for (int index = 1; index < mat.groupCount(); index++) {
if (mat.isCaptured(index)) {
int iLength = mat.length(index);
if (iLength == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(runtime, str, mat.start(index), iLength, utf8));
}
}
}
if (limit && lim <= ++i) break;
}
if (str.length() > 0 && (limit || str.length() > beg || lim < 0)) {
if (str.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(runtime, str, beg, str.length() - beg, utf8));
}
}
} // regexp split
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString)result.eltInternal(result.size() - 1)).value.realSize == 0)
result.pop();
}
return result;
}
/** get_pat
*
*/
private final RubyRegexp getPat(IRubyObject pattern, boolean quote) {
if (pattern instanceof RubyRegexp) {
return (RubyRegexp)pattern;
} else if (!(pattern instanceof RubyString)) {
IRubyObject val = pattern.checkStringType();
if(val.isNil()) throw getRuntime().newTypeError("wrong argument type " + pattern.getMetaClass() + " (expected Regexp)");
pattern = val;
}
RubyString strPattern = (RubyString)pattern;
String str = strPattern.toString();
if (quote) str = RubyRegexp.escapeSpecialChars(strPattern.toString());
return RubyRegexp.newRegexp(getRuntime(), str, 0, null);
}
/** rb_str_scan
*
*/
@JRubyMethod(name = "scan", required = 1, frame = true)
public IRubyObject scan(IRubyObject arg, Block block) {
RubyRegexp pattern = getPat(arg, true);
Ruby runtime = getRuntime();
ThreadContext context = runtime.getCurrentContext();
// Fix for JRUBY-97: Temporary fix pending
// decision on UTF8-based string implementation.
// Move toString() call outside loop.
boolean utf8 = pattern.getCode() == KCode.UTF8;
String str = toString(utf8);
RegexpPattern pat = pattern.getPattern();
RegexpMatcher mat = pat.matcher(str);
if (!block.isGiven()) {
RubyArray result = runtime.newArray();
RubyMatchData md = matchdata(runtime, str, mat, utf8);
context.getPreviousFrame().setBackRef(md);
while(mat.find()) {
int groups = mat.groupCount();
if (groups == 1) {
result.append(substr(runtime, str, mat.start(0), mat.length(0), utf8));
} else {
RubyArray sub = runtime.newArray(groups);
for (int i=1; i < groups; i++){
sub.append(mat.isCaptured(i) ? substr(runtime, str, mat.start(i), mat.length(i), utf8) : runtime.getNil());
}
result.append(sub);
}
md.invalidateRegs();
}
return result;
}
while(mat.find()) {
int groups = mat.groupCount();
context.getPreviousFrame().setBackRef(matchdata(runtime, str, mat, utf8));
if (groups == 1) {
block.yield(context, substr(runtime, str, mat.start(0), mat.length(0), utf8));
} else {
RubyArray sub = runtime.newArray(groups);
for (int i=1; i < groups; i++){
sub.append(mat.isCaptured(i) ? substr(runtime, str, mat.start(i), mat.length(i), utf8) : runtime.getNil());
}
block.yield(context, sub);
}
}
context.getPreviousFrame().setBackRef(matchdata(runtime, str, mat, utf8));
return this;
}
private final RubyString substr(Ruby runtime, String str, int beg, int len, boolean utf8) {
if (utf8) {
if (len == 0) return newEmptyString(runtime, getMetaClass());
return new RubyString(runtime, getMetaClass(), new ByteList(toUTF(str.substring(beg, beg + len)), false));
} else {
return makeShared(beg, len);
}
}
private final String toString(boolean utf8) {
String str = toString();
if (utf8) {
try {
str = new String(ByteList.plain(str), "UTF8");
} catch(Exception e){}
}
return str;
}
private final RubyMatchData matchdata(Ruby runtime, String str, RegexpMatcher mat, boolean utf8) {
return mat.createOrReplace(null, str, this, utf8);
}
private static final ByteList SPACE_BYTELIST = new ByteList(ByteList.plain(" "));
private final IRubyObject justify(IRubyObject[]args, char jflag) {
Ruby runtime = getRuntime();
Arity.scanArgs(runtime, args, 1, 1);
int width = RubyFixnum.num2int(args[0]);
int f, flen = 0;
byte[]fbuf;
IRubyObject pad;
if (args.length == 2) {
pad = args[1].convertToString();
ByteList fList = ((RubyString)pad).value;
f = fList.begin;
flen = fList.realSize;
if (flen == 0) throw getRuntime().newArgumentError("zero width padding");
fbuf = fList.bytes;
} else {
f = SPACE_BYTELIST.begin;
flen = SPACE_BYTELIST.realSize;
fbuf = SPACE_BYTELIST.bytes;
pad = runtime.getNil();
}
if (width < 0 || value.realSize >= width) return strDup();
ByteList res = new ByteList(width);
res.realSize = width;
int p = res.begin;
int pend;
byte[] pbuf = res.bytes;
if (jflag != 'l') {
int n = width - value.realSize;
pend = p + ((jflag == 'r') ? n : n / 2);
if (flen <= 1) {
while (p < pend) pbuf[p++] = fbuf[f];
} else {
int q = f;
while (p + flen <= pend) {
System.arraycopy(fbuf, f, pbuf, p, flen);
p += flen;
}
while (p < pend) pbuf[p++] = fbuf[q++];
}
}
System.arraycopy(value.bytes, value.begin, pbuf, p, value.realSize);
if (jflag != 'r') {
p += value.realSize;
pend = res.begin + width;
if (flen <= 1) {
while (p < pend) pbuf[p++] = fbuf[f];
} else {
while (p + flen <= pend) {
System.arraycopy(fbuf, f, pbuf, p, flen);
p += flen;
}
while (p < pend) pbuf[p++] = fbuf[f++];
}
}
RubyString resStr = new RubyString(runtime, getMetaClass(), res);
resStr.infectBy(this);
if (flen > 0) resStr.infectBy(pad);
return resStr;
}
/** rb_str_ljust
*
*/
@JRubyMethod(name = "ljust", required = 1, optional = 1)
public IRubyObject ljust(IRubyObject [] args) {
return justify(args, 'l');
}
/** rb_str_rjust
*
*/
@JRubyMethod(name = "rjust", required = 1, optional = 1)
public IRubyObject rjust(IRubyObject [] args) {
return justify(args, 'r');
}
@JRubyMethod(name = "center", required = 1, optional = 1)
public IRubyObject center(IRubyObject[] args) {
return justify(args, 'c');
}
@JRubyMethod(name = "chop")
public IRubyObject chop() {
RubyString str = strDup();
str.chop_bang();
return str;
}
/** rb_str_chop_bang
*
*/
@JRubyMethod(name = "chop!")
public IRubyObject chop_bang() {
int end = value.realSize - 1;
if (end < 0) return getRuntime().getNil();
if ((value.bytes[value.begin + end]) == '\n') {
if (end > 0 && (value.bytes[value.begin + end - 1]) == '\r') end--;
}
view(0, end);
return this;
}
/** rb_str_chop
*
*/
@JRubyMethod(name = "chomp", optional = 1)
public RubyString chomp(IRubyObject[] args) {
RubyString str = strDup();
str.chomp_bang(args);
return str;
}
/**
* rb_str_chomp_bang
*
* In the common case, removes CR and LF characters in various ways depending on the value of
* the optional args[0].
* If args.length==0 removes one instance of CR, CRLF or LF from the end of the string.
* If args.length>0 and args[0] is "\n" then same behaviour as args.length==0 .
* If args.length>0 and args[0] is "" then removes trailing multiple LF or CRLF (but no CRs at
* all(!)).
* @param args See method description.
*/
@JRubyMethod(name = "chomp!", optional = 1)
public IRubyObject chomp_bang(IRubyObject[] args) {
IRubyObject rsObj;
if (Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0) {
int len = value.length();
if (len == 0) return getRuntime().getNil();
byte[]buff = value.bytes;
rsObj = getRuntime().getGlobalVariables().get("$/");
if (rsObj == getRuntime().getGlobalVariables().getDefaultSeparator()) {
int realSize = value.realSize;
if ((buff[len - 1] & 0xFF) == '\n') {
realSize--;
if (realSize > 0 && (buff[realSize - 1] & 0xFF) == '\r') realSize--;
view(0, realSize);
} else if ((buff[len - 1] & 0xFF) == '\r') {
realSize--;
view(0, realSize);
} else {
modifyCheck();
return getRuntime().getNil();
}
return this;
}
} else {
rsObj = args[0];
}
if (rsObj.isNil()) return getRuntime().getNil();
RubyString rs = rsObj.convertToString();
int len = value.realSize;
if (len == 0) return getRuntime().getNil();
byte[]buff = value.bytes;
int rslen = rs.value.realSize;
if (rslen == 0) {
while (len > 0 && (buff[len - 1] & 0xFF) == '\n') {
len--;
if (len > 0 && (buff[len - 1] & 0xFF) == '\r') len--;
}
if (len < value.realSize) {
view(0, len);
return this;
}
return getRuntime().getNil();
}
if (rslen > len) return getRuntime().getNil();
int newline = rs.value.bytes[rslen - 1] & 0xFF;
if (rslen == 1 && newline == '\n') {
buff = value.bytes;
int realSize = value.realSize;
if ((buff[len - 1] & 0xFF) == '\n') {
realSize--;
if (realSize > 0 && (buff[realSize - 1] & 0xFF) == '\r') realSize--;
view(0, realSize);
} else if ((buff[len - 1] & 0xFF) == '\r') {
realSize--;
view(0, realSize);
} else {
modifyCheck();
return getRuntime().getNil();
}
return this;
}
if ((buff[len - 1] & 0xFF) == newline && rslen <= 1 || value.endsWith(rs.value)) {
view(0, value.realSize - rslen);
return this;
}
return getRuntime().getNil();
}
/** rb_str_lstrip
*
*/
@JRubyMethod(name = "lstrip")
public IRubyObject lstrip() {
RubyString str = strDup();
str.lstrip_bang();
return str;
}
private final static boolean[] WHITESPACE = new boolean[256];
static {
WHITESPACE[((byte)' ')+128] = true;
WHITESPACE[((byte)'\t')+128] = true;
WHITESPACE[((byte)'\n')+128] = true;
WHITESPACE[((byte)'\r')+128] = true;
WHITESPACE[((byte)'\f')+128] = true;
}
/** rb_str_lstrip_bang
*/
@JRubyMethod(name = "lstrip!")
public IRubyObject lstrip_bang() {
if (value.realSize == 0) return getRuntime().getNil();
int i=0;
while (i < value.realSize && WHITESPACE[value.bytes[value.begin+i]+128]) i++;
if (i > 0) {
view(i, value.realSize - i);
return this;
}
return getRuntime().getNil();
}
/** rb_str_rstrip
*
*/
@JRubyMethod(name = "rstrip")
public IRubyObject rstrip() {
RubyString str = strDup();
str.rstrip_bang();
return str;
}
/** rb_str_rstrip_bang
*/
@JRubyMethod(name = "rstrip!")
public IRubyObject rstrip_bang() {
if (value.realSize == 0) return getRuntime().getNil();
int i=value.realSize - 1;
while (i >= 0 && value.bytes[value.begin+i] == 0) i--;
while (i >= 0 && WHITESPACE[value.bytes[value.begin+i]+128]) i--;
if (i < value.realSize - 1) {
view(0, i + 1);
return this;
}
return getRuntime().getNil();
}
/** rb_str_strip
*
*/
@JRubyMethod(name = "strip")
public IRubyObject strip() {
RubyString str = strDup();
str.strip_bang();
return str;
}
/** rb_str_strip_bang
*/
@JRubyMethod(name = "strip!")
public IRubyObject strip_bang() {
IRubyObject l = lstrip_bang();
IRubyObject r = rstrip_bang();
if(l.isNil() && r.isNil()) {
return l;
}
return this;
}
/** rb_str_count
*
*/
@JRubyMethod(name = "count", required = 1, rest = true)
public IRubyObject count(IRubyObject[] args) {
if (args.length < 1) throw getRuntime().newArgumentError("wrong number of arguments");
if (value.realSize == 0) return getRuntime().newFixnum(0);
boolean[]table = new boolean[TRANS_SIZE];
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(table, init);
init = false;
}
int s = value.begin;
int send = s + value.realSize;
byte[]buf = value.bytes;
int i = 0;
while (s < send) if (table[buf[s++] & 0xff]) i++;
return getRuntime().newFixnum(i);
}
/** rb_str_delete
*
*/
@JRubyMethod(name = "delete", required = 1, rest = true)
public IRubyObject delete(IRubyObject[] args) {
RubyString str = strDup();
str.delete_bang(args);
return str;
}
/** rb_str_delete_bang
*
*/
@JRubyMethod(name = "delete!", required = 1, rest = true)
public IRubyObject delete_bang(IRubyObject[] args) {
if (args.length < 1) throw getRuntime().newArgumentError("wrong number of arguments");
boolean[]squeeze = new boolean[TRANS_SIZE];
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(squeeze, init);
init = false;
}
modify();
if (value.realSize == 0) return getRuntime().getNil();
int s = value.begin;
int t = s;
int send = s + value.realSize;
byte[]buf = value.bytes;
boolean modify = false;
while (s < send) {
if (squeeze[buf[s] & 0xff]) {
modify = true;
} else {
buf[t++] = buf[s];
}
s++;
}
value.realSize = t - value.begin;
if (modify) return this;
return getRuntime().getNil();
}
/** rb_str_squeeze
*
*/
@JRubyMethod(name = "squeeze", rest = true)
public IRubyObject squeeze(IRubyObject[] args) {
RubyString str = strDup();
str.squeeze_bang(args);
return str;
}
/** rb_str_squeeze_bang
*
*/
@JRubyMethod(name = "squeeze!", rest = true)
public IRubyObject squeeze_bang(IRubyObject[] args) {
if (value.realSize == 0) return getRuntime().getNil();
final boolean squeeze[] = new boolean[TRANS_SIZE];
if (args.length == 0) {
for (int i=0; i<TRANS_SIZE; i++) squeeze[i] = true;
} else {
boolean init = true;
for (int i=0; i<args.length; i++) {
RubyString s = args[i].convertToString();
s.setup_table(squeeze, init);
init = false;
}
}
modify();
int s = value.begin;
int t = s;
int send = s + value.realSize;
byte[]buf = value.bytes;
int save = -1;
while (s < send) {
int c = buf[s++] & 0xff;
if (c != save || !squeeze[c]) buf[t++] = (byte)(save = c);
}
if (t - value.begin != value.realSize) { // modified
value.realSize = t - value.begin;
return this;
}
return getRuntime().getNil();
}
/** rb_str_tr
*
*/
@JRubyMethod(name = "tr", required = 2)
public IRubyObject tr(IRubyObject src, IRubyObject repl) {
RubyString str = strDup();
str.tr_trans(src, repl, false);
return str;
}
/** rb_str_tr_bang
*
*/
@JRubyMethod(name = "tr!", required = 2)
public IRubyObject tr_bang(IRubyObject src, IRubyObject repl) {
return tr_trans(src, repl, false);
}
private static final class TR {
int gen, now, max;
int p, pend;
byte[]buf;
}
private static final int TRANS_SIZE = 256;
/** tr_setup_table
*
*/
private final void setup_table(boolean[]table, boolean init) {
final boolean[]buf = new boolean[TRANS_SIZE];
final TR tr = new TR();
int c;
boolean cflag = false;
tr.p = value.begin;
tr.pend = value.begin + value.realSize;
tr.buf = value.bytes;
tr.gen = tr.now = tr.max = 0;
if (value.realSize > 1 && value.bytes[value.begin] == '^') {
cflag = true;
tr.p++;
}
if (init) for (int i=0; i<TRANS_SIZE; i++) table[i] = true;
for (int i=0; i<TRANS_SIZE; i++) buf[i] = cflag;
while ((c = trnext(tr)) >= 0) buf[c & 0xff] = !cflag;
for (int i=0; i<TRANS_SIZE; i++) table[i] = table[i] && buf[i];
}
/** tr_trans
*
*/
private final IRubyObject tr_trans(IRubyObject src, IRubyObject repl, boolean sflag) {
if (value.realSize == 0) return getRuntime().getNil();
ByteList replList = repl.convertToString().value;
if (replList.realSize == 0) return delete_bang(new IRubyObject[]{src});
ByteList srcList = src.convertToString().value;
final TR trsrc = new TR();
final TR trrepl = new TR();
boolean cflag = false;
boolean modify = false;
trsrc.p = srcList.begin;
trsrc.pend = srcList.begin + srcList.realSize;
trsrc.buf = srcList.bytes;
if (srcList.realSize >= 2 && srcList.bytes[srcList.begin] == '^') {
cflag = true;
trsrc.p++;
}
trrepl.p = replList.begin;
trrepl.pend = replList.begin + replList.realSize;
trrepl.buf = replList.bytes;
trsrc.gen = trrepl.gen = 0;
trsrc.now = trrepl.now = 0;
trsrc.max = trrepl.max = 0;
int c;
final int[]trans = new int[TRANS_SIZE];
if (cflag) {
for (int i=0; i<TRANS_SIZE; i++) trans[i] = 1;
while ((c = trnext(trsrc)) >= 0) trans[c & 0xff] = -1;
while ((c = trnext(trrepl)) >= 0);
for (int i=0; i<TRANS_SIZE; i++) {
if (trans[i] >= 0) trans[i] = trrepl.now;
}
} else {
for (int i=0; i<TRANS_SIZE; i++) trans[i] = -1;
while ((c = trnext(trsrc)) >= 0) {
int r = trnext(trrepl);
if (r == -1) r = trrepl.now;
trans[c & 0xff] = r;
}
}
modify();
int s = value.begin;
int send = s + value.realSize;
byte sbuf[] = value.bytes;
if (sflag) {
int t = s;
int c0, last = -1;
while (s < send) {
c0 = sbuf[s++];
if ((c = trans[c0 & 0xff]) >= 0) {
if (last == c) continue;
last = c;
sbuf[t++] = (byte)(c & 0xff);
modify = true;
} else {
last = -1;
sbuf[t++] = (byte)c0;
}
}
if (value.realSize > (t - value.begin)) {
value.realSize = t - value.begin;
modify = true;
}
} else {
while (s < send) {
if ((c = trans[sbuf[s] & 0xff]) >= 0) {
sbuf[s] = (byte)(c & 0xff);
modify = true;
}
s++;
}
}
if (modify) return this;
return getRuntime().getNil();
}
/** trnext
*
*/
private final int trnext(TR t) {
byte [] buf = t.buf;
for (;;) {
if (t.gen == 0) {
if (t.p == t.pend) return -1;
if (t.p < t.pend -1 && buf[t.p] == '\\') t.p++;
t.now = buf[t.p++];
if (t.p < t.pend - 1 && buf[t.p] == '-') {
t.p++;
if (t.p < t.pend) {
if (t.now > buf[t.p]) {
t.p++;
continue;
}
t.gen = 1;
t.max = buf[t.p++];
}
}
return t.now & 0xff;
} else if (++t.now < t.max) {
return t.now & 0xff;
} else {
t.gen = 0;
return t.max & 0xff;
}
}
}
/** rb_str_tr_s
*
*/
@JRubyMethod(name = "tr_s", required = 2)
public IRubyObject tr_s(IRubyObject src, IRubyObject repl) {
RubyString str = strDup();
str.tr_trans(src, repl, true);
return str;
}
/** rb_str_tr_s_bang
*
*/
@JRubyMethod(name = "tr_s!", required = 2)
public IRubyObject tr_s_bang(IRubyObject src, IRubyObject repl) {
return tr_trans(src, repl, true);
}
/** rb_str_each_line
*
*/
@JRubyMethod(name = {"each_line", "each"}, required = 0, optional = 1, frame = true)
public IRubyObject each_line(IRubyObject[] args, Block block) {
byte newline;
int p = value.begin;
int pend = p + value.realSize;
int s;
int ptr = p;
int len = value.realSize;
int rslen;
IRubyObject line;
IRubyObject _rsep;
if (Arity.checkArgumentCount(getRuntime(), args, 0, 1) == 0) {
_rsep = getRuntime().getGlobalVariables().get("$/");
} else {
_rsep = args[0];
}
ThreadContext tc = getRuntime().getCurrentContext();
if(_rsep.isNil()) {
block.yield(tc, this);
return this;
}
RubyString rsep = stringValue(_rsep);
ByteList rsepValue = rsep.value;
byte[] strBytes = value.bytes;
rslen = rsepValue.realSize;
if(rslen == 0) {
newline = '\n';
} else {
newline = rsepValue.bytes[rsepValue.begin + rslen-1];
}
s = p;
p+=rslen;
for(; p < pend; p++) {
if(rslen == 0 && strBytes[p] == '\n') {
if(strBytes[++p] != '\n') {
continue;
}
while(strBytes[p] == '\n') {
p++;
}
}
if(ptr<p && strBytes[p-1] == newline &&
(rslen <= 1 ||
ByteList.memcmp(rsepValue.bytes, rsepValue.begin, rslen, strBytes, p-rslen, rslen) == 0)) {
line = RubyString.newStringShared(getRuntime(), getMetaClass(), this.value.makeShared(s, p-s));
line.infectBy(this);
block.yield(tc, line);
modifyCheck(strBytes,len);
s = p;
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
line = RubyString.newStringShared(getRuntime(), getMetaClass(), this.value.makeShared(s, p-s));
line.infectBy(this);
block.yield(tc, line);
}
return this;
}
/**
* rb_str_each_byte
*/
@JRubyMethod(name = "each_byte", frame = true)
public RubyString each_byte(Block block) {
int lLength = value.length();
Ruby runtime = getRuntime();
ThreadContext context = runtime.getCurrentContext();
for (int i = 0; i < lLength; i++) {
block.yield(context, runtime.newFixnum(value.get(i) & 0xFF));
}
return this;
}
/** rb_str_intern
*
*/
public RubySymbol intern() {
String s = toString();
if (s.length() == 0) {
throw getRuntime().newArgumentError("interning empty string");
}
if (s.indexOf('\0') >= 0) {
throw getRuntime().newArgumentError("symbol string may not contain '\\0'");
}
return RubySymbol.newSymbol(getRuntime(), toString());
}
@JRubyMethod(name = {"to_sym", "intern"})
public RubySymbol to_sym() {
return intern();
}
@JRubyMethod(name = "sum", optional = 1)
public RubyInteger sum(IRubyObject[] args) {
if (args.length > 1) {
throw getRuntime().newArgumentError("wrong number of arguments (" + args.length + " for 1)");
}
long bitSize = 16;
if (args.length == 1) {
long bitSizeArg = ((RubyInteger) args[0].convertToInteger()).getLongValue();
if (bitSizeArg > 0) {
bitSize = bitSizeArg;
}
}
long result = 0;
for (int i = 0; i < value.length(); i++) {
result += value.get(i) & 0xFF;
}
return getRuntime().newFixnum(bitSize == 0 ? result : result % (long) Math.pow(2, bitSize));
}
public static RubyString unmarshalFrom(UnmarshalStream input) throws java.io.IOException {
RubyString result = newString(input.getRuntime(), input.unmarshalString());
input.registerLinkTarget(result);
return result;
}
/**
* @see org.jruby.util.Pack#unpack
*/
@JRubyMethod(name = "unpack", required = 1)
public RubyArray unpack(IRubyObject obj) {
return Pack.unpack(getRuntime(), this.value, stringValue(obj).value);
}
/**
* Mutator for internal string representation.
*
* @param value The new java.lang.String this RubyString should encapsulate
*/
public void setValue(CharSequence value) {
view(ByteList.plain(value));
}
public void setValue(ByteList value) {
view(value);
}
public CharSequence getValue() {
return toString();
}
public String getUnicodeValue() {
try {
return new String(value.bytes,value.begin,value.realSize, "UTF8");
} catch (Exception e) {
throw new RuntimeException("Something's seriously broken with encodings", e);
}
}
public static byte[] toUTF(String string) {
try {
return string.getBytes("UTF8");
} catch (Exception e) {
throw new RuntimeException("Something's seriously broken with encodings", e);
}
}
public void setUnicodeValue(String newValue) {
view(toUTF(newValue));
}
public byte[] getBytes() {
return value.bytes();
}
public ByteList getByteList() {
return value;
}
}
| false | true | public RubyArray split(IRubyObject[] args) {
int beg, end, i = 0;
int lim = 0;
boolean limit = false;
Ruby runtime = getRuntime();
if (Arity.checkArgumentCount(runtime, args, 0, 2) == 2) {
lim = RubyNumeric.fix2int(args[1]);
if (lim == 1) {
if (value.realSize == 0) return runtime.newArray();
return runtime.newArray(this);
} else if (lim > 0) {
limit = true;
}
if (lim > 0) limit = true;
i = 1;
}
IRubyObject spat = (args.length == 0 || args[0].isNil()) ? null : args[0];
boolean awkSplit = false;
if (spat == null && (spat = runtime.getGlobalVariables().get("$;")).isNil()) {
awkSplit = true;
} else {
if (spat instanceof RubyString && ((RubyString)spat).value.realSize == 1) {
if (((RubyString)spat).value.get(0) == ' ') {
awkSplit = true;
}
}
}
RubyArray result = runtime.newArray();
if (awkSplit) { // awk split
int ptr = value.begin;
int eptr = ptr + value.realSize;
byte[]buff = value.bytes;
boolean skip = true;
for (end = beg = 0; ptr < eptr; ptr++) {
if (skip) {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
result.append(makeShared(beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(beg, value.realSize - beg));
}
}
} else if(spat instanceof RubyString) { // string split
ByteList rsep = ((RubyString)spat).value;
int rslen = rsep.realSize;
int ptr = value.begin;
int pend = ptr + value.realSize;
byte[]buff = value.bytes;
int p = ptr;
byte lastVal = rsep.bytes[rsep.begin+rslen-1];
int s = p;
p+=rslen;
for(; p < pend; p++) {
if(ptr<p && buff[p-1] == lastVal &&
(rslen <= 1 ||
ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)) {
result.append(makeShared(s-ptr, (p - s) - rslen));
s = p;
if(limit) {
i++;
if(lim<=i) {
p = pend;
break;
}
}
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
if(!(limit && lim<=i) && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
result.append(makeShared(s-ptr, (p - s)-rslen));
if(lim < 0) {
result.append(newEmptyString(runtime, getMetaClass()));
}
} else {
result.append(makeShared(s-ptr, p - s));
}
}
} else { // regexp split
boolean utf8 = false;
String str;
RubyRegexp rr =(RubyRegexp)getPat(spat,true);
if (runtime.getKCode() == KCode.UTF8) {
// We're in UTF8 mode; try to convert the string to UTF8, but fall back on raw bytes if we can't decode
// TODO: all this decoder and charset stuff could be centralized...in KCode perhaps?
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
str = decoder.decode(ByteBuffer.wrap(value.unsafeBytes(), value.begin, value.realSize)).toString();
utf8 = true;
} catch (CharacterCodingException cce) {
// ignore, just use the unencoded string
str = toString();
}
} else {
utf8 = rr.getCode() == KCode.UTF8;
str = toString(utf8);
}
RegexpPattern pat = rr.getPattern();
RegexpMatcher mat = pat.matcher(str);
beg = 0;
boolean lastNull = false;
while (mat.find()) {
end = mat.start();
if (beg == end && mat.length(0) == 0) {
if (value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if (lastNull) {
beg = end;
} else {
lastNull = true;
continue;
}
} else {
result.append(substr(runtime, str, beg, end - beg, utf8));
beg = mat.end(0);
}
lastNull = false;
for (int index = 1; index < mat.groupCount(); index++) {
if (mat.isCaptured(index)) {
int iLength = mat.length(index);
if (iLength == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(runtime, str, mat.start(index), iLength, utf8));
}
}
}
if (limit && lim <= ++i) break;
}
if (str.length() > 0 && (limit || str.length() > beg || lim < 0)) {
if (str.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(runtime, str, beg, str.length() - beg, utf8));
}
}
} // regexp split
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString)result.eltInternal(result.size() - 1)).value.realSize == 0)
result.pop();
}
return result;
}
| public RubyArray split(IRubyObject[] args) {
int beg, end, i = 0;
int lim = 0;
boolean limit = false;
Ruby runtime = getRuntime();
if (Arity.checkArgumentCount(runtime, args, 0, 2) == 2) {
lim = RubyNumeric.fix2int(args[1]);
if (lim == 1) {
if (value.realSize == 0) return runtime.newArray();
return runtime.newArray(this);
} else if (lim > 0) {
limit = true;
}
if (lim > 0) limit = true;
i = 1;
}
IRubyObject spat = (args.length == 0 || args[0].isNil()) ? null : args[0];
boolean awkSplit = false;
if (spat == null && (spat = runtime.getGlobalVariables().get("$;")).isNil()) {
awkSplit = true;
} else {
if (spat instanceof RubyString && ((RubyString)spat).value.realSize == 1) {
if (((RubyString)spat).value.get(0) == ' ') {
awkSplit = true;
}
}
}
RubyArray result = runtime.newArray();
if (awkSplit) { // awk split
int ptr = value.begin;
int eptr = ptr + value.realSize;
byte[]buff = value.bytes;
boolean skip = true;
for (end = beg = 0; ptr < eptr; ptr++) {
if (skip) {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
beg++;
} else {
end = beg + 1;
skip = false;
if (limit && lim <= i) break;
}
} else {
if (Character.isWhitespace((char)(buff[ptr] & 0xff))) {
result.append(makeShared(beg, end - beg));
skip = true;
beg = end + 1;
if (limit) i++;
} else {
end++;
}
}
}
if (value.realSize > 0 && (limit || value.realSize > beg || lim < 0)) {
if (value.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(makeShared(beg, value.realSize - beg));
}
}
} else if(spat instanceof RubyString) { // string split
ByteList rsep = ((RubyString)spat).value;
int rslen = rsep.realSize;
int ptr = value.begin;
int pend = ptr + value.realSize;
byte[]buff = value.bytes;
int p = ptr;
byte lastVal = rslen == 0 ? 0 : rsep.bytes[rsep.begin+rslen-1];
int s = p;
p+=rslen;
for(; p < pend; p++) {
if(ptr<p && (rslen ==0 || (buff[p-1] == lastVal &&
(rslen <= 1 ||
ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0)))) {
result.append(makeShared(s-ptr, (p - s) - rslen));
s = p;
if(limit) {
i++;
if(lim<=i) {
p = pend;
break;
}
}
}
}
if(s != pend) {
if(p > pend) {
p = pend;
}
if(!(limit && lim<=i) && ByteList.memcmp(rsep.bytes, rsep.begin, rslen, buff, p-rslen, rslen) == 0) {
result.append(makeShared(s-ptr, (p - s)-rslen));
if(lim < 0) {
result.append(newEmptyString(runtime, getMetaClass()));
}
} else {
result.append(makeShared(s-ptr, p - s));
}
}
} else { // regexp split
boolean utf8 = false;
String str;
RubyRegexp rr =(RubyRegexp)getPat(spat,true);
if (runtime.getKCode() == KCode.UTF8) {
// We're in UTF8 mode; try to convert the string to UTF8, but fall back on raw bytes if we can't decode
// TODO: all this decoder and charset stuff could be centralized...in KCode perhaps?
CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
decoder.onMalformedInput(CodingErrorAction.REPORT);
decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
str = decoder.decode(ByteBuffer.wrap(value.unsafeBytes(), value.begin, value.realSize)).toString();
utf8 = true;
} catch (CharacterCodingException cce) {
// ignore, just use the unencoded string
str = toString();
}
} else {
utf8 = rr.getCode() == KCode.UTF8;
str = toString(utf8);
}
RegexpPattern pat = rr.getPattern();
RegexpMatcher mat = pat.matcher(str);
beg = 0;
boolean lastNull = false;
while (mat.find()) {
end = mat.start();
if (beg == end && mat.length(0) == 0) {
if (value.realSize == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
break;
} else if (lastNull) {
beg = end;
} else {
lastNull = true;
continue;
}
} else {
result.append(substr(runtime, str, beg, end - beg, utf8));
beg = mat.end(0);
}
lastNull = false;
for (int index = 1; index < mat.groupCount(); index++) {
if (mat.isCaptured(index)) {
int iLength = mat.length(index);
if (iLength == 0) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(runtime, str, mat.start(index), iLength, utf8));
}
}
}
if (limit && lim <= ++i) break;
}
if (str.length() > 0 && (limit || str.length() > beg || lim < 0)) {
if (str.length() == beg) {
result.append(newEmptyString(runtime, getMetaClass()));
} else {
result.append(substr(runtime, str, beg, str.length() - beg, utf8));
}
}
} // regexp split
if (!limit && lim == 0) {
while (result.size() > 0 && ((RubyString)result.eltInternal(result.size() - 1)).value.realSize == 0)
result.pop();
}
return result;
}
|
diff --git a/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/gs/ReprojectProcessTest.java b/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/gs/ReprojectProcessTest.java
index cd4a180f3d..f0a01f9e95 100644
--- a/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/gs/ReprojectProcessTest.java
+++ b/src/extension/wps/wps-core/src/test/java/org/geoserver/wps/gs/ReprojectProcessTest.java
@@ -1,93 +1,93 @@
package org.geoserver.wps.gs;
import static org.custommonkey.xmlunit.XMLAssert.*;
import java.util.HashMap;
import java.util.Map;
import org.custommonkey.xmlunit.SimpleNamespaceContext;
import org.custommonkey.xmlunit.XMLUnit;
import org.geoserver.data.test.MockData;
import org.geoserver.wps.WPSTestSupport;
import org.w3c.dom.Document;
public class ReprojectProcessTest extends WPSTestSupport {
protected void setUpInternal() throws Exception {
super.setUpInternal();
// init xmlunit
Map<String, String> namespaces = new HashMap<String, String>();
namespaces.put("wps", "http://www.opengis.net/wps/1.0.0");
namespaces.put("ows", "http://www.opengis.net/ows/1.1");
namespaces.put("gml", "http://www.opengis.net/gml");
namespaces.put("wfs", "http://www.opengis.net/wfs");
namespaces.put("xlink", "http://www.w3.org/1999/xlink");
namespaces.put("feature", "http://www.opengis.net/cite");
XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
};
public void testForce() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<wps:Execute version=\"1.0.0\" service=\"WPS\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd\">\n"
+ " <ows:Identifier>gs:Reproject</ows:Identifier>\n"
+ " <wps:DataInputs>\n"
+ " <wps:Input>\n"
+ " <ows:Identifier>features</ows:Identifier>\n"
+ " <wps:Reference mimeType=\"text/xml; subtype=wfs-collection/1.0\" xlink:href=\"http://geoserver/wfs\" method=\"POST\">\n"
+ " <wps:Body>\n"
+ " <wfs:GetFeature service=\"WFS\" version=\"1.0.0\" outputFormat=\"GML2\">\n"
+ " <wfs:Query typeName=\"" + getLayerId(MockData.BASIC_POLYGONS)
+ "\"/>\n" + " </wfs:GetFeature>\n" + " </wps:Body>\n"
+ " </wps:Reference>\n" + " </wps:Input>\n" + " <wps:Input>\n"
+ " <ows:Identifier>forcedCRS</ows:Identifier>\n" + " <wps:Data>\n"
+ " <wps:LiteralData>EPSG:4269</wps:LiteralData>\n" + " </wps:Data>\n"
+ " </wps:Input>\n" + " </wps:DataInputs>\n" + " <wps:ResponseForm>\n"
+ " <wps:RawDataOutput mimeType=\"text/xml; subtype=wfs-collection/1.0\">\n"
+ " <ows:Identifier>result</ows:Identifier>\n" + " </wps:RawDataOutput>\n"
+ " </wps:ResponseForm>\n" + "</wps:Execute>";
Document response = postAsDOM(root(), xml);
// print(response);
assertXpathEvaluatesTo("http://www.opengis.net/gml/srs/epsg.xml#4269",
"//gml:MultiPolygon/@srsName", response);
}
public void testReproject() throws Exception {
// note, we use 3395 instead of 900913 because it's more accurate, the referencing subsystem
// with assertions enabled will flip if we use the latter due to small reprojection errors
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<wps:Execute version=\"1.0.0\" service=\"WPS\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd\">\n"
+ " <ows:Identifier>gs:Reproject</ows:Identifier>\n"
+ " <wps:DataInputs>\n"
+ " <wps:Input>\n"
+ " <ows:Identifier>features</ows:Identifier>\n"
+ " <wps:Reference mimeType=\"text/xml; subtype=wfs-collection/1.0\" xlink:href=\"http://geoserver/wfs\" method=\"POST\">\n"
+ " <wps:Body>\n"
+ " <wfs:GetFeature service=\"WFS\" version=\"1.0.0\" outputFormat=\"GML2\">\n"
+ " <wfs:Query typeName=\"" + getLayerId(MockData.BASIC_POLYGONS)
+ "\"/>\n" + " </wfs:GetFeature>\n" + " </wps:Body>\n"
+ " </wps:Reference>\n" + " </wps:Input>\n" + " <wps:Input>\n"
+ " <ows:Identifier>targetCRS</ows:Identifier>\n" + " <wps:Data>\n"
+ " <wps:LiteralData>EPSG:3395</wps:LiteralData>\n" + " </wps:Data>\n"
+ " </wps:Input>\n" + " </wps:DataInputs>\n" + " <wps:ResponseForm>\n"
+ " <wps:RawDataOutput mimeType=\"text/xml; subtype=wfs-collection/1.1\">\n"
+ " <ows:Identifier>result</ows:Identifier>\n" + " </wps:RawDataOutput>\n"
+ " </wps:ResponseForm>\n" + "</wps:Execute>";
Document response = postAsDOM(root(), xml);
// print(response);
assertXpathEvaluatesTo(
"http://www.opengis.net/gml/srs/epsg.xml#3395",
- "//feature:BasicPolygons[@gml:id='BasicPolygons.1107531493630']/gml:boundedBy/gml:Envelope/@srsName",
+ "(//gml:boundedBy)[2]/gml:Envelope/@srsName",
response);
assertXpathEvaluatesTo("-222638.98158654713 -110579.96522189587",
- "//wfs:FeatureCollection/gml:boundedBy/gml:Envelope/gml:lowerCorner", response);
+ "(//gml:boundedBy)[1]/gml:Envelope/gml:lowerCorner", response);
}
}
| false | true | public void testReproject() throws Exception {
// note, we use 3395 instead of 900913 because it's more accurate, the referencing subsystem
// with assertions enabled will flip if we use the latter due to small reprojection errors
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<wps:Execute version=\"1.0.0\" service=\"WPS\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd\">\n"
+ " <ows:Identifier>gs:Reproject</ows:Identifier>\n"
+ " <wps:DataInputs>\n"
+ " <wps:Input>\n"
+ " <ows:Identifier>features</ows:Identifier>\n"
+ " <wps:Reference mimeType=\"text/xml; subtype=wfs-collection/1.0\" xlink:href=\"http://geoserver/wfs\" method=\"POST\">\n"
+ " <wps:Body>\n"
+ " <wfs:GetFeature service=\"WFS\" version=\"1.0.0\" outputFormat=\"GML2\">\n"
+ " <wfs:Query typeName=\"" + getLayerId(MockData.BASIC_POLYGONS)
+ "\"/>\n" + " </wfs:GetFeature>\n" + " </wps:Body>\n"
+ " </wps:Reference>\n" + " </wps:Input>\n" + " <wps:Input>\n"
+ " <ows:Identifier>targetCRS</ows:Identifier>\n" + " <wps:Data>\n"
+ " <wps:LiteralData>EPSG:3395</wps:LiteralData>\n" + " </wps:Data>\n"
+ " </wps:Input>\n" + " </wps:DataInputs>\n" + " <wps:ResponseForm>\n"
+ " <wps:RawDataOutput mimeType=\"text/xml; subtype=wfs-collection/1.1\">\n"
+ " <ows:Identifier>result</ows:Identifier>\n" + " </wps:RawDataOutput>\n"
+ " </wps:ResponseForm>\n" + "</wps:Execute>";
Document response = postAsDOM(root(), xml);
// print(response);
assertXpathEvaluatesTo(
"http://www.opengis.net/gml/srs/epsg.xml#3395",
"//feature:BasicPolygons[@gml:id='BasicPolygons.1107531493630']/gml:boundedBy/gml:Envelope/@srsName",
response);
assertXpathEvaluatesTo("-222638.98158654713 -110579.96522189587",
"//wfs:FeatureCollection/gml:boundedBy/gml:Envelope/gml:lowerCorner", response);
}
| public void testReproject() throws Exception {
// note, we use 3395 instead of 900913 because it's more accurate, the referencing subsystem
// with assertions enabled will flip if we use the latter due to small reprojection errors
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<wps:Execute version=\"1.0.0\" service=\"WPS\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsAll.xsd\">\n"
+ " <ows:Identifier>gs:Reproject</ows:Identifier>\n"
+ " <wps:DataInputs>\n"
+ " <wps:Input>\n"
+ " <ows:Identifier>features</ows:Identifier>\n"
+ " <wps:Reference mimeType=\"text/xml; subtype=wfs-collection/1.0\" xlink:href=\"http://geoserver/wfs\" method=\"POST\">\n"
+ " <wps:Body>\n"
+ " <wfs:GetFeature service=\"WFS\" version=\"1.0.0\" outputFormat=\"GML2\">\n"
+ " <wfs:Query typeName=\"" + getLayerId(MockData.BASIC_POLYGONS)
+ "\"/>\n" + " </wfs:GetFeature>\n" + " </wps:Body>\n"
+ " </wps:Reference>\n" + " </wps:Input>\n" + " <wps:Input>\n"
+ " <ows:Identifier>targetCRS</ows:Identifier>\n" + " <wps:Data>\n"
+ " <wps:LiteralData>EPSG:3395</wps:LiteralData>\n" + " </wps:Data>\n"
+ " </wps:Input>\n" + " </wps:DataInputs>\n" + " <wps:ResponseForm>\n"
+ " <wps:RawDataOutput mimeType=\"text/xml; subtype=wfs-collection/1.1\">\n"
+ " <ows:Identifier>result</ows:Identifier>\n" + " </wps:RawDataOutput>\n"
+ " </wps:ResponseForm>\n" + "</wps:Execute>";
Document response = postAsDOM(root(), xml);
// print(response);
assertXpathEvaluatesTo(
"http://www.opengis.net/gml/srs/epsg.xml#3395",
"(//gml:boundedBy)[2]/gml:Envelope/@srsName",
response);
assertXpathEvaluatesTo("-222638.98158654713 -110579.96522189587",
"(//gml:boundedBy)[1]/gml:Envelope/gml:lowerCorner", response);
}
|
diff --git a/src/net/rptools/maptool/model/SightType.java b/src/net/rptools/maptool/model/SightType.java
index 2f459a39..3707c3f3 100644
--- a/src/net/rptools/maptool/model/SightType.java
+++ b/src/net/rptools/maptool/model/SightType.java
@@ -1,159 +1,160 @@
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.rptools.maptool.model;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
public class SightType {
private String name;
private double multiplier;
private LightSource personalLightSource;
private ShapeType shape;
private int arc = 0;
private float distance = 0;
private int offset = 0;
public int getOffset()
{
return this.offset;
}
public void setOffset(int offset2)
{
this.offset = offset2;
}
public float getDistance()
{
return this.distance;
}
public void setDistance(float range)
{
this.distance = range;
}
public ShapeType getShape() {
return shape != null ? shape : ShapeType.CIRCLE;
}
public void setShape(ShapeType shape) {
this.shape = shape;
}
public SightType() {
// For serialization
}
public SightType(String name, double multiplier, LightSource personalLightSource)
{
this(name, multiplier, personalLightSource, ShapeType.CIRCLE);
}
public SightType(String name, double multiplier, LightSource personalLightSource, ShapeType shape) {
this.name = name;
this.multiplier = multiplier;
this.personalLightSource = personalLightSource;
this.shape = shape;
}
public SightType(String name, double multiplier, LightSource personalLightSource, ShapeType shape, int arc) {
this.name = name;
this.multiplier = multiplier;
this.personalLightSource = personalLightSource;
this.shape = shape;
this.arc = arc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMultiplier() {
return multiplier;
}
public void setMultiplier(double multiplier) {
this.multiplier = multiplier;
}
public boolean hasPersonalLightSource() {
return personalLightSource != null;
}
public LightSource getPersonalLightSource() {
return personalLightSource;
}
public void setPersonalLightSource(LightSource personalLightSource) {
this.personalLightSource = personalLightSource;
}
public void setArc(int arc)
{
this.arc = arc;
}
public int getArc()
{
return arc;
}
public Area getVisionShape(Token token, Zone zone)
{
float visionRange = getDistance();
int visionDistance = zone.getTokenVisionInPixels();
Area visibleArea = new Area();
visionRange = (visionRange == 0 ) ? visionDistance: visionRange * zone.getGrid().getSize() / zone.getUnitsPerCell() ;
//now calculate the shape and return the shaped Area to the caller
switch (getShape())
{
case CIRCLE:
visibleArea = new Area(new Ellipse2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
case SQUARE:
visibleArea = new Area(new Rectangle2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
case CONE:
if (token.getFacing() == null) {
token.setFacing(0);
}
int offsetAngle = getOffset();
int arcAngle = getArc() ;
//TODO: confirm if we want the offset to be positive-counter-clockwise, negative-clockwise or vice versa
//simply a matter of changing the sign on offsetAngle
Area tempvisibleArea = new Area(new Arc2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2
, 360.0 - (arcAngle/2.0) + (offsetAngle*1.0), arcAngle, Arc2D.PIE));
// Rotate
tempvisibleArea = tempvisibleArea.createTransformedArea(AffineTransform.getRotateInstance(-Math.toRadians(token.getFacing())));
Area footprint = new Area(token.getFootprint(zone.getGrid()).getBounds(zone.getGrid()));
footprint = footprint.createTransformedArea(AffineTransform.getTranslateInstance(-footprint.getBounds().getWidth()/2, -footprint.getBounds().getHeight()/2));
visibleArea.add(footprint);
visibleArea.add(tempvisibleArea);
break;
default:
+ visibleArea = new Area(new Ellipse2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
}
return visibleArea;
}
}
| true | true | public Area getVisionShape(Token token, Zone zone)
{
float visionRange = getDistance();
int visionDistance = zone.getTokenVisionInPixels();
Area visibleArea = new Area();
visionRange = (visionRange == 0 ) ? visionDistance: visionRange * zone.getGrid().getSize() / zone.getUnitsPerCell() ;
//now calculate the shape and return the shaped Area to the caller
switch (getShape())
{
case CIRCLE:
visibleArea = new Area(new Ellipse2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
case SQUARE:
visibleArea = new Area(new Rectangle2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
case CONE:
if (token.getFacing() == null) {
token.setFacing(0);
}
int offsetAngle = getOffset();
int arcAngle = getArc() ;
//TODO: confirm if we want the offset to be positive-counter-clockwise, negative-clockwise or vice versa
//simply a matter of changing the sign on offsetAngle
Area tempvisibleArea = new Area(new Arc2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2
, 360.0 - (arcAngle/2.0) + (offsetAngle*1.0), arcAngle, Arc2D.PIE));
// Rotate
tempvisibleArea = tempvisibleArea.createTransformedArea(AffineTransform.getRotateInstance(-Math.toRadians(token.getFacing())));
Area footprint = new Area(token.getFootprint(zone.getGrid()).getBounds(zone.getGrid()));
footprint = footprint.createTransformedArea(AffineTransform.getTranslateInstance(-footprint.getBounds().getWidth()/2, -footprint.getBounds().getHeight()/2));
visibleArea.add(footprint);
visibleArea.add(tempvisibleArea);
break;
default:
break;
}
return visibleArea;
}
| public Area getVisionShape(Token token, Zone zone)
{
float visionRange = getDistance();
int visionDistance = zone.getTokenVisionInPixels();
Area visibleArea = new Area();
visionRange = (visionRange == 0 ) ? visionDistance: visionRange * zone.getGrid().getSize() / zone.getUnitsPerCell() ;
//now calculate the shape and return the shaped Area to the caller
switch (getShape())
{
case CIRCLE:
visibleArea = new Area(new Ellipse2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
case SQUARE:
visibleArea = new Area(new Rectangle2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
case CONE:
if (token.getFacing() == null) {
token.setFacing(0);
}
int offsetAngle = getOffset();
int arcAngle = getArc() ;
//TODO: confirm if we want the offset to be positive-counter-clockwise, negative-clockwise or vice versa
//simply a matter of changing the sign on offsetAngle
Area tempvisibleArea = new Area(new Arc2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2
, 360.0 - (arcAngle/2.0) + (offsetAngle*1.0), arcAngle, Arc2D.PIE));
// Rotate
tempvisibleArea = tempvisibleArea.createTransformedArea(AffineTransform.getRotateInstance(-Math.toRadians(token.getFacing())));
Area footprint = new Area(token.getFootprint(zone.getGrid()).getBounds(zone.getGrid()));
footprint = footprint.createTransformedArea(AffineTransform.getTranslateInstance(-footprint.getBounds().getWidth()/2, -footprint.getBounds().getHeight()/2));
visibleArea.add(footprint);
visibleArea.add(tempvisibleArea);
break;
default:
visibleArea = new Area(new Ellipse2D.Double(-visionRange, -visionRange, visionRange*2, visionRange*2));
break;
}
return visibleArea;
}
|
diff --git a/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/SelectionVisualHandler.java b/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/SelectionVisualHandler.java
index ca1f8fd3..da862937 100644
--- a/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/SelectionVisualHandler.java
+++ b/net.sourceforge.vrapper.eclipse/src/net/sourceforge/vrapper/eclipse/interceptor/SelectionVisualHandler.java
@@ -1,89 +1,92 @@
package net.sourceforge.vrapper.eclipse.interceptor;
import net.sourceforge.vrapper.eclipse.activator.VrapperPlugin;
import net.sourceforge.vrapper.eclipse.platform.EclipseCursorAndSelection;
import net.sourceforge.vrapper.log.VrapperLog;
import net.sourceforge.vrapper.vim.DefaultEditorAdaptor;
import net.sourceforge.vrapper.vim.Options;
import net.sourceforge.vrapper.vim.commands.motions.StickyColumnPolicy;
import net.sourceforge.vrapper.vim.modes.AbstractVisualMode;
import net.sourceforge.vrapper.vim.modes.CommandBasedMode;
import net.sourceforge.vrapper.vim.modes.EditorMode;
import net.sourceforge.vrapper.vim.modes.InsertMode;
import net.sourceforge.vrapper.vim.modes.NormalMode;
import net.sourceforge.vrapper.vim.modes.TempVisualMode;
import net.sourceforge.vrapper.vim.modes.TemporaryMode;
import net.sourceforge.vrapper.vim.modes.VisualMode;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
public class SelectionVisualHandler implements ISelectionChangedListener {
private DefaultEditorAdaptor editorAdaptor;
private EclipseCursorAndSelection selectionService;
private ITextViewer textViewer;
private int selectionResetOffset = -1;
public SelectionVisualHandler(DefaultEditorAdaptor editorAdaptor,
EclipseCursorAndSelection selectionService, ITextViewer viewer) {
this.editorAdaptor = editorAdaptor;
this.textViewer = viewer;
this.selectionService = selectionService;
}
public void selectionChanged(SelectionChangedEvent event) {
if (!VrapperPlugin.isVrapperEnabled() || !(event.getSelection() instanceof TextSelection)
|| selectionService.isSelectionInProgress()) {
return;
}
TextSelection selection = (TextSelection) event.getSelection();
// selection.isEmpty() is false even if length == 0, don't use it
if (selection.getLength() == 0) {
+ // Explicitly reset selection. EclipseCursorAndSelection's SelectionChangeListener is
+ // only fired after this listener, returning a stale selection during a mode switch.
+ selectionService.setSelection(null);
try {
int offset = selection.getOffset();
IRegion lineInfo = textViewer.getDocument().getLineInformationOfOffset(offset);
// Checks if cursor is just before line end because Normalmode will move it.
if (lineInfo.getOffset() + lineInfo.getLength() == offset) {
selectionResetOffset = offset;
} else {
selectionResetOffset = -1;
}
} catch (BadLocationException e) {
VrapperLog.error("Received bad selection offset in selectionchange handler", e);
}
EditorMode currentMode = editorAdaptor.getMode(editorAdaptor.getCurrentModeName());
// User cleared selection or moved caret with mouse in a temporary mode.
if(currentMode instanceof TemporaryMode) {
editorAdaptor.changeModeSafely(InsertMode.NAME);
} else if(currentMode instanceof AbstractVisualMode){
editorAdaptor.changeModeSafely(NormalMode.NAME);
// Cursor can be after the line if an Eclipse operation cleared the selection, e.g. undo
} else if (currentMode instanceof CommandBasedMode) {
CommandBasedMode commandMode = (CommandBasedMode) currentMode;
commandMode.placeCursor(StickyColumnPolicy.RESET_EOL);
}
} else if ( ! VrapperPlugin.isMouseDown()
|| !editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE)) {
return;
// Detect if a reverse selection got its last character chopped off.
} else if (selectionResetOffset != -1
&& (selection.getOffset() + selection.getLength() + 1) == selectionResetOffset) {
textViewer.setSelectedRange(selectionResetOffset, - (selection.getLength() + 1));
selectionResetOffset = -1;
} else if (selection.getLength() != 0) {
if(NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(VisualMode.NAME, AbstractVisualMode.KEEP_SELECTION_HINT);
}
else if (InsertMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(TempVisualMode.NAME,
AbstractVisualMode.KEEP_SELECTION_HINT, InsertMode.DONT_MOVE_CURSOR);
}
}
}
}
| true | true | public void selectionChanged(SelectionChangedEvent event) {
if (!VrapperPlugin.isVrapperEnabled() || !(event.getSelection() instanceof TextSelection)
|| selectionService.isSelectionInProgress()) {
return;
}
TextSelection selection = (TextSelection) event.getSelection();
// selection.isEmpty() is false even if length == 0, don't use it
if (selection.getLength() == 0) {
try {
int offset = selection.getOffset();
IRegion lineInfo = textViewer.getDocument().getLineInformationOfOffset(offset);
// Checks if cursor is just before line end because Normalmode will move it.
if (lineInfo.getOffset() + lineInfo.getLength() == offset) {
selectionResetOffset = offset;
} else {
selectionResetOffset = -1;
}
} catch (BadLocationException e) {
VrapperLog.error("Received bad selection offset in selectionchange handler", e);
}
EditorMode currentMode = editorAdaptor.getMode(editorAdaptor.getCurrentModeName());
// User cleared selection or moved caret with mouse in a temporary mode.
if(currentMode instanceof TemporaryMode) {
editorAdaptor.changeModeSafely(InsertMode.NAME);
} else if(currentMode instanceof AbstractVisualMode){
editorAdaptor.changeModeSafely(NormalMode.NAME);
// Cursor can be after the line if an Eclipse operation cleared the selection, e.g. undo
} else if (currentMode instanceof CommandBasedMode) {
CommandBasedMode commandMode = (CommandBasedMode) currentMode;
commandMode.placeCursor(StickyColumnPolicy.RESET_EOL);
}
} else if ( ! VrapperPlugin.isMouseDown()
|| !editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE)) {
return;
// Detect if a reverse selection got its last character chopped off.
} else if (selectionResetOffset != -1
&& (selection.getOffset() + selection.getLength() + 1) == selectionResetOffset) {
textViewer.setSelectedRange(selectionResetOffset, - (selection.getLength() + 1));
selectionResetOffset = -1;
} else if (selection.getLength() != 0) {
if(NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(VisualMode.NAME, AbstractVisualMode.KEEP_SELECTION_HINT);
}
else if (InsertMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(TempVisualMode.NAME,
AbstractVisualMode.KEEP_SELECTION_HINT, InsertMode.DONT_MOVE_CURSOR);
}
}
}
| public void selectionChanged(SelectionChangedEvent event) {
if (!VrapperPlugin.isVrapperEnabled() || !(event.getSelection() instanceof TextSelection)
|| selectionService.isSelectionInProgress()) {
return;
}
TextSelection selection = (TextSelection) event.getSelection();
// selection.isEmpty() is false even if length == 0, don't use it
if (selection.getLength() == 0) {
// Explicitly reset selection. EclipseCursorAndSelection's SelectionChangeListener is
// only fired after this listener, returning a stale selection during a mode switch.
selectionService.setSelection(null);
try {
int offset = selection.getOffset();
IRegion lineInfo = textViewer.getDocument().getLineInformationOfOffset(offset);
// Checks if cursor is just before line end because Normalmode will move it.
if (lineInfo.getOffset() + lineInfo.getLength() == offset) {
selectionResetOffset = offset;
} else {
selectionResetOffset = -1;
}
} catch (BadLocationException e) {
VrapperLog.error("Received bad selection offset in selectionchange handler", e);
}
EditorMode currentMode = editorAdaptor.getMode(editorAdaptor.getCurrentModeName());
// User cleared selection or moved caret with mouse in a temporary mode.
if(currentMode instanceof TemporaryMode) {
editorAdaptor.changeModeSafely(InsertMode.NAME);
} else if(currentMode instanceof AbstractVisualMode){
editorAdaptor.changeModeSafely(NormalMode.NAME);
// Cursor can be after the line if an Eclipse operation cleared the selection, e.g. undo
} else if (currentMode instanceof CommandBasedMode) {
CommandBasedMode commandMode = (CommandBasedMode) currentMode;
commandMode.placeCursor(StickyColumnPolicy.RESET_EOL);
}
} else if ( ! VrapperPlugin.isMouseDown()
|| !editorAdaptor.getConfiguration().get(Options.VISUAL_MOUSE)) {
return;
// Detect if a reverse selection got its last character chopped off.
} else if (selectionResetOffset != -1
&& (selection.getOffset() + selection.getLength() + 1) == selectionResetOffset) {
textViewer.setSelectedRange(selectionResetOffset, - (selection.getLength() + 1));
selectionResetOffset = -1;
} else if (selection.getLength() != 0) {
if(NormalMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(VisualMode.NAME, AbstractVisualMode.KEEP_SELECTION_HINT);
}
else if (InsertMode.NAME.equals(editorAdaptor.getCurrentModeName())) {
editorAdaptor.changeModeSafely(TempVisualMode.NAME,
AbstractVisualMode.KEEP_SELECTION_HINT, InsertMode.DONT_MOVE_CURSOR);
}
}
}
|
diff --git a/com.ibm.wala.cast.js/source/com/ibm/wala/cast/js/html/DefaultSourceExtractor.java b/com.ibm.wala.cast.js/source/com/ibm/wala/cast/js/html/DefaultSourceExtractor.java
index 45ec62b16..ed5b6e622 100644
--- a/com.ibm.wala.cast.js/source/com/ibm/wala/cast/js/html/DefaultSourceExtractor.java
+++ b/com.ibm.wala.cast.js/source/com/ibm/wala/cast/js/html/DefaultSourceExtractor.java
@@ -1,185 +1,185 @@
/******************************************************************************
* Copyright (c) 2002 - 2011 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package com.ibm.wala.cast.js.html;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Pair;
public class DefaultSourceExtractor extends DomLessSourceExtractor{
private static class HtmlCallBack extends DomLessSourceExtractor.HtmlCallback{
private final HashMap<String, String> constructors = HashMapFactory.make();
private final Stack<String> stack = new Stack<String>();
private final Stack<ITag> forms = new Stack<ITag>();
private final Set<Pair<ITag,String>> sets = new HashSet<Pair<ITag,String>>();
public HtmlCallBack(URL entrypointUrl, IUrlResolver urlResolver) {
super(entrypointUrl, urlResolver);
constructors.put("FORM", "DOMHTMLFormElement");
constructors.put("TABLE", "DOMHTMLTableElement");
}
@Override
public void handleEndTag(ITag tag) {
super.handleEndTag(tag);
endElement(stack.pop());
if (tag.getName().equalsIgnoreCase("FORM")) {
forms.pop();
}
for(Entry<String,Pair<String, Position>> e : tag.getAllAttributes().entrySet()) {
String a = e.getKey();
String v = e.getValue().fst;
if (v != null && v.startsWith("javascript:")) {
try {
entrypointRegion.println(" " + v.substring(11), e.getValue().snd, new URL(tag.getElementPosition().getURL().toString() + "#" + a));
} catch (MalformedURLException ex) {
entrypointRegion.println(v.substring(11), e.getValue().snd, entrypointUrl);
}
}
}
}
@Override
protected void handleDOM(ITag tag, String funcName) {
String cons = constructors.get(tag.getName().toUpperCase());
if(cons == null) cons = "DOMHTMLElement";
writeElement(tag, cons, funcName);
newLine();
}
private void printlnIndented(String line, ITag relatedTag){
printlnIndented(line, relatedTag==null? null: relatedTag.getElementPosition());
}
private void printlnIndented(String line, Position pos){
StringBuilder indentedLine = new StringBuilder();
for (int i = 0 ; i < stack.size() ; i++){
indentedLine.append(" ");
}
indentedLine.append(line);
if (pos == null){
domRegion.println(indentedLine.toString());
} else {
domRegion.println(indentedLine.toString(), pos, entrypointUrl);
}
}
private void newLine(){
domRegion.println("");
}
protected void writeElement(ITag tag, String cons, String varName){
Map<String, Pair<String, Position>> attrs = tag.getAllAttributes();
printlnIndented("function make_" + varName + "(parent) {", tag);
stack.push(varName);
printlnIndented("this.temp = " + cons + ";", tag);
printlnIndented("this.temp(\"" + tag.getName() + "\");", tag);
for (Map.Entry<String, Pair<String, Position>> e : attrs.entrySet()){
String attr = e.getKey();
String value = e.getValue().fst;
writeAttribute(tag, e.getValue().snd, attr, value, "this", varName);
}
if (tag.getName().equalsIgnoreCase("FORM")) {
forms.push(tag);
printlnIndented(" document.forms[document.formCount++] = this;", tag);
printlnIndented(" var currentForm = this;", tag);
} if (tag.getName().equalsIgnoreCase("INPUT")) {
- String prop = attrs.get("name").fst;
- String type = attrs.get("type").fst;
+ String prop = attrs.containsKey("name") ? attrs.get("name").fst : null;
+ String type = attrs.containsKey("type") ? attrs.get("type").fst : null;
if (type != null && prop != null) {
if (type.equalsIgnoreCase("RADIO")) {
if (! sets.contains(Pair.make(forms.peek(), prop))) {
sets.add(Pair.make(forms.peek(), prop));
printlnIndented(" currentForm." + prop + " = new Array();", tag);
printlnIndented(" currentForm." + prop + "Counter = 0;", tag);
}
printlnIndented(" currentForm." + prop + "[currentForm." + prop + "Counter++] = this;", tag);
} else {
printlnIndented(" currentForm." + prop + " = this;", tag);
}
}
}
printlnIndented(varName + " = this;", tag);
printlnIndented("document." + varName + " = this;", tag);
printlnIndented("parent.appendChild(this);", tag);
}
protected void writeAttribute(ITag tag, Position pos, String attr, String value, String varName, String varName2) {
writePortletAttribute(tag, attr, value, varName);
writeEventAttribute(tag, pos, attr, value, varName, varName2);
}
protected void writeEventAttribute(ITag tag, Position pos, String attr, String value, String varName, String varName2){
if(attr.substring(0,2).equals("on")) {
printlnIndented(varName + "." + attr + " = function " + tag.getName().toLowerCase() + "_" + attr + "(event) {" + value + "};", tag);
entrypointRegion.println(varName2 + "." + attr + "(null);", tag.getElementPosition(), entrypointUrl);
} else if (value != null) {
if (value.indexOf('\'') > 0) {
value = value.replaceAll("\\'", "\\\\'");
}
if (value.indexOf('\n') > 0) {
value = value.replaceAll("\\n", "\\\\n");
}
if (attr.equals(attr.toUpperCase())) {
attr = attr.toLowerCase();
}
printlnIndented(varName + "['" + attr + "'] = '" + value + "';", tag);
}
}
protected void writePortletAttribute(ITag tag, String attr, String value, String varName){
if(attr.equals("portletid")) {
if(value.substring(value.length()-4).equals("vice")) {
newLine(); newLine();
printlnIndented("function cVice() { var contextVice = " + varName + "; }\ncVice();\n", tag);
} else if(value.substring(value.length()-4).equals("root")) {
newLine(); newLine();
printlnIndented("function cRoot() { var contextRoot = " + varName + "; }\ncRoot();\n", tag);
}
}
}
protected void endElement(String name) {
printlnIndented("};", (Position)null);
if (stack.isEmpty()) {
printlnIndented("new make_" + name + "(document);\n\n", (Position)null);
} else {
printlnIndented("new make_" + name + "(this);\n", (Position)null);
}
}
}
@Override
protected IGeneratorCallback createHtmlCallback(URL entrypointUrl, IUrlResolver urlResolver) {
return new HtmlCallBack(entrypointUrl, urlResolver);
}
}
| true | true | protected void writeElement(ITag tag, String cons, String varName){
Map<String, Pair<String, Position>> attrs = tag.getAllAttributes();
printlnIndented("function make_" + varName + "(parent) {", tag);
stack.push(varName);
printlnIndented("this.temp = " + cons + ";", tag);
printlnIndented("this.temp(\"" + tag.getName() + "\");", tag);
for (Map.Entry<String, Pair<String, Position>> e : attrs.entrySet()){
String attr = e.getKey();
String value = e.getValue().fst;
writeAttribute(tag, e.getValue().snd, attr, value, "this", varName);
}
if (tag.getName().equalsIgnoreCase("FORM")) {
forms.push(tag);
printlnIndented(" document.forms[document.formCount++] = this;", tag);
printlnIndented(" var currentForm = this;", tag);
} if (tag.getName().equalsIgnoreCase("INPUT")) {
String prop = attrs.get("name").fst;
String type = attrs.get("type").fst;
if (type != null && prop != null) {
if (type.equalsIgnoreCase("RADIO")) {
if (! sets.contains(Pair.make(forms.peek(), prop))) {
sets.add(Pair.make(forms.peek(), prop));
printlnIndented(" currentForm." + prop + " = new Array();", tag);
printlnIndented(" currentForm." + prop + "Counter = 0;", tag);
}
printlnIndented(" currentForm." + prop + "[currentForm." + prop + "Counter++] = this;", tag);
} else {
printlnIndented(" currentForm." + prop + " = this;", tag);
}
}
}
printlnIndented(varName + " = this;", tag);
printlnIndented("document." + varName + " = this;", tag);
printlnIndented("parent.appendChild(this);", tag);
}
| protected void writeElement(ITag tag, String cons, String varName){
Map<String, Pair<String, Position>> attrs = tag.getAllAttributes();
printlnIndented("function make_" + varName + "(parent) {", tag);
stack.push(varName);
printlnIndented("this.temp = " + cons + ";", tag);
printlnIndented("this.temp(\"" + tag.getName() + "\");", tag);
for (Map.Entry<String, Pair<String, Position>> e : attrs.entrySet()){
String attr = e.getKey();
String value = e.getValue().fst;
writeAttribute(tag, e.getValue().snd, attr, value, "this", varName);
}
if (tag.getName().equalsIgnoreCase("FORM")) {
forms.push(tag);
printlnIndented(" document.forms[document.formCount++] = this;", tag);
printlnIndented(" var currentForm = this;", tag);
} if (tag.getName().equalsIgnoreCase("INPUT")) {
String prop = attrs.containsKey("name") ? attrs.get("name").fst : null;
String type = attrs.containsKey("type") ? attrs.get("type").fst : null;
if (type != null && prop != null) {
if (type.equalsIgnoreCase("RADIO")) {
if (! sets.contains(Pair.make(forms.peek(), prop))) {
sets.add(Pair.make(forms.peek(), prop));
printlnIndented(" currentForm." + prop + " = new Array();", tag);
printlnIndented(" currentForm." + prop + "Counter = 0;", tag);
}
printlnIndented(" currentForm." + prop + "[currentForm." + prop + "Counter++] = this;", tag);
} else {
printlnIndented(" currentForm." + prop + " = this;", tag);
}
}
}
printlnIndented(varName + " = this;", tag);
printlnIndented("document." + varName + " = this;", tag);
printlnIndented("parent.appendChild(this);", tag);
}
|
diff --git a/src/main/java/nl/surfnet/bod/service/ReservationService.java b/src/main/java/nl/surfnet/bod/service/ReservationService.java
index 93b6b0f81..518ecf16e 100644
--- a/src/main/java/nl/surfnet/bod/service/ReservationService.java
+++ b/src/main/java/nl/surfnet/bod/service/ReservationService.java
@@ -1,127 +1,127 @@
/**
* The owner of the original code is SURFnet BV.
*
* Portions created by the original owner are Copyright (C) 2011-2012 the
* original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of the SURFnet7 Bandwidth on Demand software.
*
* The SURFnet7 Bandwidth on Demand software is free software: you can
* redistribute it and/or modify it under the terms of the BSD license
* included with this distribution.
*
* If the BSD license cannot be found with this distribution, it is available
* at the following location <http://www.opensource.org/licenses/BSD-3-Clause>
*/
package nl.surfnet.bod.service;
import static com.google.common.base.Preconditions.checkState;
import static nl.surfnet.bod.domain.ReservationStatus.CANCELLED;
import static nl.surfnet.bod.domain.ReservationStatus.RUNNING;
import static nl.surfnet.bod.domain.ReservationStatus.SCHEDULED;
import java.util.Collection;
import java.util.Collections;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import nl.surfnet.bod.domain.Reservation;
import nl.surfnet.bod.domain.ReservationStatus;
import nl.surfnet.bod.repo.ReservationRepo;
import nl.surfnet.bod.web.security.RichUserDetails;
import nl.surfnet.bod.web.security.Security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ReservationService {
@Autowired
private ReservationRepo reservationRepo;
@Autowired
@Qualifier("nbiService")
private NbiService nbiService;
public void reserve(Reservation reservation) throws ReservationFailedException {
checkState(reservation.getSourcePort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
checkState(reservation.getDestinationPort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
final String reservationId = nbiService.createReservation(reservation);
if (reservationId == null) {
throw new ReservationFailedException("Unable to create reservation: " + reservation);
}
reservation.setReservationId(reservationId);
- reservation.setStatus(getStatus(null));
+ reservation.setStatus(getStatus(reservation));
reservationRepo.save(reservation);
}
public Reservation find(Long id) {
return reservationRepo.findOne(id);
}
public Collection<Reservation> findEntries(int firstResult, int maxResults) {
final RichUserDetails user = Security.getUserDetails();
if (user.getUserGroups().isEmpty()) {
return Collections.emptyList();
}
return reservationRepo.findAll(forCurrentUser(user), new PageRequest(firstResult / maxResults, maxResults))
.getContent();
}
public long count() {
final RichUserDetails user = Security.getUserDetails();
if (user.getUserGroups().isEmpty()) {
return 0;
}
return reservationRepo.count(forCurrentUser(user));
}
private Specification<Reservation> forCurrentUser(final RichUserDetails user) {
return new Specification<Reservation>() {
@Override
public Predicate toPredicate(Root<Reservation> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.and(root.get("virtualResourceGroup").get("surfConextGroupName").in(user.getUserGroupIds()));
}
};
}
public Reservation update(Reservation reservation) {
checkState(reservation.getSourcePort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
checkState(reservation.getDestinationPort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
return reservationRepo.save(reservation);
}
public void cancel(Reservation reservation) {
if (reservation.getStatus() == RUNNING || reservation.getStatus() == SCHEDULED) {
reservation.setStatus(CANCELLED);
nbiService.cancelReservation(reservation.getReservationId());
reservationRepo.save(reservation);
}
}
public ReservationStatus getStatus(Reservation reservation) {
return nbiService.getReservationStatus(reservation.getReservationId());
}
}
| true | true | public void reserve(Reservation reservation) throws ReservationFailedException {
checkState(reservation.getSourcePort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
checkState(reservation.getDestinationPort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
final String reservationId = nbiService.createReservation(reservation);
if (reservationId == null) {
throw new ReservationFailedException("Unable to create reservation: " + reservation);
}
reservation.setReservationId(reservationId);
reservation.setStatus(getStatus(null));
reservationRepo.save(reservation);
}
| public void reserve(Reservation reservation) throws ReservationFailedException {
checkState(reservation.getSourcePort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
checkState(reservation.getDestinationPort().getVirtualResourceGroup().equals(reservation.getVirtualResourceGroup()));
final String reservationId = nbiService.createReservation(reservation);
if (reservationId == null) {
throw new ReservationFailedException("Unable to create reservation: " + reservation);
}
reservation.setReservationId(reservationId);
reservation.setStatus(getStatus(reservation));
reservationRepo.save(reservation);
}
|
diff --git a/src/org/python/util/PyFilter.java b/src/org/python/util/PyFilter.java
index 1375c5cc..35534d39 100644
--- a/src/org/python/util/PyFilter.java
+++ b/src/org/python/util/PyFilter.java
@@ -1,143 +1,144 @@
package org.python.util;
import java.io.File;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.python.core.PyException;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;
/**
* Enables you to write Jython modules that inherit from <code>javax.servlet.Filter</code>, and to
* insert them in your servlet container's filter chain, like any Java <code>Filter</code>.
*
* <p>
* Example:
*
* <p>
* <b>/WEB-INF/filters/HeaderFilter.py:</b>
*
* <pre>
* from javax.servlet import Filter
*
* # Module must contain a class with the same name as the module
* # which in turn must implement javax.servlet.Filter
* class HeaderFilter (Filter):
* def init(self, config):
* self.header = config.getInitParameter('header')
*
* def doFilter(self, request, response, chain):
* response.setHeader(self.header, "Yup")
* chain.doFilter(request, response)
* </pre>
*
* <p>
* <b>web.xml:</b>
* </p>
*
* <pre>
* <!-- Initialize the Jython runtime -->
* <listener>
* <listener-class>org.python.util.PyServletInitializer</listener-class>
* <load-on-startup>1</load-on-startup>
* </listener>
*
* <!-- Declare a uniquely-named PyFilter -->
* <filter>
* <filter-name>HeaderFilter</filter-name>
* <filter-class>org.python.util.PyFilter</filter-class>
*
* <!-- The special param __filter__ gives the context-relative path to the Jython source file -->
* <init-param>
* <param-name>__filter__</param-name>
* <param-value>/WEB-INF/pyfilter/HeaderFilter.py</param-value>
* </init-param>
*
* <!-- Other params are passed on the the Jython filter -->
* <init-param>
* <param-name>header</param-name>
* <param-value>X-LookMaNoJava</param-value>
* </init-param>
* </filter>
* <filter-mapping>
* <filter-name>HeaderFilter</filter-name>
* <url-pattern>/*</url-pattern>
* </filter-mapping>
* </pre>
*/
public class PyFilter implements Filter {
public static final String FILTER_PATH_PARAM = "__filter__";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setAttribute("pyfilter", this);
getFilter().doFilter(request, response, chain);
}
public void init(FilterConfig config) throws ServletException {
if (config.getServletContext().getAttribute(PyServlet.INIT_ATTR) == null) {
- throw new ServletException("PyServlet has not been initialized, either as a servlet "
- + "or as context listener. This must happen before PyFilter is initialized.");
+ throw new ServletException("Jython has not been initialized. Add "
+ + "org.python.util.PyServletInitializer as a listener to your "
+ + "web.xml.");
}
this.config = config;
String filterPath = config.getInitParameter(FILTER_PATH_PARAM);
if (filterPath == null) {
throw new ServletException("Missing required param '" + FILTER_PATH_PARAM + "'");
}
source = new File(getRealPath(config.getServletContext(), filterPath));
if (!source.exists()) {
throw new ServletException(source.getAbsolutePath() + " does not exist.");
}
interp = new PythonInterpreter(null, new PySystemState());
}
private String getRealPath(ServletContext context, String appPath) {
String realPath = context.getRealPath(appPath);
// This madness seems to be necessary on Windows
return realPath.replaceAll("\\\\", "/");
}
private Filter getFilter() throws ServletException, IOException {
if (cached == null || source.lastModified() > loadedMtime) {
return loadFilter();
}
return cached;
}
private Filter loadFilter() throws ServletException, IOException {
loadedMtime = source.lastModified();
cached = PyServlet.createInstance(interp, source, Filter.class);
try {
cached.init(config);
} catch (PyException e) {
throw new ServletException(e);
}
return cached;
}
public void destroy() {
if (cached != null) {
cached.destroy();
}
if (interp != null) {
interp.cleanup();
}
}
private PythonInterpreter interp;
private FilterConfig config;
private File source;
private Filter cached;
private long loadedMtime;
}
| true | true | public void init(FilterConfig config) throws ServletException {
if (config.getServletContext().getAttribute(PyServlet.INIT_ATTR) == null) {
throw new ServletException("PyServlet has not been initialized, either as a servlet "
+ "or as context listener. This must happen before PyFilter is initialized.");
}
this.config = config;
String filterPath = config.getInitParameter(FILTER_PATH_PARAM);
if (filterPath == null) {
throw new ServletException("Missing required param '" + FILTER_PATH_PARAM + "'");
}
source = new File(getRealPath(config.getServletContext(), filterPath));
if (!source.exists()) {
throw new ServletException(source.getAbsolutePath() + " does not exist.");
}
interp = new PythonInterpreter(null, new PySystemState());
}
| public void init(FilterConfig config) throws ServletException {
if (config.getServletContext().getAttribute(PyServlet.INIT_ATTR) == null) {
throw new ServletException("Jython has not been initialized. Add "
+ "org.python.util.PyServletInitializer as a listener to your "
+ "web.xml.");
}
this.config = config;
String filterPath = config.getInitParameter(FILTER_PATH_PARAM);
if (filterPath == null) {
throw new ServletException("Missing required param '" + FILTER_PATH_PARAM + "'");
}
source = new File(getRealPath(config.getServletContext(), filterPath));
if (!source.exists()) {
throw new ServletException(source.getAbsolutePath() + " does not exist.");
}
interp = new PythonInterpreter(null, new PySystemState());
}
|
diff --git a/pi/pipair.java b/pi/pipair.java
index 53191df..a7fc0ac 100644
--- a/pi/pipair.java
+++ b/pi/pipair.java
@@ -1,278 +1,278 @@
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Collections;
import java.io.IOException;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.math.RoundingMode;
class Pipair {
int tSupport = 3;
float tConfidence = 0.65f;
class Pair {
private String _aName;
private String _bName;
private int _support = 0;
private float _aWithoutB = 0;
public Pair(String aName, String bName) {
_aName = aName;
_bName = bName;
}
public String getSource() {
return _aName;
}
public String getTarget() {
return _bName;
}
public void strengthen() {
_support++;
}
public void weaken() {
_aWithoutB++;
}
public int getSupport() {
return _support;
}
public float getConfidence() {
return (float)_support / _aWithoutB;
}
public String toString() {
NumberFormat numf = NumberFormat.getNumberInstance();
numf.setMaximumFractionDigits(2);
numf.setRoundingMode(RoundingMode.HALF_EVEN);
return "pair: (" +
getSource() + " " + getTarget() + "), support: " +
getSupport() + ", confidence: " +
numf.format(getConfidence() * 100.0) + "%";
}
}
class Violation {
private String _caller;
private Pair _pair;
public Violation(String caller, Pair pair) {
_caller = caller;
_pair = pair;
}
public String toString() {
return "bug: " + _pair.getSource() + " in " + _caller + ", " +
_pair.toString();
}
}
public Hashtable<String,ArrayList<String>> parseFile(String fileName) {
Runtime rt = Runtime.getRuntime();
Hashtable<String, ArrayList<String>> table = new Hashtable<String,ArrayList<String>>();
try {
- Process pr = rt.exec("opt -print-callgraph " + fileName);
+ Process pr = rt.exec("opt -print-callgraph -disable-output " + fileName);
InputStream st = pr.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(st));
String line = null;
int state = 0; //0 - Empty Line, 1 - Call graph
String current = null;
while ((line = in.readLine()) != null) {
//System.out.println(line + " " + line.length());
switch (state) {
case(1):
if (line.matches("(.*)CS<0x[0-9a-f]*> calls function(.*)")) {
String[] slist = line.split("\'");
String func = slist[1];
ArrayList<String> curList = table.get(current);
curList.add(func);
//System.out.println(func);
break;
}
case(0):
if (line.startsWith("Call graph node for function")) {
String[] slist = line.split("\'");
current = slist[1];
ArrayList<String> nlist = new ArrayList<String>();
table.put(current,nlist);
state = 1;
//System.out.println(current);
break;
}
default:
if (line.length() == 0) {
state = 0;
//System.out.println("");
}
break;
}
}
} catch (IOException e) {
}
return table;
}
public Hashtable<String,Hashtable<String,Pair>>
getInvariantPairs(Hashtable<String,ArrayList<String>> cg) {
Hashtable<String,Hashtable<String,Pair>> pairs = getAllInvariantPairs(cg);
rejectWeakPairs(pairs);
return pairs;
}
private Hashtable<String,Hashtable<String,Pair>> getAllInvariantPairs(Hashtable<String,ArrayList<String>> cg) {
Hashtable<String,Hashtable<String,Pair>> pairs =
new Hashtable<String,Hashtable<String,Pair>>();
Enumeration funcs = cg.elements();
while (funcs.hasMoreElements()) {
ArrayList<String> calls = (ArrayList<String>)funcs.nextElement();
calls = removeDuplicateCalls(calls);
for (int i = 0; i < calls.size(); i++) {
for (int j = i + 1; j < calls.size(); j++) {
createOrStrengthenPair(pairs, calls.get(i), calls.get(j));
createOrStrengthenPair(pairs, calls.get(j), calls.get(i));
}
Hashtable<String,Pair> existingPairs = pairs.get(calls.get(i));
if (existingPairs != null) {
Enumeration e = existingPairs.elements();
while (e.hasMoreElements()) {
Pair p = (Pair)e.nextElement();
p.weaken();
}
}
}
}
return pairs;
}
private void
rejectWeakPairs(Hashtable<String,Hashtable<String,Pair>> pairs) {
Enumeration<Hashtable<String,Pair>> pairLists = pairs.elements();
while (pairLists.hasMoreElements()) {
Hashtable<String,Pair> pairList = (Hashtable<String,Pair>)pairLists.nextElement();
Enumeration<String> bNames = pairList.keys();
while (bNames.hasMoreElements()) {
String bName = bNames.nextElement();
Pair p = (Pair)pairList.get(bName);
if (p.getSupport() < tSupport ||
p.getConfidence() < tConfidence) {
pairList.remove(bName);
}
}
}
}
private void createOrStrengthenPair(Hashtable<String,Hashtable<String,Pair>>
pairs,
String f1, String f2) {
Hashtable<String,Pair> funcPairs = pairs.get(f1);
if (funcPairs == null) {
funcPairs = new Hashtable<String,Pair>();
pairs.put(f1, funcPairs);
}
Pair p = funcPairs.get(f2);
if (p == null) {
p = new Pair(f1, f2);
funcPairs.put(f2, p);
}
p.strengthen();
}
private ArrayList<String> removeDuplicateCalls(ArrayList<String> calls) {
HashSet<String> callSet = new HashSet<String>(calls);
calls = new ArrayList<String>(callSet);
return calls;
}
public ArrayList<Violation>
getViolations(Hashtable<String,ArrayList<String>> cg,
Hashtable<String,Hashtable<String,Pair>> invariants) {
ArrayList<Violation> violations = new ArrayList<Violation>();
Set<Map.Entry<String,ArrayList<String>>> cgSet = cg.entrySet();
Iterator functions = cgSet.iterator();
while (functions.hasNext()) {
Map.Entry<String,ArrayList<String>> entry = (Map.Entry<String,ArrayList<String>>)functions.next();
String functionName = (String)entry.getKey();
ArrayList<String> callsL = (ArrayList<String>)entry.getValue();
HashSet<String> calls = new HashSet<String>(callsL);
Iterator i = calls.iterator();
while (i.hasNext()) {
Hashtable<String,Pair> invariantsForCall = invariants.get(i.next());
if (invariantsForCall == null) {
continue;
}
Enumeration pairs = invariantsForCall.elements();
while (pairs.hasMoreElements()) {
Pair invariant = (Pair)pairs.nextElement();
if (!calls.contains(invariant.getTarget())) {
violations.add(new Violation(functionName,
invariant));
}
}
}
}
return violations;
}
public void run(String cgFile) {
Hashtable<String,ArrayList<String>> cg = parseFile(cgFile);
Hashtable<String,Hashtable<String,Pair>> invariants =
getInvariantPairs(cg);
ArrayList<Violation> violations = getViolations(cg, invariants);
printViolations(violations);
}
public void printViolations(ArrayList<Violation> violations) {
Enumeration e = Collections.enumeration(violations);
while (e.hasMoreElements()) {
Violation v = (Violation)e.nextElement();
System.out.println(v);
}
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: ./pipair <bitcode file> <T SUPPORT> <T CONFIDENCE>,");
System.exit(0);
}
Pipair prog = new Pipair();
if (args.length >= 2) {
prog.tSupport = Integer.parseInt(args[1]);
}
if (args.length >= 3) {
prog.tConfidence = Float.parseFloat(args[2]);
}
prog.run(args[0]);
}
}
| true | true | public Hashtable<String,ArrayList<String>> parseFile(String fileName) {
Runtime rt = Runtime.getRuntime();
Hashtable<String, ArrayList<String>> table = new Hashtable<String,ArrayList<String>>();
try {
Process pr = rt.exec("opt -print-callgraph " + fileName);
InputStream st = pr.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(st));
String line = null;
int state = 0; //0 - Empty Line, 1 - Call graph
String current = null;
while ((line = in.readLine()) != null) {
//System.out.println(line + " " + line.length());
switch (state) {
case(1):
if (line.matches("(.*)CS<0x[0-9a-f]*> calls function(.*)")) {
String[] slist = line.split("\'");
String func = slist[1];
ArrayList<String> curList = table.get(current);
curList.add(func);
//System.out.println(func);
break;
}
case(0):
if (line.startsWith("Call graph node for function")) {
String[] slist = line.split("\'");
current = slist[1];
ArrayList<String> nlist = new ArrayList<String>();
table.put(current,nlist);
state = 1;
//System.out.println(current);
break;
}
default:
if (line.length() == 0) {
state = 0;
//System.out.println("");
}
break;
}
}
} catch (IOException e) {
}
return table;
}
| public Hashtable<String,ArrayList<String>> parseFile(String fileName) {
Runtime rt = Runtime.getRuntime();
Hashtable<String, ArrayList<String>> table = new Hashtable<String,ArrayList<String>>();
try {
Process pr = rt.exec("opt -print-callgraph -disable-output " + fileName);
InputStream st = pr.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(st));
String line = null;
int state = 0; //0 - Empty Line, 1 - Call graph
String current = null;
while ((line = in.readLine()) != null) {
//System.out.println(line + " " + line.length());
switch (state) {
case(1):
if (line.matches("(.*)CS<0x[0-9a-f]*> calls function(.*)")) {
String[] slist = line.split("\'");
String func = slist[1];
ArrayList<String> curList = table.get(current);
curList.add(func);
//System.out.println(func);
break;
}
case(0):
if (line.startsWith("Call graph node for function")) {
String[] slist = line.split("\'");
current = slist[1];
ArrayList<String> nlist = new ArrayList<String>();
table.put(current,nlist);
state = 1;
//System.out.println(current);
break;
}
default:
if (line.length() == 0) {
state = 0;
//System.out.println("");
}
break;
}
}
} catch (IOException e) {
}
return table;
}
|
diff --git a/src/UltraCommand.java b/src/UltraCommand.java
index 0274120..fa95bad 100644
--- a/src/UltraCommand.java
+++ b/src/UltraCommand.java
@@ -1,353 +1,353 @@
package com.kierdavis.ultracommand;
import com.kierdavis.flex.FlexCommandExecutor;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import org.mcstats.Metrics;
public class UltraCommand extends JavaPlugin {
private File commandsFile;
private FileConfiguration commandsConfig;
private BukkitTask saveCommandsTask;
private boolean dirty;
public void onEnable() {
commandsFile = new File(getDataFolder(), "commands.yml");
loadCustomCommands();
getServer().getPluginManager().registerEvents(new PlayerListener(this), this);
FlexCommandExecutor cmdExec = FlexCommandExecutor.getInstance();
cmdExec.addHandler(this, new AddCommandHandler(this));
cmdExec.addHandler(this, new ListCommandHandler(this));
cmdExec.addHandler(this, new MiscCommandHandler(this));
cmdExec.addHandler(this, new RemoveCommandHandler(this));
cmdExec.alias("ultracommand", "uc");
dirty = false;
saveCommandsTask = new SaveCommandsTask(this).runTaskTimer(this, 20 * 60, 20 * 60); // Check every minute.
// Start Metrics
try {
Metrics metrics = new Metrics(this);
metrics.start();
}
catch (IOException e) {
getLogger().severe("Failed to submit stats to Metrics: " + e.toString());
}
}
public void onDisable() {
saveCommandsTask.cancel();
saveCustomCommands();
}
public void loadCustomCommands() {
if (!commandsFile.exists()) {
createCommandsFile();
}
commandsConfig = YamlConfiguration.loadConfiguration(commandsFile);
getLogger().info("Loaded " + commandsFile.toString());
}
public void saveCustomCommands() {
try {
commandsConfig.save(commandsFile);
dirty = false;
getLogger().info("Saved " + commandsFile.toString());
}
catch (IOException e) {
getLogger().severe("Could not save " + commandsFile.toString() + ": " + e.toString());
}
}
public Set<String> getCustomCommands() {
return getCommandsSection().getKeys(false);
}
public CustomCommandContext getCustomCommandContext(String name, Player player, String[] args) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
CustomCommandContext cmd = new CustomCommandContext(getLogger(), player, args);
List<String> l;
l = commandSection.getStringList("text");
if (l != null && l.size() > 0) cmd.setText(l);
l = commandSection.getStringList("chat");
if (l != null && l.size() > 0) cmd.setText(l);
l = commandSection.getStringList("playerCommands");
if (l != null && l.size() > 0) cmd.setPlayerCommands(l);
l = commandSection.getStringList("consoleCommands");
if (l != null && l.size() > 0) cmd.setConsoleCommands(l);
String usage = commandSection.getString("usage");
if (usage != null && usage.length() > 0) cmd.setUsage(usage);
return cmd;
}
public boolean addCustomCommand(String name) {
ConfigurationSection commandsSection = getCommandsSection();
name = name.toLowerCase();
if (commandsSection.contains(name)) {
return false;
}
ConfigurationSection commandSection = commandsSection.createSection(name);
//commandSection.set("text", new ArrayList<String>());
//commandSection.set("chat", new ArrayList<String>());
//commandSection.set("playerCommands", new ArrayList<String>());
//commandSection.set("consoleCommands", new ArrayList<String>());
dirty = true;
return true;
}
public boolean hasCustomCommand(String name) {
return getCommandSection(name) != null;
}
public boolean removeCustomCommand(String name) {
ConfigurationSection commandsSection = getCommandsSection();
name = name.toLowerCase();
if (!commandsSection.contains(name)) {
return false;
}
commandsSection.set(name, null);
dirty = true;
return true;
}
public boolean addText(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("text");
l.add(s);
commandSection.set("text", l);
dirty = true;
return true;
}
public boolean addChat(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("chat");
l.add(s);
commandSection.set("chat", l);
dirty = true;
return true;
}
public boolean addPlayerCommand(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("playerCommands");
l.add(s);
commandSection.set("playerCommands", l);
dirty = true;
return true;
}
public boolean addConsoleCommand(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
List<String> l = commandSection.getStringList("consoleCommands");
l.add(s);
commandSection.set("consoleCommands", l);
dirty = true;
return true;
}
public boolean setUsage(String name, String s) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("usage", s);
dirty = true;
return true;
}
public List<String> getText(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("text");
}
public List<String> getChat(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("chat");
}
public List<String> getPlayerCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("playerCommands");
}
public List<String> getConsoleCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getStringList("consoleCommands");
}
public String getUsage(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return null;
return commandSection.getString("usage");
}
public boolean clearText(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("text", new ArrayList<String>());
dirty = true;
return true;
}
public boolean clearChat(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("chat", new ArrayList<String>());
dirty = true;
return true;
}
public boolean clearPlayerCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("playerCommands", new ArrayList<String>());
dirty = true;
return true;
}
public boolean clearConsoleCommands(String name) {
ConfigurationSection commandSection = getCommandSection(name);
if (commandSection == null) return false;
commandSection.set("consoleCommands", new ArrayList<String>());
dirty = true;
return true;
}
private ConfigurationSection getCommandsSection() {
ConfigurationSection commandsSection = commandsConfig.getConfigurationSection("commands");
if (commandsSection == null) {
commandsSection = commandsConfig.createSection("commands");
}
return commandsSection;
}
private ConfigurationSection getCommandSection(String name) {
return getCommandsSection().getConfigurationSection(name.toLowerCase());
}
private void createCommandsFile() {
File parent = commandsFile.getParentFile();
try {
if (!parent.exists()) {
parent.mkdirs();
}
if (!commandsFile.exists()) {
boolean b = commandsFile.createNewFile();
if (b) {
getLogger().info("Created " + commandsFile.toString());
}
}
}
catch (IOException e) {
getLogger().warning("Could not create " + commandsFile.toString() + ": " + e.toString());
}
}
public boolean isDirty() {
return dirty;
}
public boolean doCommand(Player player, String[] parts) {
CustomCommandContext ccc = null;
String cmdName = "";
StringBuilder b = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) b.append(" ");
b.append(parts[i]);
String thisCmdName = b.toString().replaceAll(" ", "_");
- CustomCommandContext thisCCC = getCustomCommandContext(cmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
+ CustomCommandContext thisCCC = getCustomCommandContext(thisCmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
if (thisCCC != null) {
cmdName = thisCmdName;
ccc = thisCCC;
}
- getLogger().info(ccc.toString());
- getLogger().info(thisCCC.toString());
- getLogger().info(cmdName.toString());
- getLogger().info(thisCmdName.toString());
+ //getLogger().info(ccc.toString());
+ //getLogger().info(thisCCC.toString());
+ //getLogger().info(cmdName.toString());
+ //getLogger().info(thisCmdName.toString());
}
if (ccc != null) {
String perm = "ultracommand.commands." + cmdName;
if (!player.hasPermission(perm) && !player.hasPermission("ultracommand.commands.*")) {
player.sendMessage(ChatColor.YELLOW + "You don't have permission for this command (" + perm + ")");
return true;
}
getLogger().info(player.getName() + " issued custom command: /" + b.toString());
ccc.execute();
return true;
}
return false;
}
}
| false | true | public boolean doCommand(Player player, String[] parts) {
CustomCommandContext ccc = null;
String cmdName = "";
StringBuilder b = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) b.append(" ");
b.append(parts[i]);
String thisCmdName = b.toString().replaceAll(" ", "_");
CustomCommandContext thisCCC = getCustomCommandContext(cmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
if (thisCCC != null) {
cmdName = thisCmdName;
ccc = thisCCC;
}
getLogger().info(ccc.toString());
getLogger().info(thisCCC.toString());
getLogger().info(cmdName.toString());
getLogger().info(thisCmdName.toString());
}
if (ccc != null) {
String perm = "ultracommand.commands." + cmdName;
if (!player.hasPermission(perm) && !player.hasPermission("ultracommand.commands.*")) {
player.sendMessage(ChatColor.YELLOW + "You don't have permission for this command (" + perm + ")");
return true;
}
getLogger().info(player.getName() + " issued custom command: /" + b.toString());
ccc.execute();
return true;
}
return false;
}
| public boolean doCommand(Player player, String[] parts) {
CustomCommandContext ccc = null;
String cmdName = "";
StringBuilder b = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) b.append(" ");
b.append(parts[i]);
String thisCmdName = b.toString().replaceAll(" ", "_");
CustomCommandContext thisCCC = getCustomCommandContext(thisCmdName, player, Arrays.copyOfRange(parts, i+1, parts.length));
if (thisCCC != null) {
cmdName = thisCmdName;
ccc = thisCCC;
}
//getLogger().info(ccc.toString());
//getLogger().info(thisCCC.toString());
//getLogger().info(cmdName.toString());
//getLogger().info(thisCmdName.toString());
}
if (ccc != null) {
String perm = "ultracommand.commands." + cmdName;
if (!player.hasPermission(perm) && !player.hasPermission("ultracommand.commands.*")) {
player.sendMessage(ChatColor.YELLOW + "You don't have permission for this command (" + perm + ")");
return true;
}
getLogger().info(player.getName() + " issued custom command: /" + b.toString());
ccc.execute();
return true;
}
return false;
}
|
diff --git a/toolsrc/org/mozilla/javascript/tools/shell/ShellLine.java b/toolsrc/org/mozilla/javascript/tools/shell/ShellLine.java
index 61d1de0a..3cabd52b 100755
--- a/toolsrc/org/mozilla/javascript/tools/shell/ShellLine.java
+++ b/toolsrc/org/mozilla/javascript/tools/shell/ShellLine.java
@@ -1,167 +1,168 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1998.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Matthieu Riou
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.tools.shell;
import java.io.InputStream;
import java.util.List;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationTargetException;
import org.mozilla.javascript.Kit;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Function;
/**
* Provides a specialized input stream for consoles to handle line
* editing, history and completion. Relies on the JLine library (see
* <http://jline.sourceforge.net>).
*/
public class ShellLine {
public static InputStream getStream(Scriptable scope) {
// We don't want a compile-time dependency on the JLine jar, so use
// reflection to load and reference the JLine classes.
ClassLoader classLoader = ShellLine.class.getClassLoader();
Class<?> readerClass = Kit.classOrNull(classLoader, "jline.ConsoleReader");
if (readerClass == null)
return null;
try {
// ConsoleReader reader = new ConsoleReader();
Constructor<?> c = readerClass.getConstructor();
Object reader = c.newInstance();
// reader.setBellEnabled(false);
Method m = readerClass.getMethod("setBellEnabled", Boolean.TYPE);
m.invoke(reader, Boolean.FALSE);
// reader.addCompletor(new FlexibleCompletor(prefixes));
Class<?> completorClass = Kit.classOrNull(classLoader,
"jline.Completor");
m = readerClass.getMethod("addCompletor", completorClass);
Object completor = Proxy.newProxyInstance(classLoader,
new Class[] { completorClass },
new FlexibleCompletor(completorClass, scope));
m.invoke(reader, completor);
// return new ConsoleReaderInputStream(reader);
Class<?> inputStreamClass = Kit.classOrNull(classLoader,
"jline.ConsoleReaderInputStream");
c = inputStreamClass.getConstructor(readerClass);
return (InputStream) c.newInstance(reader);
} catch (NoSuchMethodException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
return null;
}
}
/**
* The completors provided with JLine are pretty uptight, they only
* complete on a line that it can fully recognize (only composed of
* completed strings). This one completes whatever came before.
*/
class FlexibleCompletor implements java.lang.reflect.InvocationHandler {
private Method completeMethod;
private Scriptable global;
FlexibleCompletor(Class<?> completorClass, Scriptable global)
throws NoSuchMethodException
{
this.global = global;
this.completeMethod = completorClass.getMethod("complete", String.class,
Integer.TYPE, List.class);
}
@SuppressWarnings({"unchecked"})
public Object invoke(Object proxy, Method method, Object[] args) {
if (method.equals(this.completeMethod)) {
int result = complete((String)args[0], ((Integer) args[1]).intValue(),
(List<String>) args[2]);
return Integer.valueOf(result);
}
throw new NoSuchMethodError(method.toString());
}
public int complete(String buffer, int cursor, List<String> candidates) {
// Starting from "cursor" at the end of the buffer, look backward
// and collect a list of identifiers separated by (possibly zero)
// dots. Then look up each identifier in turn until getting to the
// last, presumably incomplete fragment. Then enumerate all the
// properties of the last object and find any that have the
// fragment as a prefix and return those for autocompletion.
int m = cursor - 1;
while (m >= 0) {
- char c = buffer.charAt(m--);
+ char c = buffer.charAt(m);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
+ m--;
}
String namesAndDots = buffer.substring(m+1, cursor);
- String[] names = namesAndDots.split("\\.");
+ String[] names = namesAndDots.split("\\.", -1);
Scriptable obj = this.global;
for (int i=0; i < names.length - 1; i++) {
Object val = obj.get(names[i], global);
if (val instanceof Scriptable)
obj = (Scriptable) val;
else {
return buffer.length(); // no matches
}
}
Object[] ids = (obj instanceof ScriptableObject)
? ((ScriptableObject)obj).getAllIds()
: obj.getIds();
String lastPart = names[names.length-1];
for (int i=0; i < ids.length; i++) {
if (!(ids[i] instanceof String))
continue;
String id = (String)ids[i];
if (id.startsWith(lastPart)) {
if (obj.get(id, obj) instanceof Function)
id += "(";
candidates.add(id);
}
}
return buffer.length() - lastPart.length();
}
}
| false | true | public int complete(String buffer, int cursor, List<String> candidates) {
// Starting from "cursor" at the end of the buffer, look backward
// and collect a list of identifiers separated by (possibly zero)
// dots. Then look up each identifier in turn until getting to the
// last, presumably incomplete fragment. Then enumerate all the
// properties of the last object and find any that have the
// fragment as a prefix and return those for autocompletion.
int m = cursor - 1;
while (m >= 0) {
char c = buffer.charAt(m--);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
}
String namesAndDots = buffer.substring(m+1, cursor);
String[] names = namesAndDots.split("\\.");
Scriptable obj = this.global;
for (int i=0; i < names.length - 1; i++) {
Object val = obj.get(names[i], global);
if (val instanceof Scriptable)
obj = (Scriptable) val;
else {
return buffer.length(); // no matches
}
}
Object[] ids = (obj instanceof ScriptableObject)
? ((ScriptableObject)obj).getAllIds()
: obj.getIds();
String lastPart = names[names.length-1];
for (int i=0; i < ids.length; i++) {
if (!(ids[i] instanceof String))
continue;
String id = (String)ids[i];
if (id.startsWith(lastPart)) {
if (obj.get(id, obj) instanceof Function)
id += "(";
candidates.add(id);
}
}
return buffer.length() - lastPart.length();
}
| public int complete(String buffer, int cursor, List<String> candidates) {
// Starting from "cursor" at the end of the buffer, look backward
// and collect a list of identifiers separated by (possibly zero)
// dots. Then look up each identifier in turn until getting to the
// last, presumably incomplete fragment. Then enumerate all the
// properties of the last object and find any that have the
// fragment as a prefix and return those for autocompletion.
int m = cursor - 1;
while (m >= 0) {
char c = buffer.charAt(m);
if (!Character.isJavaIdentifierPart(c) && c != '.')
break;
m--;
}
String namesAndDots = buffer.substring(m+1, cursor);
String[] names = namesAndDots.split("\\.", -1);
Scriptable obj = this.global;
for (int i=0; i < names.length - 1; i++) {
Object val = obj.get(names[i], global);
if (val instanceof Scriptable)
obj = (Scriptable) val;
else {
return buffer.length(); // no matches
}
}
Object[] ids = (obj instanceof ScriptableObject)
? ((ScriptableObject)obj).getAllIds()
: obj.getIds();
String lastPart = names[names.length-1];
for (int i=0; i < ids.length; i++) {
if (!(ids[i] instanceof String))
continue;
String id = (String)ids[i];
if (id.startsWith(lastPart)) {
if (obj.get(id, obj) instanceof Function)
id += "(";
candidates.add(id);
}
}
return buffer.length() - lastPart.length();
}
|
diff --git a/src/main/java/org/lisak/pguide/controllers/AdminController.java b/src/main/java/org/lisak/pguide/controllers/AdminController.java
index 6f94fd7..dcdbdf0 100644
--- a/src/main/java/org/lisak/pguide/controllers/AdminController.java
+++ b/src/main/java/org/lisak/pguide/controllers/AdminController.java
@@ -1,334 +1,335 @@
package org.lisak.pguide.controllers;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import geo.gps.Coordinates;
import org.lisak.pguide.dao.ContentDao;
import org.lisak.pguide.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Formatter;
import java.util.List;
import java.util.logging.Logger;
/**
* Created with IntelliJ IDEA.
* User: lisak
* Date: 06.08.13
* Time: 13:59
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
private static final Logger log = Logger.getLogger(AdminController.class.getName());
private ContentDao contentDao;
private CategoryFactory categoryFactory;
public CategoryFactory getCategoryFactory() {
return categoryFactory;
}
public void setCategoryFactory(CategoryFactory categoryFactory) {
this.categoryFactory = categoryFactory;
}
public ContentDao getContentDao() {
return contentDao;
}
public void setContentDao(ContentDao contentDao) {
this.contentDao = contentDao;
}
// ******** Article upload & processing **********
@RequestMapping(value = "/article/{articleId}", method = RequestMethod.GET)
public String showArticle(@PathVariable("articleId") String articleId,
@RequestParam(value = "delete", required = false) String delete,
Model model) {
List<Article> articleList = contentDao.getArticles();
Collections.sort(articleList, Article.TitleComparator);
model.addAttribute("articleList", articleList);
Article article;
if(delete == null) {
article = (Article) contentDao.get(articleId);
} else {
contentDao.delete(articleId);
article = new Article();
model.addAttribute(article);
return "redirect:/admin/article";
}
model.addAttribute(article);
return "admin/articleForm";
}
@RequestMapping(value = "/article", method = RequestMethod.GET)
public String newArticle(HttpServletRequest req, Model model) {
List<Article> articleList = contentDao.getArticles();
model.addAttribute("articleList", articleList);
model.addAttribute(new Article());
return "admin/articleForm";
}
@RequestMapping(value = "/article", method = RequestMethod.POST)
public String saveArticle(Article article) {
contentDao.save(article);
return "redirect:/admin/article/" + article.getId();
}
// ******** Image upload & processing **********
@RequestMapping(value = "/image/{imageId}", method = RequestMethod.GET)
public String showImage(@PathVariable("imageId") String imageId,
@RequestParam(value = "filter", required = false) String filter,
@RequestParam(value = "delete", required = false) String delete,
Model model) {
List<Image> imgList;
if(filter==null) {
imgList = contentDao.getImages();
} else {
imgList = contentDao.getImages(filter);
model.addAttribute(filter);
}
model.addAttribute("imageList", imgList);
Image image;
if(delete == null) {
image = (Image) contentDao.get(imageId);
model.addAttribute(image);
return "admin/imageForm";
} else {
contentDao.delete(imageId);
return "redirect:/admin/image";
}
}
@RequestMapping(value = "/image", method = RequestMethod.GET)
public String newImage(@RequestParam(value = "filter", required = false) String filter, Model model) {
List<Image> imgList;
if(filter==null) {
imgList = contentDao.getImages();
} else {
imgList = contentDao.getImages(filter);
model.addAttribute(filter);
}
model.addAttribute("imageList", imgList);
model.addAttribute(new Image());
return "admin/imageForm";
}
@RequestMapping(value = "/image", method = RequestMethod.POST)
public String saveImage(Image image, @RequestParam(value = "imageData") MultipartFile data){
try {
if(data.getBytes().length>0) {
image.setData(data.getBytes());
} else {
//fetch original image from DB (otherwise NULL will be saved as image data):
Image _img = (Image)contentDao.get(image.getId());
image.setData(_img.getData());
}
image.setFileType("jpg");
} catch (IOException e) {
return "admin/imageForm";
}
contentDao.save(image);
return "redirect:/admin/image/" + image.getId();
}
// ******** Profile upload & processing **********
@RequestMapping(value = "/profile", method = RequestMethod.GET)
public String newProfile(@RequestParam(value = "filter", required = false) String filter,
Model model) {
List<Profile> profileList;
profileList = contentDao.getProfiles();
model.addAttribute(profileList);
if(filter == null)
filter = "";
model.addAttribute("filter", filter);
List<Image> imageList = contentDao.getImages();
model.addAttribute("strImgList", imageList.toString());
List<Category> categoryList = categoryFactory.getCategoryList();
model.addAttribute(categoryList);
model.addAttribute("profile", new Profile());
return "admin/profileForm";
}
@RequestMapping(value = "/profile/{profileId}", method = RequestMethod.GET)
public String showProfile(@PathVariable("profileId") String profileId,
@RequestParam(value = "delete", required = false) String delete,
@RequestParam(value = "filter", required = false) String filter,
Model model) {
List<Profile> profileList;
profileList = contentDao.getProfiles();
model.addAttribute(profileList);
if(filter == null)
filter = "";
model.addAttribute("filter", filter);
List<Image> imageList = contentDao.getImages();
model.addAttribute("strImgList", imageList.toString());
List<Category> categoryList = categoryFactory.getCategoryList();
model.addAttribute(categoryList);
Profile profile;
if(delete == null) {
profile = (Profile) contentDao.get(profileId);
model.addAttribute(profile);
return "admin/profileForm";
} else {
contentDao.delete(profileId);
return "redirect:/admin/profile";
}
}
@RequestMapping(value = "/profile", method = RequestMethod.POST)
public String saveProfile(@ModelAttribute("profile") Profile profile,
@RequestParam(value = "filter", required = false) String filter){
contentDao.save(profile);
return "redirect:/admin/profile/" + profile.getId() + "?filter=" + filter;
}
@RequestMapping(value = "/createStaticMap", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void createStaticMap(@ModelAttribute("id") String id,
@ModelAttribute("gps") String gps,
+ @ModelAttribute("category") String category,
HttpServletResponse response) throws IOException {
String staticMapURL = "http://maps.googleapis.com/maps/api/staticmap?";
String staticMapParams = "zoom=15&size=318x126&sensor=false&" +
- "visual_refresh=true&markers=icon:http://www.pguide.cz/resources/img/coffee-selected.png%%7C%s,%s";
+ "visual_refresh=true&markers=icon:http://www.pguide.cz/resources/img/" + category + "-selected.png%%7C%s,%s";
//parameters: id, long, lat
//called via AJAX/jquery from edit profile page
// - creates new static google map from specified coordinates
// - uploads the resulting map to DB as image with ID "{id}-map"
//returns HTTP 200 when successful
//** prepare URL **
//parse GPS (it may not be normalized by servlet yet)
//FIXME: this should be moved to geo.gps
Coordinates coords = new Coordinates();
//remove NE completely - it fucks with the default format
String _buf = gps.replaceAll("[NE]", "");
//replace all chars except for [0-9,.] with spaces
_buf = _buf.replaceAll("[^\\d,.]", " ");
coords.parse(_buf);
StringBuilder sb = new StringBuilder();
DecimalFormat df = new DecimalFormat("#.00000");
String _fillParams = String.format(staticMapParams,
df.format(coords.getLatitude()),
df.format(coords.getLongitude()));
URL url = new URL(staticMapURL + _fillParams);
log.info("Static map URL: " + url.toString());
//fetch static google image
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
//create & store new image
Image img = new Image();
img.setId(id);
img.setData(out.toByteArray());
img.setFileType("jpg");
contentDao.save(img);
}
@RequestMapping(value = "/emptyreport", method = RequestMethod.GET)
public String emptyValueReport(Model model) {
Formatter fm = new Formatter();
List<String> resultList = new ArrayList<String>();
List<Article> articleList = contentDao.getArticles();
for(Article a:articleList) {
if(a.getTitle() == null || a.getTitle().equals("")) {
resultList.add(String.format("Article id <a href='/admin/article/%s'>%s</a>: empty title", a.getId(), a.getId()));
}
if(a.getText() == null || a.getText().equals("")) {
resultList.add(String.format("Article id <a href='/admin/article/%s'>%s</a>: empty text", a.getId(), a.getId()));
}
}
for(Profile p: contentDao.getProfiles()) {
if(p.getName() == null || p.getName().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty name", p.getId(), p.getId()));
}
if(p.getUrl() == null || p.getUrl().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty url", p.getId(), p.getId()));
}
if(p.getGpsCoords() == null || p.getGpsCoords().replaceAll("[0. ]","").equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty GPS coords", p.getId(), p.getId()));
}
if(p.getAddress() == null || p.getAddress().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty address", p.getId(), p.getId()));
}
if(p.getOpeningHours() == null || p.getOpeningHours().size() == 0) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty opening hours", p.getId(), p.getId()));
}
if(p.getPrices() == null || p.getPrices().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty prices", p.getId(), p.getId()));
}
if(p.getProfileImg() == null || p.getProfileImg().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty profile image", p.getId(), p.getId()));
}
if(p.getStaticMapImg() == null || p.getStaticMapImg().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty static map image", p.getId(), p.getId()));
}
if(p.getProfileImg() == null || p.getProfileImg().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty profile image", p.getId(), p.getId()));
}
if(p.getGallery() == null || p.getGallery().size() == 0) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty image gallery", p.getId(), p.getId()));
}
if(p.getText() == null || p.getText().equals("")) {
resultList.add(String.format("Profile id <a href='/admin/profile/%s'>%s</a>: empty text", p.getId(), p.getId()));
}
}
model.addAttribute("emptyValueList", resultList);
return "admin/emptyValueReport";
}
}
| false | true | public void createStaticMap(@ModelAttribute("id") String id,
@ModelAttribute("gps") String gps,
HttpServletResponse response) throws IOException {
String staticMapURL = "http://maps.googleapis.com/maps/api/staticmap?";
String staticMapParams = "zoom=15&size=318x126&sensor=false&" +
"visual_refresh=true&markers=icon:http://www.pguide.cz/resources/img/coffee-selected.png%%7C%s,%s";
//parameters: id, long, lat
//called via AJAX/jquery from edit profile page
// - creates new static google map from specified coordinates
// - uploads the resulting map to DB as image with ID "{id}-map"
//returns HTTP 200 when successful
//** prepare URL **
//parse GPS (it may not be normalized by servlet yet)
//FIXME: this should be moved to geo.gps
Coordinates coords = new Coordinates();
//remove NE completely - it fucks with the default format
String _buf = gps.replaceAll("[NE]", "");
//replace all chars except for [0-9,.] with spaces
_buf = _buf.replaceAll("[^\\d,.]", " ");
coords.parse(_buf);
StringBuilder sb = new StringBuilder();
DecimalFormat df = new DecimalFormat("#.00000");
String _fillParams = String.format(staticMapParams,
df.format(coords.getLatitude()),
df.format(coords.getLongitude()));
URL url = new URL(staticMapURL + _fillParams);
log.info("Static map URL: " + url.toString());
//fetch static google image
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
//create & store new image
Image img = new Image();
img.setId(id);
img.setData(out.toByteArray());
img.setFileType("jpg");
contentDao.save(img);
}
| public void createStaticMap(@ModelAttribute("id") String id,
@ModelAttribute("gps") String gps,
@ModelAttribute("category") String category,
HttpServletResponse response) throws IOException {
String staticMapURL = "http://maps.googleapis.com/maps/api/staticmap?";
String staticMapParams = "zoom=15&size=318x126&sensor=false&" +
"visual_refresh=true&markers=icon:http://www.pguide.cz/resources/img/" + category + "-selected.png%%7C%s,%s";
//parameters: id, long, lat
//called via AJAX/jquery from edit profile page
// - creates new static google map from specified coordinates
// - uploads the resulting map to DB as image with ID "{id}-map"
//returns HTTP 200 when successful
//** prepare URL **
//parse GPS (it may not be normalized by servlet yet)
//FIXME: this should be moved to geo.gps
Coordinates coords = new Coordinates();
//remove NE completely - it fucks with the default format
String _buf = gps.replaceAll("[NE]", "");
//replace all chars except for [0-9,.] with spaces
_buf = _buf.replaceAll("[^\\d,.]", " ");
coords.parse(_buf);
StringBuilder sb = new StringBuilder();
DecimalFormat df = new DecimalFormat("#.00000");
String _fillParams = String.format(staticMapParams,
df.format(coords.getLatitude()),
df.format(coords.getLongitude()));
URL url = new URL(staticMapURL + _fillParams);
log.info("Static map URL: " + url.toString());
//fetch static google image
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
//create & store new image
Image img = new Image();
img.setId(id);
img.setData(out.toByteArray());
img.setFileType("jpg");
contentDao.save(img);
}
|
diff --git a/DesktopDataLaboratory/src/org/gephi/desktop/datalab/general/actions/MergeColumnsUI.java b/DesktopDataLaboratory/src/org/gephi/desktop/datalab/general/actions/MergeColumnsUI.java
index 3477b1b70..32365a751 100644
--- a/DesktopDataLaboratory/src/org/gephi/desktop/datalab/general/actions/MergeColumnsUI.java
+++ b/DesktopDataLaboratory/src/org/gephi/desktop/datalab/general/actions/MergeColumnsUI.java
@@ -1,449 +1,449 @@
/*
Copyright 2008-2010 Gephi
Authors : Eduardo Ramos <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi 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
(at your option) any later version.
Gephi 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.desktop.datalab.general.actions;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import org.gephi.data.attributes.api.AttributeColumn;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeTable;
import org.gephi.datalab.api.DataLaboratoryHelper;
import org.gephi.datalab.spi.columns.merge.AttributeColumnsMergeStrategy;
import org.gephi.ui.components.richtooltip.RichTooltip;
import org.netbeans.validation.api.Problems;
import org.netbeans.validation.api.Validator;
import org.netbeans.validation.api.ui.ValidationGroup;
import org.netbeans.validation.api.ui.ValidationPanel;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
/**
* UI for choosing columns to merge and a merge strategy.
* @author Eduardo Ramos <[email protected]>
*/
public class MergeColumnsUI extends javax.swing.JPanel {
private JButton okButton;
public enum Mode {
NODES_TABLE,
EDGES_TABLE
}
private Mode mode = Mode.NODES_TABLE;
private AttributeTable table;
private DefaultListModel availableColumnsModel;
private DefaultListModel columnsToMergeModel;
private AttributeColumnsMergeStrategy[] availableMergeStrategies;
/** Creates new form MergeColumnsUI */
public MergeColumnsUI() {
initComponents();
infoLabel.addMouseListener(new MouseAdapter() {
RichTooltip richTooltip;
@Override
public void mouseEntered(MouseEvent e) {
int index = availableStrategiesComboBox.getSelectedIndex();
if (infoLabel.isEnabled() && index != -1) {
richTooltip = buildTooltip(availableMergeStrategies[index]);
}
if (richTooltip != null) {
richTooltip.showTooltip(infoLabel);
}
}
@Override
public void mouseExited(MouseEvent e) {
if (richTooltip != null) {
richTooltip.hideTooltip();
richTooltip = null;
}
}
private RichTooltip buildTooltip(AttributeColumnsMergeStrategy strategy) {
if (strategy.getDescription() != null && !strategy.getDescription().isEmpty()) {
RichTooltip tooltip = new RichTooltip(strategy.getName(), strategy.getDescription());
if (strategy.getIcon() != null) {
tooltip.setMainImage(ImageUtilities.icon2Image(strategy.getIcon()));
}
return tooltip;
} else {
return null;
}
}
});
availableColumnsModel = new DefaultListModel();
columnsToMergeModel = new DefaultListModel();
columnsToMergeModel.addListDataListener(new ListDataListener() {
public void intervalAdded(ListDataEvent e) {
refreshAvailableMergeStrategies();
}
public void intervalRemoved(ListDataEvent e) {
refreshAvailableMergeStrategies();
}
public void contentsChanged(ListDataEvent e) {
refreshAvailableMergeStrategies();
}
});
}
private void loadColumns() {
availableColumnsModel.clear();
columnsToMergeModel.clear();
AttributeController ac = Lookup.getDefault().lookup(AttributeController.class);
AttributeColumn[] columns;
if (mode == Mode.NODES_TABLE) {
table = ac.getModel().getNodeTable();
columns = table.getColumns();
} else {
table = ac.getModel().getEdgeTable();
columns = table.getColumns();
}
for (int i = 0; i < columns.length; i++) {
availableColumnsModel.addElement(new ColumnWrapper(columns[i]));
}
availableColumnsList.setModel(availableColumnsModel);
columnsToMergeList.setModel(columnsToMergeModel);
}
private void refreshAvailableMergeStrategies() {
//Save currently selected strategy index:
int selectedStrategyIndex = availableStrategiesComboBox.getSelectedIndex();
availableStrategiesComboBox.removeAllItems();
AttributeColumn[] columnsToMerge = getColumnsToMerge();
if (columnsToMerge.length < 1) {
return;
}
AttributeColumnsMergeStrategy[] strategies = DataLaboratoryHelper.getDefault().getAttributeColumnsMergeStrategies();
ArrayList<AttributeColumnsMergeStrategy> availableStrategiesList = new ArrayList<AttributeColumnsMergeStrategy>();
for (AttributeColumnsMergeStrategy strategy : strategies) {
strategy.setup(table, columnsToMerge);
availableStrategiesList.add(strategy);//Add all but disallow executing the strategies that cannot be executed with given column
}
availableMergeStrategies = availableStrategiesList.toArray(new AttributeColumnsMergeStrategy[0]);
for (AttributeColumnsMergeStrategy s : availableMergeStrategies) {
availableStrategiesComboBox.addItem(s.getName());
}
if (selectedStrategyIndex >= 0 && selectedStrategyIndex < availableStrategiesComboBox.getItemCount()) {
availableStrategiesComboBox.setSelectedIndex(selectedStrategyIndex);
}
}
private void refreshOkButton() {
if (okButton != null) {
okButton.setEnabled(canExecuteSelectedStrategy());
}
}
public boolean canExecuteSelectedStrategy() {
int index = availableStrategiesComboBox.getSelectedIndex();
boolean result;
if (index != -1) {
result = availableMergeStrategies[index].canExecute();
} else {
result = false;
}
return result;
}
private AttributeColumn[] getColumnsToMerge() {
Object[] elements = columnsToMergeModel.toArray();
AttributeColumn[] columns = new AttributeColumn[elements.length];
for (int i = 0; i < elements.length; i++) {
columns[i] = ((ColumnWrapper) elements[i]).getColumn();
}
return columns;
}
public void setup(Mode mode) {
this.mode = mode;
loadColumns();
}
public void execute() {
int index = availableStrategiesComboBox.getSelectedIndex();
if (index != -1) {
DataLaboratoryHelper.getDefault().executeManipulator(availableMergeStrategies[index]);
}
}
public String getDisplayName() {
return NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.title");
}
public void setOkButton(JButton okButton) {
this.okButton = okButton;
refreshOkButton();
}
/**
* Class to contain a column and return its name + type with toString method.
*/
class ColumnWrapper {
private AttributeColumn column;
public ColumnWrapper(AttributeColumn column) {
this.column = column;
}
public AttributeColumn getColumn() {
return column;
}
public void setColumn(AttributeColumn column) {
this.column = column;
}
@Override
public String toString() {
return column.getTitle() + " -- " + column.getType().getTypeString();
}
}
private void moveElementsFromListToOtherList(JList sourceList, JList targetList) {
DefaultListModel sourceModel, targetModel;
sourceModel = (DefaultListModel) sourceList.getModel();
targetModel = (DefaultListModel) targetList.getModel();
Object[] selection = sourceList.getSelectedValues();
for (Object element : selection) {
sourceModel.removeElement(element);
targetModel.addElement(element);
}
}
public static ValidationPanel createValidationPanel(MergeColumnsUI innerPanel) {
ValidationPanel validationPanel = new ValidationPanel();
if (innerPanel == null) {
innerPanel = new MergeColumnsUI();
}
validationPanel.setInnerComponent(innerPanel);
ValidationGroup group = validationPanel.getValidationGroup();
group.add(innerPanel.availableStrategiesComboBox, new MergeStrategyValidator(innerPanel));
return validationPanel;
}
private static class MergeStrategyValidator implements Validator<ComboBoxModel> {
private MergeColumnsUI ui;
public MergeStrategyValidator(MergeColumnsUI ui) {
this.ui = ui;
}
public boolean validate(Problems problems, String string, ComboBoxModel t) {
if (t.getSelectedItem() != null) {
if (ui.canExecuteSelectedStrategy()) {
return true;
} else {
problems.add(NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.problems.not_executable_strategy"));
return false;
}
} else {
problems.add(NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.problems.less_than_2_columns_selected"));
return false;
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
columnsToMergeList = new javax.swing.JList();
description = new javax.swing.JLabel();
addColumnButton = new javax.swing.JButton();
removeColumnButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
availableColumnsList = new javax.swing.JList();
availableColumnsLabel = new javax.swing.JLabel();
columnsToMergeLabel = new javax.swing.JLabel();
availableStrategiesLabel = new javax.swing.JLabel();
availableStrategiesComboBox = new javax.swing.JComboBox();
infoLabel = new javax.swing.JLabel();
jScrollPane1.setViewportView(columnsToMergeList);
description.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
description.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.description.text")); // NOI18N
addColumnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/arrow.png"))); // NOI18N
addColumnButton.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.addColumnButton.text")); // NOI18N
addColumnButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addColumnButtonActionPerformed(evt);
}
});
removeColumnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/arrow-180.png"))); // NOI18N
removeColumnButton.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.removeColumnButton.text")); // NOI18N
removeColumnButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeColumnButtonActionPerformed(evt);
}
});
jScrollPane2.setViewportView(availableColumnsList);
availableColumnsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
availableColumnsLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.availableColumnsLabel.text")); // NOI18N
columnsToMergeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
columnsToMergeLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.columnsToMergeLabel.text")); // NOI18N
availableStrategiesLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
availableStrategiesLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.availableStrategiesLabel.text")); // NOI18N
availableStrategiesComboBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
availableStrategiesComboBoxItemStateChanged(evt);
}
});
infoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
- infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/ui/datatable/resources/info.png"))); // NOI18N
+ infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/info.png"))); // NOI18N
infoLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.infoLabel.text")); // NOI18N
infoLabel.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(description, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(availableColumnsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
.addComponent(availableStrategiesLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(addColumnButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(removeColumnButton, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(columnsToMergeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
- .addComponent(availableStrategiesComboBox, 0, 232, Short.MAX_VALUE)
+ .addComponent(availableStrategiesComboBox, 0, 218, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(infoLabel)
.addContainerGap())))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(description, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(availableColumnsLabel)
.addComponent(columnsToMergeLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(addColumnButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeColumnButton)
.addGap(94, 94, 94)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(availableStrategiesComboBox, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(infoLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
.addComponent(availableStrategiesLabel))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
private void addColumnButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addColumnButtonActionPerformed
moveElementsFromListToOtherList(availableColumnsList, columnsToMergeList);
}//GEN-LAST:event_addColumnButtonActionPerformed
private void removeColumnButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeColumnButtonActionPerformed
moveElementsFromListToOtherList(columnsToMergeList, availableColumnsList);
}//GEN-LAST:event_removeColumnButtonActionPerformed
private void availableStrategiesComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_availableStrategiesComboBoxItemStateChanged
refreshOkButton();
infoLabel.setEnabled(availableStrategiesComboBox.getSelectedIndex() != -1);
}//GEN-LAST:event_availableStrategiesComboBoxItemStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addColumnButton;
private javax.swing.JLabel availableColumnsLabel;
private javax.swing.JList availableColumnsList;
private javax.swing.JComboBox availableStrategiesComboBox;
private javax.swing.JLabel availableStrategiesLabel;
private javax.swing.JLabel columnsToMergeLabel;
private javax.swing.JList columnsToMergeList;
private javax.swing.JLabel description;
private javax.swing.JLabel infoLabel;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JButton removeColumnButton;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
columnsToMergeList = new javax.swing.JList();
description = new javax.swing.JLabel();
addColumnButton = new javax.swing.JButton();
removeColumnButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
availableColumnsList = new javax.swing.JList();
availableColumnsLabel = new javax.swing.JLabel();
columnsToMergeLabel = new javax.swing.JLabel();
availableStrategiesLabel = new javax.swing.JLabel();
availableStrategiesComboBox = new javax.swing.JComboBox();
infoLabel = new javax.swing.JLabel();
jScrollPane1.setViewportView(columnsToMergeList);
description.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
description.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.description.text")); // NOI18N
addColumnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/arrow.png"))); // NOI18N
addColumnButton.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.addColumnButton.text")); // NOI18N
addColumnButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addColumnButtonActionPerformed(evt);
}
});
removeColumnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/arrow-180.png"))); // NOI18N
removeColumnButton.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.removeColumnButton.text")); // NOI18N
removeColumnButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeColumnButtonActionPerformed(evt);
}
});
jScrollPane2.setViewportView(availableColumnsList);
availableColumnsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
availableColumnsLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.availableColumnsLabel.text")); // NOI18N
columnsToMergeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
columnsToMergeLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.columnsToMergeLabel.text")); // NOI18N
availableStrategiesLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
availableStrategiesLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.availableStrategiesLabel.text")); // NOI18N
availableStrategiesComboBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
availableStrategiesComboBoxItemStateChanged(evt);
}
});
infoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/ui/datatable/resources/info.png"))); // NOI18N
infoLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.infoLabel.text")); // NOI18N
infoLabel.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(description, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(availableColumnsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
.addComponent(availableStrategiesLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(addColumnButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(removeColumnButton, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(columnsToMergeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availableStrategiesComboBox, 0, 232, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(infoLabel)
.addContainerGap())))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(description, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(availableColumnsLabel)
.addComponent(columnsToMergeLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(addColumnButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeColumnButton)
.addGap(94, 94, 94)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(availableStrategiesComboBox, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(infoLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
.addComponent(availableStrategiesLabel))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
columnsToMergeList = new javax.swing.JList();
description = new javax.swing.JLabel();
addColumnButton = new javax.swing.JButton();
removeColumnButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
availableColumnsList = new javax.swing.JList();
availableColumnsLabel = new javax.swing.JLabel();
columnsToMergeLabel = new javax.swing.JLabel();
availableStrategiesLabel = new javax.swing.JLabel();
availableStrategiesComboBox = new javax.swing.JComboBox();
infoLabel = new javax.swing.JLabel();
jScrollPane1.setViewportView(columnsToMergeList);
description.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
description.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.description.text")); // NOI18N
addColumnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/arrow.png"))); // NOI18N
addColumnButton.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.addColumnButton.text")); // NOI18N
addColumnButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addColumnButtonActionPerformed(evt);
}
});
removeColumnButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/arrow-180.png"))); // NOI18N
removeColumnButton.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.removeColumnButton.text")); // NOI18N
removeColumnButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeColumnButtonActionPerformed(evt);
}
});
jScrollPane2.setViewportView(availableColumnsList);
availableColumnsLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
availableColumnsLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.availableColumnsLabel.text")); // NOI18N
columnsToMergeLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
columnsToMergeLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.columnsToMergeLabel.text")); // NOI18N
availableStrategiesLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
availableStrategiesLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.availableStrategiesLabel.text")); // NOI18N
availableStrategiesComboBox.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
availableStrategiesComboBoxItemStateChanged(evt);
}
});
infoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gephi/desktop/datalab/resources/info.png"))); // NOI18N
infoLabel.setText(org.openide.util.NbBundle.getMessage(MergeColumnsUI.class, "MergeColumnsUI.infoLabel.text")); // NOI18N
infoLabel.setEnabled(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(description, javax.swing.GroupLayout.DEFAULT_SIZE, 394, Short.MAX_VALUE)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(availableColumnsLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
.addComponent(availableStrategiesLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(addColumnButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(removeColumnButton, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(columnsToMergeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(availableStrategiesComboBox, 0, 218, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(infoLabel)
.addContainerGap())))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(description, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(availableColumnsLabel)
.addComponent(columnsToMergeLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(12, 12, 12))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(addColumnButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(removeColumnButton)
.addGap(94, 94, 94)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(availableStrategiesComboBox, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(infoLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
.addComponent(availableStrategiesLabel))
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/test/java/com/github/trecloux/flashcookie/web/IntegrationTest.java b/src/test/java/com/github/trecloux/flashcookie/web/IntegrationTest.java
index ce098e5..da5c6b2 100644
--- a/src/test/java/com/github/trecloux/flashcookie/web/IntegrationTest.java
+++ b/src/test/java/com/github/trecloux/flashcookie/web/IntegrationTest.java
@@ -1,63 +1,63 @@
package com.github.trecloux.flashcookie.web;
import net.sourceforge.jwebunit.junit.WebTester;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.webapp.WebAppContext;
public class IntegrationTest extends WebTester {
private static final String WEBAPP = "src/main/webapp/";
private static final String CONTEXTPATH = "/";
private Server server;
@Test
public void shouldShowFlashAttributeAfterRedirect() throws Exception {
beginAt("/");
assertTextNotPresent("It works");
clickLinkWithExactText("Set Flash Attribute");
assertTextPresent("It works");
}
@Test
public void shouldShowFlashAttributeAfterRedirectAndDeleteAfterRefresh() throws Exception {
beginAt("/");
clickLinkWithExactText("Set Flash Attribute");
assertTextPresent("It works");
clickLinkWithExactText("Refresh");
assertTextNotPresent("It works");
}
@Before
- public void startSever() throws Exception {
+ public void startServer() throws Exception {
server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(8080);
connector.setHost("0.0.0.0");
server.addConnector(connector);
WebAppContext wac = new WebAppContext();
wac.setContextPath(CONTEXTPATH);
wac.setWar(WEBAPP);
server.setHandler(wac);
server.setStopAtShutdown(true);
server.start();
}
@After
public void stopServer() throws Exception {
server.stop();
}
}
| true | true | public void startSever() throws Exception {
server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(8080);
connector.setHost("0.0.0.0");
server.addConnector(connector);
WebAppContext wac = new WebAppContext();
wac.setContextPath(CONTEXTPATH);
wac.setWar(WEBAPP);
server.setHandler(wac);
server.setStopAtShutdown(true);
server.start();
}
| public void startServer() throws Exception {
server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(8080);
connector.setHost("0.0.0.0");
server.addConnector(connector);
WebAppContext wac = new WebAppContext();
wac.setContextPath(CONTEXTPATH);
wac.setWar(WEBAPP);
server.setHandler(wac);
server.setStopAtShutdown(true);
server.start();
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java b/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java
index c2f440891..f418048e1 100644
--- a/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java
+++ b/src/main/java/net/aufdemrand/denizen/scripts/containers/core/WorldScriptHelper.java
@@ -1,4439 +1,4439 @@
package net.aufdemrand.denizen.scripts.containers.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import net.aufdemrand.denizen.Settings;
import net.aufdemrand.denizen.objects.Duration;
import net.aufdemrand.denizen.objects.Element;
import net.aufdemrand.denizen.objects.aH;
import net.aufdemrand.denizen.objects.aH.Argument;
import net.aufdemrand.denizen.objects.dEntity;
import net.aufdemrand.denizen.objects.dInventory;
import net.aufdemrand.denizen.objects.dItem;
import net.aufdemrand.denizen.objects.dList;
import net.aufdemrand.denizen.objects.dLocation;
import net.aufdemrand.denizen.objects.dMaterial;
import net.aufdemrand.denizen.objects.dNPC;
import net.aufdemrand.denizen.objects.dObject;
import net.aufdemrand.denizen.objects.dPlayer;
import net.aufdemrand.denizen.objects.dWorld;
import net.aufdemrand.denizen.scripts.ScriptBuilder;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.scripts.commands.core.DetermineCommand;
import net.aufdemrand.denizen.scripts.queues.ScriptQueue;
import net.aufdemrand.denizen.scripts.queues.core.InstantQueue;
import net.aufdemrand.denizen.tags.TagManager;
import net.aufdemrand.denizen.utilities.Conversion;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.entity.Position;
import org.bukkit.Bukkit;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.ItemFrame;
import org.bukkit.entity.Player;
import org.bukkit.entity.Sheep;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockBurnEvent;
import org.bukkit.event.block.BlockCanBuildEvent;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockDispenseEvent;
import org.bukkit.event.block.BlockFadeEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockGrowEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.BlockRedstoneEvent;
import org.bukkit.event.block.LeavesDecayEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.CreeperPowerEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityPortalEnterEvent;
import org.bukkit.event.entity.EntityPortalExitEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.EntityTeleportEvent;
import org.bukkit.event.entity.EntityUnleashEvent;
import org.bukkit.event.entity.ExplosionPrimeEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.HorseJumpEvent;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.event.entity.PigZapEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.PlayerLeashEntityEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.entity.SheepDyeWoolEvent;
import org.bukkit.event.entity.SheepRegrowWoolEvent;
import org.bukkit.event.entity.SlimeSplitEvent;
import org.bukkit.event.hanging.HangingBreakByEntityEvent;
import org.bukkit.event.hanging.HangingBreakEvent;
import org.bukkit.event.hanging.HangingPlaceEvent;
import org.bukkit.event.inventory.BrewEvent;
import org.bukkit.event.inventory.FurnaceBurnEvent;
import org.bukkit.event.inventory.FurnaceExtractEvent;
import org.bukkit.event.inventory.FurnaceSmeltEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerBedLeaveEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLevelChangeEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerShearEntityEvent;
import org.bukkit.event.player.PlayerToggleFlightEvent;
import org.bukkit.event.player.PlayerToggleSneakEvent;
import org.bukkit.event.player.PlayerToggleSprintEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.vehicle.VehicleBlockCollisionEvent;
import org.bukkit.event.vehicle.VehicleCreateEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleEntityCollisionEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.weather.LightningStrikeEvent;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.event.world.SpawnChangeEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.event.world.WorldInitEvent;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.BlockIterator;
@SuppressWarnings("deprecation")
public class WorldScriptHelper implements Listener {
public static Map<String, WorldScriptContainer> world_scripts = new ConcurrentHashMap<String, WorldScriptContainer>(8, 0.9f, 1);
public WorldScriptHelper() {
DenizenAPI.getCurrentInstance().getServer().getPluginManager()
.registerEvents(this, DenizenAPI.getCurrentInstance());
}
/////////////////////
// EVENT HANDLER
/////////////////
public static String doEvents(List<String> eventNames, dNPC npc, Player player, Map<String, dObject> context) {
String determination = "none";
if (dB.showEventsFiring) dB.log("Fired for '" + eventNames.toString() + "'");
for (WorldScriptContainer script : world_scripts.values()) {
if (script == null) continue;
for (String eventName : eventNames) {
// Check for event's name with and without dObject prefixes
if (!script.contains("EVENTS.ON " + eventName.toUpperCase()))
continue;
// Fetch script from Event
//
// Note: a "new dPlayer(null)" will not be null itself,
// so keep a ternary operator here
List<ScriptEntry> entries = script.getEntries
(player != null ? new dPlayer(player) : null,
npc, "events.on " + eventName);
if (entries.isEmpty()) continue;
dB.report("Event",
aH.debugObj("Type", "On " + eventName)
+ script.getAsScriptArg().debug()
+ (npc != null ? aH.debugObj("NPC", npc.toString()) : "")
+ (player != null ? aH.debugObj("Player", player.getName()) : "")
+ (context != null ? aH.debugObj("Context", context.toString()) : ""));
dB.echoDebug(dB.DebugElement.Header, "Building event 'On " + eventName.toUpperCase() + "' for " + script.getName());
// Create new ID -- this is what we will look for when determining an outcome
long id = DetermineCommand.getNewId();
// Add the reqId to each of the entries for the determine command (this may be slightly outdated, add to TODO)
ScriptBuilder.addObjectToEntries(entries, "ReqId", id);
// Add entries and context to the queue
ScriptQueue queue = InstantQueue.getQueue(null).addEntries(entries);
if (context != null) {
for (Map.Entry<String, dObject> entry : context.entrySet()) {
queue.addContext(entry.getKey(), entry.getValue());
}
}
// Start the queue!
queue.start();
// Check the determination
if (DetermineCommand.hasOutcome(id))
determination = DetermineCommand.getOutcome(id);
}
}
return determination;
}
/////////////////////
// BLOCK EVENTS
/////////////////
// <--[event]
// @Events
// player breaks block
// player breaks <material>
// player breaks block with <item>
// player breaks <material> with <item>
// player breaks block with <material>
// player breaks <material> with <material>
//
// @Triggers when a player breaks a block.
// @Context
// <context.location> returns the dLocation the block was broken at.
// <context.material> returns the dMaterial of the block that was broken.
//
// @Determine
// "CANCELLED" to stop the block from breaking.
// "NOTHING" to make the block drop no items.
// dList(dItem) to make the block drop a specified list of items.
//
// -->
@EventHandler
public void blockBreak(BlockBreakEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Block block = event.getBlock();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(block.getLocation()));
context.put("material", material);
dItem item = new dItem(event.getPlayer().getItemInHand());
dMaterial itemMaterial = item.getMaterial();
List<String> events = new ArrayList<String>();
events.add("player breaks block");
events.add("player breaks " + material.identify());
events.add("player breaks block with " + item.identify());
events.add("player breaks " + material.identify() + " with " + item.identify());
events.add("player breaks block with " + itemMaterial.identify());
events.add("player breaks " + material.identify() + " with " + itemMaterial.identify());
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
// Make nothing drop, usually used as "drop:nothing"
else if (determination.toUpperCase().startsWith("NOTHING")) {
event.setCancelled(true);
block.setType(Material.AIR);
}
// Get a dList of dItems to drop
else if (Argument.valueOf(determination).matchesArgumentList(dItem.class)) {
// Cancel the event
event.setCancelled(true);
block.setType(Material.AIR);
// Get the list of items
Object list = dList.valueOf(determination).filter(dItem.class);
@SuppressWarnings("unchecked")
List<dItem> newItems = (List<dItem>) list;
for (dItem newItem : newItems) {
block.getWorld().dropItemNaturally(block.getLocation(),
newItem.getItemStack()); // Drop each item
}
}
}
// <--[event]
// @Events
// block burns
// <block> burns
//
// @Triggers when a block is destroyed by fire.
// @Context
// <context.location> returns the dLocation the block was burned at.
// <context.material> returns the dMaterial of the block that was burned.
//
// @Determine
// "CANCELLED" to stop the block from being destroyed.
//
// -->
@EventHandler
public void blockBurn(BlockBurnEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("location", new dLocation(event.getBlock().getLocation()));
dMaterial material = new dMaterial(event.getBlock().getType());
String determination = doEvents(Arrays.asList
("block burns",
material.identify() + " burns"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// block being built
// block being built on <material>
// <material> being built
// <material> being built on <material>
//
// @Triggers when an attempt is made to build a block on another block. Not necessarily caused by players.
// @Context
// <context.location> returns the dLocation of the block the player is trying to build on.
// <context.old_material> returns the dMaterial of the block the player is trying to build on.
// <context.new_material> returns the dMaterial of the block the player is trying to build.
//
// @Determine
// "BUILDABLE" to allow the building.
// "CANCELLED" to cancel the building.
//
// -->
@EventHandler
public void blockCanBuild(BlockCanBuildEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial oldMaterial = new dMaterial(event.getBlock().getType());
dMaterial newMaterial = new dMaterial(event.getMaterial());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("old_material", oldMaterial);
context.put("new_material", newMaterial);
String determination = doEvents(Arrays.asList
("block being built",
"block being built on " + oldMaterial.identify(),
newMaterial.identify() + " being built",
newMaterial.identify() + " being built on " +
oldMaterial.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("BUILDABLE"))
event.setBuildable(true);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setBuildable(false);
}
// <--[event]
// @Events
// player damages block
// player damages <material>
//
// @Triggers when a block is damaged by a player.
// @Context
// <context.location> returns the dLocation the block that was damaged.
// <context.material> returns the dMaterial of the block that was damaged.
//
// @Determine
// "CANCELLED" to stop the block from being damaged.
// "INSTABREAK" to make the block get broken instantly.
//
// -->
@EventHandler
public void blockDamage(BlockDamageEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("player damages block",
"player damages " + material.identify()),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (determination.toUpperCase().startsWith("INSTABREAK"))
event.setInstaBreak(true);
}
// <--[event]
// @Events
// block dispenses item
// block dispenses <item>
// <block> dispenses item
// <block> dispenses <item>
//
// @Triggers when a block dispenses an item.
// @Context
// <context.location> returns the dLocation of the dispenser.
// <context.item> returns the dItem of the item being dispensed.
//
// @Determine
// "CANCELLED" to stop the block from dispensing.
// Element(Double) to set the power with which the item is shot.
//
// -->
@EventHandler
public void blockDispense(BlockDispenseEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getItem());
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("item", item);
String determination = doEvents(Arrays.asList
("block dispenses item",
"block dispenses " + item.identify(),
material.identify() + " dispenses item",
material.identify() + " dispenses " + item.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setVelocity(event.getVelocity().normalize()
.multiply(aH.getDoubleFrom(determination)));
}
}
// <--[event]
// @Events
// block fades
// <block> fades
//
// @Triggers when a block fades, melts or disappears based on world conditions.
// @Context
// <context.location> returns the dLocation the block faded at.
// <context.material> returns the dMaterial of the block that faded.
//
// @Determine
// "CANCELLED" to stop the block from fading.
//
// -->
@EventHandler
public void blockFade(BlockFadeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("block fades",
material.identify() + " fades"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// block spreads
// <block> spreads
//
// @Triggers when a liquid block spreads.
// @Context
// <context.destination> returns the dLocation the block spread to.
// <context.location> returns the dLocation the block spread from.
// <context.type> returns the dMaterial of the block that spread.
//
// @Determine
// "CANCELLED" to stop the block from spreading.
//
// -->
@EventHandler
public void blockFromTo(BlockFromToEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("destination", new dLocation(event.getToBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("block spreads",
material.identify() + " spreads"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// block grows
// <block> grows
//
// @Triggers when a block grows naturally in the world.
// @Context
// <context.location> returns the dLocation the block.
// <context.material> returns the dMaterial of the block.
//
// @Determine
// "CANCELLED" to stop the block from growing.
//
// -->
@EventHandler
public void blockGrow(BlockGrowEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("block grows",
material.identify() + " grows"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// block ignites
// <block> ignites
//
// @Triggers when a block is set on fire.
// @Context
// <context.location> returns the dLocation the block was set on fire at.
// <context.material> returns the dMaterial of the block that was set on fire.
//
// @Determine
// "CANCELLED" to stop the block from being ignited.
//
// -->
@EventHandler
public void blockIgnite(BlockIgniteEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("block ignites",
material.identify() + " ignites"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// block moves
// <block> moves
//
// @Triggers when a block moves.
// @Context
// <context.location> returns the dLocation the block moved to.
// <context.material> returns the dMaterial of the block that moved.
//
// @Determine
// "CANCELLED" to stop the block from being moved.
//
// -->
@EventHandler
public void blockPhysics(BlockPhysicsEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("block moves",
material.identify() + " moves"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// piston extends
// <block> extends
//
// @Triggers when a piston extends.
// @Context
// <context.location> returns the dLocation of the piston.
// <context.material> returns the dMaterial of the piston.
// <context.length> returns the number of blocks that will be moved by the piston.
//
// @Determine
// "CANCELLED" to stop the piston from extending.
//
// -->
@EventHandler
public void blockPistonExtend(BlockPistonExtendEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
context.put("length", new Element(event.getLength()));
String determination = doEvents(Arrays.asList
("piston extends",
material.identify() + " extends"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// piston retracts
// <block> retracts
//
// @Triggers when a piston retracts.
// @Context
// <context.location> returns the dLocation of the piston.
// <context.retract_location> returns the new dLocation of the block that
// will be moved by the piston if it is sticky.
// <context.material> returns the dMaterial of the piston.
//
// @Determine
// "CANCELLED" to stop the piston from retracting.
//
// -->
@EventHandler
public void blockPistonRetract(BlockPistonRetractEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("retract_location", new dLocation(event.getRetractLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("piston retracts",
material.identify() + " retracts"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player places block
// player places <block>
//
// @Triggers when a player places a block.
// @Context
// <context.location> returns the dLocation of the block that was placed.
// <context.material> returns the dMaterial of the block that was placed.
//
// @Determine
// "CANCELLED" to stop the block from being placed.
//
// -->
@EventHandler
public void blockPlace(BlockPlaceEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("player places block",
"player places " + material.identify()),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// block powered
// <block> powered
// block unpowered
// <block> unpowered
//
// @Triggers when a block is (un)powered.
// @Context
// <context.location> returns the dLocation of the block that was (un)powered.
// <context.type> returns the dMaterial of the block that was (un)powered.
//
// @Determine
// "CANCELLED" to stop the block from being (un)powered.
//
// -->
@EventHandler
public void blockRedstone(BlockRedstoneEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
List<String> events = new ArrayList<String>();
if (event.getNewCurrent() > 0) {
events.add("block powered");
events.add(material.identify() + " powered");
}
else {
events.add("block unpowered");
events.add(material.identify() + " unpowered");
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setNewCurrent(event.getOldCurrent());
}
// <--[event]
// @Events
// brewing stand brews
//
// @Triggers when a brewing stand brews a potion.
// @Context
// <context.location> returns the dLocation of the brewing stand.
// <context.inventory> returns the dInventory of the brewing stand's contents.
//
// @Determine
// "CANCELLED" to stop the brewing stand from brewing.
//
// -->
@EventHandler
public void brew(BrewEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("inventory", new dInventory(event.getContents()));
String determination = doEvents(Arrays.asList
("brewing stand brews"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// furnace burns item
// furnace burns <item>
//
// @Triggers when a furnace burns an item used as fuel.
// @Context
// <context.location> returns the dLocation of the furnace.
// <context.item> returns the dItem burnt.
//
// @Determine
// "CANCELLED" to stop the furnace from burning the item.
// Element(Integer) to set the burn time for this fuel.
//
// -->
@EventHandler
public void furnaceBurn(FurnaceBurnEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getFuel());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("item", item);
String determination = doEvents(Arrays.asList
("furnace burns item",
"furnace burns " + item.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Integer)) {
event.setBurnTime(aH.getIntegerFrom(determination));
}
}
// <--[event]
// @Events
// player takes item from furnace
// player takes <item> from furnace
// player takes <material> from furnace
//
// @Triggers when a player takes an item from a furnace.
// @Context
// <context.location> returns the dLocation of the furnace.
// <context.item> returns the dItem taken out of the furnace.
//
// @Determine
// Element(Integer) to set the amount of experience the player will get.
//
// -->
@EventHandler
public void furnaceExtract(FurnaceExtractEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial itemMaterial = new dMaterial(event.getItemType());
dItem item = new dItem(itemMaterial, event.getItemAmount());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("item", item);
String determination = doEvents(Arrays.asList
("player takes item from furnace",
"player takes " + item.identify() + " from furnace",
"player takes " + itemMaterial.identify() + " from furnace"),
null, event.getPlayer(), context);
if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Integer)) {
event.setExpToDrop(aH.getIntegerFrom(determination));
}
}
// <--[event]
// @Events
// furnace smelts item (into <item>)
// furnace smelts <item> (into <item>)
//
// @Triggers when a furnace smelts an item.
// @Context
// <context.location> returns the dLocation of the furnace.
// <context.source> returns the dItem that is smelted.
// <context.result> returns the dItem that is the result of the smelting.
//
// @Determine
// "CANCELLED" to stop the furnace from smelting the item.
// dItem to set the item that is the result of the smelting.
//
// -->
@EventHandler
public void furnaceSmelt(FurnaceSmeltEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem source = new dItem(event.getSource());
dItem result = new dItem(event.getResult());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("source_item", source);
context.put("result_item", result);
String determination = doEvents(Arrays.asList
("furnace smelts item",
"furnace smelts " + source.identify(),
"furnace smelts item into " + result.identify(),
"furnace smelts " + source.identify() + " into " + result.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (dItem.matches(determination)) {
event.setResult(dItem.valueOf(determination).getItemStack());
}
}
// <--[event]
// @Events
// leaves decay
// <block> decay
//
// @Triggers when leaves decay.
// @Context
// <context.location> returns the dLocation of the leaves.
// <context.material> returns the dMaterial of the leaves.
//
// @Determine
// "CANCELLED" to stop the leaves from decaying.
//
// -->
@EventHandler
public void leavesDecay(LeavesDecayEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dMaterial material = new dMaterial(event.getBlock().getType());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("leaves decay",
material.identify() + " decay"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player changes sign
// player changes wall_sign
// player changes sign_post
//
// @Triggers when a player changes a sign.
// @Context
// <context.location> returns the dLocation of the sign.
// <context.new> returns the new sign text as a dList.
// <context.old> returns the old sign text as a dList.
// <context.material> returns the dMaterial of the sign.
//
// @Determine
// "CANCELLED" to stop the sign from being changed.
//
// -->
@EventHandler
public void signChange(final SignChangeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Player player = event.getPlayer();
Block block = event.getBlock();
Sign sign = (Sign) block.getState();
dMaterial material = new dMaterial(block.getType());
context.put("old", new dList(Arrays.asList(sign.getLines())));
context.put("new", new dList(Arrays.asList(event.getLines())));
context.put("location", new dLocation(block.getLocation()));
context.put("material", material);
String determination = doEvents(Arrays.asList
("player changes sign",
"player changes " + material.identify()),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// CUSTOM EVENTS
/////////////////
// <--[event]
// @Events
// server start
//
// @Triggers when the server starts
//
// @Determine "CANCELLED" to save all plugins and cancel server startup.
//
// -->
public void serverStartEvent() {
// Start the 'timeEvent'
Bukkit.getScheduler().scheduleSyncRepeatingTask(DenizenAPI.getCurrentInstance(),
new Runnable() {
@Override
public void run() {
timeEvent();
}
}, Settings.WorldScriptTimeEventFrequency().getTicks(), Settings.WorldScriptTimeEventFrequency().getTicks());
// Fire the 'Server Start' event
String determination = doEvents(Arrays.asList("server start"),
null, null, null);
if (determination.toUpperCase().startsWith("CANCELLED"))
Bukkit.getServer().shutdown();
}
private final Map<String, Integer> current_time = new HashMap<String, Integer>();
// <--[event]
// @Events
// time changes in <world>
// <0-23>:00 in <world>
// time <0-23> in <world>
//
// @Triggers when a block is set on fire.
// @Context
// <context.time> returns the current time.
// <context.world> returns the world.
//
// -->
public void timeEvent() {
for (World world : Bukkit.getWorlds()) {
int hour = Double.valueOf(world.getTime() / 1000).intValue();
hour = hour + 6;
// Get the hour
if (hour >= 24) hour = hour - 24;
dWorld currentWorld = new dWorld(world);
if (!current_time.containsKey(currentWorld.identify())
|| current_time.get(currentWorld.identify()) != hour) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("time", new Element(hour));
context.put("world", currentWorld);
doEvents(Arrays.asList
("time changes in " + currentWorld.identify(),
String.valueOf(hour) + ":00 in " + currentWorld.identify(),
"time " + String.valueOf(hour) + " in " + currentWorld.identify()),
null, null, context);
current_time.put(currentWorld.identify(), hour);
}
}
}
/////////////////////
// HANGING EVENTS
/////////////////
// <--[event]
// @Events
// hanging breaks
// hanging breaks because <cause>
// <hanging> breaks
// <hanging> breaks because <cause>
//
// @Triggers when a hanging entity (painting or itemframe) is broken.
// @Context
// <context.cause> returns the cause of the entity breaking.
// <context.entity> returns the dEntity that broke the hanging entity, if any.
// <context.hanging> returns the dEntity of the hanging.
//
// @Determine
// "CANCELLED" to stop the hanging from being broken.
//
// -->
@EventHandler
public void hangingBreak(HangingBreakEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity hanging = new dEntity(event.getEntity());
String hangingType = hanging.getEntityType().name();
String cause = event.getCause().name();
context.put("hanging", hanging);
context.put("cause", new Element(cause));
List<String> events = new ArrayList<String>();
events.add("hanging breaks");
events.add("hanging breaks because " + cause);
events.add(hangingType + " breaks");
events.add(hangingType +
" breaks because " + cause);
if (event instanceof HangingBreakByEntityEvent) {
// <--[event]
// @Events
// <entity> breaks hanging
// <entity> breaks hanging because <cause>
// <entity> breaks <hanging>
// <entity> breaks <hanging> because <cause>
//
// @Triggers when a hanging entity is broken by an entity.
// @Context
// <context.cause> returns the cause of the entity breaking.
// <context.entity> returns the dEntity that broke the hanging entity.
// <context.hanging> returns the hanging entity as a dEntity.
//
// @Determine
// "CANCELLED" to stop the hanging entity from being broken.
//
// -->
HangingBreakByEntityEvent subEvent = (HangingBreakByEntityEvent) event;
dEntity entity = new dEntity(subEvent.getRemover());
String entityType = entity.getEntityType().name();
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
events.add("entity breaks hanging");
events.add("entity breaks hanging because " + cause);
events.add("entity breaks " + hangingType);
events.add("entity breaks " + hangingType + " because " + cause);
events.add(entityType + " breaks hanging");
events.add(entityType + " breaks hanging because " + cause);
events.add(entityType + " breaks " + hangingType);
events.add(entityType + " breaks " + hangingType + " because " + cause);
}
String determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player places hanging
// player places <hanging>
//
// @Triggers when a hanging entity (painting or itemframe) is placed.
// @Context
// <context.hanging> returns the dEntity of the hanging.
// <context.location> returns the dLocation of the block the hanging was placed on.
//
// @Determine
// "CANCELLED" to stop the hanging from being placed.
//
// -->
@EventHandler
public void hangingPlace(HangingPlaceEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity hanging = new dEntity(event.getEntity());
String hangingType = hanging.getEntityType().name();
context.put("hanging", hanging);
context.put("location", new dLocation(event.getBlock().getLocation()));
String determination = doEvents(Arrays.asList
("player places hanging",
"player places " + hangingType),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// ENTITY EVENTS
/////////////////
// <--[event]
// @Events
// entity spawns
// entity spawns because <cause>
// <entity> spawns
// <entity> spawns because <cause>
//
// @Triggers when an entity spawns.
// @Context
// <context.entity> returns the dEntity that spawned.
// <context.reason> returns the reason the entity spawned.
//
// @Determine
// "CANCELLED" to stop the entity from spawning.
//
// -->
@EventHandler
public void creatureSpawn(CreatureSpawnEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String reason = event.getSpawnReason().name();
context.put("entity", entity);
context.put("reason", new Element(reason));
String determination = doEvents(Arrays.asList
("entity spawns",
"entity spawns because " + event.getSpawnReason().name(),
entityType + " spawns",
entityType + " spawns because " + reason),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// creeper powered (because <cause>)
//
// @Triggers when a creeper is struck by lightning and turned into a powered creeper.
// @Context
// <context.entity> returns the dEntity of the creeper.
// <context.lightning> returns the dEntity of the lightning.
// <context.cause> returns an Element of the cause for the creeper being powered.
//
// @Determine
// "CANCELLED" to stop the creeper from being powered.
//
// -->
@EventHandler
public void creeperPower(CreeperPowerEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
dEntity lightning = new dEntity(event.getLightning());
String cause = event.getCause().name();
context.put("entity", entity);
context.put("lightning", lightning);
context.put("cause", new Element(cause));
String determination = doEvents(Arrays.asList
("creeper powered",
"creeper powered because " + cause),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity changes block
// <entity> changes block
// <entity> changes block
//
// @Triggers when an entity changes the material of a block.
// @Context
// <context.entity> returns the dEntity that changed the block.
// <context.location> returns the dLocation of the changed block.
// <context.old_material> returns the old material of the block.
// <context.new_material> returns the new material of the block.
//
// @Determine
// "CANCELLED" to stop the entity from changing the block.
//
// -->
@EventHandler
public void entityChangeBlock(EntityChangeBlockEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
dMaterial oldMaterial = new dMaterial(event.getBlock().getType());
dMaterial newMaterial = new dMaterial(event.getTo());
context.put("entity", entity.getDenizenObject());
context.put("location", new dLocation(event.getBlock().getLocation()));
context.put("old_material", oldMaterial);
context.put("new_material", newMaterial);
String determination = doEvents(Arrays.asList
("entity changes block",
"entity changes " + oldMaterial.identify(),
"entity changes block into " + newMaterial.identify(),
"entity changes " + oldMaterial.identify() +
" into " + newMaterial.identify(),
entityType + " changes block",
entityType + " changes " + oldMaterial.identify(),
entityType + " changes block into " + newMaterial.identify(),
entityType + " changes " + oldMaterial.identify() +
" into " + newMaterial.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity combusts
// <entity> combusts
//
// @Triggers when an entity combusts.
// @Context
// <context.duration> returns how long the entity takes to combust.
// <context.entity> returns the dEntity that combusted.
//
// @Determine
// "CANCELLED" to stop the entity from combusting.
//
// -->
@EventHandler
public void entityCombust(EntityCombustEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity).getDenizenObject());
context.put("duration", new Duration((long) event.getDuration()));
String determination = doEvents(Arrays.asList
("entity combusts",
entity.getType().name() + " combusts"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity damaged
// entity damaged by <cause>
// <entity> damaged
// <entity> damaged by <cause>
//
// @Triggers when an entity is damaged.
// @Context
// <context.cause> returns the reason the entity was damaged.
// <context.damage> returns the amount of damage dealt.
// <context.entity> returns the dEntity that was damaged.
//
// @Determine
// "CANCELLED" to stop the entity from being damaged.
// Element(Double) to set the amount of damage the entity receives.
//
// -->
@EventHandler
public void entityDamage(EntityDamageEvent event) {
Player player = null;
dNPC npc = null;
String determination;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String cause = event.getCause().name();
context.put("entity", entity.getDenizenObject());
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
boolean isFatal = false;
- if (entity.isValid()) {
+ if (entity.isValid() && entity.isLivingEntity()) {
if (event.getDamage() >= entity.getLivingEntity().getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal) {
// <--[event]
// @Events
// entity killed
// entity killed by <cause>
// <entity> killed
// <entity> killed by <cause>
//
// @Triggers when an entity is killed.
// @Context
// <context.cause> returns the reason the entity was killed.
// <context.entity> returns the dEntity that was killed.
// <context.damage> returns the amount of damage dealt.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being killed.
// Element(Double) to set the amount of damage the entity receives, instead of dying.
//
// -->
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
// <--[event]
// @Events
// entity damages entity
// entity damages <entity>
// <entity> damages entity
// <entity> damages <entity>
//
// @Triggers when an entity damages another entity.
// @Context
// <context.cause> returns the reason the entity was damaged.
// <context.entity> returns the dEntity that was damaged.
// <context.damage> returns the amount of damage dealt.
// <context.damager> returns the dEntity damaging the other entity.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being damaged.
// Element(Double) to set the amount of damage the entity receives.
//
// -->
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Have a different set of player and NPC contexts for events
// like "player damages player" from the one we have for
// "player damaged by player"
Player subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getEntityType().name();
context.put("damager", damager.getDenizenObject());
if (damager.isNPC()) {
subNPC = damager.getDenizenNPC();
damagerType = "npc";
// If we had no NPC in our regular context, use this one
if (npc == null) npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = damager.getPlayer();
// If we had no player in our regular context, use this one
if (player == null) player = subPlayer;
}
// If the damager is a projectile, add its shooter (which can be null)
// to the context
else if (damager.hasShooter()) {
dEntity shooter = damager.getShooter();
context.put("shooter", shooter.getDenizenObject());
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
// Have a new list of events for the subContextPlayer
// and subContextNPC
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
// <--[event]
// @Events
// entity kills entity
// entity kills <entity>
// <entity> kills entity
// <entity> kills <entity>
//
// @Triggers when an entity kills another entity.
// @Context
// <context.cause> returns the reason the entity was killed.
// <context.entity> returns the dEntity that was killed.
// <context.damager> returns the dEntity killing the other entity.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being killed.
// Element(Number) to set the amount of damage the entity receives, instead of dying.
//
// -->
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, subPlayer, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
// <--[event]
// @Events
// entity explodes
// <entity> explodes
//
// @Triggers when an entity explodes.
// @Context
// <context.blocks> returns a dList of blocks that the entity blew up.
// <context.entity> returns the dEntity that exploded.
// <context.location> returns the dLocation the entity blew up at.
//
// @Determine
// "CANCELLED" to stop the entity from exploding.
//
// -->
@EventHandler
public void entityExplode(EntityExplodeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("entity", entity.getDenizenObject());
context.put("location", new dLocation(event.getLocation()));
String blocks = "";
for (Block block : event.blockList()) {
blocks = blocks + new dLocation(block.getLocation()) + "|";
}
context.put("blocks", blocks.length() > 0 ? new dList(blocks) : null);
String determination = doEvents(Arrays.asList
("entity explodes",
entityType + " explodes"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity heals (because <cause>)
// <entity> heals (because <cause>)
//
// @Triggers when an entity heals.
// @Context
// <context.amount> returns the amount the entity healed.
// <context.entity> returns the dEntity that healed.
// <context.reason> returns the cause of the entity healing.
//
// @Determine
// "CANCELLED" to stop the entity from healing.
// Element(Double) to set the amount of health the entity receives.
//
// -->
@EventHandler
public void entityRegainHealth(EntityRegainHealthEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String reason = event.getRegainReason().name();
context.put("reason", new Element(event.getRegainReason().name()));
context.put("amount", new Element(event.getAmount()));
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
String determination = doEvents(Arrays.asList
("entity heals",
"entity heals because " + reason,
entityType + " heals",
entityType + " heals because " + reason),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setAmount(aH.getDoubleFrom(determination));
}
}
// <--[event]
// @Events
// entity enters portal
// <entity> enters portal
//
// @Triggers when an entity enters a portal.
// @Context
// <context.entity> returns the dEntity.
// <context.location> returns the dLocation of the portal block touched by the entity.
//
// -->
@EventHandler
public void entityPortalEnter(EntityPortalEnterEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("location", new dLocation(event.getLocation()));
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
doEvents(Arrays.asList
("entity enters portal",
entityType + " enters portal"),
npc, player, context);
}
// <--[event]
// @Events
// entity exits portal
// <entity> exits portal
//
// @Triggers when an entity exits a portal.
// @Context
// <context.entity> returns the dEntity.
// <context.location> returns the dLocation of the portal block touched by the entity.
//
// -->
@EventHandler
public void entityPortalExit(EntityPortalExitEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("location", new dLocation(event.getTo()));
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
doEvents(Arrays.asList
("entity exits portal",
entityType + " exits portal"),
npc, player, context);
}
// <--[event]
// @Events
// entity shoots bow
// <entity> shoots bow
//
// @Triggers when an entity shoots something out of a bow.
// @Context
// <context.entity> returns the dEntity that shot the bow.
// <context.projectile> returns a dEntity of the projectile.
//
// @Determine
// "CANCELLED" to stop the entity from shooting the bow.
// dList(dEntity) to change the projectile(s) being shot.
//
// -->
@EventHandler
public void entityShootBow(EntityShootBowEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Player player = null;
dNPC npc = null;
dItem bow = new dItem(event.getBow());
dEntity projectile = new dEntity(event.getProjectile());
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("bow", bow);
context.put("projectile", projectile);
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
String determination = doEvents(Arrays.asList
("entity shoots bow",
"entity shoots " + bow.identify(),
entityType + " shoots bow",
entityType + " shoots " + bow.identify()),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED")) {
event.setCancelled(true);
}
// Don't use event.setProjectile() because it doesn't work
else if (Argument.valueOf(determination).matchesArgumentList(dEntity.class)) {
event.setCancelled(true);
// Get the list of entities
Object list = dList.valueOf(determination).filter(dEntity.class);
@SuppressWarnings("unchecked")
List<dEntity> newProjectiles = (List<dEntity>) list;
// Go through all the entities, spawning/teleporting them
for (dEntity newProjectile : newProjectiles) {
if (!newProjectile.isSpawned()) {
newProjectile.spawnAt(projectile.getLocation());
}
else {
newProjectile.teleport(projectile.getLocation());
}
// Set the entity as the shooter of the projectile,
// where applicable
if (newProjectile.isProjectile()) {
newProjectile.setShooter(entity);
}
}
// Mount the projectiles on top of each other
Position.mount(Conversion.convert(newProjectiles));
// Get the last entity on the list, i.e. the one at the bottom
// if there are many mounted on top of each other
Entity lastProjectile = newProjectiles.get
(newProjectiles.size() - 1).getBukkitEntity();
// Give it the same velocity as the arrow that would
// have been shot by the bow
lastProjectile.setVelocity(projectile.getVelocity());
}
}
// <--[event]
// @Events
// entity tamed
// <entity> tamed
// player tames entity
// player tames <entity>
//
// @Triggers when an entity is tamed.
// @Context
// <context.entity> returns a dEntity of the tamed entity.
//
// @Determine
// "CANCELLED" to stop the entity from being tamed.
//
// -->
@EventHandler
public void entityTame(EntityTameEvent event) {
Player player = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("entity", entity);
List<String> events = new ArrayList<String>();
events.add("entity tamed");
events.add(entityType + " tamed");
if (event.getOwner() instanceof Player) {
player = (Player) event.getOwner();
events.add("player tames entity");
events.add("player tames " + entityType);
}
String determination = doEvents(events, null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity targets (<entity>)
// entity targets (<entity>) because <cause>
// <entity> targets (<entity>)
// <entity> targets (<entity>) because <cause>
//
// @Triggers when an entity targets a new entity.
// @Context
// <context.entity> returns the targeting entity.
// <context.reason> returns the reason the entity changed targets.
// <context.target> returns the targeted entity.
//
// @Determine
// "CANCELLED" to stop the entity from being targeted.
// dEntity to make the entity target a different entity instead.
//
// -->
@EventHandler
public void entityTarget(EntityTargetEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
final dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String reason = event.getReason().name();
context.put("entity", entity);
context.put("reason", new Element(reason));
List<String> events = new ArrayList<String>();
events.add("entity targets");
events.add("entity targets because " + reason);
events.add(entityType + " targets");
events.add(entityType + " targets because " + reason);
if (event.getTarget() != null) {
dEntity target = new dEntity(event.getTarget());
String targetType = target.getEntityType().name();
context.put("target", target.getDenizenObject());
if (target.isNPC()) { npc = target.getDenizenNPC(); targetType = "npc"; }
else if (target.isPlayer()) player = target.getPlayer();
events.add("entity targets entity");
events.add("entity targets entity because " + reason);
events.add("entity targets " + targetType);
events.add("entity targets " + targetType + " because " + reason);
events.add(entityType + " targets entity");
events.add(entityType + " targets entity because " + reason);
events.add(entityType + " targets " + targetType);
events.add(entityType + " targets " + targetType + " because " + reason);
}
String determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
// If the determination matches a dEntity, change the event's target
// using a scheduled task (otherwise, the target will not be changed)
//
// Note: this does not work with all monster types
else if (dEntity.matches(determination)) {
final dEntity newTarget = dEntity.valueOf(determination);
Bukkit.getScheduler().scheduleSyncDelayedTask(DenizenAPI.getCurrentInstance(), new Runnable() {
@Override
public void run() {
entity.target(newTarget.getLivingEntity());
}
}, 1);
}
}
// <--[event]
// @Events
// entity teleports
// <entity> teleports
//
// @Triggers when an entity teleports.
// @Context
// <context.entity> returns the dEntity.
// <context.origin> returns the dLocation the entity teleported from.
// <context.entity> returns the dLocation the entity teleported to.
//
// @Determine
// "CANCELLED" to stop the entity from teleporting.
//
// -->
@EventHandler
public void entityTeleport(EntityTeleportEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("origin", new dLocation(event.getFrom()));
context.put("destination", new dLocation(event.getTo()));
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
String determination = doEvents(Arrays.asList
("entity teleports",
entityType + " teleports"),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity unleashed (because <reason>)
// <entity> unleashed (because <reason>)
//
// @Triggers when an entity is unleashed.
// @Context
// <context.entity> returns the dEntity.
// <context.reason> returns an Element of the reason for the unleashing.
//
// -->
@EventHandler
public void entityUnleash(EntityUnleashEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String reason = event.getReason().name();
context.put("entity", entity.getDenizenObject());
context.put("reason", new Element(reason));
doEvents(Arrays.asList
("entity unleashed",
"entity unleashed because " + reason,
entityType + " unleashed",
entityType + " unleashed because " + reason),
null, null, context);
}
// <--[event]
// @Events
// entity explosion primes
// <entity> explosion primes
//
// @Triggers when an entity decides to explode.
// @Context
// <context.entity> returns the dEntity.
// <context.origin> returns an Element of the explosion's radius.
// <context.fire> returns an Element with a value of "true" if the explosion will create fire and "false" otherwise.
//
// @Determine
// "CANCELLED" to stop the entity from deciding to explode.
//
// -->
@EventHandler
public void explosionPrimeEvent(ExplosionPrimeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Entity entity = event.getEntity();
context.put("entity", new dEntity(entity));
context.put("radius", new Element(event.getRadius()));
context.put("fire", new Element(event.getFire()));
String determination = doEvents(Arrays.asList
("entity explosion primes",
entity.getType().name() + " explosion primes"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity changes food level
// <entity> changes food level
//
// @Triggers when an entity's food level changes.
// @Context
// <context.entity> returns the dEntity.
// <context.food> returns an Element(Integer) of the entity's new food level.
//
// @Determine
// "CANCELLED" to stop the entity's food level from changing.
// Element(Double) to set the entity's new food level.
//
// -->
@EventHandler
public void foodLevelChange(FoodLevelChangeEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("food", new Element(event.getFoodLevel()));
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
String determination = doEvents(Arrays.asList
("entity changes food level",
entityType + " changes food level"),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Integer)) {
event.setFoodLevel(aH.getIntegerFrom(determination));
}
}
// <--[event]
// @Events
// horse jumps
// (<color>) (<type>) jumps
//
// @Triggers when a horse jumps.
// @Context
// <context.entity> returns the dEntity of the horse.
// <context.color> returns an Element of the horse's color.
// <context.variant> returns an Element of the horse's variant.
// <context.food> returns an Element(Float) of the jump's power.
//
// @Determine
// "CANCELLED" to stop the horse from jumping.
// Element(Double) to set the power of the jump.
//
// -->
@EventHandler
public void horseJump(HorseJumpEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
String variant = event.getEntity().getVariant().name();
String color = event.getEntity().getColor().name();
dEntity entity = new dEntity(event.getEntity());
context.put("variant", new Element(variant));
context.put("color", new Element(color));
context.put("power", new Element(event.getPower()));
context.put("entity", entity);
String determination = doEvents(Arrays.asList
("horse jumps",
variant + " jumps",
color + " jumps",
color + " " + variant + " jumps"),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Float)) {
event.setPower(aH.getFloatFrom(determination));
}
}
// <--[event]
// @Events
// item despawns
// <item> despawns
// <material> despawns
//
// @Triggers when an item entity despawns.
// @Context
// <context.item> returns the dItem of the entity.
// <context.entity> returns the dEntity.
//
// @Determine
// "CANCELLED" to stop the item entity from despawning.
//
// -->
@EventHandler
public void itemDespawn(ItemDespawnEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getEntity().getItemStack());
dMaterial itemMaterial = item.getMaterial();
context.put("item", item);
context.put("entity", new dEntity(event.getEntity()));
List<String> events = new ArrayList<String>();
events.add("item despawns");
events.add(item.identify() + " despawns");
events.add(itemMaterial.identify() + " despawns");
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// item spawns
// <item> spawns
// <material> spawns
//
// @Triggers when an item entity spawns.
// @Context
// <context.item> returns the dItem of the entity.
// <context.entity> returns the dEntity.
//
// @Determine
// "CANCELLED" to stop the item entity from spawning.
//
// -->
@EventHandler
public void itemSpawn(ItemSpawnEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getEntity().getItemStack());
dMaterial itemMaterial = item.getMaterial();
context.put("item", item);
context.put("entity", new dEntity(event.getEntity()));
List<String> events = new ArrayList<String>();
events.add("item spawns");
events.add(item.identify() + " spawns");
events.add(itemMaterial.identify() + " spawns");
if (!item.identify().equals(item.identify().split(":")[0])) {
events.add(item.identify().split(":")[0] + " spawns");
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// pig zapped
//
// @Triggers when a pig is zapped by lightning and turned into a pig zombie.
// @Context
// <context.pig> returns the dEntity of the pig.
// <context.pig_zombie> returns the dEntity of the pig zombie.
// <context.lightning> returns the dEntity of the lightning.
//
// @Determine
// "CANCELLED" to stop the pig from being zapped.
//
// -->
@EventHandler
public void pigZap(PigZapEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity pig = new dEntity(event.getEntity());
dEntity pigZombie = new dEntity(event.getPigZombie());
dEntity lightning = new dEntity(event.getLightning());
context.put("pig", pig);
context.put("pig_zombie", pigZombie);
context.put("lightning", lightning);
String determination = doEvents(Arrays.asList
("pig zapped"), null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// projectile hits block
// projectile hits <material>
// <projectile> hits block
// <projectile> hits <material>
//
// @Triggers when a projectile hits a block.
// @Context
// <context.projectile> returns the dEntity of the projectile.
// <context.shooter> returns the dEntity of the shooter, if there is one.
// <context.location> returns the dLocation of the block that was hit.
//
// -->
@EventHandler
public void projectileHit(ProjectileHitEvent event) {
Player player = null;
dNPC npc = null;
dEntity projectile = new dEntity(event.getEntity());
Block block = null;
BlockIterator bi = new BlockIterator(projectile.getLocation().getWorld(), projectile.getLocation().toVector(), projectile.getLocation().getDirection().normalize(), 0, 4);
while(bi.hasNext()) {
block = bi.next();
if(block.getTypeId() != 0) {
break;
}
}
String entityType = projectile.getEntityType().name();
dEntity shooter = projectile.getShooter();
dMaterial material = new dMaterial(block.getType());
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("projectile", projectile);
context.put("location", new dLocation(block.getLocation()));
List<String> events = new ArrayList<String>();
events.add("projectile hits block");
events.add("projectile hits " + material.identify());
events.add(entityType + " hits block");
events.add(entityType + " hits " + material.identify());
if (shooter != null) {
context.put("shooter", shooter.getDenizenObject());
// <--[event]
// @Events
// entity shoots block
// entity shoots <material>
// entity shoots <material> with <projectile>
// <entity> shoots block
// <entity> shoots <material>
// <entity> shoots <material> with <projectile>
//
// @Triggers when a projectile shot by an entity hits a block.
// @Context
// <context.projectile> returns the dEntity of the projectile.
// <context.shooter> returns the dEntity of the shooter, if there is one.
// <context.location> returns the dLocation of the block that was hit.
//
// -->
String shooterType = shooter.getEntityType().name();
if (shooter.isNPC()) { npc = shooter.getDenizenNPC(); shooterType = "npc"; }
else if (shooter.isPlayer()) player = shooter.getPlayer();
events.add("entity shoots block");
events.add("entity shoots block with " + entityType);
events.add("entity shoots " + material.identify() + " with " + entityType);
events.add(shooterType + " shoots block");
events.add(shooterType + " shoots block with " + entityType);
events.add(shooterType + " shoots " + material.identify() + " with " + entityType);
}
doEvents(events, npc, player, context);
}
// <--[event]
// @Events
// player dyes sheep (<color>)
// sheep dyed (<color>)
//
// @Triggers when a sheep is dyed by a player.
// @Context
// <context.entity> returns the dEntity of the sheep.
// <context.color> returns an Element of the color the sheep is being dyed.
//
// @Determine
// "CANCELLED" to stop it from being dyed.
// Element(String) that matches DyeColor to dye it a different color.
//
// -->
@EventHandler
public void sheepDyeWool(SheepDyeWoolEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String color = event.getColor().name();
context.put("entity", entity);
context.put("color", new Element(color));
String determination = doEvents(Arrays.asList
("player dyes sheep",
"player dyes sheep " + color,
"sheep dyed",
"sheep dyed " + color), null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (DyeColor.valueOf(determination) != null)
event.setColor(DyeColor.valueOf(determination));
}
// <--[event]
// @Events
// sheep regrows wool
//
// @Triggers when a sheep regrows wool.
// @Context
// <context.entity> returns the dEntity of the sheep.
//
// @Determine
// "CANCELLED" to stop it from regrowing wool.
//
// -->
@EventHandler
public void sheepRegrowWool(SheepRegrowWoolEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
context.put("entity", entity);
String determination = doEvents(Arrays.asList
("sheep regrows wool"), null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// slime splits (into <#>)
//
// @Triggers when a slime splits into smaller slimes.
// @Context
// <context.entity> returns the dEntity of the slime.
// <context.count> returns an Element(Integer) of the number of smaller slimes it will split into.
//
// @Determine
// "CANCELLED" to stop it from splitting.
// Element(Integer) to set the number of smaller slimes it will split into.
//
// -->
@EventHandler
public void slimeSplit(SlimeSplitEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
int count = event.getCount();
context.put("entity", entity);
context.put("count", new Element(count));
String determination = doEvents(Arrays.asList
("slime splits",
"slime splits into " + count),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Integer)) {
event.setCount(aH.getIntegerFrom(determination));
}
}
/////////////////////
// INVENTORY EVENTS
/////////////////
// <--[event]
// @Events
// item enchanted
// <item> enchanted
//
// @Triggers when an item is enchanted.
// @Context
// <context.location> returns the dLocation of the enchanting table.
// <context.inventory> returns the dInventory of the enchanting table.
// <context.item> returns the dItem to be enchanted.
//
// @Determine
// "CANCELLED" to stop the item from being enchanted.
//
// -->
@EventHandler
public void enchantItemEvent(EnchantItemEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Player player = event.getEnchanter();
dItem item = new dItem(event.getItem());
context.put("location", new dLocation(event.getEnchantBlock().getLocation()));
context.put("inventory", new dInventory(event.getInventory()));
context.put("item", item);
String determination = doEvents(Arrays.asList
("item enchanted",
item.identify() + " enchanted"),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player (<click type>) clicks (<item>) (in <inventory>)
//
// @Triggers when a player clicks in an inventory.
// @Context
// <context.item> returns the dItem the player has clicked on.
// <context.item> returns the dInventory.
// <context.click> returns an Element with the name of the click type.
// <context.slot_type> returns an Element with the name of the slot type that was clicked.
//
// @Determine
// "CANCELLED" to stop the player from clicking.
//
// -->
@EventHandler
public void inventoryClickEvent(InventoryClickEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = null;
Player player = (Player) event.getWhoClicked();
String type = event.getInventory().getType().name();
String click = event.getClick().name();
String slotType = event.getSlotType().name();
context.put("inventory", new dInventory(event.getInventory()));
context.put("click", new Element(click));
context.put("slot_type", new Element(slotType));
List<String> events = new ArrayList<String>();
events.add("player clicks in inventory");
events.add("player clicks in " + type);
String interaction = "player " + click + " clicks";
events.add(interaction + " in inventory");
events.add(interaction + " in " + type);
if (event.getCurrentItem() != null) {
item = new dItem(event.getCurrentItem());
dMaterial itemMaterial = item.getMaterial();
events.add("player clicks " +
item.identify() + " in inventory");
events.add(interaction +
item.identify() + " in inventory");
events.add(interaction +
item.identify() + " in " + type);
events.add("player clicks " +
itemMaterial.identify() + " in inventory");
events.add(interaction +
itemMaterial.identify() + " in inventory");
events.add(interaction +
itemMaterial.identify() + " in " + type);
}
context.put("item", item);
String determination = doEvents(events, null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player closes <inventory>
//
// @Triggers when a player closes an inventory.
// @Context
// <context.inventory> returns the dInventory.
//
// -->
@EventHandler
public void inventoryCloseEvent(InventoryCloseEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Player player = (Player) event.getPlayer();
String type = event.getInventory().getType().name();
context.put("inventory", new dInventory(event.getInventory()));
doEvents(Arrays.asList
("player closes inventory",
"player closes " + type),
null, player, context);
}
// <--[event]
// @Events
// player drags (<item>) (in <inventory>)
//
// @Triggers when a player drags in an inventory.
// @Context
// <context.item> returns the dItem the player has dragged.
// <context.item> returns the dInventory.
//
// @Determine
// "CANCELLED" to stop the player from dragging.
//
// -->
@EventHandler
public void inventoryDragEvent(InventoryDragEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = null;
Player player = (Player) event.getWhoClicked();
String type = event.getInventory().getType().name();
context.put("inventory", new dInventory(event.getInventory()));
List<String> events = new ArrayList<String>();
events.add("player drags");
events.add("player drags in inventory");
events.add("player drags in " + type);
if (event.getOldCursor() != null) {
item = new dItem(event.getOldCursor());
dMaterial itemMaterial = item.getMaterial();
events.add("player drags " +
item.identify());
events.add("player drags " +
item.identify() + " in inventory");
events.add("player drags " +
item.identify() + " in " + type);
events.add("player drags " +
itemMaterial.identify());
events.add("player drags " +
itemMaterial.identify() + " in inventory");
events.add("player drags " +
itemMaterial.identify() + " in " + type);
}
context.put("item", item);
String determination = doEvents(events, null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// item moves from inventory (to <inventory>)
// item moves from <inventory> (to <inventory>)
//
// @Triggers when an entity or block moves an item from one inventory to another.
// @Context
// <context.origin> returns the origin dInventory.
// <context.destination> returns the destination dInventory.
// <context.initiator> returns the dInventory that initiatied the item's transfer.
// <context.item> returns the dItem that was moved.
//
// @Determine
// "CANCELLED" to stop the item from being moved.
// dItem to set a different item to be moved.
//
// -->
@EventHandler
public void inventoryMoveItemEvent(InventoryMoveItemEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getItem());
String originType = event.getSource().getType().name();
String destinationType = event.getDestination().getType().name();
context.put("origin", new dInventory(event.getSource()));
context.put("destination", new dInventory(event.getDestination()));
context.put("initiator", new dInventory(event.getInitiator()));
context.put("item", item);
String determination = doEvents(Arrays.asList
("item moves from inventory",
"item moves from " + originType,
"item moves from " + originType
+ " to " + destinationType,
item.identify() + " moves from inventory",
item.identify() + " moves from " + originType,
item.identify() + " moves from " + originType
+ " to " + destinationType),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (dItem.matches(determination))
event.setItem(dItem.valueOf(determination).getItemStack());
}
// <--[event]
// @Events
// player opens <inventory>
//
// @Triggers when a player opens an inventory.
// @Context
// <context.inventory> returns the dInventory.
//
// @Determine
// "CANCELLED" to stop the player from opening the inventory.
//
// -->
@EventHandler
public void inventoryOpenEvent(InventoryOpenEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Player player = (Player) event.getPlayer();
String type = event.getInventory().getType().name();
context.put("inventory", new dInventory(event.getInventory()));
String determination = doEvents(Arrays.asList
("player opens inventory",
"player opens " + type),
null, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// inventory picks up item
// inventory picks up <item>
// <inventory> picks up item
// <inventory> picks up <item>
//
// @Triggers when a hopper or hopper minecart picks up an item.
// @Context
// <context.inventory> returns the dInventory that picked up the item.
// <context.item> returns the dItem.
//
// @Determine
// "CANCELLED" to stop the item from being moved.
//
// -->
@EventHandler
public void inventoryPickupItemEvent(InventoryPickupItemEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getItem());
dInventory inventory = new dInventory(event.getInventory());
String type = inventory.getInventoryType().name();
context.put("inventory", inventory);
context.put("item", item);
String determination = doEvents(Arrays.asList
("inventory picks up item",
"inventory picks up " + item.identify(),
type + " picks up item",
type + " picks up " + item.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// PLAYER EVENTS
/////////////////
// <--[event]
// @Events
// player chats
//
// @Triggers when a player chats.
// @Context
// <context.message> returns the player's message as an Element.
//
// @Determine
// "CANCELLED" to stop the player from chatting.
// Element(String) to change the message.
//
// -->
@EventHandler(priority = EventPriority.LOWEST)
public void asyncPlayerChat(final AsyncPlayerChatEvent event) {
// Return if "Use asynchronous event" is false in config file
if (!Settings.WorldScriptChatEventAsynchronous()) return;
final Map<String, dObject> context = new HashMap<String, dObject>();
context.put("message", new Element(event.getMessage()));
Callable<String> call = new Callable<String>() {
@Override
public String call() {
return doEvents(Arrays.asList("player chats"),
null, event.getPlayer(), context);
}
};
String determination = null;
try {
determination = event.isAsynchronous() ? Bukkit.getScheduler().callSyncMethod(DenizenAPI.getCurrentInstance(), call).get() : call.call();
} catch (InterruptedException e) {
// TODO: Need to find a way to fix this eventually
// e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (determination == null)
return;
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (!determination.equals("none")) {
event.setMessage(determination);
}
}
// <--[event]
// @Events
// player animates (<animation>)
//
// @Triggers when a player performs an animation.
// @Context
// <context.animation> returns the name of the animation.
//
// @Determine
// "CANCELLED" to stop the player from animating.
//
// -->
@EventHandler
public void playerAnimation(PlayerAnimationEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
String animation = event.getAnimationType().name();
context.put("animation", new Element(animation));
String determination = doEvents(Arrays.asList
("player animates",
"player animates " + animation),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player enters bed
//
// @Triggers when a player enters a bed.
// @Context
// <context.location> returns the dLocation of the bed.
//
// @Determine
// "CANCELLED" to stop the player from entering the bed.
//
// -->
@EventHandler
public void playerBedEnter(PlayerBedEnterEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("location", new dLocation(event.getBed().getLocation()));
String determination = doEvents
(Arrays.asList("player enters bed"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player leaves bed
//
// @Triggers when a player leaves a bed.
// @Context
// <context.location> returns the dLocation of the bed.
//
// -->
@EventHandler
public void playerBedLeave(PlayerBedLeaveEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("location", new dLocation(event.getBed().getLocation()));
doEvents(Arrays.asList
("player leaves bed"),
null, event.getPlayer(), context);
}
// <--[event]
// @Events
// player empties bucket
//
// @Triggers when a player empties a bucket.
// @Context
// <context.item> returns the dItem of the bucket.
// <context.location> returns the dLocation of the block clicked with the bucket.
//
// @Determine
// "CANCELLED" to stop the player from emptying the bucket.
// dItem to set the item in the player's hand after the event.
//
// -->
@EventHandler
public void playerBucketEmpty(PlayerBucketEmptyEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("item", new dItem(event.getBucket()));
context.put("location", new dLocation(event.getBlockClicked().getLocation()));
String determination = doEvents(Arrays.asList
("player empties bucket"),
null, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (dItem.matches(determination)) {
ItemStack is = dItem.valueOf(determination).getItemStack();
event.setItemStack( is != null ? is : new ItemStack(Material.AIR));
}
}
// <--[event]
// @Events
// player fills bucket
//
// @Triggers when a player fills a bucket.
// @Context
// <context.item> returns the dItem of the bucket.
// <context.location> returns the dLocation of the block clicked with the bucket.
//
// @Determine
// "CANCELLED" to stop the player from filling the bucket.
// dItem to set the item in the player's hand after the event.
//
// -->
@EventHandler
public void playerBucketFill(PlayerBucketFillEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("item", new dItem(event.getBucket()));
context.put("location", new dLocation(event.getBlockClicked().getLocation()));
String determination = doEvents(Arrays.asList
("player fills bucket"),
null, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (dItem.matches(determination)) {
ItemStack is = dItem.valueOf(determination).getItemStack();
event.setItemStack( is != null ? is : new ItemStack(Material.AIR));
}
}
// <--[event]
// @Events
// player changes world
// player changes world from <world>
// player changes world to <world>
// player changes world from <world> to <world>
//
// @Triggers when a player moves to a different world.
// @Context
// <context.origin_world> returns the dWorld that the player was previously on.
//
// -->
@EventHandler
public void playerChangedWorld(PlayerChangedWorldEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld originWorld = new dWorld(event.getFrom());
dWorld destinationWorld = new dWorld(event.getPlayer().getWorld());
context.put("origin_world", originWorld);
doEvents(Arrays.asList
("player changes world",
"player changes world from " + originWorld.identify(),
"player changes world to " + destinationWorld.identify(),
"player changes world from " + originWorld.identify() +
" to " + destinationWorld.identify()),
null, event.getPlayer(), context);
}
// Shares description with asyncPlayerChat
@EventHandler
public void playerChat(final PlayerChatEvent event) {
// Return if "Use asynchronous event" is true in config file
if (Settings.WorldScriptChatEventAsynchronous()) return;
final Map<String, dObject> context = new HashMap<String, dObject>();
context.put("message", new Element(event.getMessage()));
String determination = doEvents(Arrays.asList("player chats"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (!determination.equals("none")) {
event.setMessage(determination);
}
}
// <--[example]
// @Title On Command Event tutorial
// @Description
// Denizen contains the ability to run script entries in the form
// of a bukkit /command. Here's an example script that shows basic usage.
//
// @Code
// # +--------------------
// # | On Command Event tutorial
//
// # | Denizen contains the ability to run script entries in the form
// # | of a Bukkit /command. Here's an example script that shows basic usage.
//
// On Command Event Tutorial:
// type: world
//
// # +-- EVENTS: Node --+
// # To 'hook' into the on command event, just create a 'on <command_name> command'
// # node as a child of the events node in any world script. Change out <command_name>
// # with the desired name of the command. This can only be one word.
//
// events:
//
// # The following example will trigger on the use of '/testcommand'
// on testcommand command:
//
// # Why not state the obvious? Just to be sure!
// - narrate 'You just used the /testcommand command!'
//
// # You can utilize any arguments that come along with the command, too!
// # <c.args> returns a list of the arguments, run through the Denizen argument
// # interpreter. Using quotes will allow the use of multiple word arguments,
// # just like Denizen!
// # Just need what was typed after the command? Use <c.raw_args> for a String
// # Element containing the uninterpreted arguments.
// - define arg_size <c.args.size>
// - narrate "'%arg_size%' arguments were used."
// - if %arg_size% > 0 {
// - narrate "'<c.args.get[1]>' was the first argument."
// - narrate "Here's a list of all the arguments<&co> <c.args.as_cslist>"
// }
//
// # When a command isn't found, Bukkit reports an error. To let bukkit know
// # that the command was handled, use the 'determine fulfilled' command/arg.
// - determine fulfilled
//
// -->
// <--[event]
// @Events
// command
// <command_name> command
//
// @Triggers when a player or console runs a Bukkit command. This happens before
// any code of established commands allowing scripters to 'override' existing commands.
// @Context
// <context.command> returns the command name as an Element.
// <context.raw_args> returns any args used as an Element.
// <context.args> returns a dList of the arguments, parsed with Denizen's
// argument parser. Just like any Denizen Command, quotes and tags can be used.
// <context.server> returns true if the command was run from the console.
//
// @Determine
// "FULFILLED" to tell Bukkit the command was handled.
//
// -->
@EventHandler
public void playerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dPlayer player = dPlayer.valueOf(event.getPlayer().getName());
// Well, this is ugly :(
// Fill tags in any arguments
List<String> args = Arrays.asList(
aH.buildArgs(
TagManager.tag(player, null,
(event.getMessage().split(" ").length > 1 ? event.getMessage().split(" ", 2)[1] : ""))));
dList args_list = new dList(args);
String command = event.getMessage().split(" ")[0].replace("/", "").toUpperCase();
// Fill context
context.put("args", args_list);
context.put("command", new Element(command));
context.put("raw_args", new Element((event.getMessage().split(" ").length > 1
? event.getMessage().split(" ", 2)[1] : "")));
context.put("server", Element.FALSE);
String determination;
// Run any event scripts and get the determination.
determination = doEvents(Arrays.asList
("command",
command + " command"),
null, event.getPlayer(), context).toUpperCase();
// If a script has determined fulfilled, cancel this event so the player doesn't
// receive the default 'Invalid command' gibberish from bukkit.
if (determination.equals("FULFILLED") || determination.equals("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player dies
// player death
//
// @Triggers when a player dies.
// @Context
// <context.message> returns an Element of the death message.
//
// @Determine
// Element(String) to change the death message.
//
// -->
@EventHandler
public void playerDeath(PlayerDeathEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("message", new Element(event.getDeathMessage()));
String determination = doEvents(Arrays.asList
("player dies",
"player death"),
null, event.getEntity(), context);
// Handle message
if (!determination.equals("none")) {
event.setDeathMessage(determination);
}
}
// <--[event]
// @Events
// player drops item
// player drops <item>
//
// @Triggers when a player drops an item.
// @Context
// <context.item> returns the dItem.
// <context.entity> returns a dEntity of the item.
// <context.location> returns a dLocation of the item's location.
//
// @Determine
// "CANCELLED" to stop the item from being dropped.
//
// -->
@EventHandler
public void playerDropItem(PlayerDropItemEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getItemDrop().getItemStack());
context.put("item", item);
context.put("entity", new dEntity(event.getItemDrop()));
context.put("location", new dLocation(event.getItemDrop().getLocation()));
List<String> events = new ArrayList<String>();
events.add("player drops item");
events.add("player drops " + item.identify());
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player throws (hatching/non-hatching) egg
//
// @Triggers when a player throws an egg.
// @Context
// <context.item> returns the dEntity of the egg.
// <context.is_hatching> returns an Element with a value of "true" if the egg will hatch and "false" otherwise.
//
// @Determine
// dEntity to set the type of the hatching entity.
//
// -->
@EventHandler
public void playerEggThrow(PlayerEggThrowEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity egg = new dEntity(event.getEgg());
context.put("egg", egg);
context.put("is_hatching", new Element(event.isHatching()));
List<String> events = new ArrayList<String>();
events.add("player throws egg");
if (event.isHatching()) events.add("player throws hatching egg");
else events.add("player throws non-hatching egg");
String determination = doEvents(events, null, event.getPlayer(), context);
if (dEntity.matches(determination)) {
event.setHatching(true);
event.setHatchingType(dEntity.valueOf(determination).getEntityType());
}
}
// <--[event]
// @Events
// player fishes (while <state>)
//
// @Triggers when a player uses a fishing rod.
// @Context
// <context.hook> returns a dItem of the hook.
// <context.state> returns an Element of the fishing state.
// <context.entity> returns a dEntity, dPlayer or dNPC of the entity being fished.
//
// @Determine
// "CANCELLED" to stop the player from fishing.
//
// -->
@EventHandler
public void playerFish(PlayerFishEvent event) {
dNPC npc = null;
String state = event.getState().name();
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("hook", new dEntity(event.getHook()));
context.put("state", new Element(state));
List<String> events = new ArrayList<String>();
events.add("player fishes");
events.add("player fishes while " + state);
if (event.getCaught() != null) {
dEntity entity = new dEntity(event.getCaught());
String entityType = entity.getEntityType().name();
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
events.add("player fishes " + entityType);
events.add("player fishes " + entityType + " while " + state);
}
String determination = doEvents(events, npc, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player changes gamemode (to <gamemode>)
//
// @Triggers when a player's gamemode is changed.
// @Context
// <context.gamemode> returns an Element of the gamemode.
//
// @Determine
// "CANCELLED" to stop the gamemode from being changed.
//
// -->
@EventHandler
public void playerGameModeChange(PlayerGameModeChangeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("gamemode", new Element(event.getNewGameMode().name()));
String determination = doEvents(Arrays.asList
("player changes gamemode",
"player changes gamemode to " + event.getNewGameMode().name()),
null, event.getPlayer(), context);
// Handle message
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player (<click type>) clicks (<material>) (with <item>)
// player stands on <pressure plate>
//
// @Triggers when a player clicks on a block or stands on a pressure plate.
// @Context
// <context.item> returns the dItem the player is clicking with.
// <context.location> returns the dLocation the player is clicking on.
//
// @Determine
// "CANCELLED" to stop the click from happening.
//
// -->
@EventHandler
public void playerInteract(PlayerInteractEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
Action action = event.getAction();
dItem item = null;
dMaterial itemMaterial = null;
List<String> events = new ArrayList<String>();
String interaction;
if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK)
interaction = "player left clicks";
else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK)
interaction = "player right clicks";
// The only other action is PHYSICAL, which is triggered when a player
// stands on a pressure plate
else interaction = "player stands on";
events.add(interaction);
if (event.hasItem()) {
item = new dItem(event.getItem());
itemMaterial = item.getMaterial();
context.put("item", item);
events.add(interaction + " with item");
events.add(interaction + " with " + item.identify());
events.add(interaction + " with " + itemMaterial.identify());
}
if (event.hasBlock()) {
Block block = event.getClickedBlock();
context.put("location", new dLocation(block.getLocation()));
interaction = interaction + " " + block.getType().name();
events.add(interaction);
if (event.hasItem()) {
events.add(interaction + " with item");
events.add(interaction + " with " + item.identify());
events.add(interaction + " with " + itemMaterial.identify());
}
}
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player right clicks entity (with item)
//
// @Triggers when a player right clicks on an entity.
// @Context
// <context.entity> returns the dEntity the player is clicking on.
// <context.item> returns the dItem the player is clicking with.
//
// @Determine
// "CANCELLED" to stop the click from happening.
//
// -->
@EventHandler
public void playerInteractEntity(PlayerInteractEntityEvent event) {
String determination;
dNPC npc = null;
dItem item = new dItem(event.getPlayer().getItemInHand());
dMaterial itemMaterial = item.getMaterial();
dEntity entity = new dEntity(event.getRightClicked());
String entityType = entity.getEntityType().name();
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("location", new dLocation(event.getRightClicked().getLocation()));
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
List<String> events = new ArrayList<String>();
events.add("player right clicks entity");
events.add("player right clicks " + entityType);
events.add("player right clicks entity with " +
item.identify());
events.add("player right clicks " + entityType + " with " +
item.identify());
events.add("player right clicks entity with " +
itemMaterial.identify());
events.add("player right clicks " + entityType + " with " +
itemMaterial.identify());
if (entity.getBukkitEntity() instanceof ItemFrame) {
dItem itemFrame = new dItem(((ItemFrame) entity).getItem());
dMaterial itemFrameMaterial = itemFrame.getMaterial();
context.put("itemframe", itemFrame);
events.add("player right clicks " + entityType + " " +
itemFrame.identify());
events.add("player right clicks " + entityType + " " +
itemFrameMaterial.identify());
}
determination = doEvents(events, npc, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player consumes item
// player consumes <item>
//
// @Triggers when a player consumes an item.
// @Context
// <context.item> returns the dItem.
//
// @Determine
// "CANCELLED" to stop the item from being consumed.
//
// -->
@EventHandler
public void playerItemConsume(PlayerItemConsumeEvent event) {
dItem item = new dItem(event.getItem());
dMaterial itemMaterial = item.getMaterial();
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("item", item);
List<String> events = new ArrayList<String>();
events.add("player consumes " + item.identify());
events.add("player consumes " + itemMaterial.identify());
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player joins
// player join
//
// @Triggers when a player joins the server.
// @Context
// <context.message> returns an Element of the join message.
//
// @Determine
// Element(String) to change the join message.
//
// -->
@EventHandler
public void playerJoinEvent(PlayerJoinEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("message", new Element(event.getJoinMessage()));
String determination = doEvents(Arrays.asList
("player joins",
"player join"),
null, event.getPlayer(), context);
// Handle message
if (!determination.equals("none")) {
event.setJoinMessage(determination);
}
}
// <--[event]
// @Events
// player kicked
//
// @Triggers when a player is kicked from the server.
// @Context
// <context.message> returns an Element of the kick message.
//
// @Determine
// Element(String) to change the kick message.
//
// -->
@EventHandler
public void playerKick(PlayerKickEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("message", new Element(event.getLeaveMessage()));
String determination = doEvents(Arrays.asList
("player kicked"),
null, event.getPlayer(), context);
if (!determination.equals("none")) {
event.setLeaveMessage(determination);
}
}
// <--[event]
// @Events
// player leashes entity
// player leashes <entity>
//
// @Triggers when a player leashes an entity.
// @Context
// <context.entity> returns the dEntity of the leashed entity.
// <context.holder> returns the dEntity that is holding the leash.
//
// -->
@EventHandler
public void playerLeashEntity(PlayerLeashEntityEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("entity", entity);
context.put("holder", new dEntity(event.getLeashHolder()));
doEvents(Arrays.asList
("player leashes entity",
"entity leashes " + entityType),
null, event.getPlayer(), context);
}
// <--[event]
// @Events
// player levels up (from <level>/to <level>)
//
// @Triggers when a player levels up.
// @Context
// <context.level> returns an Element of the player's new level.
//
// -->
@EventHandler
public void playerLevelChange(PlayerLevelChangeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("level", new Element(event.getNewLevel()));
doEvents(Arrays.asList
("player levels up",
"player levels up to " + event.getNewLevel(),
"player levels up from " + event.getOldLevel()),
null, event.getPlayer(), context);
}
// <--[event]
// @Events
// player logs in
// player login
//
// @Triggers when a player logs in to the server.
// @Context
// <context.hostname> returns an Element of the player's hostname.
//
// @Determine
// "KICKED" to kick the player from the server.
//
// -->
@EventHandler
public void playerLogin(PlayerLoginEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("hostname", new Element(event.getHostname()));
String determination = doEvents(Arrays.asList
("player logs in",
"player login"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("KICKED"))
event.disallow(PlayerLoginEvent.Result.KICK_OTHER, determination);
}
// <--[event]
// @Events
// player walks over notable
// player walks over <notable>
//
// @Triggers when a player walks over a notable location.
// @Context
// <context.notable> returns an Element of the notable location's name.
//
// @Determine
// "CANCELLED" to stop the player from moving to the notable location.
//
// -->
@EventHandler
public void playerMove(PlayerMoveEvent event) {
if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return;
String name = dLocation.getSaved(event.getPlayer().getLocation());
if (name != null) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("notable", new Element(name));
String determination = doEvents(Arrays.asList
("player walks over notable",
"player walks over " + name,
"walked over notable",
"walked over " + name),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED") ||
determination.toUpperCase().startsWith("FROZEN"))
event.setCancelled(true);
}
}
// <--[event]
// @Events
// player picks up item
// player picks up <item>
// player takes item
// player takes <item>
//
// @Triggers when a player picks up an item.
// @Context
// <context.item> returns the dItem.
// <context.entity> returns a dEntity of the item.
// <context.location> returns a dLocation of the item's location.
//
// @Determine
// "CANCELLED" to stop the item from picked up.
//
// -->
@EventHandler
public void playerPickupItem(PlayerPickupItemEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dItem item = new dItem(event.getItem().getItemStack());
context.put("item", item);
context.put("entity", new dEntity(event.getItem()));
context.put("location", new dLocation(event.getItem().getLocation()));
List<String> events = new ArrayList<String>();
events.add("player picks up item");
events.add("player picks up " + item.identify());
events.add("player takes item");
events.add("player takes " + item.identify());
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player quits
// player quit
//
// @Triggers when a player quit the server.
// @Context
// <context.message> returns an Element of the quit message.
//
// @Determine
// Element(String) to change the quit message.
//
// -->
@EventHandler
public void playerQuit(PlayerQuitEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("message", new Element(event.getQuitMessage()));
String determination = doEvents(Arrays.asList
("player quits",
"player quit"),
null, event.getPlayer(), context);
if (!determination.equals("none")) {
event.setQuitMessage(determination);
}
}
// <--[event]
// @Events
// player respawns (at bed/elsewhere)
//
// @Triggers when a player respawns.
// @Context
// <context.location> returns a dLocation of the respawn location.
//
// @Determine
// dLocation to change the respawn location.
//
// -->
@EventHandler
public void playerRespawn(PlayerRespawnEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("location", new dLocation(event.getRespawnLocation()));
List<String> events = new ArrayList<String>();
events.add("player respawns");
if (event.isBedSpawn()) events.add("player respawns at bed");
else events.add("player respawns elsewhere");
String determination = doEvents(events, null, event.getPlayer(), context);
if (dLocation.matches(determination)) {
dLocation location = dLocation.valueOf(determination);
if (location != null) event.setRespawnLocation(location);
}
}
// <--[event]
// @Events
// player shears entity
// player shears <entity>
// player shears <color> sheep
//
// @Triggers when a player shears an entity.
// @Context
// <context.state> returns the dEntity.
//
// @Determine
// "CANCELLED" to stop the player from shearing the entity.
//
// -->
@EventHandler
public void playerShearEntity(PlayerShearEntityEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
context.put("entity", entity);
List<String> events = new ArrayList<String>();
events.add("player shears entity");
events.add("player shears " + entityType);
if (entity.getEntityType().equals(EntityType.SHEEP)) {
String color = ((Sheep) entity.getBukkitEntity()).getColor().name();
events.add("player shears " + color + " sheep");
}
String determination = doEvents(events, null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player toggles flight
// player starts/stops flying
//
// @Triggers when a player starts or stops flying.
// @Context
// <context.state> returns an Element with a value of "true" if the player is now flying and "false" otherwise.
//
// @Determine
// "CANCELLED" to stop the player from toggling flying.
//
// -->
@EventHandler
public void playerToggleFlight(PlayerToggleFlightEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("state", new Element(event.isFlying()));
String determination = doEvents(Arrays.asList
("player toggles flight",
"player " + (event.isFlying() ? "starts" : "stops") + " flying"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player toggles sneak
// player starts/stops sneaking
//
// @Triggers when a player starts or stops sneaking.
// @Context
// <context.state> returns an Element with a value of "true" if the player is now sneaking and "false" otherwise.
//
// @Determine
// "CANCELLED" to stop the player from toggling sneaking.
//
// -->
@EventHandler
public void playerToggleSneak(PlayerToggleSneakEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("state", new Element(event.isSneaking()));
String determination = doEvents(Arrays.asList
("player toggles sneak",
"player " + (event.isSneaking() ? "starts" : "stops") + " sneaking"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// player toggles sprint
// player starts/stops sprinting
//
// @Triggers when a player starts or stops sprinting.
// @Context
// <context.state> returns an Element with a value of "true" if the player is now sprinting and "false" otherwise.
//
// @Determine
// "CANCELLED" to stop the player from toggling sprinting.
//
// -->
@EventHandler
public void playerToggleSprint(PlayerToggleSprintEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("state", new Element(event.isSprinting()));
String determination = doEvents(Arrays.asList
("player toggles sprint",
"player " + (event.isSprinting() ? "starts" : "stops") + " sprinting"),
null, event.getPlayer(), context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// SERVER EVENTS
/////////////////
// Shares description with playerCommandPreprocess
@EventHandler
public void serverCommand(ServerCommandEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
List<String> args = Arrays.asList(
aH.buildArgs(
TagManager.tag(null, null,
(event.getCommand().split(" ").length > 1 ? event.getCommand().split(" ", 2)[1] : ""))));
dList args_list = new dList(args);
String command = event.getCommand().split(" ")[0].replace("/", "").toUpperCase();
// Fill context
context.put("args", args_list);
context.put("command", new Element(command));
context.put("raw_args", new Element((event.getCommand().split(" ").length > 1 ? event.getCommand().split(" ", 2)[1] : "")));
context.put("server", Element.TRUE);
doEvents(Arrays.asList("command",
command + " command"),
null, null, context);
}
/////////////////////
// VEHICLE EVENTS
/////////////////
// <--[event]
// @Events
// vehicle collides with block
// vehicle collides with <material>
// <vehicle> collides with block
// <vehicle> collides with <material>
//
// @Triggers when a vehicle collides with a block.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
// <context.location> returns the dLocation of the block.
//
// -->
@EventHandler
public void vehicleBlockCollision(VehicleBlockCollisionEvent event) {
Player player = null;
dNPC npc = null;
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
dMaterial material = new dMaterial(event.getBlock().getType());
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("vehicle", vehicle);
context.put("location", new dLocation(event.getBlock().getLocation()));
List<String> events = new ArrayList<String>();
events.add("vehicle collides with block");
events.add("vehicle collides with " + material.identify());
events.add(vehicleType + " collides with block");
events.add(vehicleType + " collides with " + material.identify());
doEvents(events, npc, player, context);
}
// <--[event]
// @Events
// vehicle collides with entity
// vehicle collides with <entity>
// <vehicle> collides with entity
// <vehicle> collides with <entity>
//
// @Triggers when a vehicle collides with an entity.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
// <context.entity> returns the dEntity of the entity the vehicle has collided with.
//
// @Determine
// "CANCELLED" to stop the collision from happening.
// "NOPICKUP" to stop the vehicle from picking up the entity.
//
// -->
@EventHandler
public void vehicleEntityCollision(VehicleEntityCollisionEvent event) {
Player player = null;
dNPC npc = null;
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("vehicle", vehicle);
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
List<String> events = new ArrayList<String>();
events.add("vehicle collides with entity");
events.add("vehicle collides with " + entityType);
events.add(vehicleType + " collides with entity");
events.add(vehicleType + " collides with " + entityType);
String determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
if (determination.toUpperCase().startsWith("NOPICKUP"))
event.setPickupCancelled(true);
}
// <--[event]
// @Events
// vehicle created
// <vehicle> created
//
// @Triggers when a vehicle is created.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
//
// @Determine
// "CANCELLED" to stop the entity from entering the vehicle.
//
// -->
@EventHandler
public void vehicleCreate(VehicleCreateEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
context.put("vehicle", vehicle);
doEvents(Arrays.asList
("vehicle created",
vehicleType + " created"),
null, null, context);
}
// <--[event]
// @Events
// vehicle damaged
// <vehicle> damaged
// entity damages vehicle
// <entity> damages vehicle
// entity damages <vehicle>
// <entity> damages <vehicle>
//
// @Triggers when a vehicle is damaged.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
// <context.entity> returns the dEntity of the attacking entity.
//
// @Determine
// "CANCELLED" to stop the entity from damaging the vehicle.
// Element(Double) to set the value of the damage received by the vehicle.
//
// -->
@EventHandler
public void vehicleDamage(VehicleDamageEvent event) {
Player player = null;
dNPC npc = null;
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("damage", new Element(event.getDamage()));
context.put("vehicle", vehicle);
List<String> events = new ArrayList<String>();
events.add("vehicle damaged");
events.add(vehicleType + " damaged");
if (event.getAttacker() != null) {
dEntity entity = new dEntity(event.getAttacker());
String entityType = entity.getEntityType().name();
context.put("entity", entity.getDenizenObject());
if (entity.isPlayer()) {
player = entity.getPlayer();
}
else {
npc = entity.getDenizenNPC();
entityType = "npc";
}
events.add("entity damages vehicle");
events.add("entity damages " + vehicleType);
events.add(entityType + " damages vehicle");
events.add(entityType + " damages " + vehicleType);
}
String determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
@EventHandler
public void vehicleDestroy(VehicleDestroyEvent event) {
// <--[event]
// @Events
// vehicle destroyed
// <vehicle> destroyed
// entity destroys vehicle
// <entity> destroys vehicle
// entity destroys <vehicle>
// <entity> destroys <vehicle>
//
// @Triggers when a vehicle is destroyed.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
// <context.entity> returns the dEntity of the attacking entity.
//
// @Determine
// "CANCELLED" to stop the entity from destroying the vehicle.
//
// -->
Player player = null;
dNPC npc = null;
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
Map<String, dObject> context = new HashMap<String, dObject>();
context.put("vehicle", vehicle);
List<String> events = new ArrayList<String>();
events.add("vehicle destroyed");
events.add(vehicleType + " destroyed");
if (event.getAttacker() != null) {
dEntity entity = new dEntity(event.getAttacker());
String entityType = entity.getEntityType().name();
context.put("entity", entity.getDenizenObject());
if (entity.isPlayer()) {
player = entity.getPlayer();
}
else {
npc = entity.getDenizenNPC();
entityType = "npc";
}
events.add("entity destroys vehicle");
events.add("entity destroys " + vehicleType);
events.add(entityType + " destroys vehicle");
events.add(entityType + " destroys " + vehicleType);
}
String determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity enters vehicle
// <entity> enters vehicle
// entity enters <vehicle>
// <entity> enters <vehicle>
//
// @Triggers when an entity enters a vehicle.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
// <context.entity> returns the dEntity of the entering entity.
//
// @Determine
// "CANCELLED" to stop the entity from entering the vehicle.
//
// -->
@EventHandler
public void vehicleEnter(VehicleEnterEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
dEntity entity = new dEntity(event.getEntered());
String entityType = entity.getEntityType().name();
context.put("vehicle", vehicle);
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
String determination = doEvents(Arrays.asList
("entity enters vehicle",
entityType + " enters vehicle",
"entity enters " + vehicleType,
entityType + " enters " + vehicleType),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// entity exits vehicle
// entity exits <vehicle>
// <entity> exits vehicle
// <entity> exits <vehicle>
//
// @Triggers when an entity exits a vehicle.
// @Context
// <context.vehicle> returns the dEntity of the vehicle.
// <context.entity> returns the dEntity of the exiting entity.
//
// @Determine
// "CANCELLED" to stop the entity from exiting the vehicle.
//
// -->
@EventHandler
public void vehicleExit(VehicleExitEvent event) {
Player player = null;
dNPC npc = null;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity vehicle = new dEntity(event.getVehicle());
String vehicleType = vehicle.getEntityType().name();
dEntity entity = new dEntity(event.getExited());
String entityType = entity.getEntityType().name();
context.put("vehicle", vehicle);
context.put("entity", entity.getDenizenObject());
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
String determination = doEvents(Arrays.asList
("entity exits vehicle",
"entity exits " + vehicleType,
entityType + " exits vehicle",
entityType + " exits " + vehicleType),
npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// WEATHER EVENTS
/////////////////
// <--[event]
// @Events
// lightning strikes (in <world>)
//
// @Triggers when lightning strikes in a world.
// @Context
// <context.world> returns the dWorld the lightning struck in.
// <context.reason> returns the dLocation where the lightning struck.
//
// @Determine
// "CANCELLED" to stop the lightning from striking.
//
// -->
@EventHandler
public void lightningStrike(LightningStrikeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
context.put("location", new dLocation(event.getLightning().getLocation()));
String determination = doEvents(Arrays.asList
("lightning strikes",
"lightning strikes in " + world.identify()),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// weather changes/rains/clears (in <world>)
//
// @Triggers when weather changes in a world.
// @Context
// <context.world> returns the dWorld the weather changed in.
// <context.weather> returns an Element with the name of the new weather.
//
// @Determine
// "CANCELLED" to stop the weather from changing.
//
// -->
@EventHandler
public void weatherChange(WeatherChangeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
List<String> events = new ArrayList<String>();
events.add("weather changes");
events.add("weather changes in " + world.identify());
if (event.toWeatherState()) {
context.put("weather", new Element("rain"));
events.add("weather rains");
events.add("weather rains in " + world.identify());
}
else {
context.put("weather", new Element("clear"));
events.add("weather clears");
events.add("weather clears in " + world.identify());
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
/////////////////////
// WORLD EVENTS
/////////////////
// <--[event]
// @Events
// portal created (in <world>) (because <reason>)
//
// @Triggers when a portal is created in a world.
// @Context
// <context.world> returns the dWorld the portal was created in.
// <context.reason> returns an Element of the reason the portal was created.
//
// @Determine
// "CANCELLED" to stop the portal from being created.
//
// -->
@EventHandler
public void portalCreate(PortalCreateEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
String reason = event.getReason().name();
context.put("world", world);
context.put("reason", new Element(reason));
String determination = doEvents(Arrays.asList
("portal created",
"portal created because " + reason,
"portal created in " + world.identify(),
"portal created in " + world.identify() + " because " + reason),
null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// spawn changes (in <world>)
//
// @Triggers when the world's spawn point changes.
// @Context
// <context.world> returns the dWorld that the spawn point changed in.
// <context.old_location> returns the dLocation of the old spawn point.
// <context.new_location> returns the dLocation of the new spawn point.
//
// -->
@EventHandler
public void spawnChange(SpawnChangeEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
context.put("old_location", new dLocation(event.getPreviousLocation()));
context.put("new_location", new dLocation(world.getWorld().getSpawnLocation()));
doEvents(Arrays.asList
("spawn changes",
"spawn changes in " + world.identify()),
null, null, context);
}
// <--[event]
// @Events
// structure grows (naturally/from bonemeal) (in <world>)
// <structure> grows (naturally/from bonemeal) (in <world>)
//
// @Triggers when a structure (a tree or a mushroom) grows in a world.
// @Context
// <context.world> returns the dWorld the structure grew in.
// <context.location> returns the dLocation the structure grew at.
// <context.structure> returns an Element of the structure's type.
//
// @Determine
// "CANCELLED" to stop the structure from growing.
//
// -->
@EventHandler
public void structureGrow(StructureGrowEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
String treeType = event.getSpecies().name();
context.put("world", world);
context.put("location", new dLocation(event.getLocation()));
context.put("structure", new Element(treeType));
List<String> events = new ArrayList<String>();
events.add("structure grows");
events.add("structure grows in " + world.identify());
events.add(treeType + " grows");
events.add(treeType + " grows in " + world.identify());
if (event.isFromBonemeal()) {
events.add("structure grows from bonemeal");
events.add("structure grows from bonemeal in " + world.identify());
events.add(treeType + " grows from bonemeal");
events.add(treeType + " grows from bonemeal in " + world.identify());
}
else {
events.add("structure grows naturally");
events.add("structure grows naturally in " + world.identify());
events.add(treeType + " grows naturally");
events.add(treeType + " grows naturally in " + world.identify());
}
String determination = doEvents(events, null, null, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
}
// <--[event]
// @Events
// world initializes
// <world> initializes
//
// @Triggers when a world is initialized.
// @Context
// <context.world> returns the dWorld that was initialized.
//
// -->
@EventHandler
public void worldInit(WorldInitEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
doEvents(Arrays.asList
("world initializes",
world.identify() + " initializes"),
null, null, context);
}
// <--[event]
// @Events
// world loads
// <world> loads
//
// @Triggers when a world is loaded.
// @Context
// <context.world> returns the dWorld that was loaded.
//
// -->
@EventHandler
public void worldLoad(WorldLoadEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
doEvents(Arrays.asList
("world loads",
world.identify() + " loads"),
null, null, context);
}
// <--[event]
// @Events
// world saves
// <world> saves
//
// @Triggers when a world is saved.
// @Context
// <context.world> returns the dWorld that was saved.
//
// -->
@EventHandler
public void worldSave(WorldSaveEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
doEvents(Arrays.asList
("world saves",
world.identify() + " saves"),
null, null, context);
}
// <--[event]
// @Events
// world unloads
// <world> unloads
//
// @Triggers when a world is unloaded.
// @Context
// <context.world> returns the dWorld that was unloaded.
//
// -->
@EventHandler
public void worldUnload(WorldUnloadEvent event) {
Map<String, dObject> context = new HashMap<String, dObject>();
dWorld world = new dWorld(event.getWorld());
context.put("world", world);
doEvents(Arrays.asList
("world unloads",
world.identify() + " unloads"),
null, null, context);
}
}
| true | true | public void entityDamage(EntityDamageEvent event) {
Player player = null;
dNPC npc = null;
String determination;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String cause = event.getCause().name();
context.put("entity", entity.getDenizenObject());
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
boolean isFatal = false;
if (entity.isValid()) {
if (event.getDamage() >= entity.getLivingEntity().getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal) {
// <--[event]
// @Events
// entity killed
// entity killed by <cause>
// <entity> killed
// <entity> killed by <cause>
//
// @Triggers when an entity is killed.
// @Context
// <context.cause> returns the reason the entity was killed.
// <context.entity> returns the dEntity that was killed.
// <context.damage> returns the amount of damage dealt.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being killed.
// Element(Double) to set the amount of damage the entity receives, instead of dying.
//
// -->
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
// <--[event]
// @Events
// entity damages entity
// entity damages <entity>
// <entity> damages entity
// <entity> damages <entity>
//
// @Triggers when an entity damages another entity.
// @Context
// <context.cause> returns the reason the entity was damaged.
// <context.entity> returns the dEntity that was damaged.
// <context.damage> returns the amount of damage dealt.
// <context.damager> returns the dEntity damaging the other entity.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being damaged.
// Element(Double) to set the amount of damage the entity receives.
//
// -->
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Have a different set of player and NPC contexts for events
// like "player damages player" from the one we have for
// "player damaged by player"
Player subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getEntityType().name();
context.put("damager", damager.getDenizenObject());
if (damager.isNPC()) {
subNPC = damager.getDenizenNPC();
damagerType = "npc";
// If we had no NPC in our regular context, use this one
if (npc == null) npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = damager.getPlayer();
// If we had no player in our regular context, use this one
if (player == null) player = subPlayer;
}
// If the damager is a projectile, add its shooter (which can be null)
// to the context
else if (damager.hasShooter()) {
dEntity shooter = damager.getShooter();
context.put("shooter", shooter.getDenizenObject());
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
// Have a new list of events for the subContextPlayer
// and subContextNPC
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
// <--[event]
// @Events
// entity kills entity
// entity kills <entity>
// <entity> kills entity
// <entity> kills <entity>
//
// @Triggers when an entity kills another entity.
// @Context
// <context.cause> returns the reason the entity was killed.
// <context.entity> returns the dEntity that was killed.
// <context.damager> returns the dEntity killing the other entity.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being killed.
// Element(Number) to set the amount of damage the entity receives, instead of dying.
//
// -->
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, subPlayer, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
| public void entityDamage(EntityDamageEvent event) {
Player player = null;
dNPC npc = null;
String determination;
Map<String, dObject> context = new HashMap<String, dObject>();
dEntity entity = new dEntity(event.getEntity());
String entityType = entity.getEntityType().name();
String cause = event.getCause().name();
context.put("entity", entity.getDenizenObject());
context.put("damage", new Element(event.getDamage()));
context.put("cause", new Element(event.getCause().name()));
if (entity.isNPC()) { npc = entity.getDenizenNPC(); entityType = "npc"; }
else if (entity.isPlayer()) player = entity.getPlayer();
boolean isFatal = false;
if (entity.isValid() && entity.isLivingEntity()) {
if (event.getDamage() >= entity.getLivingEntity().getHealth()) {
isFatal = true;
}
}
List<String> events = new ArrayList<String>();
events.add("entity damaged");
events.add("entity damaged by " + cause);
events.add(entityType + " damaged");
events.add(entityType + " damaged by " + cause);
if (isFatal) {
// <--[event]
// @Events
// entity killed
// entity killed by <cause>
// <entity> killed
// <entity> killed by <cause>
//
// @Triggers when an entity is killed.
// @Context
// <context.cause> returns the reason the entity was killed.
// <context.entity> returns the dEntity that was killed.
// <context.damage> returns the amount of damage dealt.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being killed.
// Element(Double) to set the amount of damage the entity receives, instead of dying.
//
// -->
events.add("entity killed");
events.add("entity killed by " + cause);
events.add(entityType + " killed");
events.add(entityType + " killed by " + cause);
}
if (event instanceof EntityDamageByEntityEvent) {
// <--[event]
// @Events
// entity damages entity
// entity damages <entity>
// <entity> damages entity
// <entity> damages <entity>
//
// @Triggers when an entity damages another entity.
// @Context
// <context.cause> returns the reason the entity was damaged.
// <context.entity> returns the dEntity that was damaged.
// <context.damage> returns the amount of damage dealt.
// <context.damager> returns the dEntity damaging the other entity.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being damaged.
// Element(Double) to set the amount of damage the entity receives.
//
// -->
EntityDamageByEntityEvent subEvent = (EntityDamageByEntityEvent) event;
// Have a different set of player and NPC contexts for events
// like "player damages player" from the one we have for
// "player damaged by player"
Player subPlayer = null;
dNPC subNPC = null;
dEntity damager = new dEntity(subEvent.getDamager());
String damagerType = damager.getEntityType().name();
context.put("damager", damager.getDenizenObject());
if (damager.isNPC()) {
subNPC = damager.getDenizenNPC();
damagerType = "npc";
// If we had no NPC in our regular context, use this one
if (npc == null) npc = subNPC;
}
else if (damager.isPlayer()) {
subPlayer = damager.getPlayer();
// If we had no player in our regular context, use this one
if (player == null) player = subPlayer;
}
// If the damager is a projectile, add its shooter (which can be null)
// to the context
else if (damager.hasShooter()) {
dEntity shooter = damager.getShooter();
context.put("shooter", shooter.getDenizenObject());
}
events.add("entity damaged by entity");
events.add("entity damaged by " + damagerType);
events.add(entityType + " damaged by entity");
events.add(entityType + " damaged by " + damagerType);
// Have a new list of events for the subContextPlayer
// and subContextNPC
List<String> subEvents = new ArrayList<String>();
subEvents.add("entity damages entity");
subEvents.add("entity damages " + entityType);
subEvents.add(damagerType + " damages entity");
subEvents.add(damagerType + " damages " + entityType);
if (isFatal) {
events.add("entity killed by entity");
events.add("entity killed by " + damagerType);
events.add(entityType + " killed by entity");
events.add(entityType + " killed by " + damagerType);
// <--[event]
// @Events
// entity kills entity
// entity kills <entity>
// <entity> kills entity
// <entity> kills <entity>
//
// @Triggers when an entity kills another entity.
// @Context
// <context.cause> returns the reason the entity was killed.
// <context.entity> returns the dEntity that was killed.
// <context.damager> returns the dEntity killing the other entity.
// <context.shooter> returns the shooter of the entity, if any.
//
// @Determine
// "CANCELLED" to stop the entity from being killed.
// Element(Number) to set the amount of damage the entity receives, instead of dying.
//
// -->
subEvents.add("entity kills entity");
subEvents.add("entity kills " + entityType);
subEvents.add(damagerType + " kills entity");
subEvents.add(damagerType + " kills " + entityType);
}
determination = doEvents(subEvents, subNPC, subPlayer, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
determination = doEvents(events, npc, player, context);
if (determination.toUpperCase().startsWith("CANCELLED"))
event.setCancelled(true);
else if (Argument.valueOf(determination)
.matchesPrimitive(aH.PrimitiveType.Double)) {
event.setDamage(aH.getDoubleFrom(determination));
}
}
|
diff --git a/esmska/src/esmska/persistence/PersistenceManager.java b/esmska/src/esmska/persistence/PersistenceManager.java
index 8bb15521..2045240c 100644
--- a/esmska/src/esmska/persistence/PersistenceManager.java
+++ b/esmska/src/esmska/persistence/PersistenceManager.java
@@ -1,595 +1,597 @@
/*
* PersistenceManager.java
*
* Created on 19. červenec 2007, 20:55
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package esmska.persistence;
import java.beans.IntrospectionException;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import esmska.data.Config;
import esmska.data.Contact;
import esmska.data.Contacts;
import esmska.data.History;
import esmska.data.Keyring;
import esmska.data.Operators;
import esmska.data.Queue;
import esmska.data.SMS;
import esmska.data.Operator;
import esmska.utils.RuntimeUtils;
import java.text.MessageFormat;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
/** Load and store settings and data
*
* @author ripper
*/
public class PersistenceManager {
private static final Logger logger = Logger.getLogger(PersistenceManager.class.getName());
private static PersistenceManager persistenceManager;
private static final String PROGRAM_DIRNAME = "esmska";
private static final String OPERATOR_DIRNAME = "operators";
private static final String BACKUP_DIRNAME = "backups";
private static final String CONFIG_FILENAME = "settings.xml";
private static final String GLOBAL_CONFIG_FILENAME = "esmska.conf";
private static final String CONTACTS_FILENAME = "contacts.csv";
private static final String QUEUE_FILENAME = "queue.csv";
private static final String HISTORY_FILENAME = "history.csv";
private static final String KEYRING_FILENAME = "keyring.csv";
private static final String LOCK_FILENAME = "running.lock";
private static final String OPERATOR_RESOURCE = "/esmska/operators/scripts";
private static File configDir =
new File(System.getProperty("user.home") + File.separator + ".config",
PROGRAM_DIRNAME);
private static File dataDir =
new File(System.getProperty("user.home") + File.separator + ".local" +
File.separator + "share", PROGRAM_DIRNAME);
private static File globalOperatorDir = new File(OPERATOR_DIRNAME);
private static File localOperatorDir = new File(dataDir, OPERATOR_DIRNAME);
private static File backupDir = new File(configDir, BACKUP_DIRNAME);
private static File configFile = new File(configDir, CONFIG_FILENAME);
private static File globalConfigFile = new File(GLOBAL_CONFIG_FILENAME);
private static File contactsFile = new File(configDir, CONTACTS_FILENAME);
private static File queueFile = new File(configDir, QUEUE_FILENAME);
private static File historyFile = new File(configDir, HISTORY_FILENAME);
private static File keyringFile = new File(configDir, KEYRING_FILENAME);
private static File lockFile = new File(configDir, LOCK_FILENAME);
private static boolean customPathSet;
private FileLock lock;
/** Creates a new instance of PersistenceManager */
private PersistenceManager() throws IOException {
//adjust program dir according to operating system
if (!customPathSet) {
String confDir, datDir;
switch (RuntimeUtils.detectOS()) {
case MAC_OS_X:
confDir = System.getProperty("user.home") + "/Library/Application Support";
datDir = confDir;
break;
case WINDOWS:
confDir = System.getenv("APPDATA");
datDir = confDir;
break;
case LINUX:
default:
confDir = System.getenv("XDG_CONFIG_HOME");
datDir = System.getenv("XDG_DATA_HOME");
break;
}
if (StringUtils.isNotEmpty(confDir)) {
setConfigDir(confDir + File.separator + PROGRAM_DIRNAME);
}
if (StringUtils.isNotEmpty(datDir)) {
setDataDir(datDir + File.separator + PROGRAM_DIRNAME);
}
}
//create config dir if necessary
if (!configDir.exists() && !configDir.mkdirs()) {
throw new IOException("Can't create config dir '" + configDir.getAbsolutePath() + "'");
}
if (!(canWrite(configDir) && configDir.canExecute())) {
throw new IOException("Can't write or execute the config dir '" + configDir.getAbsolutePath() + "'");
}
//create data dir if necessary
if (!dataDir.exists() && !dataDir.mkdirs()) {
throw new IOException("Can't create data dir '" + dataDir.getAbsolutePath() + "'");
}
if (!(canWrite(dataDir) && dataDir.canExecute())) {
throw new IOException("Can't write or execute the data dir '" + dataDir.getAbsolutePath() + "'");
}
//create local operators dir
if (!localOperatorDir.exists() && !localOperatorDir.mkdirs()) {
throw new IOException("Can't create local operator dir '" + localOperatorDir.getAbsolutePath() + "'");
}
//create backup dir
if (!backupDir.exists() && !backupDir.mkdirs()) {
throw new IOException("Can't create backup dir '" + backupDir.getAbsolutePath() + "'");
}
}
/** Set config directory */
private static void setConfigDir(String path) {
if (persistenceManager != null) {
throw new IllegalStateException("Persistence manager already exists");
}
logger.fine("Setting new config dir path: " + path);
configDir = new File(path);
backupDir = new File(configDir, BACKUP_DIRNAME);
configFile = new File(configDir, CONFIG_FILENAME);
contactsFile = new File(configDir, CONTACTS_FILENAME);
queueFile = new File(configDir, QUEUE_FILENAME);
historyFile = new File(configDir, HISTORY_FILENAME);
keyringFile = new File(configDir, KEYRING_FILENAME);
lockFile = new File(configDir, LOCK_FILENAME);
}
/** Get configuration directory */
public static File getConfigDir() {
return configDir;
}
/** Set data directory */
private static void setDataDir(String path) {
if (persistenceManager != null) {
throw new IllegalStateException("Persistence manager already exists");
}
logger.fine("Setting new data dir path: " + path);
dataDir = new File(path);
localOperatorDir = new File(dataDir, OPERATOR_DIRNAME);
}
/** Get data directory */
public static File getDataDir() {
return dataDir;
}
/** Set custom directories */
public static void setCustomDirs(String configDir, String dataDir) {
setConfigDir(configDir);
setDataDir(dataDir);
customPathSet = true;
}
/** Get PersistenceManager */
public static PersistenceManager getInstance() throws IOException {
if (persistenceManager == null) {
persistenceManager = new PersistenceManager();
}
return persistenceManager;
}
/** Save program configuration */
public void saveConfig() throws IOException {
logger.fine("Saving config...");
//store current program version into config
Config.getInstance().setVersion(Config.getLatestVersion());
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
XMLEncoder xmlEncoder = new XMLEncoder(new BufferedOutputStream(out));
xmlEncoder.writeObject(Config.getInstance());
xmlEncoder.flush();
out.getChannel().force(false);
xmlEncoder.close();
moveFileSafely(temp, configFile);
logger.finer("Saved config into file: " + configFile.getAbsolutePath());
}
/** Load program configuration */
public void loadConfig() throws IOException {
//system-wide config
if (globalConfigFile.exists()) {
logger.fine("Loading global config...");
try {
ImportManager.importGlobalConfig(globalConfigFile);
} catch (Exception ex) {
//don't stop here, continue to load local config
logger.log(Level.WARNING, "Failed to load global configuration: "
+ globalConfigFile, ex);
}
}
//per-user config
if (configFile.exists()) {
logger.fine("Loading local config...");
XMLDecoder xmlDecoder = new XMLDecoder(
new BufferedInputStream(new FileInputStream(configFile)));
Config newConfig = (Config) xmlDecoder.readObject();
xmlDecoder.close();
if (newConfig != null) {
Config.setSharedInstance(newConfig);
}
} else {
//set new config, to apply changes made through global config
Config.setSharedInstance(new Config());
}
}
/** Save contacts */
public void saveContacts() throws IOException {
logger.fine("Saving contacts...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
ExportManager.exportContacts(Contacts.getInstance().getAll(), out);
out.flush();
out.getChannel().force(false);
out.close();
moveFileSafely(temp, contactsFile);
logger.finer("Saved contacts into file: " + contactsFile.getAbsolutePath());
}
/** Load contacts */
public void loadContacts() throws Exception {
logger.fine("Loading contacts...");
if (contactsFile.exists()) {
ArrayList<Contact> newContacts = ImportManager.importContacts(contactsFile,
ContactParser.ContactType.ESMSKA_FILE);
ContinuousSaveManager.disableContacts();
Contacts.getInstance().clear();
Contacts.getInstance().addAll(newContacts);
ContinuousSaveManager.enableContacts();
}
}
/** Save sms queue */
public void saveQueue() throws IOException {
logger.fine("Saving queue...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
ExportManager.exportQueue(Queue.getInstance().getAll(), out);
out.flush();
out.getChannel().force(false);
out.close();
moveFileSafely(temp, queueFile);
logger.finer("Saved queue into file: " + queueFile.getAbsolutePath());
}
/** Load sms queue */
public void loadQueue() throws IOException {
logger.fine("Loading queue");
if (queueFile.exists()) {
ArrayList<SMS> newQueue = ImportManager.importQueue(queueFile);
ContinuousSaveManager.disableQueue();
Queue.getInstance().clear();
Queue.getInstance().addAll(newQueue);
ContinuousSaveManager.enableQueue();
}
}
/** Save sms history */
public void saveHistory() throws IOException {
logger.fine("Saving history...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
ExportManager.exportHistory(History.getInstance().getRecords(), out);
out.flush();
out.getChannel().force(false);
out.close();
moveFileSafely(temp, historyFile);
logger.finer("Saved history into file: " + historyFile.getAbsolutePath());
}
/** Load sms history */
public void loadHistory() throws Exception {
logger.fine("Loading history...");
if (historyFile.exists()) {
ArrayList<History.Record> records = ImportManager.importHistory(historyFile);
ContinuousSaveManager.disableHistory();
History.getInstance().clearRecords();
History.getInstance().addRecords(records);
ContinuousSaveManager.enableHistory();
}
}
/** Save keyring. */
public void saveKeyring() throws Exception {
logger.fine("Saving keyring...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
ExportManager.exportKeyring(Keyring.getInstance(), out);
out.flush();
out.getChannel().force(false);
out.close();
moveFileSafely(temp, keyringFile);
logger.finer("Saved keyring into file: " + keyringFile.getAbsolutePath());
}
/** Load keyring. */
public void loadKeyring() throws Exception {
logger.fine("Loading keyring...");
if (keyringFile.exists()) {
ContinuousSaveManager.disableKeyring();
Keyring.getInstance().clearKeys();
ImportManager.importKeyring(keyringFile);
ContinuousSaveManager.enableKeyring();
}
}
/** Load operators
* @throws IOException When there is problem accessing operator directory or files
* @throws IntrospectionException When current JRE does not support JavaScript execution
*/
public void loadOperators() throws IOException, IntrospectionException {
logger.fine("Loading operators...");
ArrayList<Operator> globalOperators = new ArrayList<Operator>();
TreeSet<Operator> localOperators = new TreeSet<Operator>();
//global operators
if (globalOperatorDir.exists()) {
globalOperators = new ArrayList<Operator>(ImportManager.importOperators(globalOperatorDir));
} else if (PersistenceManager.class.getResource(OPERATOR_RESOURCE) != null) {
globalOperators = new ArrayList<Operator>(ImportManager.importOperators(OPERATOR_RESOURCE));
} else {
throw new IOException("Could not find operator directory '" +
globalOperatorDir.getAbsolutePath() + "' nor jar operator resource '" +
OPERATOR_RESOURCE + "'");
}
//local operators
if (localOperatorDir.exists()) {
localOperators = ImportManager.importOperators(localOperatorDir);
}
//replace old global versions with new local ones
for (Operator op : localOperators) {
int index = globalOperators.indexOf(op);
if (index >= 0) {
Operator globOp = globalOperators.get(index);
if (op.getVersion().compareTo(globOp.getVersion()) > 0) {
globalOperators.set(index, op);
logger.finer("Local operator " + op.getName() + " is newer, replacing global one.");
} else {
logger.finer("Local operator " + op.getName() + " is not newer than global one, skipping.");
}
} else {
globalOperators.add(op);
logger.finer("Local operator " + op.getName() + " is additional to global ones, adding to operator list.");
}
}
//load it
Operators.getInstance().clear();
Operators.getInstance().addAll(globalOperators);
}
/** Save new operator to file. New or updated operator is saved in global operator
* directory (if there are sufficient permissions), otherwise in local operator
* directory.
*
* @param scriptName name of the operator/script (without suffix), not null nor empty
* @param scriptContents contents of the operator script file, not null nor empty
* @param icon operator icon, may be null
*/
public void saveOperator(String scriptName, String scriptContents, byte[] icon) throws IOException {
Validate.notEmpty(scriptName);
Validate.notEmpty(scriptContents);
logger.fine("Saving operator...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
File iconTemp = null;
FileOutputStream iconOut = null;
if (icon != null) {
iconTemp = createTempFile();
iconOut = new FileOutputStream(iconTemp);
}
//export the operator
ExportManager.exportOperator(scriptContents, icon, out, iconOut);
out.flush();
out.getChannel().force(false);
out.close();
if (icon != null) {
iconOut.flush();
iconOut.getChannel().force(false);
iconOut.close();
}
//move script file to correct location
File scriptFileGlobal = new File(globalOperatorDir, scriptName + ".operator");
File scriptFileLocal = new File(localOperatorDir, scriptName + ".operator");
if (canWrite(globalOperatorDir) && (!scriptFileGlobal.exists() || canWrite(scriptFileGlobal))) {
//first try global dir
moveFileSafely(temp, scriptFileGlobal);
+ //set readable for everyone
+ scriptFileGlobal.setReadable(true, false);
logger.finer("Saved operator script into file: " + scriptFileGlobal.getAbsolutePath());
} else if (canWrite(localOperatorDir) && (!scriptFileLocal.exists() || canWrite(scriptFileLocal))) {
//second try local dir
moveFileSafely(temp, scriptFileLocal);
logger.finer("Saved operator script into file: " + scriptFileLocal.getAbsolutePath());
} else {
//report error
throw new IOException(MessageFormat.format("Could not save operator " +
"{0} to ''{1}'' nor to ''{2}'' - no write permissions?", scriptName,
scriptFileGlobal, scriptFileLocal));
}
//move icon file to correct location
if (icon != null) {
File iconFileGlobal = new File(globalOperatorDir, scriptName + ".png");
File iconFileLocal = new File(localOperatorDir, scriptName + ".png");
if (canWrite(globalOperatorDir) && (!iconFileGlobal.exists() || canWrite(iconFileGlobal))) {
//first try global dir
moveFileSafely(iconTemp, iconFileGlobal);
logger.finer("Saved operator icon into file: " + iconFileGlobal.getAbsolutePath());
} else if (canWrite(localOperatorDir) && (!iconFileLocal.exists() || canWrite(iconFileLocal))) {
//second try local dir
moveFileSafely(iconTemp, iconFileLocal);
logger.finer("Saved operator icon into file: " + iconFileLocal.getAbsolutePath());
} else {
//report error
throw new IOException(MessageFormat.format("Could not save operator icon " +
"{0} to '{1}' nor to '{2}' - no write permissions?", scriptName,
iconFileGlobal, iconFileLocal));
}
}
}
/** Checks if this is the first instance of the program.
* Manages instances by using an exclusive lock on a file.
* @return true if this is the first instance run; false otherwise
*/
public boolean isFirstInstance() {
try {
FileOutputStream out = new FileOutputStream(lockFile);
FileChannel channel = out.getChannel();
lock = channel.tryLock();
if (lock == null) {
return false;
}
lockFile.deleteOnExit();
} catch (Throwable t) {
logger.log(Level.INFO, "Program lock could not be obtained", t);
return false;
}
return true;
}
/** Proceed with a backup. Backs up today's configuration (if not backed up
* already). Preserves last 7 backups, older ones are deleted.
*/
public void backupConfigFiles() throws IOException {
BackupManager bm = new BackupManager(backupDir);
File[] list = new File[] {
configFile, contactsFile, historyFile,
keyringFile, queueFile
};
bm.backupFiles(Arrays.asList(list), false);
bm.removeOldBackups(7);
}
/** Moves file from srcFile to destFile safely (using backup of destFile).
* If move fails, exception is thrown and attempt to restore destFile from
* backup is made.
* @param srcFile source file, not null
* @param destFile destination file, not null
*/
private void moveFileSafely(File srcFile, File destFile) throws IOException {
Validate.notNull(srcFile);
Validate.notNull(destFile);
File backup = backupFile(destFile);
try {
FileUtils.moveFile(srcFile, destFile);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Moving of " + srcFile.getAbsolutePath() + " to " +
destFile.getAbsolutePath() + " failed, trying to restore from backup", ex);
FileUtils.deleteQuietly(destFile);
//backup may be null if the destination file didn't exist
if (backup != null) {
FileUtils.moveFile(backup, destFile);
}
throw ex;
}
FileUtils.deleteQuietly(backup);
}
/** Create temp file and return it. */
private File createTempFile() throws IOException {
return File.createTempFile("esmska", null);
}
/** Copies original file to backup file with same filename, but ending with "~".
* DELETES original file!
* @return newly created backup file, or null if original file doesn't exist
*/
private File backupFile(File file) throws IOException {
if (!file.exists()) {
return null;
}
String backupName = file.getAbsolutePath() + "~";
File backup = new File(backupName);
FileUtils.copyFile(file, backup);
file.delete();
return backup;
}
/** Test if it is possible to write to a certain file/directory.
* It doesn't have to exist. This method is available because of Java bug
* on Windows which does not check permissions in File.canWrite() but only
* read-only bit (<a href="http://www.velocityreviews.com/forums/t303199-java-reporting-incorrect-directory-permission-under-windows-xp.html">reference1</a>,
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4939819>referece2</a>).
* @param file File, existing or not existing; not null
* @return true if file can be written, false if not
*/
public static boolean canWrite(File file) {
Validate.notNull(file);
if (!RuntimeUtils.isWindows()) {
//on POSIX systems file.canWrite() works
return file.canWrite();
}
//file.canWrite() does not work on Windows
boolean success = false;
try {
if (file.exists()) {
if (file.isDirectory()) {
//try to create file inside directory
String name = "writeTest.esmska";
File f = new File(file, name);
while (f.exists()) {
name = name + ".1";
f = new File(file, name);
}
f.createNewFile();
success = f.delete();
} else {
//try to open file for writing
FileOutputStream out = new FileOutputStream(file);
out.close();
success = true;
}
} else {
//try to create and delete the file
FileUtils.touch(file);
success = file.delete();
}
} catch (Exception ex) {
//be quiet, don't report anything
success = false;
}
return success;
}
}
| true | true | public void saveOperator(String scriptName, String scriptContents, byte[] icon) throws IOException {
Validate.notEmpty(scriptName);
Validate.notEmpty(scriptContents);
logger.fine("Saving operator...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
File iconTemp = null;
FileOutputStream iconOut = null;
if (icon != null) {
iconTemp = createTempFile();
iconOut = new FileOutputStream(iconTemp);
}
//export the operator
ExportManager.exportOperator(scriptContents, icon, out, iconOut);
out.flush();
out.getChannel().force(false);
out.close();
if (icon != null) {
iconOut.flush();
iconOut.getChannel().force(false);
iconOut.close();
}
//move script file to correct location
File scriptFileGlobal = new File(globalOperatorDir, scriptName + ".operator");
File scriptFileLocal = new File(localOperatorDir, scriptName + ".operator");
if (canWrite(globalOperatorDir) && (!scriptFileGlobal.exists() || canWrite(scriptFileGlobal))) {
//first try global dir
moveFileSafely(temp, scriptFileGlobal);
logger.finer("Saved operator script into file: " + scriptFileGlobal.getAbsolutePath());
} else if (canWrite(localOperatorDir) && (!scriptFileLocal.exists() || canWrite(scriptFileLocal))) {
//second try local dir
moveFileSafely(temp, scriptFileLocal);
logger.finer("Saved operator script into file: " + scriptFileLocal.getAbsolutePath());
} else {
//report error
throw new IOException(MessageFormat.format("Could not save operator " +
"{0} to ''{1}'' nor to ''{2}'' - no write permissions?", scriptName,
scriptFileGlobal, scriptFileLocal));
}
//move icon file to correct location
if (icon != null) {
File iconFileGlobal = new File(globalOperatorDir, scriptName + ".png");
File iconFileLocal = new File(localOperatorDir, scriptName + ".png");
if (canWrite(globalOperatorDir) && (!iconFileGlobal.exists() || canWrite(iconFileGlobal))) {
//first try global dir
moveFileSafely(iconTemp, iconFileGlobal);
logger.finer("Saved operator icon into file: " + iconFileGlobal.getAbsolutePath());
} else if (canWrite(localOperatorDir) && (!iconFileLocal.exists() || canWrite(iconFileLocal))) {
//second try local dir
moveFileSafely(iconTemp, iconFileLocal);
logger.finer("Saved operator icon into file: " + iconFileLocal.getAbsolutePath());
} else {
//report error
throw new IOException(MessageFormat.format("Could not save operator icon " +
"{0} to '{1}' nor to '{2}' - no write permissions?", scriptName,
iconFileGlobal, iconFileLocal));
}
}
}
| public void saveOperator(String scriptName, String scriptContents, byte[] icon) throws IOException {
Validate.notEmpty(scriptName);
Validate.notEmpty(scriptContents);
logger.fine("Saving operator...");
File temp = createTempFile();
FileOutputStream out = new FileOutputStream(temp);
File iconTemp = null;
FileOutputStream iconOut = null;
if (icon != null) {
iconTemp = createTempFile();
iconOut = new FileOutputStream(iconTemp);
}
//export the operator
ExportManager.exportOperator(scriptContents, icon, out, iconOut);
out.flush();
out.getChannel().force(false);
out.close();
if (icon != null) {
iconOut.flush();
iconOut.getChannel().force(false);
iconOut.close();
}
//move script file to correct location
File scriptFileGlobal = new File(globalOperatorDir, scriptName + ".operator");
File scriptFileLocal = new File(localOperatorDir, scriptName + ".operator");
if (canWrite(globalOperatorDir) && (!scriptFileGlobal.exists() || canWrite(scriptFileGlobal))) {
//first try global dir
moveFileSafely(temp, scriptFileGlobal);
//set readable for everyone
scriptFileGlobal.setReadable(true, false);
logger.finer("Saved operator script into file: " + scriptFileGlobal.getAbsolutePath());
} else if (canWrite(localOperatorDir) && (!scriptFileLocal.exists() || canWrite(scriptFileLocal))) {
//second try local dir
moveFileSafely(temp, scriptFileLocal);
logger.finer("Saved operator script into file: " + scriptFileLocal.getAbsolutePath());
} else {
//report error
throw new IOException(MessageFormat.format("Could not save operator " +
"{0} to ''{1}'' nor to ''{2}'' - no write permissions?", scriptName,
scriptFileGlobal, scriptFileLocal));
}
//move icon file to correct location
if (icon != null) {
File iconFileGlobal = new File(globalOperatorDir, scriptName + ".png");
File iconFileLocal = new File(localOperatorDir, scriptName + ".png");
if (canWrite(globalOperatorDir) && (!iconFileGlobal.exists() || canWrite(iconFileGlobal))) {
//first try global dir
moveFileSafely(iconTemp, iconFileGlobal);
logger.finer("Saved operator icon into file: " + iconFileGlobal.getAbsolutePath());
} else if (canWrite(localOperatorDir) && (!iconFileLocal.exists() || canWrite(iconFileLocal))) {
//second try local dir
moveFileSafely(iconTemp, iconFileLocal);
logger.finer("Saved operator icon into file: " + iconFileLocal.getAbsolutePath());
} else {
//report error
throw new IOException(MessageFormat.format("Could not save operator icon " +
"{0} to '{1}' nor to '{2}' - no write permissions?", scriptName,
iconFileGlobal, iconFileLocal));
}
}
}
|
diff --git a/src/com/redhat/qe/sm/cli/tests/ListTests.java b/src/com/redhat/qe/sm/cli/tests/ListTests.java
index ca860aed..e281481a 100644
--- a/src/com/redhat/qe/sm/cli/tests/ListTests.java
+++ b/src/com/redhat/qe/sm/cli/tests/ListTests.java
@@ -1,756 +1,756 @@
package com.redhat.qe.sm.cli.tests;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.xmlrpc.XmlRpcException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.testng.SkipException;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.redhat.qe.auto.tcms.ImplementsNitrateTest;
import com.redhat.qe.auto.testng.Assert;
import com.redhat.qe.auto.testng.BzChecker;
import com.redhat.qe.auto.testng.TestNGUtils;
import com.redhat.qe.sm.base.CandlepinType;
import com.redhat.qe.sm.base.ConsumerType;
import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript;
import com.redhat.qe.sm.cli.tasks.CandlepinTasks;
import com.redhat.qe.sm.data.EntitlementCert;
import com.redhat.qe.sm.data.InstalledProduct;
import com.redhat.qe.sm.data.OrderNamespace;
import com.redhat.qe.sm.data.ProductCert;
import com.redhat.qe.sm.data.ProductNamespace;
import com.redhat.qe.sm.data.ProductSubscription;
import com.redhat.qe.sm.data.SubscriptionPool;
import com.redhat.qe.tools.SSHCommandResult;
/**
* @author ssalevan
* @author jsefler
*
*/
@Test(groups={"ListTests"})
public class ListTests extends SubscriptionManagerCLITestScript{
// Test Methods ***********************************************************************
@Test( description="subscription-manager-cli: list available subscriptions (when not consuming)",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=41678)
public void EnsureAvailableSubscriptionsListed_Test() {
clienttasks.unregister(null, null, null);
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, false, null, null, null);
String availableSubscriptionPools = clienttasks.listAvailableSubscriptionPools().getStdout();
Assert.assertContainsMatch(availableSubscriptionPools, "Available Subscriptions","" +
"Available Subscriptions are listed for '"+sm_clientUsername+"' to consume.");
Assert.assertContainsNoMatch(availableSubscriptionPools, "No available subscription pools to list",
"Available Subscriptions are listed for '"+sm_clientUsername+"' to consume.");
log.warning("These manual TCMS instructions are not really achievable in this automated test...");
log.warning(" * List produced matches the known data contained on the Candlepin server");
log.warning(" * Confirm that the marketing names match.. see prereq link https://engineering.redhat.com/trac/IntegratedMgmtQE/wiki/sm-prerequisites");
log.warning(" * Match the marketing names w/ https://www.redhat.com/products/");
}
@Test( description="subscription-manager-cli: list available subscriptions - verify that among all the subscriptions available to this consumer, those that satisfy the hardware are listed as available",
groups={"AcceptanceTests", "blockedByBugzilla-712502","unsubscribeBeforeGroup"},
dataProvider="getSystemSubscriptionPoolProductData",
enabled=true)
@ImplementsNitrateTest(caseId=41678)
public void EnsureHardwareMatchingSubscriptionsAreListedAsAvailable_Test(String productId, JSONArray bundledProductDataAsJSONArray) {
//if(!productId.equals("null-sockets")) throw new SkipException("debugging...");
// implicitly registered in dataProvider; no need to register with force; saves time
//clienttasks.register(clientusername, clientpassword, null, null, null, null, true, null, null, null);
SubscriptionPool pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", productId, clienttasks.getCurrentlyAvailableSubscriptionPools());
Assert.assertNotNull(pool, "Expected SubscriptionPool with ProductId '"+productId+"' is listed as available for subscribing.");
}
@Test( description="subscription-manager-cli: list available subscriptions - verify that among all the subscriptions available to this consumer, those that do NOT satisfy the hardware are NOT listed as available",
groups={"AcceptanceTests", "blockedByBugzilla-712502","unsubscribeBeforeGroup"},
dataProvider="getNonAvailableSystemSubscriptionPoolProductData",
enabled=true)
@ImplementsNitrateTest(caseId=41678)
public void EnsureNonHardwareMatchingSubscriptionsAreNotListedAsAvailable_Test(String productId) {
// implicitly registered in dataProvider; no need to register with force; saves time
//clienttasks.register(clientusername, clientpassword, null, null, null, null, true, null, null, null);
SubscriptionPool pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", productId, clienttasks.getCurrentlyAvailableSubscriptionPools());
Assert.assertNull(pool, "As expected, SubscriptionPool with ProductId '"+productId+"' is NOT listed as available for subscribing.");
}
@Test( description="subscription-manager-cli: list consumed entitlements (when not consuming)",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=41679)
public void EnsureConsumedEntitlementsListed_Test() {
clienttasks.unregister(null, null, null);
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, false, null, null, null);
String consumedProductSubscription = clienttasks.listConsumedProductSubscriptions().getStdout();
Assert.assertContainsMatch(consumedProductSubscription, "No consumed subscription pools to list",
"No consumed subscription pools listed for '"+sm_clientUsername+"' after registering (without autosubscribe).");
}
@Test( description="subscription-manager-cli: list consumed entitlements",
groups={},
dataProvider="getSystemSubscriptionPoolProductData",
enabled=true)
@ImplementsNitrateTest(caseId=41679)
public void EnsureConsumedEntitlementsListed_Test(String productId, JSONArray bundledProductDataAsJSONArray) throws JSONException, Exception {
clienttasks.unregister(null, null, null);
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, false, null, null, null);
SubscriptionPool pool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", productId, clienttasks.getCurrentlyAvailableSubscriptionPools());
Assert.assertNotNull(pool, "SubscriptionPool with ProductId '"+productId+"' is available for subscribing.");
EntitlementCert entitlementCert = clienttasks.getEntitlementCertFromEntitlementCertFile(clienttasks.subscribeToSubscriptionPool_(pool));
List<ProductSubscription> consumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
Assert.assertTrue(!consumedProductSubscriptions.isEmpty(),"The list of Consumed Product Subscription is NOT empty after subscribing to a pool with ProductId '"+productId+"'.");
for (ProductSubscription productSubscription : consumedProductSubscriptions) {
Assert.assertEquals(productSubscription.serialNumber, entitlementCert.serialNumber,
"SerialNumber of Consumed Product Subscription matches the serial number from the current entitlement certificate.");
}
}
@Test( description="subscription-manager-cli: list installed products",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void EnsureInstalledProductsListed_Test() {
clienttasks.unregister(null, null, null);
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, false, null, null, null);
List <ProductCert> productCerts = clienttasks.getCurrentProductCerts();
String installedProductsAsString = clienttasks.listInstalledProducts().getStdout();
//List <InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts();
List <InstalledProduct> installedProducts = InstalledProduct.parse(installedProductsAsString);
// assert some stdout
if (installedProducts.size()>0) {
Assert.assertContainsMatch(installedProductsAsString, "Installed Product Status");
}
// assert the number of installed product matches the product certs installed
Assert.assertEquals(installedProducts.size(), productCerts.size(), "A single product is reported as installed for each product cert found in "+clienttasks.productCertDir);
// assert that each of the installed ProductCerts are listed as InstalledProducts with status "Not Subscribed"
for (ProductCert productCert : productCerts) {
InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToProductCert(productCert,installedProducts);
Assert.assertNotNull(installedProduct, "The following installed product cert is included by subscription-manager in the list --installed: "+(installedProduct==null?"null":installedProduct));
Assert.assertEquals(installedProduct.status, "Not Subscribed", "The status of installed product when newly registered: "+installedProduct);
}
}
@Test( description="subscription-manager: ensure list [--installed] produce the same results",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void EnsureListAndListInstalledAreTheSame_Test() throws JSONException, Exception {
clienttasks.unregister(null, null, null);
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, false, null, null, null);
// assert same results when no subscribed to anything...
log.info("assert list [--installed] produce same results when not subscribed to anything...");
SSHCommandResult listResult = clienttasks.list_(null, null, null, null, null, null, null, null, null);
SSHCommandResult listInstalledResult = clienttasks.list_(null, null, null, Boolean.TRUE, null, null, null, null, null);
Assert.assertEquals(listResult.getStdout(), listInstalledResult.getStdout(), "'list' and 'list --installed' produce the same stdOut results.");
Assert.assertEquals(listResult.getStderr(), listInstalledResult.getStderr(), "'list' and 'list --installed' produce the same stdErr results.");
Assert.assertEquals(listResult.getExitCode(), listInstalledResult.getExitCode(), "'list' and 'list --installed' produce the same exitCode results.");
// assert same results when subscribed to something...
log.info("assert list [--installed] produce same results when subscribed to something...");
List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools();
SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool
clienttasks.subscribeToSubscriptionPool_(pool);
listResult = clienttasks.list_(null, null, null, null, null, null, null, null, null);
listInstalledResult = clienttasks.list_(null, null, null, Boolean.TRUE, null, null, null, null, null);
Assert.assertEquals(listResult.getStdout(), listInstalledResult.getStdout(), "'list' and 'list --installed' produce the same stdOut results.");
Assert.assertEquals(listResult.getStderr(), listInstalledResult.getStderr(), "'list' and 'list --installed' produce the same stdErr results.");
Assert.assertEquals(listResult.getExitCode(), listInstalledResult.getExitCode(), "'list' and 'list --installed' produce the same exitCode results.");
}
@Test( description="subscription-manager: list of consumed entitlements should display consumed product marketing name",
groups={},
dataProvider="getAllEntitlementCertsData",
enabled=true)
@ImplementsNitrateTest(caseId=48092, fromPlan=2481)
public void EnsureListConsumedMatchesProductsListedInTheEntitlementCerts_Test(EntitlementCert entitlementCert) {
// assert: The list of consumed products matches the products listed in the entitlement cert
List<ProductSubscription> productSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
List<ProductSubscription> productSubscriptionsWithMatchingSerialNumber = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serialNumber", entitlementCert.serialNumber, productSubscriptions);
//Assert.assertTrue(productSubscriptionsWithMatchingSerialNumber.size()>0, "Found consumed product subscription(s) whose SerialNumber matches this entitlement cert: "+entitlementCert);
//Assert.assertEquals(productSubscriptionsWithMatchingSerialNumber.size(),entitlementCert.productNamespaces.size(), "Found consumed product subscription(s) for each of the bundleProducts (total of '"+entitlementCert.productNamespaces.size()+"' expected) whose SerialNumber matches this entitlement cert: "+entitlementCert);
int productSubscriptionsWithMatchingSerialNumberSizeExpected = entitlementCert.productNamespaces.size()==0?1:entitlementCert.productNamespaces.size(); // when there are 0 bundledProducts, we are still consuming 1 ProductSubscription
Assert.assertEquals(productSubscriptionsWithMatchingSerialNumber.size(),productSubscriptionsWithMatchingSerialNumberSizeExpected, "Found consumed product subscription(s) for each of the bundleProducts (total of '"+productSubscriptionsWithMatchingSerialNumberSizeExpected+"' expected) whose SerialNumber matches this entitlement cert: "+entitlementCert);
for (ProductNamespace productNamespace : entitlementCert.productNamespaces) {
List<ProductSubscription> matchingProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("productName", productNamespace.name, productSubscriptionsWithMatchingSerialNumber);
Assert.assertEquals(matchingProductSubscriptions.size(), 1, "Found one bundledProduct name '"+productNamespace.name+"' in the list of consumed product subscriptions whose SerialNumber matches this entitlement cert: "+entitlementCert);
ProductSubscription correspondingProductSubscription = matchingProductSubscriptions.get(0);
log.info("We are about to assert that this consumed Product Subscription: "+correspondingProductSubscription);
log.info("...represents this ProductNamespace: "+productNamespace);
log.info("...corresponding to this OrderNamespace: "+entitlementCert.orderNamespace);
log.info("...from this EntitlementCert: "+entitlementCert);
Assert.assertEquals(correspondingProductSubscription.productName, productNamespace.name, "productName from ProductSubscription in list --consumed matches productName from ProductNamespace in EntitlementCert.");
Assert.assertEquals(correspondingProductSubscription.contractNumber, entitlementCert.orderNamespace.contractNumber, "contractNumber from ProductSubscription in list --consumed matches contractNumber from OrderNamespace in EntitlementCert.");
Assert.assertEquals(correspondingProductSubscription.accountNumber, entitlementCert.orderNamespace.accountNumber, "accountNumber from ProductSubscription in list --consumed matches accountNumber from OrderNamespace in EntitlementCert.");
Assert.assertEquals(correspondingProductSubscription.serialNumber, entitlementCert.serialNumber, "serialNumber from ProductSubscription in list --consumed matches serialNumber from EntitlementCert.");
Calendar now = Calendar.getInstance();
if (now.after(entitlementCert.orderNamespace.startDate) && now.before(entitlementCert.orderNamespace.endDate)) {
Assert.assertTrue(correspondingProductSubscription.isActive, "isActive is True when the current time ("+EntitlementCert.formatDateString(now)+") is between the start/end dates in the EntitlementCert: "+entitlementCert);
} else {
Assert.assertFalse(correspondingProductSubscription.isActive, "isActive is False when the current time ("+EntitlementCert.formatDateString(now)+") is NOT between the start/end dates in the EntitlementCert: "+entitlementCert);
}
// TEMPORARY WORKAROUND FOR BUG: https://bugzilla.redhat.com/show_bug.cgi?id=660713 - jsefler 12/12/2010
Boolean invokeWorkaroundWhileBugIsOpen = true;
try {String bugId="660713"; if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId).toString()+" Bugzilla "+bugId+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("The workaround while this bug is open is to skip the assertion that: startDates and endDates match");
} else {
// END OF WORKAROUND
Assert.assertEquals(ProductSubscription.formatDateString(correspondingProductSubscription.startDate), ProductSubscription.formatDateString(entitlementCert.orderNamespace.startDate), "startDate from ProductSubscription in list --consumed matches startDate from OrderNamespace ("+OrderNamespace.formatDateString(entitlementCert.orderNamespace.startDate)+") after conversion from GMT in EntitlementCert to local time.");
Assert.assertEquals(ProductSubscription.formatDateString(correspondingProductSubscription.endDate), ProductSubscription.formatDateString(entitlementCert.orderNamespace.endDate), "endDate from ProductSubscription in list --consumed matches endDate from OrderNamespace ("+OrderNamespace.formatDateString(entitlementCert.orderNamespace.endDate)+") after conversion from GMT in EntitlementCert to local time.");
}
}
}
@Test( description="subscription-manager-cli: RHEL Personal should be the only available subscription to a consumer registered as type person",
groups={"EnsureOnlyRHELPersonalIsAvailableToRegisteredPerson_Test"},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void EnsureOnlyRHELPersonalIsAvailableToRegisteredPerson_Test() throws JSONException {
// String rhelPersonalProductId = getProperty("sm.rhpersonal.productId", "");
// if (rhelPersonalProductId.equals("")) throw new SkipException("This testcase requires specification of a RHPERSONAL_PRODUCTID.");
// decide what username and password to test with
String username = sm_clientUsername;
String password = sm_clientPassword;
String owner = sm_clientOrg;
if (!sm_rhpersonalUsername.equals("")) {
username = sm_rhpersonalUsername;
password = sm_rhpersonalPassword;
owner = sm_rhpersonalOrg;
}
// register a person
clienttasks.unregister(null, null, null);
clienttasks.register(username, password, owner, null, ConsumerType.person, null, null, null, null, null, (String)null, null, false, null, null, null);
// assert that subscriptions with personal productIds are available to this person consumer
List<SubscriptionPool> subscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
for (String personProductId : getPersonProductIds()) {
SubscriptionPool rhelPersonalPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", personProductId, subscriptionPools);
Assert.assertNotNull(rhelPersonalPool,"Personal ProductId '"+personProductId+"' is available to this consumer registered as type person");
}
// assert that personal subscriptions are the only available pools to this person consumer
for (SubscriptionPool subscriptionPool : subscriptionPools) {
Assert.assertTrue(getPersonProductIds().contains(subscriptionPool.productId), "This available ProductId '"+subscriptionPool.productId+"' available to the registered person is among the expected list of personal products that we expect to be consumable by this person.");
}
}
@AfterGroups(groups={}, value="EnsureOnlyRHELPersonalIsAvailableToRegisteredPerson_Test", alwaysRun=true)
public void teardownAfterEnsureOnlyRHELPersonalIsAvailableToRegisteredPerson_Test() {
if (clienttasks!=null) clienttasks.unregister_(null, null, null);
}
@Test( description="subscription-manager-cli: RHEL Personal should not be an available subscription to a consumer registered as type system",
groups={"EnsureRHELPersonalIsNotAvailableToRegisteredSystem_Test"},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void EnsureRHELPersonalIsNotAvailableToRegisteredSystem_Test() throws JSONException {
clienttasks.unregister(null, null, null);
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, ConsumerType.system, null, null, null, null, null, (String)null, null, false, null, null, null);
SubscriptionPool rhelPersonalPool = null;
for (String personProductId : getPersonProductIds()) {
// assert that RHEL Personal *is not* included in --available subscription pools
rhelPersonalPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", personProductId, clienttasks.getCurrentlyAvailableSubscriptionPools());
Assert.assertNull(rhelPersonalPool,"Personal ProductId '"+personProductId+"' is NOT available to this consumer from --available subscription pools when registered as type system.");
/* behavior changed on list --all --available (3/4/2011)
// also assert that RHEL Personal *is* included in --all --available subscription pools
rhelPersonalPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", personProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
Assert.assertNotNull(rhelPersonalPool,"Personal ProductId '"+personProductId+"' is included in --all --available subscription pools when registered as type system.");
*/
// also assert that RHEL Personal *is not* included in --all --available subscription pools
rhelPersonalPool = SubscriptionPool.findFirstInstanceWithMatchingFieldFromList("productId", personProductId, clienttasks.getCurrentlyAllAvailableSubscriptionPools());
Assert.assertNull(rhelPersonalPool,"Personal ProductId '"+personProductId+"' is NOT available to this consumer from --all --available subscription pools when registered as type system.");
}
}
@AfterGroups(groups={}, value="EnsureRHELPersonalIsNotAvailableToRegisteredSystem_Test", alwaysRun=true)
public void teardownAfterEnsureRHELPersonalIsNotAvailableToRegisteredSystem_Test() {
if (clienttasks!=null) clienttasks.unregister_(null, null, null);
}
@Test( description="subscription-manager: subcription manager list consumed should be permitted without being registered",
groups={"blockedByBug-725870"},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void AttemptListConsumedWithoutBeingRegistered_Test() {
clienttasks.unregister(null,null,null);
SSHCommandResult listResult = clienttasks.listConsumedProductSubscriptions();
// assert redemption results
Assert.assertEquals(listResult.getStdout().trim(), "No consumed subscription pools to list","List consumed should NOT require that the system be registered.");
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0),"Exit code from list consumed when executed without being registered.");
}
@Test( description="subscription-manager: subcription manager list installed should be permitted without being registered",
groups={"blockedByBug-725870"},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void AttemptListInstalledWithoutBeingRegistered_Test() {
clienttasks.unregister(null,null,null);
SSHCommandResult listResult = clienttasks.listInstalledProducts();
}
@Test( description="subscription-manager: subcription manager list should be permitted without being registered",
groups={"blockedByBug-725870"},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void AttemptListWithoutBeingRegistered_Test() {
clienttasks.unregister(null,null,null);
SSHCommandResult listResult = clienttasks.list_(null,null,null,null,null,null,null, null, null);
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0), "The exit code from the list command indicates a success.");
}
@Test( description="subscription-manager: subcription manager list available should require being registered",
groups={},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void AttemptListAvailableWithoutBeingRegistered_Test() {
SSHCommandResult listResult;
clienttasks.unregister(null,null,null);
listResult = clienttasks.list_(null,true,null,null,null,null,null, null, null);
//Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(1), "The exit code from the list available command indicates a problem.");
//Assert.assertEquals(listResult.getStdout().trim(), "Error: You need to register this system by running `register` command before using this option.","Attempting to list available subscriptions should require registration.");
// results changed after bug fix 749332
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(255), "The exit code from the list available command indicates a problem.");
Assert.assertEquals(listResult.getStdout().trim(), clienttasks.msg_ConsumerNotRegistered,"Attempting to list --available subscriptions should require registration.");
listResult = clienttasks.list_(true,true,null,null,null,null,null, null, null);
//Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(1), "The exit code from the list all available command indicates a problem.");
//Assert.assertEquals(listResult.getStdout().trim(), "Error: You need to register this system by running `register` command before using this option.","Attempting to list all available subscriptions should require registration.");
// results changed after bug fix 749332
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(255), "The exit code from the list all available command indicates a problem.");
Assert.assertEquals(listResult.getStdout().trim(), clienttasks.msg_ConsumerNotRegistered,"Attempting to list --all --available subscriptions should require registration.");
}
@Test( description="subscription-manager: subcription manager list future subscription pools for a system",
groups={"blockedByBug-672562"},
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void ListAllAvailableWithFutureOnDate_Test() throws Exception {
List<List<Object>> allFutureJSONPoolsDataAsListOfLists = getAllFutureJSONPoolsDataAsListOfLists(ConsumerType.system);
if (allFutureJSONPoolsDataAsListOfLists.size()<1) throw new SkipException("Cannot find any future subscriptions to test");
Calendar now = new GregorianCalendar();
now.setTimeInMillis(System.currentTimeMillis());
List<String> onDatesTested = new ArrayList<String>();
// assemble a list of ondate strings to test
List<String> onDatesToTest = new ArrayList<String>();
for (List<Object> l : allFutureJSONPoolsDataAsListOfLists) {
JSONObject futureJSONPool = (JSONObject) l.get(0);
String startDate = futureJSONPool.getString("startDate");
// add one day to this start date to use for subscription-manager list --ondate test (ASSUMPTION: these subscriptions last longer than one day)
Calendar onDate = parse_iso8601DateString(startDate); onDate.add(Calendar.DATE, 1);
DateFormat yyyy_MM_dd_DateFormat = new SimpleDateFormat("yyyy-MM-dd");
String onDateToTest = yyyy_MM_dd_DateFormat.format(onDate.getTime());
if (!onDatesToTest.contains(onDateToTest)) onDatesToTest.add(onDateToTest);
}
// assemble a list of future subscription poolIds to verify in the subscription-manager list --available --ondate
List<String> futurePoolIds = new ArrayList<String>();
for (List<Object> l : allFutureJSONPoolsDataAsListOfLists) {
JSONObject jsonPool = (JSONObject) l.get(0);
String id = jsonPool.getString("id");
futurePoolIds.add(id);
}
// use this list to store all of the poolIds found on a future date listing
List<String>futurePoolIdsListedOnDate = new ArrayList<String>();
for (List<Object> l : allFutureJSONPoolsDataAsListOfLists) {
JSONObject futureJSONPool = (JSONObject) l.get(0);
// add one day to this start date to use for subscription-manager list --ondate test
Calendar onDate = parse_iso8601DateString(futureJSONPool.getString("startDate")); onDate.add(Calendar.DATE, 1);
DateFormat yyyy_MM_dd_DateFormat = new SimpleDateFormat("yyyy-MM-dd");
String onDateToTest = yyyy_MM_dd_DateFormat.format(onDate.getTime());
// if we already tested with this ondate string, then continue
if (onDatesTested.contains(onDateToTest)) continue;
// list all available onDateToTest
SSHCommandResult listResult = clienttasks.list_(true,true,null,null,null,onDateToTest,null, null, null);
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0), "The exit code from the list --all --available --ondate command indicates a success.");
List<SubscriptionPool> subscriptionPools = SubscriptionPool.parse(listResult.getStdout());
Assert.assertTrue(subscriptionPools.size()>=1,"A list of SubscriptionPools was returned from the list module using a valid ondate option.");
// assert that each of the SubscriptionPools listed is indeed active on the requested date
for (SubscriptionPool subscriptionPool : subscriptionPools) {
JSONObject jsonPool = new JSONObject(CandlepinTasks.getResourceUsingRESTfulAPI(sm_clientUsername,sm_clientPassword,sm_serverUrl,"/pools/"+subscriptionPool.poolId));
Calendar startDate = parse_iso8601DateString(jsonPool.getString("startDate")); // "startDate":"2012-02-08T00:00:00.000+0000"
Calendar endDate = parse_iso8601DateString(jsonPool.getString("endDate")); // "endDate":"2013-02-07T00:00:00.000+0000"
Boolean activeSubscription = jsonPool.getBoolean("activeSubscription"); // TODO I don't yet understand how to test this property. I'm assuming it is true
Assert.assertTrue(startDate.before(onDate)&&endDate.after(onDate)&&activeSubscription,"SubscriptionPool '"+subscriptionPool.poolId+"' is indeed active and listed as available ondate='"+onDateToTest+"'.");
// for follow-up assertions keep a list of all the futurePoolIds that are found on the listing date (excluding pools that are active now since they are not considered future pools)
if (startDate.after(now)) {
if (!futurePoolIdsListedOnDate.contains(subscriptionPool.poolId)) futurePoolIdsListedOnDate.add(subscriptionPool.poolId);
}
}
// remember that this date was just tested
onDatesTested.add(onDateToTest);
}
Assert.assertEquals(futurePoolIdsListedOnDate.size(), futurePoolIds.size(),"The expected count of all of the expected future subscription pools for systems was listed on future dates.");
for (String futurePoolId : futurePoolIds) futurePoolIdsListedOnDate.remove(futurePoolId);
Assert.assertTrue(futurePoolIdsListedOnDate.isEmpty(),"All of the expected future subscription pools for systems were listed on future dates.");
}
@Test( description="subscription-manager: subcription manager list all available should filter by servicelevel when this option is passed.",
groups={"blockedByBug-800933","blockedByBug-800999"},
dataProvider="getListAvailableWithServicelevelData",
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void ListAvailableWithServicelevel_Test(Object bugzilla, String servicelevel) throws Exception {
SSHCommandResult listResult;
List<SubscriptionPool> expectedSubscriptionPools, filteredSubscriptionPools;
// list all available (without service level)
listResult = clienttasks.list_(true,true,null,null,null,null,null,null,null);
List<SubscriptionPool> allAvailableSubscriptionPools = clienttasks.getCurrentlyAllAvailableSubscriptionPools();
// determine the subset of expected pools with a matching servicelevel
expectedSubscriptionPools = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("serviceLevel", servicelevel, allAvailableSubscriptionPools);
// list all available filtered by servicelevel
listResult = clienttasks.list_(true,true,null,null,servicelevel,null,null,null,null);
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0), "The exit code from the list --all --available --servicelevel command indicates a success.");
// assert results
filteredSubscriptionPools = SubscriptionPool.parse(listResult.getStdout());
Assert.assertTrue(filteredSubscriptionPools.containsAll(expectedSubscriptionPools),"The actual list of --all --available --servicelevel=\""+servicelevel+"\" SubscriptionPools contains all of the expected SubscriptionPools (the expected list contains only pools with ServiceLevel=\""+servicelevel+"\")");
Assert.assertTrue(expectedSubscriptionPools.containsAll(filteredSubscriptionPools),"The expected list of SubscriptionPools contains all of the actual SubscriptionPools returned by list --all --available --servicelevel=\""+servicelevel+"\".");
if (expectedSubscriptionPools.isEmpty()) Assert.assertEquals(listResult.getStdout().trim(), "No available subscription pools to list","Expected message when no subscription remain after list is filtered by --servicelevel=\""+servicelevel+"\".");
// list all available (without service level)
listResult = clienttasks.list_(false,true,null,null,null,null,null,null,null);
List<SubscriptionPool> availableSubscriptionPools = clienttasks.getCurrentlyAvailableSubscriptionPools();
// determine the subset of expected pools with a matching servicelevel
expectedSubscriptionPools = SubscriptionPool.findAllInstancesWithMatchingFieldFromList("serviceLevel", servicelevel, availableSubscriptionPools);
// list available filtered by servicelevel
listResult = clienttasks.list_(false,true,null,null,servicelevel,null,null,null,null);
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0), "The exit code from the list --all --available --servicelevel command indicates a success.");
// assert results
filteredSubscriptionPools = SubscriptionPool.parse(listResult.getStdout());
Assert.assertTrue(filteredSubscriptionPools.containsAll(expectedSubscriptionPools),"The actual list of --available --servicelevel=\""+servicelevel+"\" SubscriptionPools contains all of the expected SubscriptionPools (the expected list contains only pools with ServiceLevel=\""+servicelevel+"\")");
Assert.assertTrue(expectedSubscriptionPools.containsAll(filteredSubscriptionPools),"The expected list of SubscriptionPools contains all of the actual SubscriptionPools returned by list --available --servicelevel=\""+servicelevel+"\".");
if (expectedSubscriptionPools.isEmpty()) Assert.assertEquals(listResult.getStdout().trim(), "No available subscription pools to list","Expected message when no subscription remain after list is filtered by --servicelevel=\""+servicelevel+"\".");
}
@Test( description="subscription-manager: subcription manager list consumed should filter by servicelevel when this option is passed.",
groups={"blockedByBug-800933","blockedByBug-800999"},
dataProvider="getConsumedWithServicelevelData",
enabled=true)
//@ImplementsNitrateTest(caseId=)
public void ListConsumedWithServicelevel_Test(Object bugzilla, String servicelevel) throws Exception {
SSHCommandResult listResult;
List<ProductSubscription> expectedProductSubscriptions, filteredProductSubscriptions;
// list consumed (without service level)
listResult = clienttasks.list_(false,false,true,null,null,null,null,null,null);
List<ProductSubscription> allConsumedProductSubscriptions = clienttasks.getCurrentlyConsumedProductSubscriptions();
// determine the subset of expected pools with a matching servicelevel
expectedProductSubscriptions = ProductSubscription.findAllInstancesWithMatchingFieldFromList("serviceLevel", servicelevel, allConsumedProductSubscriptions);
// list consumed filtered by servicelevel
listResult = clienttasks.list_(false,false,true,null,servicelevel,null,null,null,null);
Assert.assertEquals(listResult.getExitCode(), Integer.valueOf(0), "The exit code from the list --consumed --servicelevel command indicates a success.");
// assert results
filteredProductSubscriptions = ProductSubscription.parse(listResult.getStdout());
Assert.assertTrue(filteredProductSubscriptions.containsAll(expectedProductSubscriptions),"The actual list of --consumed --servicelevel=\""+servicelevel+"\" ProductSubscriptions contains all of the expected ProductSubscriptions (the expected list contains only consumptions with ServiceLevel=\""+servicelevel+"\")");
Assert.assertTrue(expectedProductSubscriptions.containsAll(filteredProductSubscriptions),"The expected list of ProductSubscriptions contains all of the actual ProductSubscriptions returned by list --consumed --servicelevel=\""+servicelevel+"\".");
if (expectedProductSubscriptions.isEmpty()) Assert.assertEquals(listResult.getStdout().trim(), "No consumed subscription pools to list","Expected message when no consumed subscriptions remain after list is filtered by --servicelevel=\""+servicelevel+"\".");
}
// Candidates for an automated Test:
// TODO Bug 709412 - subscription manager cli uses product name comparisons in the list command
// TODO Bug 710141 - OwnerInfo needs to only show info for pools that are active right now, for all the stats
// TODO Bug 734880 - subscription-manager list --installed reports differently between LEGACY vs NEW SKU subscriptions (Note: Bryan says that this had nothing to do with Legacy vs Non Legacy - it was simply a regression in bundled products when stacking was introduced)
// TODO Bug 803386 - display product ID in product details pane on sm-gui and cli
// TODO Bug 805415 - s390x Partially Subscribed (THIS IS EFFECTIVELY A COMPLIANCE TEST ON A 0 SOCKET SUBSCRIPTION/PRODUCT)
// Configuration methods ***********************************************************************
@BeforeClass(groups="setup")
public void registerBeforeClass() {
clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, null, null, null, (String)null, null, false, null, null, null);
}
// NOTE: This method is not necessary, but adds a little more spice to ListAvailableWithFutureOnDate_Test
@BeforeClass(groups="setup", dependsOnMethods="registerBeforeClass")
public void createFutureSubscriptionPoolBeforeClass() throws Exception {
// don't bother attempting to create a subscription unless onPremises
// if (!sm_serverType.equals(CandlepinType.standalone)) return;
if (server==null) {
log.warning("Skipping createFutureSubscriptionPoolBeforeClass() when server is null.");
return;
}
// find a randomly available product id
List<SubscriptionPool> pools = clienttasks.getCurrentlyAvailableSubscriptionPools();
SubscriptionPool pool = pools.get(randomGenerator.nextInt(pools.size())); // randomly pick a pool
String randomAvailableProductId = pool.productId;
// create a future subscription and refresh pools for it
JSONObject futureJSONPool = CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 15, 5/*years*/*365*24*60, 6/*years*/*365*24*60, getRandInt(), getRandInt(), randomAvailableProductId, null);
}
@BeforeGroups(groups="setup",value="unsubscribeBeforeGroup")
public void unsubscribeBeforeGroup() {
//clienttasks.unsubscribeFromAllOfTheCurrentlyConsumedProductSubscriptions();
clienttasks.unsubscribe_(true, null, null, null, null);
}
@BeforeClass(groups="setup")
public void createSubscriptionsWithVariationsOnProductAttributeSockets() throws JSONException, Exception {
String name,productId;
List<String> providedProductIds = new ArrayList<String>();
Map<String,String> attributes = new HashMap<String,String>();
JSONObject jsonEngProduct, jsonMktProduct, jsonSubscription;
if (server==null) {
log.warning("Skipping createSubscriptionsWithVariationsOnProductAttributeSockets() when server is null.");
return;
}
//debugTesting if (true) return;
// Awesome OS for 0 sockets
name = "Awesome OS for systems with sockets value=0";
productId = "0-sockets";
providedProductIds.clear();
providedProductIds.add("90001");
attributes.clear();
attributes.put("sockets", "0");
attributes.put("version", "1.0");
attributes.put("variant", "server");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
// Awesome OS for no sockets
name = "Awesome OS for systems with no sockets";
productId = "no-sockets";
providedProductIds.clear();
providedProductIds.add("90002");
attributes.clear();
attributes.remove("sockets");
attributes.put("version", "0.0");
attributes.put("variant", "workstation");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
// Awesome OS for "zero" sockets
name = "Awesome OS for systems with sockets value=\"unknown\"";
productId = "unknown-sockets";
providedProductIds.clear();
providedProductIds.add("90003");
attributes.clear();
attributes.put("sockets", "zero");
attributes.put("version", "0.0");
attributes.put("variant", "workstation");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// TEMPORARY WORKAROUND FOR BUG
String bugId = "795552";
boolean invokeWorkaroundWhileBugIsOpen = true;
try {if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId).toString()+" Bugzilla "+bugId+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the creation of product: "+name);
} else {
// END OF WORKAROUND
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
}
// Awesome OS for null sockets
name = "Awesome OS for systems with sockets value=null";
productId = "null-sockets";
providedProductIds.clear();
providedProductIds.add("90004");
attributes.clear();
attributes.put("sockets", null);
attributes.put("version", "0.0");
attributes.put("variant", "server");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// TEMPORARY WORKAROUND FOR BUG
invokeWorkaroundWhileBugIsOpen = true;
String bugId1 = "807452";
String bugId2 = "813529";
- try {if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId1)&&BzChecker.getInstance().isBugOpen(bugId2)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId1).toString()+" Bugzilla "+bugId1+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId1+")");log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId2).toString()+" Bugzilla "+bugId2+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId2+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
+ try {if (invokeWorkaroundWhileBugIsOpen&&(BzChecker.getInstance().isBugOpen(bugId1)||BzChecker.getInstance().isBugOpen(bugId2))) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId1).toString()+" Bugzilla "+bugId1+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId1+")");log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId2).toString()+" Bugzilla "+bugId2+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId2+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the creation of product: "+name);
} else {
// END OF WORKAROUND
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
}
}
// Data Providers ***********************************************************************
@DataProvider(name="getListAvailableWithServicelevelData")
public Object[][] getListAvailableWithServicelevelDataAs2dArray() throws JSONException, Exception {
return TestNGUtils.convertListOfListsTo2dArray(getListAvailableWithServicelevelDataAsListOfLists());
}
protected List<List<Object>>getListAvailableWithServicelevelDataAsListOfLists() throws JSONException, Exception {
List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll;
// register with force (so we can find the org to which the sm_clientUsername belongs in case sm_clientOrg is null)
String org = sm_clientOrg;
if (org==null) {
String consumerId = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, "SubscriptionServicelevelConsumer", null, null, null, null, (String)null, true, false, null, null, null));
org = CandlepinTasks.getOwnerKeyOfConsumerId(sm_clientUsername,sm_clientPassword,sm_serverUrl,consumerId);
}
// get all the valid service levels available to this org
for (String serviceLevel : CandlepinTasks.getServiceLevelsForOrgKey(sm_clientUsername, sm_clientPassword, sm_serverUrl, org)) {
ll.add(Arrays.asList(new Object[] {null, serviceLevel}));
}
ll.add(Arrays.asList(new Object[] {null, ""}));
ll.add(Arrays.asList(new Object[] {null, "FOO"}));
return ll;
}
@DataProvider(name="getConsumedWithServicelevelData")
public Object[][] getConsumedWithServicelevelDataAs2dArray() throws JSONException, Exception {
return TestNGUtils.convertListOfListsTo2dArray(getConsumedWithServicelevelDataAsListOfLists());
}
protected List<List<Object>>getConsumedWithServicelevelDataAsListOfLists() throws JSONException, Exception {
List<List<Object>> ll = new ArrayList<List<Object>>(); if (!isSetupBeforeSuiteComplete) return ll;
// register with force and subscribe to all available subscriptions collectively
String consumerId = clienttasks.getCurrentConsumerId(clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, "SubscriptionServicelevelConsumer", null, null, null, null, (String)null, true, false, null, null, null));
String org = CandlepinTasks.getOwnerKeyOfConsumerId(sm_clientUsername,sm_clientPassword,sm_serverUrl,consumerId);
clienttasks.subscribeToTheCurrentlyAllAvailableSubscriptionPoolsCollectively();
// get all the valid service levels available to this org
for (String serviceLevel : CandlepinTasks.getServiceLevelsForOrgKey(sm_clientUsername, sm_clientPassword, sm_serverUrl, org)) {
ll.add(Arrays.asList(new Object[] {null, serviceLevel}));
}
ll.add(Arrays.asList(new Object[] {null, ""}));
ll.add(Arrays.asList(new Object[] {null, "FOO"}));
return ll;
}
}
| true | true | public void createSubscriptionsWithVariationsOnProductAttributeSockets() throws JSONException, Exception {
String name,productId;
List<String> providedProductIds = new ArrayList<String>();
Map<String,String> attributes = new HashMap<String,String>();
JSONObject jsonEngProduct, jsonMktProduct, jsonSubscription;
if (server==null) {
log.warning("Skipping createSubscriptionsWithVariationsOnProductAttributeSockets() when server is null.");
return;
}
//debugTesting if (true) return;
// Awesome OS for 0 sockets
name = "Awesome OS for systems with sockets value=0";
productId = "0-sockets";
providedProductIds.clear();
providedProductIds.add("90001");
attributes.clear();
attributes.put("sockets", "0");
attributes.put("version", "1.0");
attributes.put("variant", "server");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
// Awesome OS for no sockets
name = "Awesome OS for systems with no sockets";
productId = "no-sockets";
providedProductIds.clear();
providedProductIds.add("90002");
attributes.clear();
attributes.remove("sockets");
attributes.put("version", "0.0");
attributes.put("variant", "workstation");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
// Awesome OS for "zero" sockets
name = "Awesome OS for systems with sockets value=\"unknown\"";
productId = "unknown-sockets";
providedProductIds.clear();
providedProductIds.add("90003");
attributes.clear();
attributes.put("sockets", "zero");
attributes.put("version", "0.0");
attributes.put("variant", "workstation");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// TEMPORARY WORKAROUND FOR BUG
String bugId = "795552";
boolean invokeWorkaroundWhileBugIsOpen = true;
try {if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId).toString()+" Bugzilla "+bugId+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the creation of product: "+name);
} else {
// END OF WORKAROUND
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
}
// Awesome OS for null sockets
name = "Awesome OS for systems with sockets value=null";
productId = "null-sockets";
providedProductIds.clear();
providedProductIds.add("90004");
attributes.clear();
attributes.put("sockets", null);
attributes.put("version", "0.0");
attributes.put("variant", "server");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// TEMPORARY WORKAROUND FOR BUG
invokeWorkaroundWhileBugIsOpen = true;
String bugId1 = "807452";
String bugId2 = "813529";
try {if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId1)&&BzChecker.getInstance().isBugOpen(bugId2)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId1).toString()+" Bugzilla "+bugId1+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId1+")");log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId2).toString()+" Bugzilla "+bugId2+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId2+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the creation of product: "+name);
} else {
// END OF WORKAROUND
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
}
}
| public void createSubscriptionsWithVariationsOnProductAttributeSockets() throws JSONException, Exception {
String name,productId;
List<String> providedProductIds = new ArrayList<String>();
Map<String,String> attributes = new HashMap<String,String>();
JSONObject jsonEngProduct, jsonMktProduct, jsonSubscription;
if (server==null) {
log.warning("Skipping createSubscriptionsWithVariationsOnProductAttributeSockets() when server is null.");
return;
}
//debugTesting if (true) return;
// Awesome OS for 0 sockets
name = "Awesome OS for systems with sockets value=0";
productId = "0-sockets";
providedProductIds.clear();
providedProductIds.add("90001");
attributes.clear();
attributes.put("sockets", "0");
attributes.put("version", "1.0");
attributes.put("variant", "server");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
// Awesome OS for no sockets
name = "Awesome OS for systems with no sockets";
productId = "no-sockets";
providedProductIds.clear();
providedProductIds.add("90002");
attributes.clear();
attributes.remove("sockets");
attributes.put("version", "0.0");
attributes.put("variant", "workstation");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
// Awesome OS for "zero" sockets
name = "Awesome OS for systems with sockets value=\"unknown\"";
productId = "unknown-sockets";
providedProductIds.clear();
providedProductIds.add("90003");
attributes.clear();
attributes.put("sockets", "zero");
attributes.put("version", "0.0");
attributes.put("variant", "workstation");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// TEMPORARY WORKAROUND FOR BUG
String bugId = "795552";
boolean invokeWorkaroundWhileBugIsOpen = true;
try {if (invokeWorkaroundWhileBugIsOpen&&BzChecker.getInstance().isBugOpen(bugId)) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId).toString()+" Bugzilla "+bugId+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the creation of product: "+name);
} else {
// END OF WORKAROUND
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
}
// Awesome OS for null sockets
name = "Awesome OS for systems with sockets value=null";
productId = "null-sockets";
providedProductIds.clear();
providedProductIds.add("90004");
attributes.clear();
attributes.put("sockets", null);
attributes.put("version", "0.0");
attributes.put("variant", "server");
attributes.put("arch", "ALL");
attributes.put("warning_period", "30");
// TEMPORARY WORKAROUND FOR BUG
invokeWorkaroundWhileBugIsOpen = true;
String bugId1 = "807452";
String bugId2 = "813529";
try {if (invokeWorkaroundWhileBugIsOpen&&(BzChecker.getInstance().isBugOpen(bugId1)||BzChecker.getInstance().isBugOpen(bugId2))) {log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId1).toString()+" Bugzilla "+bugId1+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId1+")");log.fine("Invoking workaround for "+BzChecker.getInstance().getBugState(bugId2).toString()+" Bugzilla "+bugId2+". (https://bugzilla.redhat.com/show_bug.cgi?id="+bugId2+")");} else {invokeWorkaroundWhileBugIsOpen=false;}} catch (XmlRpcException xre) {/* ignore exception */} catch (RuntimeException re) {/* ignore exception */}
if (invokeWorkaroundWhileBugIsOpen) {
log.warning("Skipping the creation of product: "+name);
} else {
// END OF WORKAROUND
// delete already existing subscription and products
CandlepinTasks.deleteSubscriptionsAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+productId);
CandlepinTasks.deleteResourceUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, "/products/"+providedProductIds.get(0));
// create a new engineering product, marketing product that provides the engineering product, and a subscription for the marketing product
attributes.put("type", "SVC");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name+" BITS", providedProductIds.get(0), 1, attributes, null);
attributes.put("type", "MKT");
CandlepinTasks.createProductUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, name, productId, 1, attributes, null);
CandlepinTasks.createSubscriptionAndRefreshPoolsUsingRESTfulAPI(sm_serverAdminUsername, sm_serverAdminPassword, sm_serverUrl, sm_clientOrg, 20, -1*24*60/*1 day ago*/, 15*24*60/*15 days from now*/, getRandInt(), getRandInt(), productId, providedProductIds);
}
}
|
diff --git a/src/main/java/org/graylog2/messagehandlers/gelf/GELFClientHandlerThread.java b/src/main/java/org/graylog2/messagehandlers/gelf/GELFClientHandlerThread.java
index 7a7cca78e..0b2a2aa60 100644
--- a/src/main/java/org/graylog2/messagehandlers/gelf/GELFClientHandlerThread.java
+++ b/src/main/java/org/graylog2/messagehandlers/gelf/GELFClientHandlerThread.java
@@ -1,76 +1,78 @@
/**
* Copyright 2010 Lennart Koopmann <[email protected]>
*
* This file is part of Graylog2.
*
* Graylog2 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.
*
* Graylog2 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 Graylog2. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.graylog2.messagehandlers.gelf;
import java.net.DatagramPacket;
import org.graylog2.Log;
/**
* GELFClientHandlerThread.java: Jun 23, 2010 7:09:40 PM
*
* Thread that handles a GELF client.
*
* @author: Lennart Koopmann <[email protected]>
*/
public class GELFClientHandlerThread extends Thread {
private DatagramPacket receivedGelfSentence;
/**
* Thread that handles a GELF client.
*
* @param receivedGelfSentence Raw GELF message
*/
public GELFClientHandlerThread(DatagramPacket receivedGelfSentence) {
this.receivedGelfSentence = receivedGelfSentence;
}
/**
* Start the thread. Exits when the client has been completely handled.
*/
@Override public void run() {
try {
GELFClientHandlerIF client = null;
if (GELF.isChunkedMessage(this.receivedGelfSentence)) {
Log.info("Received message is chunked. Handling now.");
client = new ChunkedGELFClientHandler(this.receivedGelfSentence);
} else {
Log.info("Received message is not chunked. Handling now.");
client = new SimpleGELFClientHandler(this.receivedGelfSentence);
}
client.handle();
} catch (InvalidGELFTypeException e) {
Log.crit("Invalid GELF type in message: " + e.toString());
} catch (InvalidGELFHeaderException e) {
Log.crit("Invalid GELF header in message: " + e.toString());
} catch (InvalidGELFCompressionMethodException e) {
Log.crit("Invalid compression method of GELF message: " + e.toString());
} catch (java.util.zip.DataFormatException e) {
Log.crit("Invalid compression data format in GELF message: " + e.toString());
} catch (java.io.UnsupportedEncodingException e) {
Log.crit("Invalid enconding of GELF message: " + e.toString());
} catch (java.io.IOException e) {
Log.crit("IO Error while handling GELF message: " + e.toString());
+ } catch (jave.io.EOFException e) {
+ Log.crit("EOF Exception while handling GELF message: " + e.toString());
}
}
}
| true | true | @Override public void run() {
try {
GELFClientHandlerIF client = null;
if (GELF.isChunkedMessage(this.receivedGelfSentence)) {
Log.info("Received message is chunked. Handling now.");
client = new ChunkedGELFClientHandler(this.receivedGelfSentence);
} else {
Log.info("Received message is not chunked. Handling now.");
client = new SimpleGELFClientHandler(this.receivedGelfSentence);
}
client.handle();
} catch (InvalidGELFTypeException e) {
Log.crit("Invalid GELF type in message: " + e.toString());
} catch (InvalidGELFHeaderException e) {
Log.crit("Invalid GELF header in message: " + e.toString());
} catch (InvalidGELFCompressionMethodException e) {
Log.crit("Invalid compression method of GELF message: " + e.toString());
} catch (java.util.zip.DataFormatException e) {
Log.crit("Invalid compression data format in GELF message: " + e.toString());
} catch (java.io.UnsupportedEncodingException e) {
Log.crit("Invalid enconding of GELF message: " + e.toString());
} catch (java.io.IOException e) {
Log.crit("IO Error while handling GELF message: " + e.toString());
}
}
| @Override public void run() {
try {
GELFClientHandlerIF client = null;
if (GELF.isChunkedMessage(this.receivedGelfSentence)) {
Log.info("Received message is chunked. Handling now.");
client = new ChunkedGELFClientHandler(this.receivedGelfSentence);
} else {
Log.info("Received message is not chunked. Handling now.");
client = new SimpleGELFClientHandler(this.receivedGelfSentence);
}
client.handle();
} catch (InvalidGELFTypeException e) {
Log.crit("Invalid GELF type in message: " + e.toString());
} catch (InvalidGELFHeaderException e) {
Log.crit("Invalid GELF header in message: " + e.toString());
} catch (InvalidGELFCompressionMethodException e) {
Log.crit("Invalid compression method of GELF message: " + e.toString());
} catch (java.util.zip.DataFormatException e) {
Log.crit("Invalid compression data format in GELF message: " + e.toString());
} catch (java.io.UnsupportedEncodingException e) {
Log.crit("Invalid enconding of GELF message: " + e.toString());
} catch (java.io.IOException e) {
Log.crit("IO Error while handling GELF message: " + e.toString());
} catch (jave.io.EOFException e) {
Log.crit("EOF Exception while handling GELF message: " + e.toString());
}
}
|
diff --git a/src/main/java/com/redhat/ceylon/js/repl/CeylonToJSTranslationServlet.java b/src/main/java/com/redhat/ceylon/js/repl/CeylonToJSTranslationServlet.java
index cb31b96..ca2ad06 100644
--- a/src/main/java/com/redhat/ceylon/js/repl/CeylonToJSTranslationServlet.java
+++ b/src/main/java/com/redhat/ceylon/js/repl/CeylonToJSTranslationServlet.java
@@ -1,147 +1,150 @@
package com.redhat.ceylon.js.repl;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.redhat.ceylon.compiler.Options;
import com.redhat.ceylon.compiler.SimpleJsonEncoder;
import com.redhat.ceylon.compiler.js.DocVisitor;
import com.redhat.ceylon.compiler.js.JsCompiler;
import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.analyzer.UsageWarning;
import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.parser.RecognitionError;
import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage;
import com.redhat.ceylon.compiler.typechecker.tree.Message;
import com.redhat.ceylon.js.util.CompilerUtils;
import com.redhat.ceylon.js.util.DocUtils;
/**
* Servlet implementation class CeylonToJSTranslationServlet
*/
@WebServlet("/translate")
public class CeylonToJSTranslationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final Options opts = Options.parse(new ArrayList<String>(Arrays.asList(
"-optimize", "-compact", "-src", ".", "-nomodule")));
private SimpleJsonEncoder json = new SimpleJsonEncoder();
/** Compiles Ceylon code and returns the resulting Javascript, along with its hover help docs.
* Expects the following keys:
* ceylon - The Ceylon code to compile
* module - The code for the module.ceylon file
* Returns a JSON object with the following keys:
* code_docs - a list of the doc descriptions
* code_refs - a list of maps, each map contains keys "ref" with the index of the doc in the code_docs list,
* "from" and "to" with the location of the token corresponding to that doc.
* code - The javascript code compiled from the Ceylon code.
* errors - A list of errors, each error is a map with the keys "msg", "code",
* "from" and optionally "to" (for the error location).
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String script = request.getParameter("ceylon");
String module = request.getParameter("module");
ScriptFile src = new ScriptFile("ROOT",
new ScriptFile("web_ide_script",
new ScriptFile("SCRIPT.ceylon", script),
new ScriptFile("module.ceylon", module)
)
);
TypeChecker typeChecker = CompilerUtils.getTypeChecker(request.getServletContext(), src);
typeChecker.process();
//While we're at it, get the docs
final DocVisitor doccer = new DocVisitor();
for (PhasedUnit pu: typeChecker.getPhasedUnits().getPhasedUnits()) {
pu.getCompilationUnit().visit(doccer);
}
//Run the compiler, if typechecker returns no errors.
final CharArrayWriter out = new CharArrayWriter(script.length()*2);
JsCompiler compiler = new JsCompiler(typeChecker, opts) {
//Override the inner output class to use the in-memory writer
class JsMemoryOutput extends JsCompiler.JsOutput {
JsMemoryOutput(Module m) throws IOException { super(m); }
@Override protected Writer getWriter() { return out; }
}
@Override
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsMemoryOutput(m);
}
//Override this to avoid generating artifacts
protected void finish() throws IOException {
out.flush();
out.close();
}
}.stopOnErrors(true);
//Don't reply on result flag, check errors instead
compiler.generate();
final Map<String, Object> resp = new HashMap<String, Object>();
resp.put("code_docs", doccer.getDocs());
resp.put("code_refs", DocUtils.referenceMapToList(doccer.getLocations()));
//Put errors in this list
- ArrayList<Object> errs = new ArrayList<Object>(compiler.listErrors().size());
+ ArrayList<Map<String, Object>> errs = new ArrayList<Map<String, Object>>(compiler.listErrors().size());
for (Message err : compiler.listErrors()) {
if (!(err instanceof UsageWarning)) {
- errs.add(encodeError(err));
+ Map<String, Object> encoded = encodeError(err);
+ if (!errs.contains(encoded)) {
+ errs.add(encodeError(err));
+ }
}
}
if (errs.isEmpty()) {
resp.put("code", out.toString());
} else {
//Print out errors
resp.put("errors", errs);
}
final CharArrayWriter swriter = new CharArrayWriter(script.length()*2);
json.encode(resp, swriter);
final String enc = swriter.toString();
response.setContentType("application/json");
response.setContentLength(enc.length());
response.getWriter().print(enc);
} catch (Exception ex) {
response.setStatus(500);
final CharArrayWriter sb = new CharArrayWriter(512);
String msg = ex.getMessage();
if (msg == null) {
msg = ex.getClass().getName();
}
ex.printStackTrace(System.out);
json.encodeList(Collections.singletonList((Object)String.format("Service error: %s", msg)), sb);
final String enc = sb.toString();
response.setContentLength(enc.length());
response.getWriter().print(enc);
}
response.getWriter().flush();
}
private Map<String, Object> encodeError(Message err) {
Map<String, Object> errmsg = new HashMap<String, Object>();
errmsg.put("msg", err.getMessage());
errmsg.put("code", err.getCode());
if (err instanceof AnalysisMessage) {
AnalysisMessage msg = (AnalysisMessage)err;
errmsg.putAll(DocUtils.locationToMap(msg.getTreeNode().getLocation(), true));
} else if (err instanceof RecognitionError) {
RecognitionError rec = (RecognitionError)err;
String pos = String.format("%d:%d", rec.getLine(), rec.getCharacterInLine());
errmsg.putAll(DocUtils.locationToMap(pos, true));
}
return errmsg;
}
}
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String script = request.getParameter("ceylon");
String module = request.getParameter("module");
ScriptFile src = new ScriptFile("ROOT",
new ScriptFile("web_ide_script",
new ScriptFile("SCRIPT.ceylon", script),
new ScriptFile("module.ceylon", module)
)
);
TypeChecker typeChecker = CompilerUtils.getTypeChecker(request.getServletContext(), src);
typeChecker.process();
//While we're at it, get the docs
final DocVisitor doccer = new DocVisitor();
for (PhasedUnit pu: typeChecker.getPhasedUnits().getPhasedUnits()) {
pu.getCompilationUnit().visit(doccer);
}
//Run the compiler, if typechecker returns no errors.
final CharArrayWriter out = new CharArrayWriter(script.length()*2);
JsCompiler compiler = new JsCompiler(typeChecker, opts) {
//Override the inner output class to use the in-memory writer
class JsMemoryOutput extends JsCompiler.JsOutput {
JsMemoryOutput(Module m) throws IOException { super(m); }
@Override protected Writer getWriter() { return out; }
}
@Override
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsMemoryOutput(m);
}
//Override this to avoid generating artifacts
protected void finish() throws IOException {
out.flush();
out.close();
}
}.stopOnErrors(true);
//Don't reply on result flag, check errors instead
compiler.generate();
final Map<String, Object> resp = new HashMap<String, Object>();
resp.put("code_docs", doccer.getDocs());
resp.put("code_refs", DocUtils.referenceMapToList(doccer.getLocations()));
//Put errors in this list
ArrayList<Object> errs = new ArrayList<Object>(compiler.listErrors().size());
for (Message err : compiler.listErrors()) {
if (!(err instanceof UsageWarning)) {
errs.add(encodeError(err));
}
}
if (errs.isEmpty()) {
resp.put("code", out.toString());
} else {
//Print out errors
resp.put("errors", errs);
}
final CharArrayWriter swriter = new CharArrayWriter(script.length()*2);
json.encode(resp, swriter);
final String enc = swriter.toString();
response.setContentType("application/json");
response.setContentLength(enc.length());
response.getWriter().print(enc);
} catch (Exception ex) {
response.setStatus(500);
final CharArrayWriter sb = new CharArrayWriter(512);
String msg = ex.getMessage();
if (msg == null) {
msg = ex.getClass().getName();
}
ex.printStackTrace(System.out);
json.encodeList(Collections.singletonList((Object)String.format("Service error: %s", msg)), sb);
final String enc = sb.toString();
response.setContentLength(enc.length());
response.getWriter().print(enc);
}
response.getWriter().flush();
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String script = request.getParameter("ceylon");
String module = request.getParameter("module");
ScriptFile src = new ScriptFile("ROOT",
new ScriptFile("web_ide_script",
new ScriptFile("SCRIPT.ceylon", script),
new ScriptFile("module.ceylon", module)
)
);
TypeChecker typeChecker = CompilerUtils.getTypeChecker(request.getServletContext(), src);
typeChecker.process();
//While we're at it, get the docs
final DocVisitor doccer = new DocVisitor();
for (PhasedUnit pu: typeChecker.getPhasedUnits().getPhasedUnits()) {
pu.getCompilationUnit().visit(doccer);
}
//Run the compiler, if typechecker returns no errors.
final CharArrayWriter out = new CharArrayWriter(script.length()*2);
JsCompiler compiler = new JsCompiler(typeChecker, opts) {
//Override the inner output class to use the in-memory writer
class JsMemoryOutput extends JsCompiler.JsOutput {
JsMemoryOutput(Module m) throws IOException { super(m); }
@Override protected Writer getWriter() { return out; }
}
@Override
protected JsOutput newJsOutput(Module m) throws IOException {
return new JsMemoryOutput(m);
}
//Override this to avoid generating artifacts
protected void finish() throws IOException {
out.flush();
out.close();
}
}.stopOnErrors(true);
//Don't reply on result flag, check errors instead
compiler.generate();
final Map<String, Object> resp = new HashMap<String, Object>();
resp.put("code_docs", doccer.getDocs());
resp.put("code_refs", DocUtils.referenceMapToList(doccer.getLocations()));
//Put errors in this list
ArrayList<Map<String, Object>> errs = new ArrayList<Map<String, Object>>(compiler.listErrors().size());
for (Message err : compiler.listErrors()) {
if (!(err instanceof UsageWarning)) {
Map<String, Object> encoded = encodeError(err);
if (!errs.contains(encoded)) {
errs.add(encodeError(err));
}
}
}
if (errs.isEmpty()) {
resp.put("code", out.toString());
} else {
//Print out errors
resp.put("errors", errs);
}
final CharArrayWriter swriter = new CharArrayWriter(script.length()*2);
json.encode(resp, swriter);
final String enc = swriter.toString();
response.setContentType("application/json");
response.setContentLength(enc.length());
response.getWriter().print(enc);
} catch (Exception ex) {
response.setStatus(500);
final CharArrayWriter sb = new CharArrayWriter(512);
String msg = ex.getMessage();
if (msg == null) {
msg = ex.getClass().getName();
}
ex.printStackTrace(System.out);
json.encodeList(Collections.singletonList((Object)String.format("Service error: %s", msg)), sb);
final String enc = sb.toString();
response.setContentLength(enc.length());
response.getWriter().print(enc);
}
response.getWriter().flush();
}
|
diff --git a/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java b/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java
index e4b78e8a6..210f9ae4d 100644
--- a/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java
+++ b/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java
@@ -1,130 +1,130 @@
package org.apache.lucene.analysis.id;
/**
* 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.IOException;
import java.io.Reader;
import java.util.Set;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.miscellaneous.KeywordMarkerFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.StopwordAnalyzerBase;
import org.apache.lucene.util.Version;
/**
* Analyzer for Indonesian (Bahasa)
*/
public final class IndonesianAnalyzer extends StopwordAnalyzerBase {
/** File containing default Indonesian stopwords. */
public final static String DEFAULT_STOPWORD_FILE = "stopwords.txt";
/**
* Returns an unmodifiable instance of the default stop-words set.
* @return an unmodifiable instance of the default stop-words set.
*/
public static Set<?> getDefaultStopSet(){
return DefaultSetHolder.DEFAULT_STOP_SET;
}
/**
* Atomically loads the DEFAULT_STOP_SET in a lazy fashion once the outer class
* accesses the static final set the first time.;
*/
private static class DefaultSetHolder {
static final Set<?> DEFAULT_STOP_SET;
static {
try {
DEFAULT_STOP_SET = loadStopwordSet(false, IndonesianAnalyzer.class, DEFAULT_STOPWORD_FILE, "#");
} catch (IOException ex) {
// default set should always be present as it is part of the
// distribution (JAR)
throw new RuntimeException("Unable to load default stopword set");
}
}
}
private final Set<?> stemExclusionSet;
/**
* Builds an analyzer with the default stop words: {@link #DEFAULT_STOPWORD_FILE}.
*/
public IndonesianAnalyzer(Version matchVersion) {
this(matchVersion, DefaultSetHolder.DEFAULT_STOP_SET);
}
/**
* Builds an analyzer with the given stop words
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
*/
public IndonesianAnalyzer(Version matchVersion, Set<?> stopwords){
this(matchVersion, stopwords, CharArraySet.EMPTY_SET);
}
/**
* Builds an analyzer with the given stop word. If a none-empty stem exclusion set is
* provided this analyzer will add a {@link KeywordMarkerFilter} before
* {@link IndonesianStemFilter}.
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
* @param stemExclusionSet
* a set of terms not to be stemmed
*/
public IndonesianAnalyzer(Version matchVersion, Set<?> stopwords, Set<?> stemExclusionSet){
super(matchVersion, stopwords);
this.stemExclusionSet = CharArraySet.unmodifiableSet(CharArraySet.copy(
matchVersion, stemExclusionSet));
}
/**
* Creates
* {@link org.apache.lucene.analysis.util.ReusableAnalyzerBase.TokenStreamComponents}
* used to tokenize all the text in the provided {@link Reader}.
*
* @return {@link org.apache.lucene.analysis.util.ReusableAnalyzerBase.TokenStreamComponents}
* built from an {@link StandardTokenizer} filtered with
* {@link StandardFilter}, {@link LowerCaseFilter},
* {@link StopFilter}, {@link KeywordMarkerFilter}
* if a stem exclusion set is provided and {@link IndonesianStemFilter}.
*/
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final Tokenizer source = new StandardTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
- result = new LowerCaseFilter(matchVersion, source);
+ result = new LowerCaseFilter(matchVersion, result);
result = new StopFilter(matchVersion, result, stopwords);
if (!stemExclusionSet.isEmpty()) {
result = new KeywordMarkerFilter(result, stemExclusionSet);
}
return new TokenStreamComponents(source, new IndonesianStemFilter(result));
}
}
| true | true | protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final Tokenizer source = new StandardTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
result = new LowerCaseFilter(matchVersion, source);
result = new StopFilter(matchVersion, result, stopwords);
if (!stemExclusionSet.isEmpty()) {
result = new KeywordMarkerFilter(result, stemExclusionSet);
}
return new TokenStreamComponents(source, new IndonesianStemFilter(result));
}
| protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final Tokenizer source = new StandardTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
result = new LowerCaseFilter(matchVersion, result);
result = new StopFilter(matchVersion, result, stopwords);
if (!stemExclusionSet.isEmpty()) {
result = new KeywordMarkerFilter(result, stemExclusionSet);
}
return new TokenStreamComponents(source, new IndonesianStemFilter(result));
}
|
diff --git a/maven-core/src/main/java/org/apache/maven/extension/DefaultExtensionManager.java b/maven-core/src/main/java/org/apache/maven/extension/DefaultExtensionManager.java
index e31c6c9ec..4f6b4298d 100644
--- a/maven-core/src/main/java/org/apache/maven/extension/DefaultExtensionManager.java
+++ b/maven-core/src/main/java/org/apache/maven/extension/DefaultExtensionManager.java
@@ -1,161 +1,160 @@
package org.apache.maven.extension;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.maven.MavenArtifactFilterManager;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.model.Extension;
import org.apache.maven.project.MavenProject;
import org.apache.maven.wagon.Wagon;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
/**
* Used to locate extensions.
*
* @author <a href="mailto:[email protected]">Brett Porter</a>
* @author Jason van Zyl
* @version $Id$
*/
public class DefaultExtensionManager
extends AbstractLogEnabled
implements ExtensionManager, Contextualizable
{
private ArtifactResolver artifactResolver;
private ArtifactMetadataSource artifactMetadataSource;
private PlexusContainer container;
private ArtifactFilter artifactFilter = MavenArtifactFilterManager.createStandardFilter();
private WagonManager wagonManager;
private static final String CONTAINER_NAME = "extensions";
public void addExtension( Extension extension, MavenProject project, ArtifactRepository localRepository )
throws ArtifactResolutionException, PlexusContainerException, ArtifactNotFoundException
{
String extensionId = ArtifactUtils.versionlessKey( extension.getGroupId(), extension.getArtifactId() );
getLogger().debug( "Initialising extension: " + extensionId );
Artifact artifact = (Artifact) project.getExtensionArtifactMap().get( extensionId );
if ( artifact != null )
{
ArtifactFilter filter = new ProjectArtifactExceptionFilter( artifactFilter, project.getArtifact() );
ArtifactResolutionResult result = artifactResolver.resolveTransitively( Collections.singleton( artifact ),
project.getArtifact(),
localRepository,
project.getRemoteArtifactRepositories(),
artifactMetadataSource, filter );
// create a child container for the extension
// TODO: this could surely be simpler/different on trunk with the new classworlds
PlexusContainer extensionContainer = getExtensionContainer();
if ( extensionContainer == null )
{
- extensionContainer = container.createChildContainer( CONTAINER_NAME,
- Collections.singletonList( artifact.getFile() ),
- Collections.EMPTY_MAP );
+ extensionContainer =
+ container.createChildContainer( CONTAINER_NAME, Collections.EMPTY_LIST, Collections.EMPTY_MAP );
}
for ( Iterator i = result.getArtifacts().iterator(); i.hasNext(); )
{
Artifact a = (Artifact) i.next();
a = project.replaceWithActiveArtifact( a );
getLogger().debug( "Adding to extension classpath: " + a.getFile() );
extensionContainer.addJarResource( a.getFile() );
}
}
}
public void registerWagons()
{
PlexusContainer extensionContainer = getExtensionContainer();
if ( extensionContainer != null )
{
try
{
Map wagons = extensionContainer.lookupMap( Wagon.ROLE );
wagonManager.registerWagons( wagons.keySet(), extensionContainer );
}
catch ( ComponentLookupException e )
{
// now wagons found in the extension
}
}
}
private PlexusContainer getExtensionContainer()
{
// note: ideally extensions would live in their own realm, but this would mean that things like wagon-scm would
// have no way to obtain SCM extensions
return container.getChildContainer( CONTAINER_NAME );
}
public void contextualize( Context context )
throws ContextException
{
this.container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
}
private static final class ProjectArtifactExceptionFilter
implements ArtifactFilter
{
private ArtifactFilter passThroughFilter;
private String projectDependencyConflictId;
ProjectArtifactExceptionFilter( ArtifactFilter passThroughFilter, Artifact projectArtifact )
{
this.passThroughFilter = passThroughFilter;
this.projectDependencyConflictId = projectArtifact.getDependencyConflictId();
}
public boolean include( Artifact artifact )
{
String depConflictId = artifact.getDependencyConflictId();
return projectDependencyConflictId.equals( depConflictId ) || passThroughFilter.include( artifact );
}
}
}
| true | true | public void addExtension( Extension extension, MavenProject project, ArtifactRepository localRepository )
throws ArtifactResolutionException, PlexusContainerException, ArtifactNotFoundException
{
String extensionId = ArtifactUtils.versionlessKey( extension.getGroupId(), extension.getArtifactId() );
getLogger().debug( "Initialising extension: " + extensionId );
Artifact artifact = (Artifact) project.getExtensionArtifactMap().get( extensionId );
if ( artifact != null )
{
ArtifactFilter filter = new ProjectArtifactExceptionFilter( artifactFilter, project.getArtifact() );
ArtifactResolutionResult result = artifactResolver.resolveTransitively( Collections.singleton( artifact ),
project.getArtifact(),
localRepository,
project.getRemoteArtifactRepositories(),
artifactMetadataSource, filter );
// create a child container for the extension
// TODO: this could surely be simpler/different on trunk with the new classworlds
PlexusContainer extensionContainer = getExtensionContainer();
if ( extensionContainer == null )
{
extensionContainer = container.createChildContainer( CONTAINER_NAME,
Collections.singletonList( artifact.getFile() ),
Collections.EMPTY_MAP );
}
for ( Iterator i = result.getArtifacts().iterator(); i.hasNext(); )
{
Artifact a = (Artifact) i.next();
a = project.replaceWithActiveArtifact( a );
getLogger().debug( "Adding to extension classpath: " + a.getFile() );
extensionContainer.addJarResource( a.getFile() );
}
}
}
| public void addExtension( Extension extension, MavenProject project, ArtifactRepository localRepository )
throws ArtifactResolutionException, PlexusContainerException, ArtifactNotFoundException
{
String extensionId = ArtifactUtils.versionlessKey( extension.getGroupId(), extension.getArtifactId() );
getLogger().debug( "Initialising extension: " + extensionId );
Artifact artifact = (Artifact) project.getExtensionArtifactMap().get( extensionId );
if ( artifact != null )
{
ArtifactFilter filter = new ProjectArtifactExceptionFilter( artifactFilter, project.getArtifact() );
ArtifactResolutionResult result = artifactResolver.resolveTransitively( Collections.singleton( artifact ),
project.getArtifact(),
localRepository,
project.getRemoteArtifactRepositories(),
artifactMetadataSource, filter );
// create a child container for the extension
// TODO: this could surely be simpler/different on trunk with the new classworlds
PlexusContainer extensionContainer = getExtensionContainer();
if ( extensionContainer == null )
{
extensionContainer =
container.createChildContainer( CONTAINER_NAME, Collections.EMPTY_LIST, Collections.EMPTY_MAP );
}
for ( Iterator i = result.getArtifacts().iterator(); i.hasNext(); )
{
Artifact a = (Artifact) i.next();
a = project.replaceWithActiveArtifact( a );
getLogger().debug( "Adding to extension classpath: " + a.getFile() );
extensionContainer.addJarResource( a.getFile() );
}
}
}
|
diff --git a/webapp/lib/src/main/java/com/github/podd/resources/UserRolesResourceImpl.java b/webapp/lib/src/main/java/com/github/podd/resources/UserRolesResourceImpl.java
index aa12661e..f9423230 100644
--- a/webapp/lib/src/main/java/com/github/podd/resources/UserRolesResourceImpl.java
+++ b/webapp/lib/src/main/java/com/github/podd/resources/UserRolesResourceImpl.java
@@ -1,339 +1,339 @@
/**
* PODD is an OWL ontology database used for scientific project management
*
* Copyright (C) 2009-2013 The University Of Queensland
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* 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, see <http://www.gnu.org/licenses/>.
*/
package com.github.podd.resources;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.openrdf.OpenRDFException;
import org.openrdf.model.Model;
import org.openrdf.model.URI;
import org.openrdf.model.impl.LinkedHashModel;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.Rio;
import org.openrdf.rio.UnsupportedRDFormatException;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.ByteArrayRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.Variant;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.security.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.ansell.restletutils.RestletUtilRole;
import com.github.ansell.restletutils.RestletUtilUser;
import com.github.ansell.restletutils.SesameRealmConstants;
import com.github.podd.restlet.PoddAction;
import com.github.podd.restlet.PoddSesameRealm;
import com.github.podd.restlet.PoddWebServiceApplication;
import com.github.podd.restlet.RestletUtils;
import com.github.podd.utils.PoddObjectLabel;
import com.github.podd.utils.PoddRdfConstants;
import com.github.podd.utils.PoddRoles;
import com.github.podd.utils.PoddUser;
import com.github.podd.utils.PoddWebConstants;
/**
*
* @author kutila
*/
public class UserRolesResourceImpl extends AbstractPoddResourceImpl
{
/**
* Handle an HTTP POST request submitting RDF data to update (i.e. map/unmap) a PoddUser's
* Roles. <br>
* <br>
* User authorization is checked for each Role to modify. The service proceeds to modify Role
* mappings in the Realm only if the current user has sufficient privileges carry out ALL the
* modifications.
*/
@Post("rdf|rj|json|ttl")
public Representation editUserRolesRdf(final Representation entity, final Variant variant) throws ResourceException
{
this.log.info("editUserRolesRdf");
final User user = this.getRequest().getClientInfo().getUser();
this.log.info("authenticated user: {}", user);
final String userIdentifier = this.getUserParameter();
this.log.info("editing Roles of user: {}", userIdentifier);
// - validate User whose Roles are to be edited
if(userIdentifier == null)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Did not specify user to edit Roles");
}
final PoddSesameRealm nextRealm = ((PoddWebServiceApplication)this.getApplication()).getRealm();
final RestletUtilUser restletUserToUpdate = nextRealm.findUser(userIdentifier);
if(restletUserToUpdate == null || !(restletUserToUpdate instanceof PoddUser))
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "User not found");
}
final PoddUser poddUser = (PoddUser)restletUserToUpdate;
// - retrieve 'delete' parameter
boolean isDelete = false;
final String deleteQueryParam = this.getQuery().getFirstValue(PoddWebConstants.KEY_DELETE, true);
if(deleteQueryParam != null)
{
isDelete = Boolean.valueOf(deleteQueryParam);
}
this.log.info(" edit Roles is a 'delete' = {}", isDelete);
Map<RestletUtilRole, Collection<URI>> rolesToEdit = null;
// parse input content to a Model
try (final InputStream inputStream = entity.getStream();)
{
final RDFFormat inputFormat =
Rio.getParserFormatForMIMEType(entity.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(inputStream, "", inputFormat);
rolesToEdit = PoddRoles.extractRoleMappingsUser(model);
}
catch(IOException | RDFParseException | UnsupportedRDFormatException e1)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not parse input");
}
if(rolesToEdit.isEmpty())
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Did not specify any role edits in body of request");
}
// - check authorization for each Role mapping
for(final RestletUtilRole role : rolesToEdit.keySet())
{
for(final URI mappedUri : rolesToEdit.get(role))
{
PoddAction action = PoddAction.PROJECT_ROLE_EDIT;
if(PoddRoles.getRepositoryRoles().contains(role))
{
action = PoddAction.REPOSITORY_ROLE_EDIT;
if(mappedUri != null)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
- "Unwanted optional Object URI found");
+ "Unwanted optional Object URI found for role: " + role);
}
}
this.checkAuthentication(action, mappedUri);
}
}
// - do the mapping/unmapping of Roles
for(final RestletUtilRole role : rolesToEdit.keySet())
{
for(final URI mappedUri : rolesToEdit.get(role))
{
if(isDelete)
{
nextRealm.unmap(poddUser, role.getRole(), mappedUri);
this.log.info(" User [{}] unmapped from Role [{}]", poddUser.getIdentifier(), role.getName());
}
else
{
nextRealm.map(poddUser, role.getRole(), mappedUri);
this.log.info(" User [{}] mapped to Role [{}], [{}]", poddUser.getIdentifier(), role.getName(),
mappedUri);
}
}
}
// - prepare response
final ByteArrayOutputStream output = new ByteArrayOutputStream(8096);
final RDFFormat outputFormat =
Rio.getWriterFormatForMIMEType(variant.getMediaType().getName(), RDFFormat.RDFXML);
try
{
Rio.write(Arrays.asList(PoddRdfConstants.VF.createStatement(poddUser.getUri(),
SesameRealmConstants.OAS_USERIDENTIFIER,
PoddRdfConstants.VF.createLiteral(poddUser.getIdentifier()))), output, outputFormat);
}
catch(final OpenRDFException e)
{
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not create response");
}
return new ByteArrayRepresentation(output.toByteArray(), MediaType.valueOf(outputFormat.getDefaultMIMEType()));
}
/**
* @param requestedUserIdentifier
* @return
*/
private PoddAction getAction(final String requestedUserIdentifier)
{
PoddAction action = PoddAction.OTHER_USER_EDIT;
if(this.getRequest().getClientInfo().isAuthenticated())
{
// Special case where they attached the user identifier and it was the same as the
// logged in user
if(requestedUserIdentifier.equals(this.getRequest().getClientInfo().getUser().getIdentifier()))
{
action = PoddAction.CURRENT_USER_EDIT;
}
}
return action;
}
/**
* Display the HTML page for User Role Management
*/
@Get(":html")
public Representation getRoleManagementPageHtml(final Variant variant) throws ResourceException
{
this.log.info("getRoleManagementHtml");
final String requestedUserIdentifier = this.getUserParameter();
PoddAction action = PoddAction.OTHER_USER_EDIT;
if(requestedUserIdentifier != null)
{
action = this.getAction(requestedUserIdentifier);
}
this.log.info("requesting role management for user: {}", requestedUserIdentifier);
this.checkAuthentication(action);
// completed checking authorization
final Map<String, Object> dataModel = RestletUtils.getBaseDataModel(this.getRequest());
dataModel.put("contentTemplate", "editUserRoles.html.ftl");
dataModel.put("pageTitle", "User Role Management");
dataModel.put("authenticatedUserIdentifier", this.getRequest().getClientInfo().getUser().getIdentifier());
final PoddSesameRealm realm = ((PoddWebServiceApplication)this.getApplication()).getRealm();
final PoddUser poddUser = (PoddUser)realm.findUser(requestedUserIdentifier);
if(poddUser == null)
{
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "User not found.");
}
else
{
dataModel.put("requestedUser", poddUser);
// - include all available PoddRoles
dataModel.put("repositoryRolesList", PoddRoles.getRepositoryRoles());
// - include user's current Roles and optional mapped objects
final List<Entry<RestletUtilRole, PoddObjectLabel>> roleList =
RestletUtils.getUsersRoles(realm, poddUser, this.getPoddArtifactManager());
dataModel.put("userRoleList", roleList);
}
// Output the base template, with contentTemplate from the dataModel defining the
// template to use for the content in the body of the page
return RestletUtils.getHtmlRepresentation(PoddWebConstants.PROPERTY_TEMPLATE_BASE, dataModel,
MediaType.TEXT_HTML, this.getPoddApplication().getTemplateConfiguration());
}
/**
* Display the HTML page for User Role Management
*/
@Get(":rdf|rj|json|ttl")
public Representation getRoleManagementRdf(final Variant variant) throws ResourceException
{
this.log.info("getRoleManagementHtml");
final String requestedUserIdentifier = this.getUserParameter();
PoddAction action = PoddAction.OTHER_USER_EDIT;
if(requestedUserIdentifier != null)
{
action = this.getAction(requestedUserIdentifier);
}
this.log.info("requesting role management for user: {}", requestedUserIdentifier);
this.checkAuthentication(action);
// completed checking authorization
final PoddSesameRealm realm = ((PoddWebServiceApplication)this.getApplication()).getRealm();
final PoddUser poddUser = (PoddUser)realm.findUser(requestedUserIdentifier);
if(poddUser == null)
{
throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, "User not found.");
}
else
{
// - include user's current Roles and optional mapped objects
final Map<RestletUtilRole, Collection<URI>> mappings = RestletUtils.getUsersRoles(realm, poddUser);
final Model results = new LinkedHashModel();
PoddRoles.dumpRoleMappingsUser(mappings, results);
// - prepare response
final ByteArrayOutputStream output = new ByteArrayOutputStream(8096);
final RDFFormat outputFormat =
Rio.getWriterFormatForMIMEType(variant.getMediaType().getName(), RDFFormat.RDFXML);
try
{
Rio.write(results, output, outputFormat);
}
catch(final OpenRDFException e)
{
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not create response");
}
return new ByteArrayRepresentation(output.toByteArray(), MediaType.valueOf(outputFormat
.getDefaultMIMEType()));
}
}
/**
* @return
* @throws ResourceException
*/
private String getUserParameter() throws ResourceException
{
String requestedUserIdentifier = this.getQuery().getFirstValue(PoddWebConstants.KEY_USER_IDENTIFIER, true);
if(requestedUserIdentifier == null)
{
if(this.getRequest().getClientInfo().isAuthenticated())
{
// Default to requesting information about the logged in user
requestedUserIdentifier = this.getRequest().getClientInfo().getUser().getIdentifier();
}
else
{
this.log.error("Did not specify user for roles resource and not logged in");
// no identifier specified.
// throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
// "Did not specify user");
}
}
return requestedUserIdentifier;
}
}
| true | true | public Representation editUserRolesRdf(final Representation entity, final Variant variant) throws ResourceException
{
this.log.info("editUserRolesRdf");
final User user = this.getRequest().getClientInfo().getUser();
this.log.info("authenticated user: {}", user);
final String userIdentifier = this.getUserParameter();
this.log.info("editing Roles of user: {}", userIdentifier);
// - validate User whose Roles are to be edited
if(userIdentifier == null)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Did not specify user to edit Roles");
}
final PoddSesameRealm nextRealm = ((PoddWebServiceApplication)this.getApplication()).getRealm();
final RestletUtilUser restletUserToUpdate = nextRealm.findUser(userIdentifier);
if(restletUserToUpdate == null || !(restletUserToUpdate instanceof PoddUser))
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "User not found");
}
final PoddUser poddUser = (PoddUser)restletUserToUpdate;
// - retrieve 'delete' parameter
boolean isDelete = false;
final String deleteQueryParam = this.getQuery().getFirstValue(PoddWebConstants.KEY_DELETE, true);
if(deleteQueryParam != null)
{
isDelete = Boolean.valueOf(deleteQueryParam);
}
this.log.info(" edit Roles is a 'delete' = {}", isDelete);
Map<RestletUtilRole, Collection<URI>> rolesToEdit = null;
// parse input content to a Model
try (final InputStream inputStream = entity.getStream();)
{
final RDFFormat inputFormat =
Rio.getParserFormatForMIMEType(entity.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(inputStream, "", inputFormat);
rolesToEdit = PoddRoles.extractRoleMappingsUser(model);
}
catch(IOException | RDFParseException | UnsupportedRDFormatException e1)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not parse input");
}
if(rolesToEdit.isEmpty())
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Did not specify any role edits in body of request");
}
// - check authorization for each Role mapping
for(final RestletUtilRole role : rolesToEdit.keySet())
{
for(final URI mappedUri : rolesToEdit.get(role))
{
PoddAction action = PoddAction.PROJECT_ROLE_EDIT;
if(PoddRoles.getRepositoryRoles().contains(role))
{
action = PoddAction.REPOSITORY_ROLE_EDIT;
if(mappedUri != null)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Unwanted optional Object URI found");
}
}
this.checkAuthentication(action, mappedUri);
}
}
// - do the mapping/unmapping of Roles
for(final RestletUtilRole role : rolesToEdit.keySet())
{
for(final URI mappedUri : rolesToEdit.get(role))
{
if(isDelete)
{
nextRealm.unmap(poddUser, role.getRole(), mappedUri);
this.log.info(" User [{}] unmapped from Role [{}]", poddUser.getIdentifier(), role.getName());
}
else
{
nextRealm.map(poddUser, role.getRole(), mappedUri);
this.log.info(" User [{}] mapped to Role [{}], [{}]", poddUser.getIdentifier(), role.getName(),
mappedUri);
}
}
}
// - prepare response
final ByteArrayOutputStream output = new ByteArrayOutputStream(8096);
final RDFFormat outputFormat =
Rio.getWriterFormatForMIMEType(variant.getMediaType().getName(), RDFFormat.RDFXML);
try
{
Rio.write(Arrays.asList(PoddRdfConstants.VF.createStatement(poddUser.getUri(),
SesameRealmConstants.OAS_USERIDENTIFIER,
PoddRdfConstants.VF.createLiteral(poddUser.getIdentifier()))), output, outputFormat);
}
catch(final OpenRDFException e)
{
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not create response");
}
return new ByteArrayRepresentation(output.toByteArray(), MediaType.valueOf(outputFormat.getDefaultMIMEType()));
}
| public Representation editUserRolesRdf(final Representation entity, final Variant variant) throws ResourceException
{
this.log.info("editUserRolesRdf");
final User user = this.getRequest().getClientInfo().getUser();
this.log.info("authenticated user: {}", user);
final String userIdentifier = this.getUserParameter();
this.log.info("editing Roles of user: {}", userIdentifier);
// - validate User whose Roles are to be edited
if(userIdentifier == null)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Did not specify user to edit Roles");
}
final PoddSesameRealm nextRealm = ((PoddWebServiceApplication)this.getApplication()).getRealm();
final RestletUtilUser restletUserToUpdate = nextRealm.findUser(userIdentifier);
if(restletUserToUpdate == null || !(restletUserToUpdate instanceof PoddUser))
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "User not found");
}
final PoddUser poddUser = (PoddUser)restletUserToUpdate;
// - retrieve 'delete' parameter
boolean isDelete = false;
final String deleteQueryParam = this.getQuery().getFirstValue(PoddWebConstants.KEY_DELETE, true);
if(deleteQueryParam != null)
{
isDelete = Boolean.valueOf(deleteQueryParam);
}
this.log.info(" edit Roles is a 'delete' = {}", isDelete);
Map<RestletUtilRole, Collection<URI>> rolesToEdit = null;
// parse input content to a Model
try (final InputStream inputStream = entity.getStream();)
{
final RDFFormat inputFormat =
Rio.getParserFormatForMIMEType(entity.getMediaType().getName(), RDFFormat.RDFXML);
final Model model = Rio.parse(inputStream, "", inputFormat);
rolesToEdit = PoddRoles.extractRoleMappingsUser(model);
}
catch(IOException | RDFParseException | UnsupportedRDFormatException e1)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not parse input");
}
if(rolesToEdit.isEmpty())
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Did not specify any role edits in body of request");
}
// - check authorization for each Role mapping
for(final RestletUtilRole role : rolesToEdit.keySet())
{
for(final URI mappedUri : rolesToEdit.get(role))
{
PoddAction action = PoddAction.PROJECT_ROLE_EDIT;
if(PoddRoles.getRepositoryRoles().contains(role))
{
action = PoddAction.REPOSITORY_ROLE_EDIT;
if(mappedUri != null)
{
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
"Unwanted optional Object URI found for role: " + role);
}
}
this.checkAuthentication(action, mappedUri);
}
}
// - do the mapping/unmapping of Roles
for(final RestletUtilRole role : rolesToEdit.keySet())
{
for(final URI mappedUri : rolesToEdit.get(role))
{
if(isDelete)
{
nextRealm.unmap(poddUser, role.getRole(), mappedUri);
this.log.info(" User [{}] unmapped from Role [{}]", poddUser.getIdentifier(), role.getName());
}
else
{
nextRealm.map(poddUser, role.getRole(), mappedUri);
this.log.info(" User [{}] mapped to Role [{}], [{}]", poddUser.getIdentifier(), role.getName(),
mappedUri);
}
}
}
// - prepare response
final ByteArrayOutputStream output = new ByteArrayOutputStream(8096);
final RDFFormat outputFormat =
Rio.getWriterFormatForMIMEType(variant.getMediaType().getName(), RDFFormat.RDFXML);
try
{
Rio.write(Arrays.asList(PoddRdfConstants.VF.createStatement(poddUser.getUri(),
SesameRealmConstants.OAS_USERIDENTIFIER,
PoddRdfConstants.VF.createLiteral(poddUser.getIdentifier()))), output, outputFormat);
}
catch(final OpenRDFException e)
{
throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not create response");
}
return new ByteArrayRepresentation(output.toByteArray(), MediaType.valueOf(outputFormat.getDefaultMIMEType()));
}
|
diff --git a/modules/org.restlet.test/src/org/restlet/test/security/HttpDigestTestCase.java b/modules/org.restlet.test/src/org/restlet/test/security/HttpDigestTestCase.java
index 95fe4380d..f9dfffa13 100644
--- a/modules/org.restlet.test/src/org/restlet/test/security/HttpDigestTestCase.java
+++ b/modules/org.restlet.test/src/org/restlet/test/security/HttpDigestTestCase.java
@@ -1,145 +1,145 @@
/**
* Copyright 2005-2010 Noelios Technologies.
*
* The contents of this file are subject to the terms of one of the following
* open source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 or EPL 1.0 (the
* "Licenses"). You can select the license that you prefer but you may not use
* this file except in compliance with one of these Licenses.
*
* You can obtain a copy of the LGPL 3.0 license at
* http://www.opensource.org/licenses/lgpl-3.0.html
*
* You can obtain a copy of the LGPL 2.1 license at
* http://www.opensource.org/licenses/lgpl-2.1.php
*
* You can obtain a copy of the CDDL 1.0 license at
* http://www.opensource.org/licenses/cddl1.php
*
* You can obtain a copy of the EPL 1.0 license at
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the Licenses for the specific language governing permissions and
* limitations under the Licenses.
*
* Alternatively, you can obtain a royalty free commercial license with less
* limitations, transferable or non-transferable, directly at
* http://www.noelios.com/products/restlet-engine
*
* Restlet is a registered trademark of Noelios Technologies.
*/
package org.restlet.test.security;
import junit.framework.TestCase;
import org.junit.Test;
import org.restlet.Application;
import org.restlet.Component;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.Server;
import org.restlet.data.ChallengeRequest;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Protocol;
import org.restlet.data.Status;
import org.restlet.ext.crypto.DigestAuthenticator;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.restlet.routing.Router;
import org.restlet.security.MapVerifier;
/**
* Restlet unit tests for HTTP DIGEST authentication client/server.
*
* @author Jerome Louvel
*/
public class HttpDigestTestCase extends TestCase {
private Component component;
private int port;
private static class MyApplication extends Application {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
DigestAuthenticator da = new DigestAuthenticator(getContext(),
"TestRealm", "mySecretServerKey");
MapVerifier mapVerifier = new MapVerifier();
mapVerifier.getLocalSecrets().put("scott", "tiger".toCharArray());
da.setWrappedVerifier(mapVerifier);
Restlet restlet = new Restlet(getContext()) {
@Override
public void handle(Request request, Response response) {
response.setEntity("hello, world", MediaType.TEXT_PLAIN);
}
};
da.setNext(restlet);
router.attach("/", da);
return router;
}
}
@Override
protected void setUp() throws Exception {
component = new Component();
Server server = component.getServers().add(Protocol.HTTP, 0);
Application application = new MyApplication();
component.getDefaultHost().attach(application);
component.start();
port = server.getEphemeralPort();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
component.stop();
super.tearDown();
}
@Test
public void testDigest() throws Exception {
ClientResource cr = new ClientResource("http://localhost:" + port + "/");
// Try unauthenticated request
try {
cr.get();
} catch (ResourceException re) {
assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, cr.getStatus());
ChallengeRequest c1 = null;
for (ChallengeRequest challengeRequest : cr.getChallengeRequests()) {
if (ChallengeScheme.HTTP_DIGEST.equals(challengeRequest
.getScheme())) {
c1 = challengeRequest;
break;
}
}
assertEquals(ChallengeScheme.HTTP_DIGEST, c1.getScheme());
String realm = c1.getRealm();
assertEquals("TestRealm", realm);
// String opaque = c1.getParameters().getFirstValue("opaque");
// String qop = c1.getParameters().getFirstValue("qop");
// assertEquals(null, opaque);
// assertEquals("auth", qop);
// Try authenticated request
cr.getRequest().setMethod(Method.GET);
- ChallengeResponse c2 = new ChallengeResponse(c1, cr.getRequest(),
- cr.getResponse(), "scott", "tiger".toCharArray());
+ ChallengeResponse c2 = new ChallengeResponse(c1, cr.getResponse(),
+ "scott", "tiger".toCharArray());
cr.setChallengeResponse(c2);
cr.get();
assertTrue(cr.getStatus().isSuccess());
}
}
}
| true | true | public void testDigest() throws Exception {
ClientResource cr = new ClientResource("http://localhost:" + port + "/");
// Try unauthenticated request
try {
cr.get();
} catch (ResourceException re) {
assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, cr.getStatus());
ChallengeRequest c1 = null;
for (ChallengeRequest challengeRequest : cr.getChallengeRequests()) {
if (ChallengeScheme.HTTP_DIGEST.equals(challengeRequest
.getScheme())) {
c1 = challengeRequest;
break;
}
}
assertEquals(ChallengeScheme.HTTP_DIGEST, c1.getScheme());
String realm = c1.getRealm();
assertEquals("TestRealm", realm);
// String opaque = c1.getParameters().getFirstValue("opaque");
// String qop = c1.getParameters().getFirstValue("qop");
// assertEquals(null, opaque);
// assertEquals("auth", qop);
// Try authenticated request
cr.getRequest().setMethod(Method.GET);
ChallengeResponse c2 = new ChallengeResponse(c1, cr.getRequest(),
cr.getResponse(), "scott", "tiger".toCharArray());
cr.setChallengeResponse(c2);
cr.get();
assertTrue(cr.getStatus().isSuccess());
}
}
| public void testDigest() throws Exception {
ClientResource cr = new ClientResource("http://localhost:" + port + "/");
// Try unauthenticated request
try {
cr.get();
} catch (ResourceException re) {
assertEquals(Status.CLIENT_ERROR_UNAUTHORIZED, cr.getStatus());
ChallengeRequest c1 = null;
for (ChallengeRequest challengeRequest : cr.getChallengeRequests()) {
if (ChallengeScheme.HTTP_DIGEST.equals(challengeRequest
.getScheme())) {
c1 = challengeRequest;
break;
}
}
assertEquals(ChallengeScheme.HTTP_DIGEST, c1.getScheme());
String realm = c1.getRealm();
assertEquals("TestRealm", realm);
// String opaque = c1.getParameters().getFirstValue("opaque");
// String qop = c1.getParameters().getFirstValue("qop");
// assertEquals(null, opaque);
// assertEquals("auth", qop);
// Try authenticated request
cr.getRequest().setMethod(Method.GET);
ChallengeResponse c2 = new ChallengeResponse(c1, cr.getResponse(),
"scott", "tiger".toCharArray());
cr.setChallengeResponse(c2);
cr.get();
assertTrue(cr.getStatus().isSuccess());
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dList.java b/src/main/java/net/aufdemrand/denizen/objects/dList.java
index 89fd437a0..e7eec9e57 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dList.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dList.java
@@ -1,549 +1,549 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.Utilities;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.ChatColor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class dList extends ArrayList<String> implements dObject {
final static Pattern flag_by_id =
Pattern.compile("(fl\\[((?:p@|n@)(.+?))\\]@|fl@)(.+)",
Pattern.CASE_INSENSITIVE);
final static Pattern split_char = Pattern.compile("\\|");
final static Pattern identifier = Pattern.compile("li@", Pattern.CASE_INSENSITIVE);
@Fetchable("li, fl")
public static dList valueOf(String string) {
if (string == null) return null;
///////
// Match @object format
// Make sure string matches what this interpreter can accept.
Matcher m;
m = flag_by_id.matcher(string);
if (m.matches()) {
FlagManager flag_manager = DenizenAPI.getCurrentInstance().flagManager();
try {
// Global
if (m.group(1).equalsIgnoreCase("fl@")) {
if (FlagManager.serverHasFlag(m.group(4)))
return new dList(flag_manager.getGlobalFlag(m.group(4)));
} else if (m.group(2).toLowerCase().startsWith("p@")) {
if (FlagManager.playerHasFlag(dPlayer.valueOf(m.group(3)), m.group(4)))
return new dList(flag_manager.getPlayerFlag(m.group(3), m.group(4)));
} else if (m.group(2).toLowerCase().startsWith("n@")) {
if (FlagManager.npcHasFlag(dNPC.valueOf(m.group(3)), m.group(4)))
return new dList(flag_manager.getNPCFlag(Integer.valueOf(m.group(3)), m.group(4)));
}
} catch (Exception e) {
dB.echoError("Flag '" + m.group() + "' could not be found!");
return null;
}
}
// Use value of string, which will seperate values by the use of a pipe '|'
return new dList(string.replaceFirst(identifier.pattern(), ""));
}
public static boolean matches(String arg) {
Matcher m;
m = flag_by_id.matcher(arg);
return m.matches() || arg.contains("|") || arg.toLowerCase().startsWith("li@");
}
/////////////
// Constructors
//////////
// A list of dObjects
public dList(ArrayList<? extends dObject> dObjectList) {
for (dObject obj : dObjectList)
add(obj.identify());
}
// Empty dList
public dList() { }
// A string of items, split by '|'
public dList(String items) {
if (items != null) addAll(Arrays.asList(split_char.split(items)));
}
// A List<String> of items
public dList(List<String> items) {
if (items != null) addAll(items);
}
// A List<String> of items, with a prefix
public dList(List<String> items, String prefix) {
for (String element : items) {
add(prefix + element);
}
}
// A Flag
public dList(FlagManager.Flag flag) {
this.flag = flag;
addAll(flag.values());
}
/////////////
// Instance Fields/Methods
//////////
private FlagManager.Flag flag = null;
//////////////////////////////
// DSCRIPT ARGUMENT METHODS
/////////////////////////
private String prefix = "List";
@Override
public String getPrefix() {
return prefix;
}
@Override
public dList setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return "<G>" + prefix + "='<Y>" + identify() + "<G>' ";
}
@Override
public boolean isUnique() {
return flag != null;
}
@Override
public String getObjectType() {
return "List";
}
public String[] toArray() {
List<String> list = new ArrayList<String>();
for (String string : this) {
list.add(string);
}
return list.toArray(new String[list.size()]);
}
// Return a list that includes only strings that match the values
// of an Enum array
public List<String> filter(Enum[] values) {
List<String> list = new ArrayList<String>();
for (String string : this) {
for (Enum value : values)
if (value.name().equalsIgnoreCase(string))
list.add(string);
}
if (!list.isEmpty())
return list;
else return null;
}
// Return a list that includes only elements belonging to a certain class
public List<dObject> filter(Class<? extends dObject> dClass) {
return filter(dClass, null);
}
public List<dObject> filter(Class<? extends dObject> dClass, ScriptEntry entry) {
List<dObject> results = new ArrayList<dObject>();
for (String element : this) {
try {
if (ObjectFetcher.checkMatch(dClass, element)) {
dObject object = (dClass.equals(dItem.class) && entry != null ?
dItem.valueOf(element, entry.getPlayer(), entry.getNPC()):
ObjectFetcher.getObjectFrom(dClass, element));
// Only add the object if it is not null, thus filtering useless
// list items
if (object != null) {
results.add(object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (results.size() > 0) return results;
else return null;
}
@Override
public String toString() {
return identify();
}
@Override
public String identify() {
if (flag != null)
return flag.toString();
if (isEmpty()) return "li@";
StringBuilder dScriptArg = new StringBuilder();
dScriptArg.append("li@");
for (String item : this) {
dScriptArg.append(item);
// Items are separated by the | character in dLists
dScriptArg.append('|');
}
return dScriptArg.toString().substring(0, dScriptArg.length() - 1);
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <[email protected]_cslist>
// @returns Element
// @description
// returns the list in a cleaner format, separated by commas.
// -->
if (attribute.startsWith("ascslist")
|| attribute.startsWith("as_cslist")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this) {
dScriptArg.append(item);
// Insert a comma and space after each item
dScriptArg.append(", ");
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the list in a human-readable format.
// EG: li@n@3|p@bob|potato returns 'GuardNPC, bob, and potato'
// -->
if (attribute.startsWith("formatted")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (int n = 0; n < this.size(); n++) {
if (dNPC.matches(get(n))) {
dNPC gotten = dNPC.valueOf(get(n));
if (gotten != null) {
dScriptArg.append(gotten.getName());
}
else {
dScriptArg.append(get(n).replaceAll("\\w\\w?@", ""));
}
}
else {
dScriptArg.append(get(n).replaceAll("\\w\\w?@", ""));
}
if (n == this.size() - 2) {
dScriptArg.append(n == 0 ? " and ": ", and ");
}
else {
dScriptArg.append(", ");
}
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// returns the size of the list.
// -->
if (attribute.startsWith("size"))
return new Element(size()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_empty>
// @returns Element(Boolean)
// @description
// returns whether the list is empty.
// -->
if (attribute.startsWith("is_empty"))
return new Element(isEmpty()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_string>
// @returns Element
// @description
// returns each item in the list as a single 'String'.
// -->
if (attribute.startsWith("asstring")
|| attribute.startsWith("as_string")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this) {
dScriptArg.append(item);
// Insert space between items.
dScriptArg.append(' ');
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][...|...]>
// @returns dList
// @description
// returns a new dList excluding the items specified.
// -->
if (attribute.startsWith("exclude") &&
attribute.hasContext(1)) {
String[] exclusions = split_char.split(attribute.getContext(1));
// Create a new dList that will contain the exclusions
dList list = new dList(this);
// Iterate through
for (String exclusion : exclusions)
for (int i = 0;i < list.size();i++)
if (list.get(i).equalsIgnoreCase(exclusion))
list.remove(i--);
// Return the modified list
return list.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][#]>
// @returns Element
// @description
- // returns an Element of the value specified by the supplied context.
+ // returns an element of the value specified by the supplied context.
// -->
if (attribute.startsWith("get") &&
attribute.hasContext(1)) {
if (isEmpty()) return "null";
int index = attribute.getIntContext(1);
- if (index > size()) index = size();
+ if (index > size()) return "null";
if (index < 1) index = 1;
attribute = attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][#].to[#]>
// @returns dList
// @description
// returns all elements in the range from the first index to the second.
// -->
if (attribute.startsWith("to") &&
attribute.hasContext(1)) {
int index2 = attribute.getIntContext(1);
if (index2 > size()) index2 = size();
if (index2 < 1) index2 = 1;
String item = "";
for (int i = index; i <= index2; i++) {
item += get(i - 1) + (i < index2 ? "|": "");
}
return new dList(item).getAttribute(attribute.fulfill(1));
}
else {
String item;
item = get(index - 1);
return new Element(item).getAttribute(attribute);
}
}
// <--[tag]
// @attribute <[email protected][<element>]>
// @returns Element(Number)
// @description
// returns the numbered location of an element within a list,
// or -1 if the list does not contain that item.
// -->
if (attribute.startsWith("find") &&
attribute.hasContext(1)) {
for (int i = 0; i < size(); i++) {
if (get(i).equalsIgnoreCase(attribute.getContext(1)))
return new Element(i + 1).getAttribute(attribute.fulfill(1));
}
for (int i = 0; i < size(); i++) {
if (get(i).toUpperCase().contains(attribute.getContext(1).toUpperCase()))
return new Element(i + 1).getAttribute(attribute.fulfill(1));
}
return new Element(-1).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the last element in the list.
// -->
if (attribute.startsWith("last")) {
return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("contains")) {
if (attribute.hasContext(1)) {
boolean state = false;
for (String element : this) {
if (element.equalsIgnoreCase(attribute.getContext(1))) {
state = true;
break;
}
}
return new Element(state).getAttribute(attribute.fulfill(1));
}
}
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("identify")) {
return new Element(identify())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("type")) {
return new Element(getObjectType())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][#]>
// @returns Element
// @description
// Gets a random item in the list and returns it as an Element.
// Optionally, add [#] to get a list of multiple randomly chosen elements.
// -->
if (attribute.startsWith("random")) {
if (!this.isEmpty()) {
if (attribute.hasContext(1)) {
int count = Integer.valueOf(attribute.getContext(1));
int times = 0;
ArrayList<String> available = new ArrayList<String>();
available.addAll(this);
dList toReturn = new dList();
while (!available.isEmpty() && times < count) {
int random = Utilities.getRandom().nextInt(available.size());
toReturn.add(available.get(random));
available.remove(random);
times++;
}
return toReturn.getAttribute(attribute.fulfill(1));
}
else {
return new Element(this.get(Utilities.getRandom().nextInt(this.size())))
.getAttribute(attribute.fulfill(1));
}
}
}
// FLAG Specific Attributes
// Note: is_expired attribute is handled in player/npc/server
// since expired flags return 'null'
// <--[tag]
// @attribute <fl@flag_name.is_expired>
// @returns Element(boolean)
// @description
// returns true of the flag is expired or does not exist, false if it
// is not yet expired, or has no expiration.
// -->
// <--[tag]
// @attribute <fl@flag_name.expiration>
// @returns Duration
// @description
// returns a Duration of the time remaining on the flag, if it
// has an expiration.
// -->
if (flag != null && attribute.startsWith("expiration")) {
return flag.expiration()
.getAttribute(attribute.fulfill(1));
}
// Need this attribute (for flags) since they return the last
// element of the list, unless '.as_list' is specified.
// <--[tag]
// @attribute <fl@flag_name.as_list>
// @returns dList
// @description
// returns a dList containing the items in the flag.
// -->
if (flag != null && (attribute.startsWith("as_list")
|| attribute.startsWith("aslist")))
return new dList(this).getAttribute(attribute.fulfill(1));
// If this is a flag, return the last element (this is how it has always worked...)
// Use as_list to return a list representation of the flag.
// If this is NOT a flag, but instead a normal dList, return an element
// with dList's identify() value.
return (flag != null
? new Element(flag.getLast().asString()).getAttribute(attribute)
: new Element(identify()).getAttribute(attribute));
}
}
| false | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <[email protected]_cslist>
// @returns Element
// @description
// returns the list in a cleaner format, separated by commas.
// -->
if (attribute.startsWith("ascslist")
|| attribute.startsWith("as_cslist")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this) {
dScriptArg.append(item);
// Insert a comma and space after each item
dScriptArg.append(", ");
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the list in a human-readable format.
// EG: li@n@3|p@bob|potato returns 'GuardNPC, bob, and potato'
// -->
if (attribute.startsWith("formatted")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (int n = 0; n < this.size(); n++) {
if (dNPC.matches(get(n))) {
dNPC gotten = dNPC.valueOf(get(n));
if (gotten != null) {
dScriptArg.append(gotten.getName());
}
else {
dScriptArg.append(get(n).replaceAll("\\w\\w?@", ""));
}
}
else {
dScriptArg.append(get(n).replaceAll("\\w\\w?@", ""));
}
if (n == this.size() - 2) {
dScriptArg.append(n == 0 ? " and ": ", and ");
}
else {
dScriptArg.append(", ");
}
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// returns the size of the list.
// -->
if (attribute.startsWith("size"))
return new Element(size()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_empty>
// @returns Element(Boolean)
// @description
// returns whether the list is empty.
// -->
if (attribute.startsWith("is_empty"))
return new Element(isEmpty()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_string>
// @returns Element
// @description
// returns each item in the list as a single 'String'.
// -->
if (attribute.startsWith("asstring")
|| attribute.startsWith("as_string")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this) {
dScriptArg.append(item);
// Insert space between items.
dScriptArg.append(' ');
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][...|...]>
// @returns dList
// @description
// returns a new dList excluding the items specified.
// -->
if (attribute.startsWith("exclude") &&
attribute.hasContext(1)) {
String[] exclusions = split_char.split(attribute.getContext(1));
// Create a new dList that will contain the exclusions
dList list = new dList(this);
// Iterate through
for (String exclusion : exclusions)
for (int i = 0;i < list.size();i++)
if (list.get(i).equalsIgnoreCase(exclusion))
list.remove(i--);
// Return the modified list
return list.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][#]>
// @returns Element
// @description
// returns an Element of the value specified by the supplied context.
// -->
if (attribute.startsWith("get") &&
attribute.hasContext(1)) {
if (isEmpty()) return "null";
int index = attribute.getIntContext(1);
if (index > size()) index = size();
if (index < 1) index = 1;
attribute = attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][#].to[#]>
// @returns dList
// @description
// returns all elements in the range from the first index to the second.
// -->
if (attribute.startsWith("to") &&
attribute.hasContext(1)) {
int index2 = attribute.getIntContext(1);
if (index2 > size()) index2 = size();
if (index2 < 1) index2 = 1;
String item = "";
for (int i = index; i <= index2; i++) {
item += get(i - 1) + (i < index2 ? "|": "");
}
return new dList(item).getAttribute(attribute.fulfill(1));
}
else {
String item;
item = get(index - 1);
return new Element(item).getAttribute(attribute);
}
}
// <--[tag]
// @attribute <[email protected][<element>]>
// @returns Element(Number)
// @description
// returns the numbered location of an element within a list,
// or -1 if the list does not contain that item.
// -->
if (attribute.startsWith("find") &&
attribute.hasContext(1)) {
for (int i = 0; i < size(); i++) {
if (get(i).equalsIgnoreCase(attribute.getContext(1)))
return new Element(i + 1).getAttribute(attribute.fulfill(1));
}
for (int i = 0; i < size(); i++) {
if (get(i).toUpperCase().contains(attribute.getContext(1).toUpperCase()))
return new Element(i + 1).getAttribute(attribute.fulfill(1));
}
return new Element(-1).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the last element in the list.
// -->
if (attribute.startsWith("last")) {
return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("contains")) {
if (attribute.hasContext(1)) {
boolean state = false;
for (String element : this) {
if (element.equalsIgnoreCase(attribute.getContext(1))) {
state = true;
break;
}
}
return new Element(state).getAttribute(attribute.fulfill(1));
}
}
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("identify")) {
return new Element(identify())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("type")) {
return new Element(getObjectType())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][#]>
// @returns Element
// @description
// Gets a random item in the list and returns it as an Element.
// Optionally, add [#] to get a list of multiple randomly chosen elements.
// -->
if (attribute.startsWith("random")) {
if (!this.isEmpty()) {
if (attribute.hasContext(1)) {
int count = Integer.valueOf(attribute.getContext(1));
int times = 0;
ArrayList<String> available = new ArrayList<String>();
available.addAll(this);
dList toReturn = new dList();
while (!available.isEmpty() && times < count) {
int random = Utilities.getRandom().nextInt(available.size());
toReturn.add(available.get(random));
available.remove(random);
times++;
}
return toReturn.getAttribute(attribute.fulfill(1));
}
else {
return new Element(this.get(Utilities.getRandom().nextInt(this.size())))
.getAttribute(attribute.fulfill(1));
}
}
}
// FLAG Specific Attributes
// Note: is_expired attribute is handled in player/npc/server
// since expired flags return 'null'
// <--[tag]
// @attribute <fl@flag_name.is_expired>
// @returns Element(boolean)
// @description
// returns true of the flag is expired or does not exist, false if it
// is not yet expired, or has no expiration.
// -->
// <--[tag]
// @attribute <fl@flag_name.expiration>
// @returns Duration
// @description
// returns a Duration of the time remaining on the flag, if it
// has an expiration.
// -->
if (flag != null && attribute.startsWith("expiration")) {
return flag.expiration()
.getAttribute(attribute.fulfill(1));
}
// Need this attribute (for flags) since they return the last
// element of the list, unless '.as_list' is specified.
// <--[tag]
// @attribute <fl@flag_name.as_list>
// @returns dList
// @description
// returns a dList containing the items in the flag.
// -->
if (flag != null && (attribute.startsWith("as_list")
|| attribute.startsWith("aslist")))
return new dList(this).getAttribute(attribute.fulfill(1));
// If this is a flag, return the last element (this is how it has always worked...)
// Use as_list to return a list representation of the flag.
// If this is NOT a flag, but instead a normal dList, return an element
// with dList's identify() value.
return (flag != null
? new Element(flag.getLast().asString()).getAttribute(attribute)
: new Element(identify()).getAttribute(attribute));
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <[email protected]_cslist>
// @returns Element
// @description
// returns the list in a cleaner format, separated by commas.
// -->
if (attribute.startsWith("ascslist")
|| attribute.startsWith("as_cslist")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this) {
dScriptArg.append(item);
// Insert a comma and space after each item
dScriptArg.append(", ");
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the list in a human-readable format.
// EG: li@n@3|p@bob|potato returns 'GuardNPC, bob, and potato'
// -->
if (attribute.startsWith("formatted")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (int n = 0; n < this.size(); n++) {
if (dNPC.matches(get(n))) {
dNPC gotten = dNPC.valueOf(get(n));
if (gotten != null) {
dScriptArg.append(gotten.getName());
}
else {
dScriptArg.append(get(n).replaceAll("\\w\\w?@", ""));
}
}
else {
dScriptArg.append(get(n).replaceAll("\\w\\w?@", ""));
}
if (n == this.size() - 2) {
dScriptArg.append(n == 0 ? " and ": ", and ");
}
else {
dScriptArg.append(", ");
}
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 2))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Number)
// @description
// returns the size of the list.
// -->
if (attribute.startsWith("size"))
return new Element(size()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_empty>
// @returns Element(Boolean)
// @description
// returns whether the list is empty.
// -->
if (attribute.startsWith("is_empty"))
return new Element(isEmpty()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_string>
// @returns Element
// @description
// returns each item in the list as a single 'String'.
// -->
if (attribute.startsWith("asstring")
|| attribute.startsWith("as_string")) {
if (isEmpty()) return new Element("").getAttribute(attribute.fulfill(1));
StringBuilder dScriptArg = new StringBuilder();
for (String item : this) {
dScriptArg.append(item);
// Insert space between items.
dScriptArg.append(' ');
}
return new Element(dScriptArg.toString().substring(0, dScriptArg.length() - 1))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][...|...]>
// @returns dList
// @description
// returns a new dList excluding the items specified.
// -->
if (attribute.startsWith("exclude") &&
attribute.hasContext(1)) {
String[] exclusions = split_char.split(attribute.getContext(1));
// Create a new dList that will contain the exclusions
dList list = new dList(this);
// Iterate through
for (String exclusion : exclusions)
for (int i = 0;i < list.size();i++)
if (list.get(i).equalsIgnoreCase(exclusion))
list.remove(i--);
// Return the modified list
return list.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][#]>
// @returns Element
// @description
// returns an element of the value specified by the supplied context.
// -->
if (attribute.startsWith("get") &&
attribute.hasContext(1)) {
if (isEmpty()) return "null";
int index = attribute.getIntContext(1);
if (index > size()) return "null";
if (index < 1) index = 1;
attribute = attribute.fulfill(1);
// <--[tag]
// @attribute <[email protected][#].to[#]>
// @returns dList
// @description
// returns all elements in the range from the first index to the second.
// -->
if (attribute.startsWith("to") &&
attribute.hasContext(1)) {
int index2 = attribute.getIntContext(1);
if (index2 > size()) index2 = size();
if (index2 < 1) index2 = 1;
String item = "";
for (int i = index; i <= index2; i++) {
item += get(i - 1) + (i < index2 ? "|": "");
}
return new dList(item).getAttribute(attribute.fulfill(1));
}
else {
String item;
item = get(index - 1);
return new Element(item).getAttribute(attribute);
}
}
// <--[tag]
// @attribute <[email protected][<element>]>
// @returns Element(Number)
// @description
// returns the numbered location of an element within a list,
// or -1 if the list does not contain that item.
// -->
if (attribute.startsWith("find") &&
attribute.hasContext(1)) {
for (int i = 0; i < size(); i++) {
if (get(i).equalsIgnoreCase(attribute.getContext(1)))
return new Element(i + 1).getAttribute(attribute.fulfill(1));
}
for (int i = 0; i < size(); i++) {
if (get(i).toUpperCase().contains(attribute.getContext(1).toUpperCase()))
return new Element(i + 1).getAttribute(attribute.fulfill(1));
}
return new Element(-1).getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the last element in the list.
// -->
if (attribute.startsWith("last")) {
return new Element(get(size() - 1)).getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("contains")) {
if (attribute.hasContext(1)) {
boolean state = false;
for (String element : this) {
if (element.equalsIgnoreCase(attribute.getContext(1))) {
state = true;
break;
}
}
return new Element(state).getAttribute(attribute.fulfill(1));
}
}
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("identify")) {
return new Element(identify())
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("type")) {
return new Element(getObjectType())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][#]>
// @returns Element
// @description
// Gets a random item in the list and returns it as an Element.
// Optionally, add [#] to get a list of multiple randomly chosen elements.
// -->
if (attribute.startsWith("random")) {
if (!this.isEmpty()) {
if (attribute.hasContext(1)) {
int count = Integer.valueOf(attribute.getContext(1));
int times = 0;
ArrayList<String> available = new ArrayList<String>();
available.addAll(this);
dList toReturn = new dList();
while (!available.isEmpty() && times < count) {
int random = Utilities.getRandom().nextInt(available.size());
toReturn.add(available.get(random));
available.remove(random);
times++;
}
return toReturn.getAttribute(attribute.fulfill(1));
}
else {
return new Element(this.get(Utilities.getRandom().nextInt(this.size())))
.getAttribute(attribute.fulfill(1));
}
}
}
// FLAG Specific Attributes
// Note: is_expired attribute is handled in player/npc/server
// since expired flags return 'null'
// <--[tag]
// @attribute <fl@flag_name.is_expired>
// @returns Element(boolean)
// @description
// returns true of the flag is expired or does not exist, false if it
// is not yet expired, or has no expiration.
// -->
// <--[tag]
// @attribute <fl@flag_name.expiration>
// @returns Duration
// @description
// returns a Duration of the time remaining on the flag, if it
// has an expiration.
// -->
if (flag != null && attribute.startsWith("expiration")) {
return flag.expiration()
.getAttribute(attribute.fulfill(1));
}
// Need this attribute (for flags) since they return the last
// element of the list, unless '.as_list' is specified.
// <--[tag]
// @attribute <fl@flag_name.as_list>
// @returns dList
// @description
// returns a dList containing the items in the flag.
// -->
if (flag != null && (attribute.startsWith("as_list")
|| attribute.startsWith("aslist")))
return new dList(this).getAttribute(attribute.fulfill(1));
// If this is a flag, return the last element (this is how it has always worked...)
// Use as_list to return a list representation of the flag.
// If this is NOT a flag, but instead a normal dList, return an element
// with dList's identify() value.
return (flag != null
? new Element(flag.getLast().asString()).getAttribute(attribute)
: new Element(identify()).getAttribute(attribute));
}
|
diff --git a/itest/itest-osgi/src/test/java/org/ops4j/pax/shiro/itest/osgi/Jetty9FacesBundleTest.java b/itest/itest-osgi/src/test/java/org/ops4j/pax/shiro/itest/osgi/Jetty9FacesBundleTest.java
index a077110..13301c1 100644
--- a/itest/itest-osgi/src/test/java/org/ops4j/pax/shiro/itest/osgi/Jetty9FacesBundleTest.java
+++ b/itest/itest-osgi/src/test/java/org/ops4j/pax/shiro/itest/osgi/Jetty9FacesBundleTest.java
@@ -1,212 +1,214 @@
/*
* Copyright 2013 Harald Wellmann
*
* 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.ops4j.pax.shiro.itest.osgi;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.ops4j.pax.exam.CoreOptions.bundle;
import static org.ops4j.pax.exam.CoreOptions.frameworkProperty;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.options;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import java.io.IOException;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.PaxExamServer;
import org.ops4j.pax.exam.util.PathUtils;
/**
* Tests shiro-faces in OSGi mode.
* <p>
* Some tests currently fail due to incomplete JSF support in Jetty in OSGi mode.
* Tags from other bundles do not get recognized and are rendered verbatim.
*
* @author Harald Wellmann
*
*/
public class Jetty9FacesBundleTest {
@ClassRule
public static PaxExamServer exam = new PaxExamServer();
@Rule
public ExpectedException thrown = ExpectedException.none();
private WebDriver webDriver = new HtmlUnitDriver();
private String port = System.getProperty("pax.shiro.itest.http.port", "18181");
@Configuration
public Option[] configuration() {
return options(
frameworkProperty("felix.bootdelegation.implicit").value("false"),
frameworkProperty("osgi.console").value("6666"),
frameworkProperty("org.osgi.service.http.port").value(port),
frameworkProperty("osgi.compatibility.bootdelegation").value("true"),
systemProperty("jetty.home.bundle").value("org.eclipse.jetty.osgi.boot"),
systemProperty("jetty.port").value("18181"),
systemProperty("org.eclipse.jetty.osgi.tldbundles").value(
"org.apache.myfaces.core.impl"),
// Set logback configuration via system property.
// This way, both the driver and the container use the same configuration
systemProperty("logback.configurationFile").value(
"file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
mavenBundle("org.slf4j", "slf4j-api", "1.6.4"),
mavenBundle("org.slf4j", "jcl-over-slf4j", "1.6.4"),
mavenBundle("ch.qos.logback", "logback-classic", "1.0.0"),
mavenBundle("ch.qos.logback", "logback-core", "1.0.0"),
mavenBundle("org.eclipse.jetty.osgi", "jetty-osgi-boot").versionAsInProject(),
mavenBundle("org.eclipse.jetty.osgi", "jetty-osgi-boot-jsp").versionAsInProject()
.noStart(),
mavenBundle("org.eclipse.jetty", "jetty-deploy").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-http").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-io").versionAsInProject(),
+ mavenBundle("org.eclipse.jetty", "jetty-jndi").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-security").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-server").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-servlet").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-xml").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-util").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-webapp").versionAsInProject(),
mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_3.0_spec").version("1.0"),
mavenBundle("org.osgi", "org.osgi.compendium", "4.3.1"),
mavenBundle("org.eclipse.jetty.orbit", "com.sun.el").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "javax.el", "2.2.0.v201303151357"),
+ mavenBundle("org.eclipse.jetty.orbit", "javax.mail.glassfish", "1.4.1.v201005082020"),
mavenBundle("org.eclipse.jetty.orbit", "javax.servlet.jsp").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "javax.servlet.jsp.jstl").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "org.apache.jasper.glassfish")
.versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "org.apache.taglibs.standard.glassfish",
"1.2.0.v201112081803"),
mavenBundle("org.eclipse.jetty.orbit", "org.eclipse.jdt.core", "3.8.2.v20130121"),
mavenBundle("commons-beanutils", "commons-beanutils", "1.8.3"),
mavenBundle("commons-collections", "commons-collections", "3.2.1"),
mavenBundle("org.apache.shiro", "shiro-web", "1.2.2"),
mavenBundle("org.apache.shiro", "shiro-core", "1.2.2"),
// mavenBundle("org.apache.myfaces.core", "myfaces-impl", "2.1.12"),
mavenBundle("org.apache.myfaces.core", "myfaces-api", "2.1.12"),
bundle("reference:file:" + PathUtils.getBaseDir() + "/target/myfaces-impl.jar"),
mavenBundle("org.apache.geronimo.specs", "geronimo-annotation_1.1_spec", "1.0.1"),
mavenBundle("org.apache.geronimo.specs", "geronimo-validation_1.0_spec", "1.1"),
mavenBundle("commons-codec", "commons-codec", "1.7"),
mavenBundle("commons-digester", "commons-digester", "1.8.1"),
mavenBundle("org.ops4j.pax.shiro.", "pax-shiro-faces", "0.1.0-SNAPSHOT"),
mavenBundle("org.ops4j.pax.shiro.samples", "sample-faces-bundle", "0.1.0-SNAPSHOT")
);
}
@Before
public void logOut() throws IOException, InterruptedException {
// wait for server to come up
Thread.sleep(2000);
// Make sure we are logged out
webDriver.get(getBaseUri());
try {
webDriver.findElement(By.partialLinkText("Log out")).click();
}
catch (NoSuchElementException e) {
// Ignore
}
}
@Test
public void logIn() {
webDriver.get(getBaseUri() + "login.jsf");
webDriver.findElement(By.name("login:username")).sendKeys("root");
webDriver.findElement(By.name("login:password")).sendKeys("secret");
webDriver.findElement(By.name("login:submit")).click();
// This'll throw an expection if not logged in
webDriver.findElement(By.partialLinkText("Log out"));
}
@Test
public void shouldRememberMeOnClientRestart() throws Exception {
webDriver.get(getBaseUri() + "login.jsf");
webDriver.findElement(By.name("login:username")).sendKeys("root");
webDriver.findElement(By.name("login:password")).sendKeys("secret");
webDriver.findElement(By.name("login:rememberMe")).click();
webDriver.findElement(By.name("login:submit")).click();
Cookie cookie = webDriver.manage().getCookieNamed("rememberMe");
webDriver.close();
webDriver = new HtmlUnitDriver();
webDriver.get(getBaseUri());
webDriver.manage().addCookie(cookie);
webDriver.get(getBaseUri());
webDriver.findElement(By.partialLinkText("Log out"));
webDriver.findElement(By.partialLinkText("account")).click();
// login page should be shown again - user remembered but not authenticated
webDriver.findElement(By.name("login:username"));
}
@Test
@Ignore("missing JSF support in Jetty OSGi")
public void shouldNotRememberMeWithoutCookie() throws Exception {
webDriver.get(getBaseUri() + "login.jsf");
webDriver.findElement(By.name("login:username")).sendKeys("root");
webDriver.findElement(By.name("login:password")).sendKeys("secret");
webDriver.findElement(By.name("login:rememberMe")).click();
webDriver.findElement(By.name("login:submit")).click();
Cookie cookie = webDriver.manage().getCookieNamed("rememberMe");
assertThat(cookie, is(notNullValue()));
webDriver.close();
webDriver = new HtmlUnitDriver();
webDriver.get(getBaseUri());
thrown.expect(NoSuchElementException.class);
webDriver.findElement(By.partialLinkText("Log out"));
}
private String getBaseUri() {
return "http://localhost:" + port + "/sample-faces-bundle/";
}
}
| false | true | public Option[] configuration() {
return options(
frameworkProperty("felix.bootdelegation.implicit").value("false"),
frameworkProperty("osgi.console").value("6666"),
frameworkProperty("org.osgi.service.http.port").value(port),
frameworkProperty("osgi.compatibility.bootdelegation").value("true"),
systemProperty("jetty.home.bundle").value("org.eclipse.jetty.osgi.boot"),
systemProperty("jetty.port").value("18181"),
systemProperty("org.eclipse.jetty.osgi.tldbundles").value(
"org.apache.myfaces.core.impl"),
// Set logback configuration via system property.
// This way, both the driver and the container use the same configuration
systemProperty("logback.configurationFile").value(
"file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
mavenBundle("org.slf4j", "slf4j-api", "1.6.4"),
mavenBundle("org.slf4j", "jcl-over-slf4j", "1.6.4"),
mavenBundle("ch.qos.logback", "logback-classic", "1.0.0"),
mavenBundle("ch.qos.logback", "logback-core", "1.0.0"),
mavenBundle("org.eclipse.jetty.osgi", "jetty-osgi-boot").versionAsInProject(),
mavenBundle("org.eclipse.jetty.osgi", "jetty-osgi-boot-jsp").versionAsInProject()
.noStart(),
mavenBundle("org.eclipse.jetty", "jetty-deploy").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-http").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-io").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-security").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-server").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-servlet").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-xml").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-util").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-webapp").versionAsInProject(),
mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_3.0_spec").version("1.0"),
mavenBundle("org.osgi", "org.osgi.compendium", "4.3.1"),
mavenBundle("org.eclipse.jetty.orbit", "com.sun.el").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "javax.el", "2.2.0.v201303151357"),
mavenBundle("org.eclipse.jetty.orbit", "javax.servlet.jsp").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "javax.servlet.jsp.jstl").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "org.apache.jasper.glassfish")
.versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "org.apache.taglibs.standard.glassfish",
"1.2.0.v201112081803"),
mavenBundle("org.eclipse.jetty.orbit", "org.eclipse.jdt.core", "3.8.2.v20130121"),
mavenBundle("commons-beanutils", "commons-beanutils", "1.8.3"),
mavenBundle("commons-collections", "commons-collections", "3.2.1"),
mavenBundle("org.apache.shiro", "shiro-web", "1.2.2"),
mavenBundle("org.apache.shiro", "shiro-core", "1.2.2"),
// mavenBundle("org.apache.myfaces.core", "myfaces-impl", "2.1.12"),
mavenBundle("org.apache.myfaces.core", "myfaces-api", "2.1.12"),
bundle("reference:file:" + PathUtils.getBaseDir() + "/target/myfaces-impl.jar"),
mavenBundle("org.apache.geronimo.specs", "geronimo-annotation_1.1_spec", "1.0.1"),
mavenBundle("org.apache.geronimo.specs", "geronimo-validation_1.0_spec", "1.1"),
mavenBundle("commons-codec", "commons-codec", "1.7"),
mavenBundle("commons-digester", "commons-digester", "1.8.1"),
mavenBundle("org.ops4j.pax.shiro.", "pax-shiro-faces", "0.1.0-SNAPSHOT"),
mavenBundle("org.ops4j.pax.shiro.samples", "sample-faces-bundle", "0.1.0-SNAPSHOT")
);
}
| public Option[] configuration() {
return options(
frameworkProperty("felix.bootdelegation.implicit").value("false"),
frameworkProperty("osgi.console").value("6666"),
frameworkProperty("org.osgi.service.http.port").value(port),
frameworkProperty("osgi.compatibility.bootdelegation").value("true"),
systemProperty("jetty.home.bundle").value("org.eclipse.jetty.osgi.boot"),
systemProperty("jetty.port").value("18181"),
systemProperty("org.eclipse.jetty.osgi.tldbundles").value(
"org.apache.myfaces.core.impl"),
// Set logback configuration via system property.
// This way, both the driver and the container use the same configuration
systemProperty("logback.configurationFile").value(
"file:" + PathUtils.getBaseDir() + "/src/test/resources/logback.xml"),
mavenBundle("org.slf4j", "slf4j-api", "1.6.4"),
mavenBundle("org.slf4j", "jcl-over-slf4j", "1.6.4"),
mavenBundle("ch.qos.logback", "logback-classic", "1.0.0"),
mavenBundle("ch.qos.logback", "logback-core", "1.0.0"),
mavenBundle("org.eclipse.jetty.osgi", "jetty-osgi-boot").versionAsInProject(),
mavenBundle("org.eclipse.jetty.osgi", "jetty-osgi-boot-jsp").versionAsInProject()
.noStart(),
mavenBundle("org.eclipse.jetty", "jetty-deploy").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-http").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-io").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-jndi").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-security").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-server").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-servlet").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-xml").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-util").versionAsInProject(),
mavenBundle("org.eclipse.jetty", "jetty-webapp").versionAsInProject(),
mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_3.0_spec").version("1.0"),
mavenBundle("org.osgi", "org.osgi.compendium", "4.3.1"),
mavenBundle("org.eclipse.jetty.orbit", "com.sun.el").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "javax.el", "2.2.0.v201303151357"),
mavenBundle("org.eclipse.jetty.orbit", "javax.mail.glassfish", "1.4.1.v201005082020"),
mavenBundle("org.eclipse.jetty.orbit", "javax.servlet.jsp").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "javax.servlet.jsp.jstl").versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "org.apache.jasper.glassfish")
.versionAsInProject(),
mavenBundle("org.eclipse.jetty.orbit", "org.apache.taglibs.standard.glassfish",
"1.2.0.v201112081803"),
mavenBundle("org.eclipse.jetty.orbit", "org.eclipse.jdt.core", "3.8.2.v20130121"),
mavenBundle("commons-beanutils", "commons-beanutils", "1.8.3"),
mavenBundle("commons-collections", "commons-collections", "3.2.1"),
mavenBundle("org.apache.shiro", "shiro-web", "1.2.2"),
mavenBundle("org.apache.shiro", "shiro-core", "1.2.2"),
// mavenBundle("org.apache.myfaces.core", "myfaces-impl", "2.1.12"),
mavenBundle("org.apache.myfaces.core", "myfaces-api", "2.1.12"),
bundle("reference:file:" + PathUtils.getBaseDir() + "/target/myfaces-impl.jar"),
mavenBundle("org.apache.geronimo.specs", "geronimo-annotation_1.1_spec", "1.0.1"),
mavenBundle("org.apache.geronimo.specs", "geronimo-validation_1.0_spec", "1.1"),
mavenBundle("commons-codec", "commons-codec", "1.7"),
mavenBundle("commons-digester", "commons-digester", "1.8.1"),
mavenBundle("org.ops4j.pax.shiro.", "pax-shiro-faces", "0.1.0-SNAPSHOT"),
mavenBundle("org.ops4j.pax.shiro.samples", "sample-faces-bundle", "0.1.0-SNAPSHOT")
);
}
|
diff --git a/ldapbrowser-core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/schema/Schema.java b/ldapbrowser-core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/schema/Schema.java
index 9226d4c2f..3796f55e3 100644
--- a/ldapbrowser-core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/schema/Schema.java
+++ b/ldapbrowser-core/src/main/java/org/apache/directory/studio/ldapbrowser/core/model/schema/Schema.java
@@ -1,793 +1,798 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldapbrowser.core.model.schema;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.apache.directory.shared.ldap.name.LdapDN;
import org.apache.directory.shared.ldap.schema.UsageEnum;
import org.apache.directory.shared.ldap.schema.syntax.AttributeTypeDescription;
import org.apache.directory.shared.ldap.schema.syntax.LdapSyntaxDescription;
import org.apache.directory.shared.ldap.schema.syntax.MatchingRuleDescription;
import org.apache.directory.shared.ldap.schema.syntax.MatchingRuleUseDescription;
import org.apache.directory.shared.ldap.schema.syntax.ObjectClassDescription;
import org.apache.directory.shared.ldap.schema.syntax.parser.AttributeTypeDescriptionSchemaParser;
import org.apache.directory.shared.ldap.schema.syntax.parser.LdapSyntaxDescriptionSchemaParser;
import org.apache.directory.shared.ldap.schema.syntax.parser.MatchingRuleDescriptionSchemaParser;
import org.apache.directory.shared.ldap.schema.syntax.parser.MatchingRuleUseDescriptionSchemaParser;
import org.apache.directory.shared.ldap.schema.syntax.parser.ObjectClassDescriptionSchemaParser;
import org.apache.directory.studio.ldapbrowser.core.model.AttributeDescription;
import org.apache.directory.studio.ldapbrowser.core.model.IAttribute;
import org.apache.directory.studio.ldifparser.LdifFormatParameters;
import org.apache.directory.studio.ldifparser.model.LdifEnumeration;
import org.apache.directory.studio.ldifparser.model.container.LdifContainer;
import org.apache.directory.studio.ldifparser.model.container.LdifContentRecord;
import org.apache.directory.studio.ldifparser.model.lines.LdifAttrValLine;
import org.apache.directory.studio.ldifparser.parser.LdifParser;
/**
* The schema is the central access point to all schema information.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class Schema
{
public static final String SCHEMA_FILTER = "(objectClass=subschema)";
public static final String SCHEMA_ATTRIBUTE_OBJECTCLASSES = "objectClasses";
public static final String SCHEMA_ATTRIBUTE_ATTRIBUTETYPES = "attributeTypes";
public static final String SCHEMA_ATTRIBUTE_LDAPSYNTAXES = "ldapSyntaxes";
public static final String SCHEMA_ATTRIBUTE_MATCHINGRULES = "matchingRules";
public static final String SCHEMA_ATTRIBUTE_MATCHINGRULEUSE = "matchingRuleUse";
public static final String RAW_SCHEMA_DEFINITION_LDIF_VALUE = "RAW_SCHEMA_DEFINITION_LDIF_VALUE";
public static final String DN_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.12";
public static final LdapSyntaxDescription DUMMY_LDAP_SYNTAX;
static
{
DUMMY_LDAP_SYNTAX = new LdapSyntaxDescription();
DUMMY_LDAP_SYNTAX.setNumericOid( "" );
DUMMY_LDAP_SYNTAX.setDescription( "" );
}
public static final Schema DEFAULT_SCHEMA;
static
{
Schema defaultSchema = null;
try
{
URL url = Schema.class.getClassLoader().getResource( "default_schema.ldif" );
InputStream is = url.openStream();
Reader reader = new InputStreamReader( is );
defaultSchema = new Schema();
defaultSchema.defaultSchema = true;
defaultSchema.loadFromLdif( reader );
}
catch ( Exception e )
{
e.printStackTrace();
}
DEFAULT_SCHEMA = defaultSchema;
}
private boolean defaultSchema = false;
public boolean isDefault()
{
return this.defaultSchema;
}
private LdifContentRecord schemaRecord;
private LdapDN dn;
private String createTimestamp;
private String modifyTimestamp;
private Map<String, ObjectClassDescription> ocdMapByNameOrNumericOid;
private Map<String, AttributeTypeDescription> atdMapByNameOrNumericOid;
private Map<String, LdapSyntaxDescription> lsdMapByNumericOid;
private Map<String, MatchingRuleDescription> mrdMapByNameOrNumericOid;
private Map<String, MatchingRuleUseDescription> mrudMapByNameOrNumericOid;
/**
* Creates a new instance of Schema.
*/
public Schema()
{
this.schemaRecord = null;
this.dn = null;
this.createTimestamp = null;
this.modifyTimestamp = null;
this.ocdMapByNameOrNumericOid = new HashMap<String, ObjectClassDescription>();
this.atdMapByNameOrNumericOid = new HashMap<String, AttributeTypeDescription>();
this.lsdMapByNumericOid = new HashMap<String, LdapSyntaxDescription>();
this.mrdMapByNameOrNumericOid = new HashMap<String, MatchingRuleDescription>();
this.mrudMapByNameOrNumericOid = new HashMap<String, MatchingRuleUseDescription>();
}
/**
* Loads all schema elements from the given reader. The input must be in
* LDIF format.
*
* @param reader the reader
*/
public void loadFromLdif( Reader reader )
{
try
{
LdifParser parser = new LdifParser();
LdifEnumeration enumeration = parser.parse( reader );
if ( enumeration.hasNext() )
{
LdifContainer container = enumeration.next();
if ( container instanceof LdifContentRecord )
{
LdifContentRecord schemaRecord = ( LdifContentRecord ) container;
parseSchemaRecord( schemaRecord );
}
}
}
catch ( Exception e )
{
System.out.println( "Schema#loadFromLdif: " + e.toString() );
}
}
/**
* Load all schema elements from the given schema record.
*
* @param schemaRecord the schema record
*/
public void loadFromRecord( LdifContentRecord schemaRecord )
{
try
{
parseSchemaRecord( schemaRecord );
}
catch ( Exception e )
{
System.out.println( "Schema#loadFromRecord: " + e.toString() );
}
}
/**
* Saves the schema in LDIF format to the given writer.
*
* @param writer
*/
public void saveToLdif( Writer writer )
{
try
{
writer.write( getSchemaRecord().toFormattedString( LdifFormatParameters.DEFAULT ) );
}
catch ( Exception e )
{
System.out.println( "Schema#saveToLdif: " + e.toString() );
}
}
/**
* Parses the schema record.
*
* @param schemaRecord the schema record
*
* @throws Exception the exception
*/
private void parseSchemaRecord( LdifContentRecord schemaRecord ) throws Exception
{
setSchemaRecord( schemaRecord );
setDn( new LdapDN( schemaRecord.getDnLine().getValueAsString() ) );
LdifAttrValLine[] lines = schemaRecord.getAttrVals();
for ( int i = 0; i < lines.length; i++ )
{
LdifAttrValLine line = lines[i];
String attributeName = line.getUnfoldedAttributeDescription();
String value = line.getValueAsString();
List<String> ldifValues = new ArrayList<String>( 1 );
ldifValues.add( value );
try
{
if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_OBJECTCLASSES ) )
{
- ObjectClassDescription ocd = new ObjectClassDescriptionSchemaParser()
- .parseObjectClassDescription( value );
+ ObjectClassDescriptionSchemaParser parser = new ObjectClassDescriptionSchemaParser();
+ parser.setQuirksMode( true );
+ ObjectClassDescription ocd = parser.parseObjectClassDescription( value );
ocd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addObjectClassDescription( ocd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_ATTRIBUTETYPES ) )
{
- AttributeTypeDescription atd = new AttributeTypeDescriptionSchemaParser()
- .parseAttributeTypeDescription( value );
+ AttributeTypeDescriptionSchemaParser parser = new AttributeTypeDescriptionSchemaParser();
+ parser.setQuirksMode( true );
+ AttributeTypeDescription atd = parser.parseAttributeTypeDescription( value );
atd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addAttributeTypeDescription( atd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_LDAPSYNTAXES ) )
{
- LdapSyntaxDescription lsd = new LdapSyntaxDescriptionSchemaParser()
- .parseLdapSyntaxDescription( value );
+ LdapSyntaxDescriptionSchemaParser parser = new LdapSyntaxDescriptionSchemaParser();
+ parser.setQuirksMode( true );
+ LdapSyntaxDescription lsd = parser.parseLdapSyntaxDescription( value );
lsd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addLdapSyntaxDescription( lsd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_MATCHINGRULES ) )
{
- MatchingRuleDescription mrd = new MatchingRuleDescriptionSchemaParser()
- .parseMatchingRuleDescription( value );
+ MatchingRuleDescriptionSchemaParser parser = new MatchingRuleDescriptionSchemaParser();
+ parser.setQuirksMode( true );
+ MatchingRuleDescription mrd = parser.parseMatchingRuleDescription( value );
mrd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addMatchingRuleDescription( mrd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_MATCHINGRULEUSE ) )
{
- MatchingRuleUseDescription mrud = new MatchingRuleUseDescriptionSchemaParser()
- .parseMatchingRuleUseDescription( value );
+ MatchingRuleUseDescriptionSchemaParser parser = new MatchingRuleUseDescriptionSchemaParser();
+ parser.setQuirksMode( true );
+ MatchingRuleUseDescription mrud = parser.parseMatchingRuleUseDescription( value );
mrud.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addMatchingRuleUseDescription( mrud );
}
else if ( attributeName.equalsIgnoreCase( IAttribute.OPERATIONAL_ATTRIBUTE_CREATE_TIMESTAMP ) )
{
setCreateTimestamp( value );
}
else if ( attributeName.equalsIgnoreCase( IAttribute.OPERATIONAL_ATTRIBUTE_MODIFY_TIMESTAMP ) )
{
setModifyTimestamp( value );
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() + ": " + attributeName + " - " + value );
e.printStackTrace();
}
}
// set extensibleObject may attributes
ObjectClassDescription extensibleObjectOcd = this
.getObjectClassDescription( SchemaConstants.EXTENSIBLE_OBJECT_OC );
Collection<AttributeTypeDescription> userAtds = SchemaUtils.getUserAttributeDescriptions( this );
Collection<String> atdNames = SchemaUtils.getNames( userAtds );
List<String> atdNames2 = new ArrayList<String>( atdNames );
extensibleObjectOcd.setMayAttributeTypes( atdNames2 );
}
/**
* Gets the schema record.
*
* @return the schema record when the schema was created using the
* loadFromLdif() method, null otherwise
*/
public LdifContentRecord getSchemaRecord()
{
return schemaRecord;
}
/**
* Sets the schema record.
*
* @param schemaRecord the new schema record
*/
public void setSchemaRecord( LdifContentRecord schemaRecord )
{
this.schemaRecord = schemaRecord;
}
/**
* Gets the DN of the schema record, may be null.
*
* @return the DN of the schema record, may be null
*/
public LdapDN getDn()
{
return dn;
}
/**
* Sets the DN.
*
* @param dn the new DN
*/
public void setDn( LdapDN dn )
{
this.dn = dn;
}
/**
* Gets the create timestamp of the schema record, may be null.
*
* @return the create timestamp of the schema record, may be null
*/
public String getCreateTimestamp()
{
return createTimestamp;
}
/**
* Sets the creates the timestamp.
*
* @param createTimestamp the new creates the timestamp
*/
public void setCreateTimestamp( String createTimestamp )
{
this.createTimestamp = createTimestamp;
}
/**
* Gets the modify timestamp of the schema record, may be null.
*
* @return the modify timestamp of the schema record, may be null
*/
public String getModifyTimestamp()
{
return modifyTimestamp;
}
/**
* Sets the modify timestamp.
*
* @param modifyTimestamp the new modify timestamp
*/
public void setModifyTimestamp( String modifyTimestamp )
{
this.modifyTimestamp = modifyTimestamp;
}
////////////////////// Object Class Description //////////////////////
/**
* Adds the object class description.
*
* @param ocd the object class description
*/
private void addObjectClassDescription( ObjectClassDescription ocd )
{
if ( ocd.getNumericOid() != null )
{
ocdMapByNameOrNumericOid.put( ocd.getNumericOid().toLowerCase(), ocd );
}
if ( ocd.getNames() != null && !ocd.getNames().isEmpty() )
{
for ( String ocdName : ocd.getNames() )
{
ocdMapByNameOrNumericOid.put( ocdName.toLowerCase(), ocd );
}
}
}
/**
* Gets the object class descriptions.
*
* @return the object class descriptions
*/
public Collection<ObjectClassDescription> getObjectClassDescriptions()
{
Set<ObjectClassDescription> set = new HashSet<ObjectClassDescription>( ocdMapByNameOrNumericOid.values() );
return set;
}
/**
* Checks if an object class descriptions with the given name or OID exists.
*
* @param nameOrOid the name numeric OID of the object class description
*
* @return true if an object class description with the given name
* or OID exists.
*/
public boolean hasObjectClassDescription( String nameOrOid )
{
return ocdMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() );
}
/**
* Returns the object class description of the given name. If no such
* object exists the default or a dummy object class description is
* returned.
*
* @param nameOrOid the name numeric OID of the object class description
*
* @return the object class description, or the default or a dummy
*/
public ObjectClassDescription getObjectClassDescription( String nameOrOid )
{
if ( ocdMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() ) )
{
return ocdMapByNameOrNumericOid.get( nameOrOid.toLowerCase() );
}
else if ( !isDefault() )
{
return DEFAULT_SCHEMA.getObjectClassDescription( nameOrOid );
}
else
{
// DUMMY
List<String> names = new ArrayList<String>();
names.add( nameOrOid );
ObjectClassDescription ocd = new ObjectClassDescription();
ocd.setNumericOid( nameOrOid );
ocd.setNames( names );
return ocd;
}
}
////////////////////// Attribute Type Description //////////////////////
/**
* Adds the attribute type description.
*
* @param atd the attribute type description
*/
private void addAttributeTypeDescription( AttributeTypeDescription atd )
{
if ( atd.getNumericOid() != null )
{
atdMapByNameOrNumericOid.put( atd.getNumericOid().toLowerCase(), atd );
}
if ( atd.getNames() != null && !atd.getNames().isEmpty() )
{
for ( String atdName : atd.getNames() )
{
atdMapByNameOrNumericOid.put( atdName.toLowerCase(), atd );
}
}
}
/**
* Gets the attribute type descriptions.
*
* @return the attribute type descriptions
*/
public Collection<AttributeTypeDescription> getAttributeTypeDescriptions()
{
Set<AttributeTypeDescription> set = new HashSet<AttributeTypeDescription>( atdMapByNameOrNumericOid.values() );
return set;
}
/**
* Checks if an attribute type descriptions with the given name or OID exists.
*
* @param nameOrOid the name numeric OID of the attribute type description
*
* @return true if an attribute type description with the given name
* or OID exists.
*/
public boolean hasAttributeTypeDescription( String nameOrOid )
{
return atdMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() );
}
/**
* Returns the attribute type description of the given name. If no such
* object exists the default or a dummy attribute type description is
* returned.
*
* @param nameOrOid the name numeric OID of the attribute type description
*
* @return the attribute type description, or the default or a dummy
*/
public AttributeTypeDescription getAttributeTypeDescription( String nameOrOid )
{
AttributeDescription ad = new AttributeDescription( nameOrOid );
String attributeType = ad.getParsedAttributeType();
if ( atdMapByNameOrNumericOid.containsKey( attributeType.toLowerCase() ) )
{
return atdMapByNameOrNumericOid.get( attributeType.toLowerCase() );
}
else if ( !isDefault() )
{
return DEFAULT_SCHEMA.getAttributeTypeDescription( attributeType );
}
else
{
// DUMMY
List<String> attributeTypes = new ArrayList<String>();
attributeTypes.add( attributeType );
AttributeTypeDescription atd = new AttributeTypeDescription();
atd.setNumericOid( attributeType );
atd.setNames( attributeTypes );
atd.setUserModifiable( false );
atd.setUsage( UsageEnum.USER_APPLICATIONS );
return atd;
}
}
//////////////////////// LDAP Syntax Description ////////////////////////
/**
* Adds the LDAP syntax description.
*
* @param lsd the LDAP syntax description
*/
private void addLdapSyntaxDescription( LdapSyntaxDescription lsd )
{
if ( lsd.getNumericOid() != null )
{
lsdMapByNumericOid.put( lsd.getNumericOid().toLowerCase(), lsd );
}
}
/**
* Gets the LDAP syntax descriptions.
*
* @return the LDAP syntax descriptions
*/
public Collection<LdapSyntaxDescription> getLdapSyntaxDescriptions()
{
Set<LdapSyntaxDescription> set = new HashSet<LdapSyntaxDescription>( lsdMapByNumericOid.values() );
return set;
}
/**
* Checks if an LDAP syntax descriptions with the given OID exists.
*
* @param numericOid the numeric OID of the LDAP syntax description
*
* @return true if an LDAP syntax description with the given OID exists.
*/
public boolean hasLdapSyntaxDescription( String numericOid )
{
return lsdMapByNumericOid.containsKey( numericOid.toLowerCase() );
}
/**
* Returns the syntax description of the given OID. If no such object
* exists the default or a dummy syntax description is returned.
*
* @param numericOid the numeric OID of the LDAP syntax description
*
* @return the attribute type description or the default or a dummy
*/
public LdapSyntaxDescription getLdapSyntaxDescription( String numericOid )
{
if ( numericOid == null )
{
return DUMMY_LDAP_SYNTAX;
}
else if ( lsdMapByNumericOid.containsKey( numericOid.toLowerCase() ) )
{
return lsdMapByNumericOid.get( numericOid.toLowerCase() );
}
else if ( !isDefault() )
{
return DEFAULT_SCHEMA.getLdapSyntaxDescription( numericOid );
}
else
{
// DUMMY
LdapSyntaxDescription lsd = new LdapSyntaxDescription();
lsd.setNumericOid( numericOid );
return lsd;
}
}
////////////////////////// Matching Rule Description //////////////////////////
/**
* Adds the matching rule description.
*
* @param mrud the matching rule description
*/
private void addMatchingRuleDescription( MatchingRuleDescription mrd )
{
if ( mrd.getNumericOid() != null )
{
mrdMapByNameOrNumericOid.put( mrd.getNumericOid().toLowerCase(), mrd );
}
if ( mrd.getNames() != null && !mrd.getNames().isEmpty() )
{
for ( String mrdName : mrd.getNames() )
{
mrdMapByNameOrNumericOid.put( mrdName.toLowerCase(), mrd );
}
}
}
/**
* Gets the matching rule descriptions.
*
* @return the matching rule descriptions
*/
public Collection<MatchingRuleDescription> getMatchingRuleDescriptions()
{
Set<MatchingRuleDescription> set = new HashSet<MatchingRuleDescription>( mrdMapByNameOrNumericOid.values() );
return set;
}
/**
* Checks if an matching rule descriptions with the given name or OID exists.
*
* @param nameOrOid the name numeric OID of the matching rule description
*
* @return true if a matching rule description with the given name
* or OID exists.
*/
public boolean hasMatchingRuleDescription( String nameOrOid )
{
return mrdMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() );
}
/**
* Returns the matching rule description of the given name or OID. If no
* such object exists the default or a dummy matching rule description
* is returned.
*
* @param nameOrOid the name or numeric OID of the matching rule description
*
* @return the matching rule description or the default or a dummy
*/
public MatchingRuleDescription getMatchingRuleDescription( String nameOrOid )
{
if ( mrdMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() ) )
{
return mrdMapByNameOrNumericOid.get( nameOrOid.toLowerCase() );
}
else if ( !isDefault() )
{
return DEFAULT_SCHEMA.getMatchingRuleDescription( nameOrOid );
}
else
{
// DUMMY
MatchingRuleDescription mrd = new MatchingRuleDescription();
mrd.setNumericOid( nameOrOid );
return mrd;
}
}
//////////////////////// Matching Rule Use Description ////////////////////////
/**
* Adds the matching rule use description.
*
* @param mrud the matching rule use description
*/
private void addMatchingRuleUseDescription( MatchingRuleUseDescription mrud )
{
if ( mrud.getNumericOid() != null )
{
mrudMapByNameOrNumericOid.put( mrud.getNumericOid().toLowerCase(), mrud );
}
if ( mrud.getNames() != null && !mrud.getNames().isEmpty() )
{
for ( String mrudName : mrud.getNames() )
{
mrudMapByNameOrNumericOid.put( mrudName.toLowerCase(), mrud );
}
}
}
/**
* Gets the matching rule use descriptions.
*
* @return the matching rule use descriptions
*/
public Collection<MatchingRuleUseDescription> getMatchingRuleUseDescriptions()
{
Set<MatchingRuleUseDescription> set = new HashSet<MatchingRuleUseDescription>( mrudMapByNameOrNumericOid.values() );
return set;
}
/**
* Checks if an matching rule use descriptions with the given name or OID exists.
*
* @param nameOrOid the name numeric OID of the matching rule use description
*
* @return true if a matching rule use description with the given name
* or OID exists.
*/
public boolean hasMatchingRuleUseDescription( String nameOrOid )
{
return mrudMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() );
}
/**
* Returns the matching rule use description of the given name or OID. If no
* such object exists the default or a dummy matching rule use description
* is returned.
*
* @param nameOrOid the name or numeric OID of the matching rule use description
*
* @return the matching rule use description or the default or a dummy
*/
public MatchingRuleUseDescription getMatchingRuleUseDescription( String nameOrOid )
{
if ( mrudMapByNameOrNumericOid.containsKey( nameOrOid.toLowerCase() ) )
{
return mrudMapByNameOrNumericOid.get( nameOrOid.toLowerCase() );
}
else if ( !isDefault() )
{
return DEFAULT_SCHEMA.getMatchingRuleUseDescription( nameOrOid );
}
else
{
// DUMMY
MatchingRuleUseDescription mrud = new MatchingRuleUseDescription();
mrud.setNumericOid( nameOrOid );
return mrud;
}
}
}
| false | true | private void parseSchemaRecord( LdifContentRecord schemaRecord ) throws Exception
{
setSchemaRecord( schemaRecord );
setDn( new LdapDN( schemaRecord.getDnLine().getValueAsString() ) );
LdifAttrValLine[] lines = schemaRecord.getAttrVals();
for ( int i = 0; i < lines.length; i++ )
{
LdifAttrValLine line = lines[i];
String attributeName = line.getUnfoldedAttributeDescription();
String value = line.getValueAsString();
List<String> ldifValues = new ArrayList<String>( 1 );
ldifValues.add( value );
try
{
if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_OBJECTCLASSES ) )
{
ObjectClassDescription ocd = new ObjectClassDescriptionSchemaParser()
.parseObjectClassDescription( value );
ocd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addObjectClassDescription( ocd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_ATTRIBUTETYPES ) )
{
AttributeTypeDescription atd = new AttributeTypeDescriptionSchemaParser()
.parseAttributeTypeDescription( value );
atd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addAttributeTypeDescription( atd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_LDAPSYNTAXES ) )
{
LdapSyntaxDescription lsd = new LdapSyntaxDescriptionSchemaParser()
.parseLdapSyntaxDescription( value );
lsd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addLdapSyntaxDescription( lsd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_MATCHINGRULES ) )
{
MatchingRuleDescription mrd = new MatchingRuleDescriptionSchemaParser()
.parseMatchingRuleDescription( value );
mrd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addMatchingRuleDescription( mrd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_MATCHINGRULEUSE ) )
{
MatchingRuleUseDescription mrud = new MatchingRuleUseDescriptionSchemaParser()
.parseMatchingRuleUseDescription( value );
mrud.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addMatchingRuleUseDescription( mrud );
}
else if ( attributeName.equalsIgnoreCase( IAttribute.OPERATIONAL_ATTRIBUTE_CREATE_TIMESTAMP ) )
{
setCreateTimestamp( value );
}
else if ( attributeName.equalsIgnoreCase( IAttribute.OPERATIONAL_ATTRIBUTE_MODIFY_TIMESTAMP ) )
{
setModifyTimestamp( value );
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() + ": " + attributeName + " - " + value );
e.printStackTrace();
}
}
// set extensibleObject may attributes
ObjectClassDescription extensibleObjectOcd = this
.getObjectClassDescription( SchemaConstants.EXTENSIBLE_OBJECT_OC );
Collection<AttributeTypeDescription> userAtds = SchemaUtils.getUserAttributeDescriptions( this );
Collection<String> atdNames = SchemaUtils.getNames( userAtds );
List<String> atdNames2 = new ArrayList<String>( atdNames );
extensibleObjectOcd.setMayAttributeTypes( atdNames2 );
}
| private void parseSchemaRecord( LdifContentRecord schemaRecord ) throws Exception
{
setSchemaRecord( schemaRecord );
setDn( new LdapDN( schemaRecord.getDnLine().getValueAsString() ) );
LdifAttrValLine[] lines = schemaRecord.getAttrVals();
for ( int i = 0; i < lines.length; i++ )
{
LdifAttrValLine line = lines[i];
String attributeName = line.getUnfoldedAttributeDescription();
String value = line.getValueAsString();
List<String> ldifValues = new ArrayList<String>( 1 );
ldifValues.add( value );
try
{
if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_OBJECTCLASSES ) )
{
ObjectClassDescriptionSchemaParser parser = new ObjectClassDescriptionSchemaParser();
parser.setQuirksMode( true );
ObjectClassDescription ocd = parser.parseObjectClassDescription( value );
ocd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addObjectClassDescription( ocd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_ATTRIBUTETYPES ) )
{
AttributeTypeDescriptionSchemaParser parser = new AttributeTypeDescriptionSchemaParser();
parser.setQuirksMode( true );
AttributeTypeDescription atd = parser.parseAttributeTypeDescription( value );
atd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addAttributeTypeDescription( atd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_LDAPSYNTAXES ) )
{
LdapSyntaxDescriptionSchemaParser parser = new LdapSyntaxDescriptionSchemaParser();
parser.setQuirksMode( true );
LdapSyntaxDescription lsd = parser.parseLdapSyntaxDescription( value );
lsd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addLdapSyntaxDescription( lsd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_MATCHINGRULES ) )
{
MatchingRuleDescriptionSchemaParser parser = new MatchingRuleDescriptionSchemaParser();
parser.setQuirksMode( true );
MatchingRuleDescription mrd = parser.parseMatchingRuleDescription( value );
mrd.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addMatchingRuleDescription( mrd );
}
else if ( attributeName.equalsIgnoreCase( Schema.SCHEMA_ATTRIBUTE_MATCHINGRULEUSE ) )
{
MatchingRuleUseDescriptionSchemaParser parser = new MatchingRuleUseDescriptionSchemaParser();
parser.setQuirksMode( true );
MatchingRuleUseDescription mrud = parser.parseMatchingRuleUseDescription( value );
mrud.addExtension( RAW_SCHEMA_DEFINITION_LDIF_VALUE, ldifValues );
addMatchingRuleUseDescription( mrud );
}
else if ( attributeName.equalsIgnoreCase( IAttribute.OPERATIONAL_ATTRIBUTE_CREATE_TIMESTAMP ) )
{
setCreateTimestamp( value );
}
else if ( attributeName.equalsIgnoreCase( IAttribute.OPERATIONAL_ATTRIBUTE_MODIFY_TIMESTAMP ) )
{
setModifyTimestamp( value );
}
}
catch ( Exception e )
{
System.out.println( e.getMessage() + ": " + attributeName + " - " + value );
e.printStackTrace();
}
}
// set extensibleObject may attributes
ObjectClassDescription extensibleObjectOcd = this
.getObjectClassDescription( SchemaConstants.EXTENSIBLE_OBJECT_OC );
Collection<AttributeTypeDescription> userAtds = SchemaUtils.getUserAttributeDescriptions( this );
Collection<String> atdNames = SchemaUtils.getNames( userAtds );
List<String> atdNames2 = new ArrayList<String>( atdNames );
extensibleObjectOcd.setMayAttributeTypes( atdNames2 );
}
|
diff --git a/src/nu/validator/htmlparser/impl/TreeBuilder.java b/src/nu/validator/htmlparser/impl/TreeBuilder.java
index 710baa9..35138ba 100644
--- a/src/nu/validator/htmlparser/impl/TreeBuilder.java
+++ b/src/nu/validator/htmlparser/impl/TreeBuilder.java
@@ -1,5644 +1,5647 @@
/*
* Copyright (c) 2007 Henri Sivonen
* Copyright (c) 2007-2010 Mozilla Foundation
* Portions of comments Copyright 2004-2008 Apple Computer, Inc., Mozilla
* Foundation, and Opera Software ASA.
*
* 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.
*/
/*
* The comments following this one that use the same comment syntax as this
* comment are quotes from the WHATWG HTML 5 spec as of 27 June 2007
* amended as of June 28 2007.
* That document came with this statement:
* "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and
* Opera Software ASA. You are granted a license to use, reproduce and
* create derivative works of this document."
*/
package nu.validator.htmlparser.impl;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import nu.validator.htmlparser.annotation.Auto;
import nu.validator.htmlparser.annotation.Const;
import nu.validator.htmlparser.annotation.IdType;
import nu.validator.htmlparser.annotation.Inline;
import nu.validator.htmlparser.annotation.Literal;
import nu.validator.htmlparser.annotation.Local;
import nu.validator.htmlparser.annotation.NoLength;
import nu.validator.htmlparser.annotation.NsUri;
import nu.validator.htmlparser.common.DoctypeExpectation;
import nu.validator.htmlparser.common.DocumentMode;
import nu.validator.htmlparser.common.DocumentModeHandler;
import nu.validator.htmlparser.common.Interner;
import nu.validator.htmlparser.common.TokenHandler;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public abstract class TreeBuilder<T> implements TokenHandler,
TreeBuilderState<T> {
/**
* Array version of U+FFFD.
*/
private static final @NoLength char[] REPLACEMENT_CHARACTER = { '\uFFFD' };
// Start dispatch groups
final static int OTHER = 0;
final static int A = 1;
final static int BASE = 2;
final static int BODY = 3;
final static int BR = 4;
final static int BUTTON = 5;
final static int CAPTION = 6;
final static int COL = 7;
final static int COLGROUP = 8;
final static int FORM = 9;
final static int FRAME = 10;
final static int FRAMESET = 11;
final static int IMAGE = 12;
final static int INPUT = 13;
final static int ISINDEX = 14;
final static int LI = 15;
final static int LINK_OR_BASEFONT_OR_BGSOUND = 16;
final static int MATH = 17;
final static int META = 18;
final static int SVG = 19;
final static int HEAD = 20;
final static int HR = 22;
final static int HTML = 23;
final static int NOBR = 24;
final static int NOFRAMES = 25;
final static int NOSCRIPT = 26;
final static int OPTGROUP = 27;
final static int OPTION = 28;
final static int P = 29;
final static int PLAINTEXT = 30;
final static int SCRIPT = 31;
final static int SELECT = 32;
final static int STYLE = 33;
final static int TABLE = 34;
final static int TEXTAREA = 35;
final static int TITLE = 36;
final static int TR = 37;
final static int XMP = 38;
final static int TBODY_OR_THEAD_OR_TFOOT = 39;
final static int TD_OR_TH = 40;
final static int DD_OR_DT = 41;
final static int H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6 = 42;
final static int MARQUEE_OR_APPLET = 43;
final static int PRE_OR_LISTING = 44;
final static int B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U = 45;
final static int UL_OR_OL_OR_DL = 46;
final static int IFRAME = 47;
final static int EMBED_OR_IMG = 48;
final static int AREA_OR_WBR = 49;
final static int DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU = 50;
final static int ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY = 51;
final static int RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR = 52;
final static int RT_OR_RP = 53;
final static int COMMAND = 54;
final static int PARAM_OR_SOURCE = 55;
final static int MGLYPH_OR_MALIGNMARK = 56;
final static int MI_MO_MN_MS_MTEXT = 57;
final static int ANNOTATION_XML = 58;
final static int FOREIGNOBJECT_OR_DESC = 59;
final static int NOEMBED = 60;
final static int FIELDSET = 61;
final static int OUTPUT_OR_LABEL = 62;
final static int OBJECT = 63;
final static int FONT = 64;
final static int KEYGEN = 65;
// start insertion modes
private static final int INITIAL = 0;
private static final int BEFORE_HTML = 1;
private static final int BEFORE_HEAD = 2;
private static final int IN_HEAD = 3;
private static final int IN_HEAD_NOSCRIPT = 4;
private static final int AFTER_HEAD = 5;
private static final int IN_BODY = 6;
private static final int IN_TABLE = 7;
private static final int IN_CAPTION = 8;
private static final int IN_COLUMN_GROUP = 9;
private static final int IN_TABLE_BODY = 10;
private static final int IN_ROW = 11;
private static final int IN_CELL = 12;
private static final int IN_SELECT = 13;
private static final int IN_SELECT_IN_TABLE = 14;
private static final int AFTER_BODY = 15;
private static final int IN_FRAMESET = 16;
private static final int AFTER_FRAMESET = 17;
private static final int AFTER_AFTER_BODY = 18;
private static final int AFTER_AFTER_FRAMESET = 19;
private static final int TEXT = 20;
private static final int FRAMESET_OK = 21;
// start charset states
private static final int CHARSET_INITIAL = 0;
private static final int CHARSET_C = 1;
private static final int CHARSET_H = 2;
private static final int CHARSET_A = 3;
private static final int CHARSET_R = 4;
private static final int CHARSET_S = 5;
private static final int CHARSET_E = 6;
private static final int CHARSET_T = 7;
private static final int CHARSET_EQUALS = 8;
private static final int CHARSET_SINGLE_QUOTED = 9;
private static final int CHARSET_DOUBLE_QUOTED = 10;
private static final int CHARSET_UNQUOTED = 11;
// end pseudo enums
// [NOCPP[
private final static String[] HTML4_PUBLIC_IDS = {
"-//W3C//DTD HTML 4.0 Frameset//EN",
"-//W3C//DTD HTML 4.0 Transitional//EN",
"-//W3C//DTD HTML 4.0//EN", "-//W3C//DTD HTML 4.01 Frameset//EN",
"-//W3C//DTD HTML 4.01 Transitional//EN",
"-//W3C//DTD HTML 4.01//EN" };
// ]NOCPP]
@Literal private final static String[] QUIRKY_PUBLIC_IDS = {
"+//silmaril//dtd html pro v0r11 19970101//",
"-//advasoft ltd//dtd html 3.0 aswedit + extensions//",
"-//as//dtd html 3.0 aswedit + extensions//",
"-//ietf//dtd html 2.0 level 1//",
"-//ietf//dtd html 2.0 level 2//",
"-//ietf//dtd html 2.0 strict level 1//",
"-//ietf//dtd html 2.0 strict level 2//",
"-//ietf//dtd html 2.0 strict//",
"-//ietf//dtd html 2.0//",
"-//ietf//dtd html 2.1e//",
"-//ietf//dtd html 3.0//",
"-//ietf//dtd html 3.2 final//",
"-//ietf//dtd html 3.2//",
"-//ietf//dtd html 3//",
"-//ietf//dtd html level 0//",
"-//ietf//dtd html level 1//",
"-//ietf//dtd html level 2//",
"-//ietf//dtd html level 3//",
"-//ietf//dtd html strict level 0//",
"-//ietf//dtd html strict level 1//",
"-//ietf//dtd html strict level 2//",
"-//ietf//dtd html strict level 3//",
"-//ietf//dtd html strict//",
"-//ietf//dtd html//",
"-//metrius//dtd metrius presentational//",
"-//microsoft//dtd internet explorer 2.0 html strict//",
"-//microsoft//dtd internet explorer 2.0 html//",
"-//microsoft//dtd internet explorer 2.0 tables//",
"-//microsoft//dtd internet explorer 3.0 html strict//",
"-//microsoft//dtd internet explorer 3.0 html//",
"-//microsoft//dtd internet explorer 3.0 tables//",
"-//netscape comm. corp.//dtd html//",
"-//netscape comm. corp.//dtd strict html//",
"-//o'reilly and associates//dtd html 2.0//",
"-//o'reilly and associates//dtd html extended 1.0//",
"-//o'reilly and associates//dtd html extended relaxed 1.0//",
"-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//",
"-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//",
"-//spyglass//dtd html 2.0 extended//",
"-//sq//dtd html 2.0 hotmetal + extensions//",
"-//sun microsystems corp.//dtd hotjava html//",
"-//sun microsystems corp.//dtd hotjava strict html//",
"-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//",
"-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//",
"-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//",
"-//w3c//dtd html 4.0 transitional//",
"-//w3c//dtd html experimental 19960712//",
"-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//",
"-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//",
"-//webtechs//dtd mozilla html//" };
private static final int NOT_FOUND_ON_STACK = Integer.MAX_VALUE;
// [NOCPP[
private static final @Local String HTML_LOCAL = "html";
// ]NOCPP]
private int mode = INITIAL;
private int originalMode = INITIAL;
/**
* Used only when moving back to IN_BODY.
*/
private boolean framesetOk = true;
private boolean inForeign = false;
protected Tokenizer tokenizer;
// [NOCPP[
protected ErrorHandler errorHandler;
private DocumentModeHandler documentModeHandler;
private DoctypeExpectation doctypeExpectation = DoctypeExpectation.HTML;
// ]NOCPP]
private boolean scriptingEnabled = false;
private boolean needToDropLF;
// [NOCPP[
private boolean wantingComments;
// ]NOCPP]
private boolean fragment;
private @Local String contextName;
private @NsUri String contextNamespace;
private T contextNode;
private @Auto StackNode<T>[] stack;
private int currentPtr = -1;
private @Auto StackNode<T>[] listOfActiveFormattingElements;
private int listPtr = -1;
private T formPointer;
private T headPointer;
/**
* Used to work around Gecko limitations. Not used in Java.
*/
private T deepTreeSurrogateParent;
protected @Auto char[] charBuffer;
protected int charBufferLen = 0;
private boolean quirks = false;
// [NOCPP[
private boolean reportingDoctype = true;
private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET;
private final Map<String, LocatorImpl> idLocations = new HashMap<String, LocatorImpl>();
private boolean html4;
// ]NOCPP]
protected TreeBuilder() {
fragment = false;
}
/**
* Reports an condition that would make the infoset incompatible with XML
* 1.0 as fatal.
*
* @throws SAXException
* @throws SAXParseException
*/
protected void fatal() throws SAXException {
}
// [NOCPP[
protected final void fatal(Exception e) throws SAXException {
SAXParseException spe = new SAXParseException(e.getMessage(),
tokenizer, e);
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
final void fatal(String s) throws SAXException {
SAXParseException spe = new SAXParseException(s, tokenizer);
if (errorHandler != null) {
errorHandler.fatalError(spe);
}
throw spe;
}
// ]NOCPP]
/**
* Reports a Parse Error.
*
* @param message
* the message
* @throws SAXException
*/
final void err(String message) throws SAXException {
// [NOCPP[
if (errorHandler == null) {
return;
}
errNoCheck(message);
// ]NOCPP]
}
/**
* Reports a Parse Error without checking if an error handler is present.
*
* @param message
* the message
* @throws SAXException
*/
final void errNoCheck(String message) throws SAXException {
// [NOCPP[
SAXParseException spe = new SAXParseException(message, tokenizer);
errorHandler.error(spe);
// ]NOCPP]
}
/**
* Reports a warning
*
* @param message
* the message
* @throws SAXException
*/
final void warn(String message) throws SAXException {
// [NOCPP[
if (errorHandler == null) {
return;
}
SAXParseException spe = new SAXParseException(message, tokenizer);
errorHandler.warning(spe);
// ]NOCPP]
}
@SuppressWarnings("unchecked") public final void startTokenization(Tokenizer self) throws SAXException {
tokenizer = self;
stack = new StackNode[64];
listOfActiveFormattingElements = new StackNode[64];
needToDropLF = false;
originalMode = INITIAL;
currentPtr = -1;
listPtr = -1;
Portability.releaseElement(formPointer);
formPointer = null;
Portability.releaseElement(headPointer);
headPointer = null;
Portability.releaseElement(deepTreeSurrogateParent);
deepTreeSurrogateParent = null;
// [NOCPP[
html4 = false;
idLocations.clear();
wantingComments = wantsComments();
// ]NOCPP]
start(fragment);
charBufferLen = 0;
charBuffer = new char[1024];
framesetOk = true;
if (fragment) {
T elt;
if (contextNode != null) {
elt = contextNode;
Portability.retainElement(elt);
} else {
elt = createHtmlElementSetAsRoot(tokenizer.emptyAttributes());
}
StackNode<T> node = new StackNode<T>(
"http://www.w3.org/1999/xhtml", ElementName.HTML, elt);
currentPtr++;
stack[currentPtr] = node;
resetTheInsertionMode();
if ("title" == contextName || "textarea" == contextName) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.RCDATA, contextName);
} else if ("style" == contextName || "xmp" == contextName
|| "iframe" == contextName || "noembed" == contextName
|| "noframes" == contextName
|| (scriptingEnabled && "noscript" == contextName)) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.RAWTEXT, contextName);
} else if ("plaintext" == contextName) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.PLAINTEXT, contextName);
} else if ("script" == contextName) {
tokenizer.setStateAndEndTagExpectation(Tokenizer.SCRIPT_DATA,
contextName);
} else {
tokenizer.setStateAndEndTagExpectation(Tokenizer.DATA, contextName);
}
Portability.releaseLocal(contextName);
contextName = null;
Portability.releaseElement(contextNode);
contextNode = null;
Portability.releaseElement(elt);
} else {
mode = INITIAL;
inForeign = false;
}
}
public final void doctype(@Local String name, String publicIdentifier,
String systemIdentifier, boolean forceQuirks) throws SAXException {
needToDropLF = false;
if (!inForeign) {
switch (mode) {
case INITIAL:
// [NOCPP[
if (reportingDoctype) {
// ]NOCPP]
String emptyString = Portability.newEmptyString();
appendDoctypeToDocument(name == null ? "" : name,
publicIdentifier == null ? emptyString
: publicIdentifier,
systemIdentifier == null ? emptyString
: systemIdentifier);
Portability.releaseString(emptyString);
// [NOCPP[
}
switch (doctypeExpectation) {
case HTML:
// ]NOCPP]
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected \u201C<!DOCTYPE html>\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
false);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
err("Almost standards mode doctype. Expected \u201C<!DOCTYPE html>\u201D.");
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
} else {
// [NOCPP[
if ((Portability.literalEqualsString(
"-//W3C//DTD HTML 4.0//EN",
publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString(
"http://www.w3.org/TR/REC-html40/strict.dtd",
systemIdentifier)))
|| (Portability.literalEqualsString(
"-//W3C//DTD HTML 4.01//EN",
publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString(
"http://www.w3.org/TR/html4/strict.dtd",
systemIdentifier)))
|| (Portability.literalEqualsString(
"-//W3C//DTD XHTML 1.0 Strict//EN",
publicIdentifier) && Portability.literalEqualsString(
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
systemIdentifier))
|| (Portability.literalEqualsString(
"-//W3C//DTD XHTML 1.1//EN",
publicIdentifier) && Portability.literalEqualsString(
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd",
systemIdentifier))
) {
warn("Obsolete doctype. Expected \u201C<!DOCTYPE html>\u201D.");
} else if (!((systemIdentifier == null || Portability.literalEqualsString(
"about:legacy-compat", systemIdentifier)) && publicIdentifier == null)) {
err("Legacy doctype. Expected \u201C<!DOCTYPE html>\u201D.");
}
// ]NOCPP]
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
}
// [NOCPP[
break;
case HTML401_STRICT:
html4 = true;
tokenizer.turnOnAdditionalHtml4Errors();
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
true);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
err("Almost standards mode doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
} else {
if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) {
if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
}
} else {
err("The doctype was not the HTML 4.01 Strict doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
}
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
}
break;
case HTML401_TRANSITIONAL:
html4 = true;
tokenizer.turnOnAdditionalHtml4Errors();
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
true);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)
&& systemIdentifier != null) {
if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
}
} else {
err("The doctype was not a non-quirky HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
}
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
} else {
err("The doctype was not the HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
true);
}
break;
case AUTO:
html4 = isHtml4Doctype(publicIdentifier);
if (html4) {
tokenizer.turnOnAdditionalHtml4Errors();
}
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
err("Quirky doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
html4);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) {
if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
}
} else {
err("Almost standards mode doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
}
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
html4);
} else {
if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) {
if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) {
warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
}
} else {
if (!(publicIdentifier == null && systemIdentifier == null)) {
err("Legacy doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
}
}
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
html4);
}
break;
case NO_DOCTYPE_ERRORS:
if (isQuirky(name, publicIdentifier,
systemIdentifier, forceQuirks)) {
documentModeInternal(DocumentMode.QUIRKS_MODE,
publicIdentifier, systemIdentifier,
false);
} else if (isAlmostStandards(publicIdentifier,
systemIdentifier)) {
documentModeInternal(
DocumentMode.ALMOST_STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
} else {
documentModeInternal(
DocumentMode.STANDARDS_MODE,
publicIdentifier, systemIdentifier,
false);
}
break;
}
// ]NOCPP]
/*
*
* Then, switch to the root element mode of the tree
* construction stage.
*/
mode = BEFORE_HTML;
return;
default:
break;
}
}
/*
* A DOCTYPE token Parse error.
*/
err("Stray doctype.");
/*
* Ignore the token.
*/
return;
}
// [NOCPP[
private boolean isHtml4Doctype(String publicIdentifier) {
if (publicIdentifier != null
&& (Arrays.binarySearch(TreeBuilder.HTML4_PUBLIC_IDS,
publicIdentifier) > -1)) {
return true;
}
return false;
}
// ]NOCPP]
public final void comment(@NoLength char[] buf, int start, int length)
throws SAXException {
needToDropLF = false;
// [NOCPP[
if (!wantingComments) {
return;
}
// ]NOCPP]
if (!inForeign) {
switch (mode) {
case INITIAL:
case BEFORE_HTML:
case AFTER_AFTER_BODY:
case AFTER_AFTER_FRAMESET:
/*
* A comment token Append a Comment node to the Document
* object with the data attribute set to the data given in
* the comment token.
*/
appendCommentToDocument(buf, start, length);
return;
case AFTER_BODY:
/*
* A comment token Append a Comment node to the first
* element in the stack of open elements (the html element),
* with the data attribute set to the data given in the
* comment token.
*/
flushCharacters();
appendComment(stack[0].node, buf, start, length);
return;
default:
break;
}
}
/*
* A comment token Append a Comment node to the current node with the
* data attribute set to the data given in the comment token.
*/
flushCharacters();
appendComment(stack[currentPtr].node, buf, start, length);
return;
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#characters(char[], int,
* int)
*/
public final void characters(@Const @NoLength char[] buf, int start, int length)
throws SAXException {
if (needToDropLF) {
if (buf[start] == '\n') {
start++;
length--;
if (length == 0) {
return;
}
}
needToDropLF = false;
}
// optimize the most common case
switch (mode) {
case IN_BODY:
case IN_CELL:
case IN_CAPTION:
if (!inForeign) {
reconstructTheActiveFormattingElements();
}
// fall through
case TEXT:
accumulateCharacters(buf, start, length);
return;
case IN_TABLE:
case IN_TABLE_BODY:
case IN_ROW:
accumulateCharactersForced(buf, start, length);
return;
default:
int end = start + length;
charactersloop: for (int i = start; i < end; i++) {
switch (buf[i]) {
case ' ':
case '\t':
case '\n':
case '\r':
case '\u000C':
/*
* A character token that is one of one of U+0009
* CHARACTER TABULATION, U+000A LINE FEED (LF),
* U+000C FORM FEED (FF), or U+0020 SPACE
*/
switch (mode) {
case INITIAL:
case BEFORE_HTML:
case BEFORE_HEAD:
/*
* Ignore the token.
*/
start = i + 1;
continue;
case IN_HEAD:
case IN_HEAD_NOSCRIPT:
case AFTER_HEAD:
case IN_COLUMN_GROUP:
case IN_FRAMESET:
case AFTER_FRAMESET:
/*
* Append the character to the current node.
*/
continue;
case FRAMESET_OK:
case IN_BODY:
case IN_CELL:
case IN_CAPTION:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Reconstruct the active formatting
* elements, if any.
*/
if (!inForeign) {
flushCharacters();
reconstructTheActiveFormattingElements();
}
/*
* Append the token's character to the
* current node.
*/
break charactersloop;
case IN_SELECT:
case IN_SELECT_IN_TABLE:
break charactersloop;
case IN_TABLE:
case IN_TABLE_BODY:
case IN_ROW:
accumulateCharactersForced(buf, i, 1);
start = i + 1;
continue;
case AFTER_BODY:
case AFTER_AFTER_BODY:
case AFTER_AFTER_FRAMESET:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Reconstruct the active formatting
* elements, if any.
*/
flushCharacters();
reconstructTheActiveFormattingElements();
/*
* Append the token's character to the
* current node.
*/
continue;
}
default:
/*
* A character token that is not one of one of
* U+0009 CHARACTER TABULATION, U+000A LINE FEED
* (LF), U+000C FORM FEED (FF), or U+0020 SPACE
*/
switch (mode) {
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Non-space characters found without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(
DocumentMode.QUIRKS_MODE, null,
null, false);
/*
* Then, switch to the root element mode of
* the tree construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
i--;
continue;
case BEFORE_HTML:
/*
* Create an HTMLElement node with the tag
* name html, in the HTML namespace. Append
* it to the Document object.
*/
// No need to flush characters here,
// because there's nothing to flush.
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
i--;
continue;
case BEFORE_HEAD:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* /Act as if a start tag token with the tag
* name "head" and no attributes had been
* seen,
*/
flushCharacters();
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element
* being generated, with the current token
* being reprocessed in the "after head"
* insertion mode.
*/
i--;
continue;
case IN_HEAD:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Act as if an end tag token with the tag
* name "head" had been seen,
*/
flushCharacters();
pop();
mode = AFTER_HEAD;
/*
* and reprocess the current token.
*/
i--;
continue;
case IN_HEAD_NOSCRIPT:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Parse error. Act as if an end tag with
* the tag name "noscript" had been seen
*/
err("Non-space character inside \u201Cnoscript\u201D inside \u201Chead\u201D.");
flushCharacters();
pop();
mode = IN_HEAD;
/*
* and reprocess the current token.
*/
i--;
continue;
case AFTER_HEAD:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Act as if a start tag token with the tag
* name "body" and no attributes had been
* seen,
*/
flushCharacters();
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
/*
* and then reprocess the current token.
*/
i--;
continue;
case FRAMESET_OK:
framesetOk = false;
mode = IN_BODY;
i--;
continue;
case IN_BODY:
case IN_CELL:
case IN_CAPTION:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Reconstruct the active formatting
* elements, if any.
*/
if (!inForeign) {
flushCharacters();
reconstructTheActiveFormattingElements();
}
/*
* Append the token's character to the
* current node.
*/
break charactersloop;
case IN_TABLE:
case IN_TABLE_BODY:
case IN_ROW:
accumulateCharactersForced(buf, i, 1);
start = i + 1;
continue;
case IN_COLUMN_GROUP:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Act as if an end tag with the tag name
* "colgroup" had been seen, and then, if
* that token wasn't ignored, reprocess the
* current token.
*/
if (currentPtr == 0) {
err("Non-space in \u201Ccolgroup\u201D when parsing fragment.");
start = i + 1;
continue;
}
flushCharacters();
pop();
mode = IN_TABLE;
i--;
continue;
case IN_SELECT:
case IN_SELECT_IN_TABLE:
break charactersloop;
case AFTER_BODY:
err("Non-space character after body.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
i--;
continue;
case IN_FRAMESET:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Parse error.
*/
err("Non-space in \u201Cframeset\u201D.");
/*
* Ignore the token.
*/
start = i + 1;
continue;
case AFTER_FRAMESET:
if (start < i) {
accumulateCharacters(buf, start, i
- start);
start = i;
}
/*
* Parse error.
*/
err("Non-space after \u201Cframeset\u201D.");
/*
* Ignore the token.
*/
start = i + 1;
continue;
case AFTER_AFTER_BODY:
/*
* Parse error.
*/
err("Non-space character in page trailer.");
/*
* Switch back to the main mode and
* reprocess the token.
*/
mode = framesetOk ? FRAMESET_OK : IN_BODY;
i--;
continue;
case AFTER_AFTER_FRAMESET:
/*
* Parse error.
*/
err("Non-space character in page trailer.");
/*
* Switch back to the main mode and
* reprocess the token.
*/
mode = IN_FRAMESET;
i--;
continue;
}
}
}
if (start < end) {
accumulateCharacters(buf, start, end - start);
}
}
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#zeroOriginatingReplacementCharacter()
*/
public void zeroOriginatingReplacementCharacter()
throws SAXException {
if (inForeign || mode == TEXT) {
characters(REPLACEMENT_CHARACTER, 0, 1);
}
}
public final void eof() throws SAXException {
flushCharacters();
eofloop: for (;;) {
if (inForeign) {
err("End of file in a foreign namespace context.");
break eofloop;
}
switch (mode) {
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("End of file seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
/*
* Create an HTMLElement node with the tag name html, in the
* HTML namespace. Append it to the Document object.
*/
appendHtmlElementToDocumentAndPush();
// XXX application cache manifest
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
case BEFORE_HEAD:
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
continue;
case IN_HEAD:
if (errorHandler != null && currentPtr > 1) {
err("End of file seen and there were open elements.");
}
while (currentPtr > 0) {
popOnEof();
}
mode = AFTER_HEAD;
continue;
case IN_HEAD_NOSCRIPT:
err("End of file seen and there were open elements.");
while (currentPtr > 1) {
popOnEof();
}
mode = IN_HEAD;
continue;
case AFTER_HEAD:
appendToCurrentNodeAndPushBodyElement();
mode = IN_BODY;
continue;
case IN_COLUMN_GROUP:
if (currentPtr == 0) {
assert fragment;
break eofloop;
} else {
popOnEof();
mode = IN_TABLE;
continue;
}
case FRAMESET_OK:
case IN_CAPTION:
case IN_CELL:
case IN_BODY:
// [NOCPP[
openelementloop: for (int i = currentPtr; i >= 0; i--) {
int group = stack[i].group;
switch (group) {
case DD_OR_DT:
case LI:
case P:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case BODY:
case HTML:
break;
default:
err("End of file seen and there were open elements.");
break openelementloop;
}
}
// ]NOCPP]
break eofloop;
case TEXT:
err("End of file seen when expecting text or an end tag.");
// XXX mark script as already executed
if (originalMode == AFTER_HEAD) {
popOnEof();
}
popOnEof();
mode = originalMode;
continue;
case IN_TABLE_BODY:
case IN_ROW:
case IN_TABLE:
case IN_SELECT:
case IN_SELECT_IN_TABLE:
case IN_FRAMESET:
if (errorHandler != null && currentPtr > 0) {
errNoCheck("End of file seen and there were open elements.");
}
break eofloop;
case AFTER_BODY:
case AFTER_FRAMESET:
case AFTER_AFTER_BODY:
case AFTER_AFTER_FRAMESET:
default:
// [NOCPP[
if (currentPtr == 0) { // This silliness is here to poison
// buggy compiler optimizations in
// GWT
System.currentTimeMillis();
}
// ]NOCPP]
break eofloop;
}
}
while (currentPtr > 0) {
popOnEof();
}
if (!fragment) {
popOnEof();
}
/* Stop parsing. */
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#endTokenization()
*/
public final void endTokenization() throws SAXException {
Portability.releaseElement(formPointer);
formPointer = null;
Portability.releaseElement(headPointer);
headPointer = null;
Portability.releaseElement(deepTreeSurrogateParent);
deepTreeSurrogateParent = null;
if (stack != null) {
while (currentPtr > -1) {
stack[currentPtr].release();
currentPtr--;
}
stack = null;
}
if (listOfActiveFormattingElements != null) {
while (listPtr > -1) {
if (listOfActiveFormattingElements[listPtr] != null) {
listOfActiveFormattingElements[listPtr].release();
}
listPtr--;
}
listOfActiveFormattingElements = null;
}
// [NOCPP[
idLocations.clear();
// ]NOCPP]
charBuffer = null;
end();
}
public final void startTag(ElementName elementName,
HtmlAttributes attributes, boolean selfClosing) throws SAXException {
flushCharacters();
// [NOCPP[
if (errorHandler != null) {
// ID uniqueness
@IdType String id = attributes.getId();
if (id != null) {
LocatorImpl oldLoc = idLocations.get(id);
if (oldLoc != null) {
err("Duplicate ID \u201C" + id + "\u201D.");
errorHandler.warning(new SAXParseException(
"The first occurrence of ID \u201C" + id
+ "\u201D was here.", oldLoc));
} else {
idLocations.put(id, new LocatorImpl(tokenizer));
}
}
}
// ]NOCPP]
int eltPos;
needToDropLF = false;
boolean needsPostProcessing = false;
starttagloop: for (;;) {
int group = elementName.group;
@Local String name = elementName.name;
if (inForeign) {
StackNode<T> currentNode = stack[currentPtr];
@NsUri String currNs = currentNode.ns;
int currGroup = currentNode.group;
if (("http://www.w3.org/1999/xhtml" == currNs)
|| ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup)))
|| ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) {
needsPostProcessing = true;
// fall through to non-foreign behavior
} else {
switch (group) {
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case BODY:
case BR:
case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR:
case DD_OR_DT:
case UL_OR_OL_OR_DL:
case EMBED_OR_IMG:
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
case HEAD:
case HR:
case LI:
case META:
case NOBR:
case P:
case PRE_OR_LISTING:
case TABLE:
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
case FONT:
if (attributes.contains(AttributeName.COLOR)
|| attributes.contains(AttributeName.FACE)
|| attributes.contains(AttributeName.SIZE)) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
}
// else fall thru
default:
if ("http://www.w3.org/2000/svg" == currNs) {
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterCamelCase(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
} else {
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterNoScoping(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
}
} // switch
} // foreignObject / annotation-xml
}
switch (mode) {
case IN_TABLE_BODY:
switch (group) {
case TR:
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_ROW;
attributes = null; // CPP
break starttagloop;
case TD_OR_TH:
err("\u201C" + name
+ "\u201D start tag in table body.");
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TR,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_ROW;
continue;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
} else {
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
}
default:
// fall through to IN_TABLE
}
case IN_ROW:
switch (group) {
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TR));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CELL;
insertMarker();
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break starttagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
intableloop: for (;;) {
switch (group) {
case CAPTION:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
insertMarker();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CAPTION;
attributes = null; // CPP
break starttagloop;
case COLGROUP:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_COLUMN_GROUP;
attributes = null; // CPP
break starttagloop;
case COL:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.COLGROUP,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_COLUMN_GROUP;
continue starttagloop;
case TBODY_OR_THEAD_OR_TFOOT:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE_BODY;
attributes = null; // CPP
break starttagloop;
case TR:
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TBODY,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_TABLE_BODY;
continue starttagloop;
case TABLE:
err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
generateImpliedEndTags();
// XXX is the next if dead code?
if (errorHandler != null && !isCurrent("table")) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case INPUT:
if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE))) {
break intableloop;
}
appendVoidElementToCurrent(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D.");
appendVoidFormToCurrent(attributes);
attributes = null; // CPP
break starttagloop;
}
default:
err("Start tag \u201C" + name
+ "\u201D seen in \u201Ctable\u201D.");
// fall through to IN_BODY
break intableloop;
}
}
case IN_CAPTION:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("Stray \u201C"
+ name
+ "\u201D start tag in \u201Ccaption\u201D.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break starttagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
eltPos = findLastInTableScopeTdTh();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No cell to close.");
break starttagloop;
} else {
closeTheCell(eltPos);
continue;
}
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
switch (group) {
case FRAMESET:
if (mode == FRAMESET_OK) {
if (currentPtr == 0 || stack[1].group != BODY) {
assert fragment;
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
} else {
err("\u201Cframeset\u201D start tag seen.");
detachFromParent(stack[1].node);
while (currentPtr > 0) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
}
} else {
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
}
// NOT falling through!
case PRE_OR_LISTING:
case LI:
case DD_OR_DT:
case BUTTON:
case MARQUEE_OR_APPLET:
case OBJECT:
case TABLE:
case AREA_OR_WBR:
case BR:
case EMBED_OR_IMG:
case INPUT:
case KEYGEN:
case HR:
case TEXTAREA:
case XMP:
case IFRAME:
case SELECT:
- if (mode == FRAMESET_OK) {
+ if (mode == FRAMESET_OK
+ && !(group == INPUT && Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
+ "hidden",
+ attributes.getValue(AttributeName.TYPE)))) {
framesetOk = false;
mode = IN_BODY;
}
// fall through to IN_BODY
default:
// fall through to IN_BODY
}
case IN_BODY:
inbodyloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case LINK_OR_BASEFONT_OR_BGSOUND:
case META:
case STYLE:
case SCRIPT:
case TITLE:
case COMMAND:
// Fall through to IN_HEAD
break inbodyloop;
case BODY:
err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open.");
if (addAttributesToBody(attributes)) {
attributes = null; // CPP
}
break starttagloop;
case P:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
implicitlyCloseP();
if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
err("Heading cannot be a child of another heading.");
pop();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FIELDSET:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
case PRE_OR_LISTING:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
implicitlyCloseP();
appendToCurrentNodeAndPushFormElementMayFoster(attributes);
attributes = null; // CPP
break starttagloop;
}
case LI:
case DD_OR_DT:
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos]; // weak
// ref
if (node.group == group) { // LI or
// DD_OR_DT
generateImpliedEndTagsExceptFor(node.name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("Unclosed elements inside a list.");
}
while (currentPtr >= eltPos) {
pop();
}
break;
} else if (node.scoping
|| (node.special
&& node.name != "p"
&& node.name != "address" && node.name != "div")) {
break;
}
eltPos--;
}
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case PLAINTEXT:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.PLAINTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case A:
int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a");
if (activeAPos != -1) {
err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element.");
StackNode<T> activeA = listOfActiveFormattingElements[activeAPos];
activeA.retain();
adoptionAgencyEndTag("a");
removeFromStack(activeA);
activeAPos = findInListOfActiveFormattingElements(activeA);
if (activeAPos != -1) {
removeFromListOfActiveFormattingElements(activeAPos);
}
activeA.release();
}
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
reconstructTheActiveFormattingElements();
maybeForgetEarlierDuplicateFormattingElement(elementName.name, attributes);
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case NOBR:
reconstructTheActiveFormattingElements();
if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) {
err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope.");
adoptionAgencyEndTag("nobr");
}
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case BUTTON:
eltPos = findLastInScope(name);
if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) {
err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope.");
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
continue starttagloop;
} else {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes,
formPointer);
attributes = null; // CPP
break starttagloop;
}
case OBJECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
insertMarker();
attributes = null; // CPP
break starttagloop;
case MARQUEE_OR_APPLET:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
insertMarker();
attributes = null; // CPP
break starttagloop;
case TABLE:
// The only quirk. Blame Hixie and
// Acid2.
if (!quirks) {
implicitlyCloseP();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE;
attributes = null; // CPP
break starttagloop;
case BR:
case EMBED_OR_IMG:
case AREA_OR_WBR:
reconstructTheActiveFormattingElements();
// FALL THROUGH to PARAM_OR_SOURCE
case PARAM_OR_SOURCE:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case HR:
implicitlyCloseP();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case IMAGE:
err("Saw a start tag \u201Cimage\u201D.");
elementName = ElementName.IMG;
continue starttagloop;
case KEYGEN:
case INPUT:
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case ISINDEX:
err("\u201Cisindex\u201D seen.");
if (formPointer != null) {
break starttagloop;
}
implicitlyCloseP();
HtmlAttributes formAttrs = new HtmlAttributes(0);
int actionIndex = attributes.getIndex(AttributeName.ACTION);
if (actionIndex > -1) {
formAttrs.addAttribute(
AttributeName.ACTION,
attributes.getValue(actionIndex)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
appendToCurrentNodeAndPushFormElementMayFoster(formAttrs);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.LABEL,
HtmlAttributes.EMPTY_ATTRIBUTES);
int promptIndex = attributes.getIndex(AttributeName.PROMPT);
if (promptIndex > -1) {
@Auto char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex));
appendCharacters(stack[currentPtr].node,
prompt, 0, prompt.length);
} else {
appendIsindexPrompt(stack[currentPtr].node);
}
HtmlAttributes inputAttributes = new HtmlAttributes(
0);
inputAttributes.addAttribute(
AttributeName.NAME,
Portability.newStringFromLiteral("isindex")
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
for (int i = 0; i < attributes.getLength(); i++) {
AttributeName attributeQName = attributes.getAttributeName(i);
if (AttributeName.NAME == attributeQName
|| AttributeName.PROMPT == attributeQName) {
attributes.releaseValue(i);
} else if (AttributeName.ACTION != attributeQName) {
inputAttributes.addAttribute(
attributeQName,
attributes.getValue(i)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
}
attributes.clearWithoutReleasingContents();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
"input", inputAttributes, formPointer);
pop(); // label
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
pop(); // form
selfClosing = false;
// Portability.delete(formAttrs);
// Portability.delete(inputAttributes);
// Don't delete attributes, they are deleted
// later
break starttagloop;
case TEXTAREA:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
originalMode = mode;
mode = TEXT;
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case XMP:
implicitlyCloseP();
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (!scriptingEnabled) {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
} else {
// fall through
}
case NOFRAMES:
case IFRAME:
case NOEMBED:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case SELECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
switch (mode) {
case IN_TABLE:
case IN_CAPTION:
case IN_COLUMN_GROUP:
case IN_TABLE_BODY:
case IN_ROW:
case IN_CELL:
mode = IN_SELECT_IN_TABLE;
break;
default:
mode = IN_SELECT;
break;
}
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
case OPTION:
/*
* If the stack of open elements has an option
* element in scope, then act as if an end tag
* with the tag name "option" had been seen.
*/
if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) {
optionendtagloop: for (;;) {
if (isCurrent("option")) {
pop();
break optionendtagloop;
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == "option") {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent("option")) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break optionendtagloop;
}
eltPos--;
}
}
}
/*
* Reconstruct the active formatting elements,
* if any.
*/
reconstructTheActiveFormattingElements();
/*
* Insert an HTML element for the token.
*/
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case RT_OR_RP:
/*
* If the stack of open elements has a ruby
* element in scope, then generate implied end
* tags. If the current node is not then a ruby
* element, this is a parse error; pop all the
* nodes from the current node up to the node
* immediately before the bottommost ruby
* element on the stack of open elements.
*
* Insert an HTML element for the token.
*/
eltPos = findLastInScope("ruby");
if (eltPos != NOT_FOUND_ON_STACK) {
generateImpliedEndTags();
}
if (eltPos != currentPtr) {
err("Unclosed children in \u201Cruby\u201D.");
while (currentPtr > eltPos) {
pop();
}
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case MATH:
reconstructTheActiveFormattingElements();
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case SVG:
reconstructTheActiveFormattingElements();
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
"http://www.w3.org/2000/svg",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/2000/svg",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case FRAME:
case FRAMESET:
case HEAD:
err("Stray start tag \u201C" + name + "\u201D.");
break starttagloop;
case OUTPUT_OR_LABEL:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
default:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
}
}
case IN_HEAD:
inheadloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case COMMAND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
case LINK_OR_BASEFONT_OR_BGSOUND:
// Fall through to IN_HEAD_NOSCRIPT
break inheadloop;
case TITLE:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (scriptingEnabled) {
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_HEAD_NOSCRIPT;
}
attributes = null; // CPP
break starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
/* Parse error. */
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
/* Ignore the token. */
break starttagloop;
default:
pop();
mode = AFTER_HEAD;
continue starttagloop;
}
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case HTML:
// XXX did Hixie really mean to omit "base"
// here?
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
checkMetaCharset(attributes);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
break starttagloop;
case NOSCRIPT:
err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open.");
break starttagloop;
default:
err("Bad start tag in \u201C" + name
+ "\u201D in \u201Chead\u201D.");
pop();
mode = IN_HEAD;
continue;
}
case IN_COLUMN_GROUP:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case COL:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break starttagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case TABLE:
err("\u201C"
+ name
+ "\u201D start tag with \u201Cselect\u201D open.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case OPTION:
if (isCurrent("option")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
if (isCurrent("option")) {
pop();
}
if (isCurrent("optgroup")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case SELECT:
err("\u201Cselect\u201D start tag where end tag expected.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("No \u201Cselect\u201D in table scope.");
break starttagloop;
} else {
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break starttagloop;
}
case INPUT:
case TEXTAREA:
case KEYGEN:
err("\u201C"
+ name
+ "\u201D start tag seen in \u201Cselect\2201D.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FRAME:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
// fall through to AFTER_FRAMESET
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HTML:
// optimize error check and streaming SAX by
// hoisting
// "html" handling here.
if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendHtmlElementToDocumentAndPush();
} else {
appendHtmlElementToDocumentAndPush(attributes);
}
// XXX application cache should fire here
mode = BEFORE_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
}
case BEFORE_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case HEAD:
/*
* A start tag whose tag name is "head"
*
* Create an element for the token.
*
* Set the head element pointer to this new element
* node.
*
* Append the new element to the current node and
* push it onto the stack of open elements.
*/
appendToCurrentNodeAndPushHeadElement(attributes);
/*
* Change the insertion mode to "in head".
*/
mode = IN_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Any other start tag token
*
* Act as if a start tag token with the tag name
* "head" and no attributes had been seen,
*/
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element being
* generated, with the current token being
* reprocessed in the "after head" insertion mode.
*/
continue;
}
case AFTER_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BODY:
if (attributes.getLength() == 0) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendToCurrentNodeAndPushBodyElement();
} else {
appendToCurrentNodeAndPushBodyElement(attributes);
}
framesetOk = false;
mode = IN_BODY;
attributes = null; // CPP
break starttagloop;
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
case BASE:
err("\u201Cbase\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
err("\u201Clink\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case META:
err("\u201Cmeta\u201D element outside \u201Chead\u201D.");
checkMetaCharset(attributes);
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case SCRIPT:
err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
err("\u201C"
+ name
+ "\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case TITLE:
err("\u201Ctitle\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Stray start tag \u201Chead\u201D.");
break starttagloop;
default:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
}
case AFTER_AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case AFTER_AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case TEXT:
assert false;
break starttagloop; // Avoid infinite loop if the assertion
// fails
}
}
if (needsPostProcessing && inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
if (errorHandler != null && selfClosing) {
errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag.");
}
if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) {
Portability.delete(attributes);
}
}
private boolean isSpecialParentInForeign(StackNode<T> stackNode) {
@NsUri String ns = stackNode.ns;
if ("http://www.w3.org/1999/xhtml" == ns) {
return true;
}
if (ns == "http://www.w3.org/2000/svg") {
return stackNode.group == FOREIGNOBJECT_OR_DESC
|| stackNode.group == TITLE;
}
assert ns == "http://www.w3.org/1998/Math/MathML" : "Unexpected namespace.";
return stackNode.group == MI_MO_MN_MS_MTEXT;
}
/**
*
* <p>
* C++ memory note: The return value must be released.
*
* @return
* @throws SAXException
* @throws StopSniffingException
*/
public static String extractCharsetFromContent(String attributeValue) {
// This is a bit ugly. Converting the string to char array in order to
// make the portability layer smaller.
int charsetState = CHARSET_INITIAL;
int start = -1;
int end = -1;
@Auto char[] buffer = Portability.newCharArrayFromString(attributeValue);
charsetloop: for (int i = 0; i < buffer.length; i++) {
char c = buffer[i];
switch (charsetState) {
case CHARSET_INITIAL:
switch (c) {
case 'c':
case 'C':
charsetState = CHARSET_C;
continue;
default:
continue;
}
case CHARSET_C:
switch (c) {
case 'h':
case 'H':
charsetState = CHARSET_H;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_H:
switch (c) {
case 'a':
case 'A':
charsetState = CHARSET_A;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_A:
switch (c) {
case 'r':
case 'R':
charsetState = CHARSET_R;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_R:
switch (c) {
case 's':
case 'S':
charsetState = CHARSET_S;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_S:
switch (c) {
case 'e':
case 'E':
charsetState = CHARSET_E;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_E:
switch (c) {
case 't':
case 'T':
charsetState = CHARSET_T;
continue;
default:
charsetState = CHARSET_INITIAL;
continue;
}
case CHARSET_T:
switch (c) {
case '\t':
case '\n':
case '\u000C':
case '\r':
case ' ':
continue;
case '=':
charsetState = CHARSET_EQUALS;
continue;
default:
return null;
}
case CHARSET_EQUALS:
switch (c) {
case '\t':
case '\n':
case '\u000C':
case '\r':
case ' ':
continue;
case '\'':
start = i + 1;
charsetState = CHARSET_SINGLE_QUOTED;
continue;
case '\"':
start = i + 1;
charsetState = CHARSET_DOUBLE_QUOTED;
continue;
default:
start = i;
charsetState = CHARSET_UNQUOTED;
continue;
}
case CHARSET_SINGLE_QUOTED:
switch (c) {
case '\'':
end = i;
break charsetloop;
default:
continue;
}
case CHARSET_DOUBLE_QUOTED:
switch (c) {
case '\"':
end = i;
break charsetloop;
default:
continue;
}
case CHARSET_UNQUOTED:
switch (c) {
case '\t':
case '\n':
case '\u000C':
case '\r':
case ' ':
case ';':
end = i;
break charsetloop;
default:
continue;
}
}
}
String charset = null;
if (start != -1) {
if (end == -1) {
end = buffer.length;
}
charset = Portability.newStringFromBuffer(buffer, start, end
- start);
}
return charset;
}
private void checkMetaCharset(HtmlAttributes attributes)
throws SAXException {
String content = attributes.getValue(AttributeName.CONTENT);
String internalCharsetLegacy = null;
if (content != null) {
internalCharsetLegacy = TreeBuilder.extractCharsetFromContent(content);
// [NOCPP[
if (errorHandler != null
&& internalCharsetLegacy != null
&& !Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"content-type",
attributes.getValue(AttributeName.HTTP_EQUIV))) {
warn("Attribute \u201Ccontent\u201D would be sniffed as an internal character encoding declaration but there was no matching \u201Chttp-equiv='Content-Type'\u201D attribute.");
}
// ]NOCPP]
}
if (internalCharsetLegacy == null) {
String internalCharsetHtml5 = attributes.getValue(AttributeName.CHARSET);
if (internalCharsetHtml5 != null) {
tokenizer.internalEncodingDeclaration(internalCharsetHtml5);
requestSuspension();
}
} else {
tokenizer.internalEncodingDeclaration(internalCharsetLegacy);
Portability.releaseString(internalCharsetLegacy);
requestSuspension();
}
}
public final void endTag(ElementName elementName) throws SAXException {
flushCharacters();
needToDropLF = false;
int eltPos;
int group = elementName.group;
@Local String name = elementName.name;
endtagloop: for (;;) {
assert !inForeign || currentPtr >= 0 : "In foreign without a root element?";
if (inForeign
&& stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") {
if (errorHandler != null && stack[currentPtr].name != name) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D did not match the name of the current open element (\u201C"
+ stack[currentPtr].popName + "\u201D).");
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == name) {
while (currentPtr >= eltPos) {
pop();
}
break endtagloop;
}
if (stack[--eltPos].ns == "http://www.w3.org/1999/xhtml") {
break;
}
}
}
switch (mode) {
case IN_ROW:
switch (group) {
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
break endtagloop;
case TABLE:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
case TBODY_OR_THEAD_OR_TFOOT:
if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
case TD_OR_TH:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_TABLE
}
case IN_TABLE_BODY:
switch (group) {
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastOrRoot(name);
if (eltPos == 0) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
break endtagloop;
case TABLE:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
assert fragment;
err("Stray end tag \u201Ctable\u201D.");
break endtagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
case TD_OR_TH:
case TR:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
switch (group) {
case TABLE:
eltPos = findLast("table");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("Stray end tag \u201Ctable\u201D.");
break endtagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break endtagloop;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case TR:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D.");
// fall through to IN_BODY
}
case IN_CAPTION:
switch (group) {
case CAPTION:
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
break endtagloop;
case TABLE:
err("\u201Ctable\u201D closed but \u201Ccaption\u201D was still open.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
case BODY:
case COL:
case COLGROUP:
case HTML:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case TR:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case TD_OR_TH:
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("Unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_ROW;
break endtagloop;
case TABLE:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
closeTheCell(findLastInTableScopeTdTh());
continue;
case BODY:
case CAPTION:
case COL:
case COLGROUP:
case HTML:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
case IN_BODY:
switch (group) {
case BODY:
if (!isSecondOnStackBody()) {
assert fragment;
err("Stray end tag \u201Cbody\u201D.");
break endtagloop;
}
assert currentPtr >= 1;
if (errorHandler != null) {
uncloseloop1: for (int i = 2; i <= currentPtr; i++) {
switch (stack[i].group) {
case DD_OR_DT:
case LI:
case OPTGROUP:
case OPTION: // is this possible?
case P:
case RT_OR_RP:
case TD_OR_TH:
case TBODY_OR_THEAD_OR_TFOOT:
break;
default:
err("End tag for \u201Cbody\u201D seen but there were unclosed elements.");
break uncloseloop1;
}
}
}
mode = AFTER_BODY;
break endtagloop;
case HTML:
if (!isSecondOnStackBody()) {
assert fragment;
err("Stray end tag \u201Chtml\u201D.");
break endtagloop;
}
if (errorHandler != null) {
uncloseloop2: for (int i = 0; i <= currentPtr; i++) {
switch (stack[i].group) {
case DD_OR_DT:
case LI:
case P:
case TBODY_OR_THEAD_OR_TFOOT:
case TD_OR_TH:
case BODY:
case HTML:
break;
default:
err("End tag for \u201Chtml\u201D seen but there were unclosed elements.");
break uncloseloop2;
}
}
}
mode = AFTER_BODY;
continue;
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case PRE_OR_LISTING:
case FIELDSET:
case BUTTON:
case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY:
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
} else {
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case FORM:
if (formPointer == null) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
Portability.releaseElement(formPointer);
formPointer = null;
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
removeFromStack(eltPos);
break endtagloop;
case P:
eltPos = findLastInButtonScope("p");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No \u201Cp\u201D element in scope but a \u201Cp\u201D end tag seen.");
// XXX inline this case
if (inForeign) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") {
pop();
}
inForeign = false;
}
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName,
HtmlAttributes.EMPTY_ATTRIBUTES);
break endtagloop;
}
generateImpliedEndTagsExceptFor("p");
assert eltPos != TreeBuilder.NOT_FOUND_ON_STACK;
if (errorHandler != null && eltPos != currentPtr) {
errNoCheck("End tag for \u201Cp\u201D seen, but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break endtagloop;
case LI:
eltPos = findLastInListScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No \u201Cli\u201D element in list scope but a \u201Cli\u201D end tag seen.");
} else {
generateImpliedEndTagsExceptFor(name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("End tag for \u201Cli\u201D seen, but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case DD_OR_DT:
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No \u201C"
+ name
+ "\u201D element in scope but a \u201C"
+ name + "\u201D end tag seen.");
} else {
generateImpliedEndTagsExceptFor(name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("End tag for \u201C"
+ name
+ "\u201D seen, but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
eltPos = findLastInScopeHn();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
} else {
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
break endtagloop;
case OBJECT:
case MARQUEE_OR_APPLET:
eltPos = findLastInScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("Stray end tag \u201C" + name + "\u201D.");
} else {
generateImpliedEndTags();
if (errorHandler != null && !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
}
break endtagloop;
case BR:
err("End tag \u201Cbr\u201D.");
if (inForeign) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") {
pop();
}
inForeign = false;
}
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName,
HtmlAttributes.EMPTY_ATTRIBUTES);
break endtagloop;
case AREA_OR_WBR:
case PARAM_OR_SOURCE:
case EMBED_OR_IMG:
case IMAGE:
case INPUT:
case KEYGEN: // XXX??
case HR:
case ISINDEX:
case IFRAME:
case NOEMBED: // XXX???
case NOFRAMES: // XXX??
case SELECT:
case TABLE:
case TEXTAREA: // XXX??
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
case NOSCRIPT:
if (scriptingEnabled) {
err("Stray end tag \u201Cnoscript\u201D.");
break endtagloop;
} else {
// fall through
}
case A:
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
case NOBR:
if (adoptionAgencyEndTag(name)) {
break endtagloop;
}
// else handle like any other tag
default:
if (isCurrent(name)) {
pop();
break endtagloop;
}
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos];
if (node.name == name) {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break endtagloop;
} else if (node.scoping || node.special) {
err("Stray end tag \u201C" + name
+ "\u201D.");
break endtagloop;
}
eltPos--;
}
}
case IN_COLUMN_GROUP:
switch (group) {
case COLGROUP:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break endtagloop;
}
pop();
mode = IN_TABLE;
break endtagloop;
case COL:
err("Stray end tag \u201Ccol\u201D.");
break endtagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break endtagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TABLE:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("\u201C"
+ name
+ "\u201D end tag with \u201Cselect\u201D open.");
if (findLastInTableScope(name) != TreeBuilder.NOT_FOUND_ON_STACK) {
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break endtagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
} else {
break endtagloop;
}
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case OPTION:
if (isCurrent("option")) {
pop();
break endtagloop;
} else {
err("Stray end tag \u201Coption\u201D");
break endtagloop;
}
case OPTGROUP:
if (isCurrent("option")
&& "optgroup" == stack[currentPtr - 1].name) {
pop();
}
if (isCurrent("optgroup")) {
pop();
} else {
err("Stray end tag \u201Coptgroup\u201D");
}
break endtagloop;
case SELECT:
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("Stray end tag \u201Cselect\u201D");
break endtagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D");
break endtagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
if (fragment) {
err("Stray end tag \u201Chtml\u201D");
break endtagloop;
} else {
mode = AFTER_AFTER_BODY;
break endtagloop;
}
default:
err("Saw an end tag after \u201Cbody\u201D had been closed.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
if (currentPtr == 0) {
assert fragment;
err("Stray end tag \u201Cframeset\u201D");
break endtagloop;
}
pop();
if ((!fragment) && !isCurrent("frameset")) {
mode = AFTER_FRAMESET;
}
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D");
break endtagloop;
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
mode = AFTER_AFTER_FRAMESET;
break endtagloop;
default:
err("Stray end tag \u201C" + name + "\u201D");
break endtagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("End tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HEAD:
case BR:
case HTML:
case BODY:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case BEFORE_HEAD:
switch (group) {
case HEAD:
case BR:
case HTML:
case BODY:
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case IN_HEAD:
switch (group) {
case HEAD:
pop();
mode = AFTER_HEAD;
break endtagloop;
case BR:
case HTML:
case BODY:
pop();
mode = AFTER_HEAD;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case NOSCRIPT:
pop();
mode = IN_HEAD;
break endtagloop;
case BR:
err("Stray end tag \u201C" + name + "\u201D.");
pop();
mode = IN_HEAD;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case AFTER_HEAD:
switch (group) {
case HTML:
case BODY:
case BR:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
default:
err("Stray end tag \u201C" + name + "\u201D.");
break endtagloop;
}
case AFTER_AFTER_BODY:
err("Stray \u201C" + name + "\u201D end tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
case AFTER_AFTER_FRAMESET:
err("Stray \u201C" + name + "\u201D end tag.");
mode = IN_FRAMESET;
continue;
case TEXT:
// XXX need to manage insertion point here
pop();
if (originalMode == AFTER_HEAD) {
silentPop();
}
mode = originalMode;
break endtagloop;
}
} // endtagloop
if (inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
}
private int findLastInTableScopeOrRootTbodyTheadTfoot() {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].group == TreeBuilder.TBODY_OR_THEAD_OR_TFOOT) {
return i;
}
}
return 0;
}
private int findLast(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInTableScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].name == "table") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInButtonScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].scoping || stack[i].name == "button") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].scoping) {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInListScope(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
} else if (stack[i].scoping || stack[i].name == "ul" || stack[i].name == "ol") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private int findLastInScopeHn() {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].group == TreeBuilder.H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
return i;
} else if (stack[i].scoping) {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private boolean hasForeignInScope() {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].ns != "http://www.w3.org/1999/xhtml") {
return true;
} else if (stack[i].scoping) {
return false;
}
}
return false;
}
private void generateImpliedEndTagsExceptFor(@Local String name)
throws SAXException {
for (;;) {
StackNode<T> node = stack[currentPtr];
switch (node.group) {
case P:
case LI:
case DD_OR_DT:
case OPTION:
case OPTGROUP:
case RT_OR_RP:
if (node.name == name) {
return;
}
pop();
continue;
default:
return;
}
}
}
private void generateImpliedEndTags() throws SAXException {
for (;;) {
switch (stack[currentPtr].group) {
case P:
case LI:
case DD_OR_DT:
case OPTION:
case OPTGROUP:
case RT_OR_RP:
pop();
continue;
default:
return;
}
}
}
private boolean isSecondOnStackBody() {
return currentPtr >= 1 && stack[1].group == TreeBuilder.BODY;
}
private void documentModeInternal(DocumentMode m, String publicIdentifier,
String systemIdentifier, boolean html4SpecificAdditionalErrorChecks)
throws SAXException {
quirks = (m == DocumentMode.QUIRKS_MODE);
if (documentModeHandler != null) {
documentModeHandler.documentMode(
m
// [NOCPP[
, publicIdentifier, systemIdentifier,
html4SpecificAdditionalErrorChecks
// ]NOCPP]
);
}
// [NOCPP[
documentMode(m, publicIdentifier, systemIdentifier,
html4SpecificAdditionalErrorChecks);
// ]NOCPP]
}
private boolean isAlmostStandards(String publicIdentifier,
String systemIdentifier) {
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd xhtml 1.0 transitional//en", publicIdentifier)) {
return true;
}
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd xhtml 1.0 frameset//en", publicIdentifier)) {
return true;
}
if (systemIdentifier != null) {
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) {
return true;
}
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) {
return true;
}
}
return false;
}
private boolean isQuirky(@Local String name, String publicIdentifier,
String systemIdentifier, boolean forceQuirks) {
if (forceQuirks) {
return true;
}
if (name != HTML_LOCAL) {
return true;
}
if (publicIdentifier != null) {
for (int i = 0; i < TreeBuilder.QUIRKY_PUBLIC_IDS.length; i++) {
if (Portability.lowerCaseLiteralIsPrefixOfIgnoreAsciiCaseString(
TreeBuilder.QUIRKY_PUBLIC_IDS[i], publicIdentifier)) {
return true;
}
}
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3o//dtd w3 html strict 3.0//en//", publicIdentifier)
|| Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-/w3c/dtd html 4.0 transitional/en",
publicIdentifier)
|| Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"html", publicIdentifier)) {
return true;
}
}
if (systemIdentifier == null) {
if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) {
return true;
} else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) {
return true;
}
} else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",
systemIdentifier)) {
return true;
}
return false;
}
private void closeTheCell(int eltPos) throws SAXException {
generateImpliedEndTags();
if (errorHandler != null && eltPos != currentPtr) {
errNoCheck("Unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_ROW;
return;
}
private int findLastInTableScopeTdTh() {
for (int i = currentPtr; i > 0; i--) {
@Local String name = stack[i].name;
if ("td" == name || "th" == name) {
return i;
} else if (name == "table") {
return TreeBuilder.NOT_FOUND_ON_STACK;
}
}
return TreeBuilder.NOT_FOUND_ON_STACK;
}
private void clearStackBackTo(int eltPos) throws SAXException {
while (currentPtr > eltPos) { // > not >= intentional
pop();
}
}
private void resetTheInsertionMode() {
inForeign = false;
StackNode<T> node;
@Local String name;
@NsUri String ns;
for (int i = currentPtr; i >= 0; i--) {
node = stack[i];
name = node.name;
ns = node.ns;
if (i == 0) {
if (!(contextNamespace == "http://www.w3.org/1999/xhtml" && (contextName == "td" || contextName == "th"))) {
name = contextName;
ns = contextNamespace;
} else {
mode = framesetOk ? FRAMESET_OK : IN_BODY; // XXX from Hixie's email
return;
}
}
if ("select" == name) {
mode = IN_SELECT;
return;
} else if ("td" == name || "th" == name) {
mode = IN_CELL;
return;
} else if ("tr" == name) {
mode = IN_ROW;
return;
} else if ("tbody" == name || "thead" == name || "tfoot" == name) {
mode = IN_TABLE_BODY;
return;
} else if ("caption" == name) {
mode = IN_CAPTION;
return;
} else if ("colgroup" == name) {
mode = IN_COLUMN_GROUP;
return;
} else if ("table" == name) {
mode = IN_TABLE;
return;
} else if ("http://www.w3.org/1999/xhtml" != ns) {
inForeign = true;
mode = framesetOk ? FRAMESET_OK : IN_BODY;
return;
} else if ("head" == name) {
mode = framesetOk ? FRAMESET_OK : IN_BODY; // really
return;
} else if ("body" == name) {
mode = framesetOk ? FRAMESET_OK : IN_BODY;
return;
} else if ("frameset" == name) {
mode = IN_FRAMESET;
return;
} else if ("html" == name) {
if (headPointer == null) {
mode = BEFORE_HEAD;
} else {
mode = AFTER_HEAD;
}
return;
} else if (i == 0) {
mode = framesetOk ? FRAMESET_OK : IN_BODY;
return;
}
}
}
/**
* @throws SAXException
*
*/
private void implicitlyCloseP() throws SAXException {
int eltPos = findLastInButtonScope("p");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
return;
}
generateImpliedEndTagsExceptFor("p");
if (errorHandler != null && eltPos != currentPtr) {
err("Unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
}
private boolean clearLastStackSlot() {
stack[currentPtr] = null;
return true;
}
private boolean clearLastListSlot() {
listOfActiveFormattingElements[listPtr] = null;
return true;
}
@SuppressWarnings("unchecked") private void push(StackNode<T> node) throws SAXException {
currentPtr++;
if (currentPtr == stack.length) {
StackNode<T>[] newStack = new StackNode[stack.length + 64];
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
stack[currentPtr] = node;
elementPushed(node.ns, node.popName, node.node);
}
@SuppressWarnings("unchecked") private void silentPush(StackNode<T> node) throws SAXException {
currentPtr++;
if (currentPtr == stack.length) {
StackNode<T>[] newStack = new StackNode[stack.length + 64];
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
stack[currentPtr] = node;
}
@SuppressWarnings("unchecked") private void append(StackNode<T> node) {
listPtr++;
if (listPtr == listOfActiveFormattingElements.length) {
StackNode<T>[] newList = new StackNode[listOfActiveFormattingElements.length + 64];
System.arraycopy(listOfActiveFormattingElements, 0, newList, 0,
listOfActiveFormattingElements.length);
listOfActiveFormattingElements = newList;
}
listOfActiveFormattingElements[listPtr] = node;
}
@Inline private void insertMarker() {
append(null);
}
private void clearTheListOfActiveFormattingElementsUpToTheLastMarker() {
while (listPtr > -1) {
if (listOfActiveFormattingElements[listPtr] == null) {
--listPtr;
return;
}
listOfActiveFormattingElements[listPtr].release();
--listPtr;
}
}
@Inline private boolean isCurrent(@Local String name) {
return name == stack[currentPtr].name;
}
private void removeFromStack(int pos) throws SAXException {
if (currentPtr == pos) {
pop();
} else {
fatal();
stack[pos].release();
System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos);
assert clearLastStackSlot();
currentPtr--;
}
}
private void removeFromStack(StackNode<T> node) throws SAXException {
if (stack[currentPtr] == node) {
pop();
} else {
int pos = currentPtr - 1;
while (pos >= 0 && stack[pos] != node) {
pos--;
}
if (pos == -1) {
// dead code?
return;
}
fatal();
node.release();
System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos);
currentPtr--;
}
}
private void removeFromListOfActiveFormattingElements(int pos) {
assert listOfActiveFormattingElements[pos] != null;
listOfActiveFormattingElements[pos].release();
if (pos == listPtr) {
assert clearLastListSlot();
listPtr--;
return;
}
assert pos < listPtr;
System.arraycopy(listOfActiveFormattingElements, pos + 1,
listOfActiveFormattingElements, pos, listPtr - pos);
assert clearLastListSlot();
listPtr--;
}
private boolean adoptionAgencyEndTag(@Local String name) throws SAXException {
// If you crash around here, perhaps some stack node variable claimed to
// be a weak ref isn't.
for (int i = 0; i < 8; ++i) {
int formattingEltListPos = listPtr;
while (formattingEltListPos > -1) {
StackNode<T> listNode = listOfActiveFormattingElements[formattingEltListPos]; // weak
// ref
if (listNode == null) {
formattingEltListPos = -1;
break;
} else if (listNode.name == name) {
break;
}
formattingEltListPos--;
}
if (formattingEltListPos == -1) {
return false;
}
StackNode<T> formattingElt = listOfActiveFormattingElements[formattingEltListPos]; // this
// *looks*
// like
// a
// weak
// ref
// to
// the
// list
// of
// formatting
// elements
int formattingEltStackPos = currentPtr;
boolean inScope = true;
while (formattingEltStackPos > -1) {
StackNode<T> node = stack[formattingEltStackPos]; // weak ref
if (node == formattingElt) {
break;
} else if (node.scoping) {
inScope = false;
}
formattingEltStackPos--;
}
if (formattingEltStackPos == -1) {
err("No element \u201C" + name + "\u201D to close.");
removeFromListOfActiveFormattingElements(formattingEltListPos);
return true;
}
if (!inScope) {
err("No element \u201C" + name + "\u201D to close.");
return true;
}
// stackPos now points to the formatting element and it is in scope
if (errorHandler != null && formattingEltStackPos != currentPtr) {
errNoCheck("End tag \u201C" + name + "\u201D violates nesting rules.");
}
int furthestBlockPos = formattingEltStackPos + 1;
while (furthestBlockPos <= currentPtr) {
StackNode<T> node = stack[furthestBlockPos]; // weak ref
if (node.scoping || node.special) {
break;
}
furthestBlockPos++;
}
if (furthestBlockPos > currentPtr) {
// no furthest block
while (currentPtr >= formattingEltStackPos) {
pop();
}
removeFromListOfActiveFormattingElements(formattingEltListPos);
return true;
}
StackNode<T> commonAncestor = stack[formattingEltStackPos - 1]; // weak
// ref
StackNode<T> furthestBlock = stack[furthestBlockPos]; // weak ref
// detachFromParent(furthestBlock.node); XXX AAA CHANGE
int bookmark = formattingEltListPos;
int nodePos = furthestBlockPos;
StackNode<T> lastNode = furthestBlock; // weak ref
for (int j = 0; j < 3; ++j) {
nodePos--;
StackNode<T> node = stack[nodePos]; // weak ref
int nodeListPos = findInListOfActiveFormattingElements(node);
if (nodeListPos == -1) {
assert formattingEltStackPos < nodePos;
assert bookmark < nodePos;
assert furthestBlockPos > nodePos;
removeFromStack(nodePos); // node is now a bad pointer in
// C++
furthestBlockPos--;
continue;
}
// now node is both on stack and in the list
if (nodePos == formattingEltStackPos) {
break;
}
if (nodePos == furthestBlockPos) {
bookmark = nodeListPos + 1;
}
// if (hasChildren(node.node)) { XXX AAA CHANGE
assert node == listOfActiveFormattingElements[nodeListPos];
assert node == stack[nodePos];
T clone = createElement("http://www.w3.org/1999/xhtml",
node.name, node.attributes.cloneAttributes(null));
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
node.name, clone, node.scoping, node.special,
node.fosterParenting, node.popName, node.attributes); // creation
// ownership
// goes
// to
// stack
node.dropAttributes(); // adopt ownership to newNode
stack[nodePos] = newNode;
newNode.retain(); // retain for list
listOfActiveFormattingElements[nodeListPos] = newNode;
node.release(); // release from stack
node.release(); // release from list
node = newNode;
Portability.releaseElement(clone);
// } XXX AAA CHANGE
detachFromParent(lastNode.node);
appendElement(lastNode.node, node.node);
lastNode = node;
}
if (commonAncestor.fosterParenting) {
fatal();
detachFromParent(lastNode.node);
insertIntoFosterParent(lastNode.node);
} else {
detachFromParent(lastNode.node);
appendElement(lastNode.node, commonAncestor.node);
}
T clone = createElement("http://www.w3.org/1999/xhtml",
formattingElt.name,
formattingElt.attributes.cloneAttributes(null));
StackNode<T> formattingClone = new StackNode<T>(
formattingElt.group, formattingElt.ns, formattingElt.name,
clone, formattingElt.scoping, formattingElt.special,
formattingElt.fosterParenting, formattingElt.popName,
formattingElt.attributes); // Ownership
// transfers
// to
// stack
// below
formattingElt.dropAttributes(); // transfer ownership to
// formattingClone
appendChildrenToNewParent(furthestBlock.node, clone);
appendElement(clone, furthestBlock.node);
removeFromListOfActiveFormattingElements(formattingEltListPos);
insertIntoListOfActiveFormattingElements(formattingClone, bookmark);
assert formattingEltStackPos < furthestBlockPos;
removeFromStack(formattingEltStackPos);
// furthestBlockPos is now off by one and points to the slot after
// it
insertIntoStack(formattingClone, furthestBlockPos);
Portability.releaseElement(clone);
}
return true;
}
private void insertIntoStack(StackNode<T> node, int position)
throws SAXException {
assert currentPtr + 1 < stack.length;
assert position <= currentPtr + 1;
if (position == currentPtr + 1) {
push(node);
} else {
System.arraycopy(stack, position, stack, position + 1,
(currentPtr - position) + 1);
currentPtr++;
stack[position] = node;
}
}
private void insertIntoListOfActiveFormattingElements(
StackNode<T> formattingClone, int bookmark) {
formattingClone.retain();
assert listPtr + 1 < listOfActiveFormattingElements.length;
if (bookmark <= listPtr) {
System.arraycopy(listOfActiveFormattingElements, bookmark,
listOfActiveFormattingElements, bookmark + 1,
(listPtr - bookmark) + 1);
}
listPtr++;
listOfActiveFormattingElements[bookmark] = formattingClone;
}
private int findInListOfActiveFormattingElements(StackNode<T> node) {
for (int i = listPtr; i >= 0; i--) {
if (node == listOfActiveFormattingElements[i]) {
return i;
}
}
return -1;
}
private int findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker(
@Local String name) {
for (int i = listPtr; i >= 0; i--) {
StackNode<T> node = listOfActiveFormattingElements[i];
if (node == null) {
return -1;
} else if (node.name == name) {
return i;
}
}
return -1;
}
private void maybeForgetEarlierDuplicateFormattingElement(
@Local String name, HtmlAttributes attributes) throws SAXException {
int candidate = -1;
int count = 0;
for (int i = listPtr; i >= 0; i--) {
StackNode<T> node = listOfActiveFormattingElements[i];
if (node == null) {
break;
}
if (node.name == name && node.attributes.equalsAnother(attributes)) {
candidate = i;
++count;
}
}
if (count >= 3) {
removeFromListOfActiveFormattingElements(candidate);
}
}
private int findLastOrRoot(@Local String name) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].name == name) {
return i;
}
}
return 0;
}
private int findLastOrRoot(int group) {
for (int i = currentPtr; i > 0; i--) {
if (stack[i].group == group) {
return i;
}
}
return 0;
}
/**
* Attempt to add attribute to the body element.
* @param attributes the attributes
* @return <code>true</code> iff the attributes were added
* @throws SAXException
*/
private boolean addAttributesToBody(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
if (currentPtr >= 1) {
StackNode<T> body = stack[1];
if (body.group == TreeBuilder.BODY) {
addAttributesToElement(body.node, attributes);
return true;
}
}
return false;
}
private void addAttributesToHtml(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
addAttributesToElement(stack[0].node, attributes);
}
private void pushHeadPointerOntoStack() throws SAXException {
assert headPointer != null;
assert !fragment;
assert mode == AFTER_HEAD;
fatal();
silentPush(new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HEAD,
headPointer));
}
/**
* @throws SAXException
*
*/
private void reconstructTheActiveFormattingElements() throws SAXException {
if (listPtr == -1) {
return;
}
StackNode<T> mostRecent = listOfActiveFormattingElements[listPtr];
if (mostRecent == null || isInStack(mostRecent)) {
return;
}
int entryPos = listPtr;
for (;;) {
entryPos--;
if (entryPos == -1) {
break;
}
if (listOfActiveFormattingElements[entryPos] == null) {
break;
}
if (isInStack(listOfActiveFormattingElements[entryPos])) {
break;
}
}
while (entryPos < listPtr) {
entryPos++;
StackNode<T> entry = listOfActiveFormattingElements[entryPos];
T clone = createElement("http://www.w3.org/1999/xhtml", entry.name,
entry.attributes.cloneAttributes(null));
StackNode<T> entryClone = new StackNode<T>(entry.group, entry.ns,
entry.name, clone, entry.scoping, entry.special,
entry.fosterParenting, entry.popName, entry.attributes);
entry.dropAttributes(); // transfer ownership to entryClone
StackNode<T> currentNode = stack[currentPtr];
if (currentNode.fosterParenting) {
insertIntoFosterParent(clone);
} else {
appendElement(clone, currentNode.node);
}
push(entryClone);
// stack takes ownership of the local variable
listOfActiveFormattingElements[entryPos] = entryClone;
// overwriting the old entry on the list, so release & retain
entry.release();
entryClone.retain();
}
}
private void insertIntoFosterParent(T child) throws SAXException {
int eltPos = findLastOrRoot(TreeBuilder.TABLE);
StackNode<T> node = stack[eltPos];
T elt = node.node;
if (eltPos == 0) {
appendElement(child, elt);
return;
}
insertFosterParentedChild(child, elt, stack[eltPos - 1].node);
}
private boolean isInStack(StackNode<T> node) {
for (int i = currentPtr; i >= 0; i--) {
if (stack[i] == node) {
return true;
}
}
return false;
}
private void pop() throws SAXException {
StackNode<T> node = stack[currentPtr];
assert clearLastStackSlot();
currentPtr--;
elementPopped(node.ns, node.popName, node.node);
node.release();
}
private void silentPop() throws SAXException {
StackNode<T> node = stack[currentPtr];
assert clearLastStackSlot();
currentPtr--;
node.release();
}
private void popOnEof() throws SAXException {
StackNode<T> node = stack[currentPtr];
assert clearLastStackSlot();
currentPtr--;
markMalformedIfScript(node.node);
elementPopped(node.ns, node.popName, node.node);
node.release();
}
// [NOCPP[
private void checkAttributes(HtmlAttributes attributes, @NsUri String ns)
throws SAXException {
if (errorHandler != null) {
int len = attributes.getXmlnsLength();
for (int i = 0; i < len; i++) {
AttributeName name = attributes.getXmlnsAttributeName(i);
if (name == AttributeName.XMLNS) {
if (html4) {
err("Attribute \u201Cxmlns\u201D not allowed here. (HTML4-only error.)");
} else {
String xmlns = attributes.getXmlnsValue(i);
if (!ns.equals(xmlns)) {
err("Bad value \u201C"
+ xmlns
+ "\u201D for the attribute \u201Cxmlns\u201D (only \u201C"
+ ns + "\u201D permitted here).");
switch (namePolicy) {
case ALTER_INFOSET:
// fall through
case ALLOW:
warn("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0.");
break;
case FATAL:
fatal("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0.");
break;
}
}
}
} else if (ns != "http://www.w3.org/1999/xhtml"
&& name == AttributeName.XMLNS_XLINK) {
String xmlns = attributes.getXmlnsValue(i);
if (!"http://www.w3.org/1999/xlink".equals(xmlns)) {
err("Bad value \u201C"
+ xmlns
+ "\u201D for the attribute \u201Cxmlns:link\u201D (only \u201Chttp://www.w3.org/1999/xlink\u201D permitted here).");
switch (namePolicy) {
case ALTER_INFOSET:
// fall through
case ALLOW:
warn("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics.");
break;
case FATAL:
fatal("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics.");
break;
}
}
} else {
err("Attribute \u201C" + attributes.getXmlnsLocalName(i)
+ "\u201D not allowed here.");
switch (namePolicy) {
case ALTER_INFOSET:
// fall through
case ALLOW:
warn("Attribute with the local name \u201C"
+ attributes.getXmlnsLocalName(i)
+ "\u201D is not serializable as XML 1.0.");
break;
case FATAL:
fatal("Attribute with the local name \u201C"
+ attributes.getXmlnsLocalName(i)
+ "\u201D is not serializable as XML 1.0.");
break;
}
}
}
}
attributes.processNonNcNames(this, namePolicy);
}
private String checkPopName(@Local String name) throws SAXException {
if (NCName.isNCName(name)) {
return name;
} else {
switch (namePolicy) {
case ALLOW:
warn("Element name \u201C" + name
+ "\u201D cannot be represented as XML 1.0.");
return name;
case ALTER_INFOSET:
warn("Element name \u201C" + name
+ "\u201D cannot be represented as XML 1.0.");
return NCName.escapeName(name);
case FATAL:
fatal("Element name \u201C" + name
+ "\u201D cannot be represented as XML 1.0.");
}
}
return null; // keep compiler happy
}
// ]NOCPP]
private void appendHtmlElementToDocumentAndPush(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createHtmlElementSetAsRoot(attributes);
StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml",
ElementName.HTML, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendHtmlElementToDocumentAndPush() throws SAXException {
appendHtmlElementToDocumentAndPush(tokenizer.emptyAttributes());
}
private void appendToCurrentNodeAndPushHeadElement(HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createElement("http://www.w3.org/1999/xhtml", "head",
attributes);
appendElement(elt, stack[currentPtr].node);
headPointer = elt;
Portability.retainElement(headPointer);
StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml",
ElementName.HEAD, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushBodyElement(HtmlAttributes attributes)
throws SAXException {
appendToCurrentNodeAndPushElement("http://www.w3.org/1999/xhtml",
ElementName.BODY, attributes);
}
private void appendToCurrentNodeAndPushBodyElement() throws SAXException {
appendToCurrentNodeAndPushBodyElement(tokenizer.emptyAttributes());
}
private void appendToCurrentNodeAndPushFormElementMayFoster(
HtmlAttributes attributes) throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createElement("http://www.w3.org/1999/xhtml", "form",
attributes);
formPointer = elt;
Portability.retainElement(formPointer);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml",
ElementName.FORM, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushFormattingElementMayFoster(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// This method can't be called for custom elements
T elt = createElement(ns, elementName.name, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt,
attributes.cloneAttributes(null));
push(node);
append(node);
node.retain(); // append doesn't retain itself
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElement(@NsUri String ns,
ElementName elementName, HtmlAttributes attributes)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// This method can't be called for custom elements
T elt = createElement(ns, elementName.name, attributes);
appendElement(elt, stack[currentPtr].node);
StackNode<T> node = new StackNode<T>(ns, elementName, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns,
ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.name;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFosterNoScoping(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.name;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName,
false);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFosterCamelCase(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.camelCaseName;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName,
ElementName.FOREIGNOBJECT == elementName);
push(node);
Portability.releaseElement(elt);
}
private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns,
ElementName elementName, HtmlAttributes attributes, T form)
throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// Can't be called for custom elements
T elt = createElement(ns, elementName.name, attributes, fragment ? null
: form);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
StackNode<T> node = new StackNode<T>(ns, elementName, elt);
push(node);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrentMayFoster(
@NsUri String ns, @Local String name, HtmlAttributes attributes,
T form) throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// Can't be called for custom elements
T elt = createElement(ns, name, attributes, fragment ? null : form);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
elementPushed(ns, name, elt);
elementPopped(ns, name, elt);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrentMayFoster(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.name;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
elementPushed(ns, popName, elt);
elementPopped(ns, popName, elt);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrentMayFosterCamelCase(
@NsUri String ns, ElementName elementName, HtmlAttributes attributes)
throws SAXException {
@Local String popName = elementName.camelCaseName;
// [NOCPP[
checkAttributes(attributes, ns);
if (elementName.custom) {
popName = checkPopName(popName);
}
// ]NOCPP]
T elt = createElement(ns, popName, attributes);
StackNode<T> current = stack[currentPtr];
if (current.fosterParenting) {
fatal();
insertIntoFosterParent(elt);
} else {
appendElement(elt, current.node);
}
elementPushed(ns, popName, elt);
elementPopped(ns, popName, elt);
Portability.releaseElement(elt);
}
private void appendVoidElementToCurrent(
@NsUri String ns, @Local String name, HtmlAttributes attributes,
T form) throws SAXException {
// [NOCPP[
checkAttributes(attributes, ns);
// ]NOCPP]
// Can't be called for custom elements
T elt = createElement(ns, name, attributes, fragment ? null : form);
StackNode<T> current = stack[currentPtr];
appendElement(elt, current.node);
elementPushed(ns, name, elt);
elementPopped(ns, name, elt);
Portability.releaseElement(elt);
}
private void appendVoidFormToCurrent(HtmlAttributes attributes) throws SAXException {
// [NOCPP[
checkAttributes(attributes, "http://www.w3.org/1999/xhtml");
// ]NOCPP]
T elt = createElement("http://www.w3.org/1999/xhtml", "form",
attributes);
formPointer = elt;
// ownership transferred to form pointer
StackNode<T> current = stack[currentPtr];
appendElement(elt, current.node);
elementPushed("http://www.w3.org/1999/xhtml", "form", elt);
elementPopped("http://www.w3.org/1999/xhtml", "form", elt);
}
// [NOCPP[
private final void accumulateCharactersForced(@Const @NoLength char[] buf,
int start, int length) throws SAXException {
int newLen = charBufferLen + length;
if (newLen > charBuffer.length) {
char[] newBuf = new char[newLen];
System.arraycopy(charBuffer, 0, newBuf, 0, charBufferLen);
charBuffer = newBuf;
}
System.arraycopy(buf, start, charBuffer, charBufferLen, length);
charBufferLen = newLen;
}
// ]NOCPP]
protected void accumulateCharacters(@Const @NoLength char[] buf, int start,
int length) throws SAXException {
appendCharacters(stack[currentPtr].node, buf, start, length);
}
// ------------------------------- //
protected final void requestSuspension() {
tokenizer.requestSuspension();
}
protected abstract T createElement(@NsUri String ns, @Local String name,
HtmlAttributes attributes) throws SAXException;
protected T createElement(@NsUri String ns, @Local String name,
HtmlAttributes attributes, T form) throws SAXException {
return createElement("http://www.w3.org/1999/xhtml", name, attributes);
}
protected abstract T createHtmlElementSetAsRoot(HtmlAttributes attributes)
throws SAXException;
protected abstract void detachFromParent(T element) throws SAXException;
protected abstract boolean hasChildren(T element) throws SAXException;
protected abstract void appendElement(T child, T newParent)
throws SAXException;
protected abstract void appendChildrenToNewParent(T oldParent, T newParent)
throws SAXException;
protected abstract void insertFosterParentedChild(T child, T table,
T stackParent) throws SAXException;
protected abstract void insertFosterParentedCharacters(
@NoLength char[] buf, int start, int length, T table, T stackParent)
throws SAXException;
protected abstract void appendCharacters(T parent, @NoLength char[] buf,
int start, int length) throws SAXException;
protected abstract void appendIsindexPrompt(T parent) throws SAXException;
protected abstract void appendComment(T parent, @NoLength char[] buf,
int start, int length) throws SAXException;
protected abstract void appendCommentToDocument(@NoLength char[] buf,
int start, int length) throws SAXException;
protected abstract void addAttributesToElement(T element,
HtmlAttributes attributes) throws SAXException;
protected void markMalformedIfScript(T elt) throws SAXException {
}
protected void start(boolean fragmentMode) throws SAXException {
}
protected void end() throws SAXException {
}
protected void appendDoctypeToDocument(@Local String name,
String publicIdentifier, String systemIdentifier)
throws SAXException {
}
protected void elementPushed(@NsUri String ns, @Local String name, T node)
throws SAXException {
}
protected void elementPopped(@NsUri String ns, @Local String name, T node)
throws SAXException {
}
// [NOCPP[
protected void documentMode(DocumentMode m, String publicIdentifier,
String systemIdentifier, boolean html4SpecificAdditionalErrorChecks)
throws SAXException {
}
/**
* @see nu.validator.htmlparser.common.TokenHandler#wantsComments()
*/
public boolean wantsComments() {
return wantingComments;
}
public void setIgnoringComments(boolean ignoreComments) {
wantingComments = !ignoreComments;
}
/**
* Sets the errorHandler.
*
* @param errorHandler
* the errorHandler to set
*/
public final void setErrorHandler(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
/**
* Returns the errorHandler.
*
* @return the errorHandler
*/
public ErrorHandler getErrorHandler() {
return errorHandler;
}
/**
* The argument MUST be an interned string or <code>null</code>.
*
* @param context
*/
public final void setFragmentContext(@Local String context) {
this.contextName = context;
this.contextNamespace = "http://www.w3.org/1999/xhtml";
this.contextNode = null;
this.fragment = (contextName != null);
this.quirks = false;
}
// ]NOCPP]
/**
* @see nu.validator.htmlparser.common.TokenHandler#cdataSectionAllowed()
*/
public boolean cdataSectionAllowed() throws SAXException {
return inForeign && currentPtr >= 0
&& stack[currentPtr].ns != "http://www.w3.org/1999/xhtml";
}
/**
* The argument MUST be an interned string or <code>null</code>.
*
* @param context
*/
public final void setFragmentContext(@Local String context,
@NsUri String ns, T node, boolean quirks) {
this.contextName = context;
Portability.retainLocal(context);
this.contextNamespace = ns;
this.contextNode = node;
Portability.retainElement(node);
this.fragment = (contextName != null);
this.quirks = quirks;
}
protected final T currentNode() {
return stack[currentPtr].node;
}
/**
* Returns the scriptingEnabled.
*
* @return the scriptingEnabled
*/
public boolean isScriptingEnabled() {
return scriptingEnabled;
}
/**
* Sets the scriptingEnabled.
*
* @param scriptingEnabled
* the scriptingEnabled to set
*/
public void setScriptingEnabled(boolean scriptingEnabled) {
this.scriptingEnabled = scriptingEnabled;
}
// [NOCPP[
/**
* Sets the doctypeExpectation.
*
* @param doctypeExpectation
* the doctypeExpectation to set
*/
public void setDoctypeExpectation(DoctypeExpectation doctypeExpectation) {
this.doctypeExpectation = doctypeExpectation;
}
public void setNamePolicy(XmlViolationPolicy namePolicy) {
this.namePolicy = namePolicy;
}
/**
* Sets the documentModeHandler.
*
* @param documentModeHandler
* the documentModeHandler to set
*/
public void setDocumentModeHandler(DocumentModeHandler documentModeHandler) {
this.documentModeHandler = documentModeHandler;
}
/**
* Sets the reportingDoctype.
*
* @param reportingDoctype
* the reportingDoctype to set
*/
public void setReportingDoctype(boolean reportingDoctype) {
this.reportingDoctype = reportingDoctype;
}
// ]NOCPP]
/**
* Flushes the pending characters. Public for document.write use cases only.
* @throws SAXException
*/
public final void flushCharacters() throws SAXException {
if (charBufferLen > 0) {
if ((mode == IN_TABLE || mode == IN_TABLE_BODY || mode == IN_ROW)
&& charBufferContainsNonWhitespace()) {
err("Misplaced non-space characters insided a table.");
reconstructTheActiveFormattingElements();
if (!stack[currentPtr].fosterParenting) {
// reconstructing gave us a new current node
appendCharacters(currentNode(), charBuffer, 0,
charBufferLen);
charBufferLen = 0;
return;
}
int eltPos = findLastOrRoot(TreeBuilder.TABLE);
StackNode<T> node = stack[eltPos];
T elt = node.node;
if (eltPos == 0) {
appendCharacters(elt, charBuffer, 0, charBufferLen);
charBufferLen = 0;
return;
}
insertFosterParentedCharacters(charBuffer, 0, charBufferLen,
elt, stack[eltPos - 1].node);
charBufferLen = 0;
return;
}
appendCharacters(currentNode(), charBuffer, 0, charBufferLen);
charBufferLen = 0;
}
}
private boolean charBufferContainsNonWhitespace() {
for (int i = 0; i < charBufferLen; i++) {
switch (charBuffer[i]) {
case ' ':
case '\t':
case '\n':
case '\r':
case '\u000C':
continue;
default:
return true;
}
}
return false;
}
/**
* Creates a comparable snapshot of the tree builder state. Snapshot
* creation is only supported immediately after a script end tag has been
* processed. In C++ the caller is responsible for calling
* <code>delete</code> on the returned object.
*
* @return a snapshot.
* @throws SAXException
*/
@SuppressWarnings("unchecked") public TreeBuilderState<T> newSnapshot()
throws SAXException {
StackNode<T>[] listCopy = new StackNode[listPtr + 1];
for (int i = 0; i < listCopy.length; i++) {
StackNode<T> node = listOfActiveFormattingElements[i];
if (node != null) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
node.name, node.node, node.scoping, node.special,
node.fosterParenting, node.popName,
node.attributes.cloneAttributes(null));
listCopy[i] = newNode;
} else {
listCopy[i] = null;
}
}
StackNode<T>[] stackCopy = new StackNode[currentPtr + 1];
for (int i = 0; i < stackCopy.length; i++) {
StackNode<T> node = stack[i];
int listIndex = findInListOfActiveFormattingElements(node);
if (listIndex == -1) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
node.name, node.node, node.scoping, node.special,
node.fosterParenting, node.popName,
null);
stackCopy[i] = newNode;
} else {
stackCopy[i] = listCopy[listIndex];
stackCopy[i].retain();
}
}
Portability.retainElement(formPointer);
return new StateSnapshot<T>(stackCopy, listCopy, formPointer, headPointer, deepTreeSurrogateParent, mode, originalMode, framesetOk, inForeign, needToDropLF, quirks);
}
public boolean snapshotMatches(TreeBuilderState<T> snapshot) {
StackNode<T>[] stackCopy = snapshot.getStack();
int stackLen = snapshot.getStackLength();
StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements();
int listLen = snapshot.getListOfActiveFormattingElementsLength();
if (stackLen != currentPtr + 1
|| listLen != listPtr + 1
|| formPointer != snapshot.getFormPointer()
|| headPointer != snapshot.getHeadPointer()
|| deepTreeSurrogateParent != snapshot.getDeepTreeSurrogateParent()
|| mode != snapshot.getMode()
|| originalMode != snapshot.getOriginalMode()
|| framesetOk != snapshot.isFramesetOk()
|| inForeign != snapshot.isInForeign()
|| needToDropLF != snapshot.isNeedToDropLF()
|| quirks != snapshot.isQuirks()) { // maybe just assert quirks
return false;
}
for (int i = listLen - 1; i >= 0; i--) {
if (listCopy[i] == null
&& listOfActiveFormattingElements[i] == null) {
continue;
} else if (listCopy[i] == null
|| listOfActiveFormattingElements[i] == null) {
return false;
}
if (listCopy[i].node != listOfActiveFormattingElements[i].node) {
return false; // it's possible that this condition is overly
// strict
}
}
for (int i = stackLen - 1; i >= 0; i--) {
if (stackCopy[i].node != stack[i].node) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked") public void loadState(
TreeBuilderState<T> snapshot, Interner interner)
throws SAXException {
StackNode<T>[] stackCopy = snapshot.getStack();
int stackLen = snapshot.getStackLength();
StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements();
int listLen = snapshot.getListOfActiveFormattingElementsLength();
for (int i = 0; i <= listPtr; i++) {
if (listOfActiveFormattingElements[i] != null) {
listOfActiveFormattingElements[i].release();
}
}
if (listOfActiveFormattingElements.length < listLen) {
listOfActiveFormattingElements = new StackNode[listLen];
}
listPtr = listLen - 1;
for (int i = 0; i <= currentPtr; i++) {
stack[i].release();
}
if (stack.length < stackLen) {
stack = new StackNode[stackLen];
}
currentPtr = stackLen - 1;
for (int i = 0; i < listLen; i++) {
StackNode<T> node = listCopy[i];
if (node != null) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
Portability.newLocalFromLocal(node.name, interner), node.node,
node.scoping, node.special, node.fosterParenting,
Portability.newLocalFromLocal(node.popName, interner),
node.attributes.cloneAttributes(null));
listOfActiveFormattingElements[i] = newNode;
} else {
listOfActiveFormattingElements[i] = null;
}
}
for (int i = 0; i < stackLen; i++) {
StackNode<T> node = stackCopy[i];
int listIndex = findInArray(node, listCopy);
if (listIndex == -1) {
StackNode<T> newNode = new StackNode<T>(node.group, node.ns,
Portability.newLocalFromLocal(node.name, interner), node.node,
node.scoping, node.special, node.fosterParenting,
Portability.newLocalFromLocal(node.popName, interner),
null);
stack[i] = newNode;
} else {
stack[i] = listOfActiveFormattingElements[listIndex];
stack[i].retain();
}
}
Portability.releaseElement(formPointer);
formPointer = snapshot.getFormPointer();
Portability.retainElement(formPointer);
Portability.releaseElement(headPointer);
headPointer = snapshot.getHeadPointer();
Portability.retainElement(headPointer);
Portability.releaseElement(deepTreeSurrogateParent);
deepTreeSurrogateParent = snapshot.getDeepTreeSurrogateParent();
Portability.retainElement(deepTreeSurrogateParent);
mode = snapshot.getMode();
originalMode = snapshot.getOriginalMode();
framesetOk = snapshot.isFramesetOk();
inForeign = snapshot.isInForeign();
needToDropLF = snapshot.isNeedToDropLF();
quirks = snapshot.isQuirks();
}
private int findInArray(StackNode<T> node, StackNode<T>[] arr) {
for (int i = listPtr; i >= 0; i--) {
if (node == arr[i]) {
return i;
}
}
return -1;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getFormPointer()
*/
public T getFormPointer() {
return formPointer;
}
/**
* Returns the headPointer.
*
* @return the headPointer
*/
public T getHeadPointer() {
return headPointer;
}
/**
* Returns the deepTreeSurrogateParent.
*
* @return the deepTreeSurrogateParent
*/
public T getDeepTreeSurrogateParent() {
return deepTreeSurrogateParent;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElements()
*/
public StackNode<T>[] getListOfActiveFormattingElements() {
return listOfActiveFormattingElements;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getStack()
*/
public StackNode<T>[] getStack() {
return stack;
}
/**
* Returns the mode.
*
* @return the mode
*/
public int getMode() {
return mode;
}
/**
* Returns the originalMode.
*
* @return the originalMode
*/
public int getOriginalMode() {
return originalMode;
}
/**
* Returns the framesetOk.
*
* @return the framesetOk
*/
public boolean isFramesetOk() {
return framesetOk;
}
/**
* Returns the foreignFlag.
*
* @return the foreignFlag
*/
public boolean isInForeign() {
return inForeign;
}
/**
* Returns the needToDropLF.
*
* @return the needToDropLF
*/
public boolean isNeedToDropLF() {
return needToDropLF;
}
/**
* Returns the quirks.
*
* @return the quirks
*/
public boolean isQuirks() {
return quirks;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElementsLength()
*/
public int getListOfActiveFormattingElementsLength() {
return listPtr + 1;
}
/**
* @see nu.validator.htmlparser.impl.TreeBuilderState#getStackLength()
*/
public int getStackLength() {
return currentPtr + 1;
}
}
| true | true | public final void startTag(ElementName elementName,
HtmlAttributes attributes, boolean selfClosing) throws SAXException {
flushCharacters();
// [NOCPP[
if (errorHandler != null) {
// ID uniqueness
@IdType String id = attributes.getId();
if (id != null) {
LocatorImpl oldLoc = idLocations.get(id);
if (oldLoc != null) {
err("Duplicate ID \u201C" + id + "\u201D.");
errorHandler.warning(new SAXParseException(
"The first occurrence of ID \u201C" + id
+ "\u201D was here.", oldLoc));
} else {
idLocations.put(id, new LocatorImpl(tokenizer));
}
}
}
// ]NOCPP]
int eltPos;
needToDropLF = false;
boolean needsPostProcessing = false;
starttagloop: for (;;) {
int group = elementName.group;
@Local String name = elementName.name;
if (inForeign) {
StackNode<T> currentNode = stack[currentPtr];
@NsUri String currNs = currentNode.ns;
int currGroup = currentNode.group;
if (("http://www.w3.org/1999/xhtml" == currNs)
|| ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup)))
|| ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) {
needsPostProcessing = true;
// fall through to non-foreign behavior
} else {
switch (group) {
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case BODY:
case BR:
case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR:
case DD_OR_DT:
case UL_OR_OL_OR_DL:
case EMBED_OR_IMG:
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
case HEAD:
case HR:
case LI:
case META:
case NOBR:
case P:
case PRE_OR_LISTING:
case TABLE:
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
case FONT:
if (attributes.contains(AttributeName.COLOR)
|| attributes.contains(AttributeName.FACE)
|| attributes.contains(AttributeName.SIZE)) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
}
// else fall thru
default:
if ("http://www.w3.org/2000/svg" == currNs) {
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterCamelCase(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
} else {
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterNoScoping(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
}
} // switch
} // foreignObject / annotation-xml
}
switch (mode) {
case IN_TABLE_BODY:
switch (group) {
case TR:
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_ROW;
attributes = null; // CPP
break starttagloop;
case TD_OR_TH:
err("\u201C" + name
+ "\u201D start tag in table body.");
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TR,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_ROW;
continue;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
} else {
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
}
default:
// fall through to IN_TABLE
}
case IN_ROW:
switch (group) {
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TR));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CELL;
insertMarker();
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break starttagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
intableloop: for (;;) {
switch (group) {
case CAPTION:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
insertMarker();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CAPTION;
attributes = null; // CPP
break starttagloop;
case COLGROUP:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_COLUMN_GROUP;
attributes = null; // CPP
break starttagloop;
case COL:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.COLGROUP,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_COLUMN_GROUP;
continue starttagloop;
case TBODY_OR_THEAD_OR_TFOOT:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE_BODY;
attributes = null; // CPP
break starttagloop;
case TR:
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TBODY,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_TABLE_BODY;
continue starttagloop;
case TABLE:
err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
generateImpliedEndTags();
// XXX is the next if dead code?
if (errorHandler != null && !isCurrent("table")) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case INPUT:
if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE))) {
break intableloop;
}
appendVoidElementToCurrent(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D.");
appendVoidFormToCurrent(attributes);
attributes = null; // CPP
break starttagloop;
}
default:
err("Start tag \u201C" + name
+ "\u201D seen in \u201Ctable\u201D.");
// fall through to IN_BODY
break intableloop;
}
}
case IN_CAPTION:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("Stray \u201C"
+ name
+ "\u201D start tag in \u201Ccaption\u201D.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break starttagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
eltPos = findLastInTableScopeTdTh();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No cell to close.");
break starttagloop;
} else {
closeTheCell(eltPos);
continue;
}
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
switch (group) {
case FRAMESET:
if (mode == FRAMESET_OK) {
if (currentPtr == 0 || stack[1].group != BODY) {
assert fragment;
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
} else {
err("\u201Cframeset\u201D start tag seen.");
detachFromParent(stack[1].node);
while (currentPtr > 0) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
}
} else {
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
}
// NOT falling through!
case PRE_OR_LISTING:
case LI:
case DD_OR_DT:
case BUTTON:
case MARQUEE_OR_APPLET:
case OBJECT:
case TABLE:
case AREA_OR_WBR:
case BR:
case EMBED_OR_IMG:
case INPUT:
case KEYGEN:
case HR:
case TEXTAREA:
case XMP:
case IFRAME:
case SELECT:
if (mode == FRAMESET_OK) {
framesetOk = false;
mode = IN_BODY;
}
// fall through to IN_BODY
default:
// fall through to IN_BODY
}
case IN_BODY:
inbodyloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case LINK_OR_BASEFONT_OR_BGSOUND:
case META:
case STYLE:
case SCRIPT:
case TITLE:
case COMMAND:
// Fall through to IN_HEAD
break inbodyloop;
case BODY:
err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open.");
if (addAttributesToBody(attributes)) {
attributes = null; // CPP
}
break starttagloop;
case P:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
implicitlyCloseP();
if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
err("Heading cannot be a child of another heading.");
pop();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FIELDSET:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
case PRE_OR_LISTING:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
implicitlyCloseP();
appendToCurrentNodeAndPushFormElementMayFoster(attributes);
attributes = null; // CPP
break starttagloop;
}
case LI:
case DD_OR_DT:
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos]; // weak
// ref
if (node.group == group) { // LI or
// DD_OR_DT
generateImpliedEndTagsExceptFor(node.name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("Unclosed elements inside a list.");
}
while (currentPtr >= eltPos) {
pop();
}
break;
} else if (node.scoping
|| (node.special
&& node.name != "p"
&& node.name != "address" && node.name != "div")) {
break;
}
eltPos--;
}
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case PLAINTEXT:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.PLAINTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case A:
int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a");
if (activeAPos != -1) {
err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element.");
StackNode<T> activeA = listOfActiveFormattingElements[activeAPos];
activeA.retain();
adoptionAgencyEndTag("a");
removeFromStack(activeA);
activeAPos = findInListOfActiveFormattingElements(activeA);
if (activeAPos != -1) {
removeFromListOfActiveFormattingElements(activeAPos);
}
activeA.release();
}
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
reconstructTheActiveFormattingElements();
maybeForgetEarlierDuplicateFormattingElement(elementName.name, attributes);
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case NOBR:
reconstructTheActiveFormattingElements();
if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) {
err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope.");
adoptionAgencyEndTag("nobr");
}
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case BUTTON:
eltPos = findLastInScope(name);
if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) {
err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope.");
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
continue starttagloop;
} else {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes,
formPointer);
attributes = null; // CPP
break starttagloop;
}
case OBJECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
insertMarker();
attributes = null; // CPP
break starttagloop;
case MARQUEE_OR_APPLET:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
insertMarker();
attributes = null; // CPP
break starttagloop;
case TABLE:
// The only quirk. Blame Hixie and
// Acid2.
if (!quirks) {
implicitlyCloseP();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE;
attributes = null; // CPP
break starttagloop;
case BR:
case EMBED_OR_IMG:
case AREA_OR_WBR:
reconstructTheActiveFormattingElements();
// FALL THROUGH to PARAM_OR_SOURCE
case PARAM_OR_SOURCE:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case HR:
implicitlyCloseP();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case IMAGE:
err("Saw a start tag \u201Cimage\u201D.");
elementName = ElementName.IMG;
continue starttagloop;
case KEYGEN:
case INPUT:
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case ISINDEX:
err("\u201Cisindex\u201D seen.");
if (formPointer != null) {
break starttagloop;
}
implicitlyCloseP();
HtmlAttributes formAttrs = new HtmlAttributes(0);
int actionIndex = attributes.getIndex(AttributeName.ACTION);
if (actionIndex > -1) {
formAttrs.addAttribute(
AttributeName.ACTION,
attributes.getValue(actionIndex)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
appendToCurrentNodeAndPushFormElementMayFoster(formAttrs);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.LABEL,
HtmlAttributes.EMPTY_ATTRIBUTES);
int promptIndex = attributes.getIndex(AttributeName.PROMPT);
if (promptIndex > -1) {
@Auto char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex));
appendCharacters(stack[currentPtr].node,
prompt, 0, prompt.length);
} else {
appendIsindexPrompt(stack[currentPtr].node);
}
HtmlAttributes inputAttributes = new HtmlAttributes(
0);
inputAttributes.addAttribute(
AttributeName.NAME,
Portability.newStringFromLiteral("isindex")
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
for (int i = 0; i < attributes.getLength(); i++) {
AttributeName attributeQName = attributes.getAttributeName(i);
if (AttributeName.NAME == attributeQName
|| AttributeName.PROMPT == attributeQName) {
attributes.releaseValue(i);
} else if (AttributeName.ACTION != attributeQName) {
inputAttributes.addAttribute(
attributeQName,
attributes.getValue(i)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
}
attributes.clearWithoutReleasingContents();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
"input", inputAttributes, formPointer);
pop(); // label
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
pop(); // form
selfClosing = false;
// Portability.delete(formAttrs);
// Portability.delete(inputAttributes);
// Don't delete attributes, they are deleted
// later
break starttagloop;
case TEXTAREA:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
originalMode = mode;
mode = TEXT;
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case XMP:
implicitlyCloseP();
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (!scriptingEnabled) {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
} else {
// fall through
}
case NOFRAMES:
case IFRAME:
case NOEMBED:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case SELECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
switch (mode) {
case IN_TABLE:
case IN_CAPTION:
case IN_COLUMN_GROUP:
case IN_TABLE_BODY:
case IN_ROW:
case IN_CELL:
mode = IN_SELECT_IN_TABLE;
break;
default:
mode = IN_SELECT;
break;
}
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
case OPTION:
/*
* If the stack of open elements has an option
* element in scope, then act as if an end tag
* with the tag name "option" had been seen.
*/
if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) {
optionendtagloop: for (;;) {
if (isCurrent("option")) {
pop();
break optionendtagloop;
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == "option") {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent("option")) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break optionendtagloop;
}
eltPos--;
}
}
}
/*
* Reconstruct the active formatting elements,
* if any.
*/
reconstructTheActiveFormattingElements();
/*
* Insert an HTML element for the token.
*/
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case RT_OR_RP:
/*
* If the stack of open elements has a ruby
* element in scope, then generate implied end
* tags. If the current node is not then a ruby
* element, this is a parse error; pop all the
* nodes from the current node up to the node
* immediately before the bottommost ruby
* element on the stack of open elements.
*
* Insert an HTML element for the token.
*/
eltPos = findLastInScope("ruby");
if (eltPos != NOT_FOUND_ON_STACK) {
generateImpliedEndTags();
}
if (eltPos != currentPtr) {
err("Unclosed children in \u201Cruby\u201D.");
while (currentPtr > eltPos) {
pop();
}
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case MATH:
reconstructTheActiveFormattingElements();
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case SVG:
reconstructTheActiveFormattingElements();
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
"http://www.w3.org/2000/svg",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/2000/svg",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case FRAME:
case FRAMESET:
case HEAD:
err("Stray start tag \u201C" + name + "\u201D.");
break starttagloop;
case OUTPUT_OR_LABEL:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
default:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
}
}
case IN_HEAD:
inheadloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case COMMAND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
case LINK_OR_BASEFONT_OR_BGSOUND:
// Fall through to IN_HEAD_NOSCRIPT
break inheadloop;
case TITLE:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (scriptingEnabled) {
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_HEAD_NOSCRIPT;
}
attributes = null; // CPP
break starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
/* Parse error. */
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
/* Ignore the token. */
break starttagloop;
default:
pop();
mode = AFTER_HEAD;
continue starttagloop;
}
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case HTML:
// XXX did Hixie really mean to omit "base"
// here?
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
checkMetaCharset(attributes);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
break starttagloop;
case NOSCRIPT:
err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open.");
break starttagloop;
default:
err("Bad start tag in \u201C" + name
+ "\u201D in \u201Chead\u201D.");
pop();
mode = IN_HEAD;
continue;
}
case IN_COLUMN_GROUP:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case COL:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break starttagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case TABLE:
err("\u201C"
+ name
+ "\u201D start tag with \u201Cselect\u201D open.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case OPTION:
if (isCurrent("option")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
if (isCurrent("option")) {
pop();
}
if (isCurrent("optgroup")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case SELECT:
err("\u201Cselect\u201D start tag where end tag expected.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("No \u201Cselect\u201D in table scope.");
break starttagloop;
} else {
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break starttagloop;
}
case INPUT:
case TEXTAREA:
case KEYGEN:
err("\u201C"
+ name
+ "\u201D start tag seen in \u201Cselect\2201D.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FRAME:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
// fall through to AFTER_FRAMESET
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HTML:
// optimize error check and streaming SAX by
// hoisting
// "html" handling here.
if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendHtmlElementToDocumentAndPush();
} else {
appendHtmlElementToDocumentAndPush(attributes);
}
// XXX application cache should fire here
mode = BEFORE_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
}
case BEFORE_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case HEAD:
/*
* A start tag whose tag name is "head"
*
* Create an element for the token.
*
* Set the head element pointer to this new element
* node.
*
* Append the new element to the current node and
* push it onto the stack of open elements.
*/
appendToCurrentNodeAndPushHeadElement(attributes);
/*
* Change the insertion mode to "in head".
*/
mode = IN_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Any other start tag token
*
* Act as if a start tag token with the tag name
* "head" and no attributes had been seen,
*/
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element being
* generated, with the current token being
* reprocessed in the "after head" insertion mode.
*/
continue;
}
case AFTER_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BODY:
if (attributes.getLength() == 0) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendToCurrentNodeAndPushBodyElement();
} else {
appendToCurrentNodeAndPushBodyElement(attributes);
}
framesetOk = false;
mode = IN_BODY;
attributes = null; // CPP
break starttagloop;
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
case BASE:
err("\u201Cbase\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
err("\u201Clink\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case META:
err("\u201Cmeta\u201D element outside \u201Chead\u201D.");
checkMetaCharset(attributes);
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case SCRIPT:
err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
err("\u201C"
+ name
+ "\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case TITLE:
err("\u201Ctitle\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Stray start tag \u201Chead\u201D.");
break starttagloop;
default:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
}
case AFTER_AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case AFTER_AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case TEXT:
assert false;
break starttagloop; // Avoid infinite loop if the assertion
// fails
}
}
if (needsPostProcessing && inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
if (errorHandler != null && selfClosing) {
errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag.");
}
if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) {
Portability.delete(attributes);
}
}
| public final void startTag(ElementName elementName,
HtmlAttributes attributes, boolean selfClosing) throws SAXException {
flushCharacters();
// [NOCPP[
if (errorHandler != null) {
// ID uniqueness
@IdType String id = attributes.getId();
if (id != null) {
LocatorImpl oldLoc = idLocations.get(id);
if (oldLoc != null) {
err("Duplicate ID \u201C" + id + "\u201D.");
errorHandler.warning(new SAXParseException(
"The first occurrence of ID \u201C" + id
+ "\u201D was here.", oldLoc));
} else {
idLocations.put(id, new LocatorImpl(tokenizer));
}
}
}
// ]NOCPP]
int eltPos;
needToDropLF = false;
boolean needsPostProcessing = false;
starttagloop: for (;;) {
int group = elementName.group;
@Local String name = elementName.name;
if (inForeign) {
StackNode<T> currentNode = stack[currentPtr];
@NsUri String currNs = currentNode.ns;
int currGroup = currentNode.group;
if (("http://www.w3.org/1999/xhtml" == currNs)
|| ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup)))
|| ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) {
needsPostProcessing = true;
// fall through to non-foreign behavior
} else {
switch (group) {
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case BODY:
case BR:
case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR:
case DD_OR_DT:
case UL_OR_OL_OR_DL:
case EMBED_OR_IMG:
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
case HEAD:
case HR:
case LI:
case META:
case NOBR:
case P:
case PRE_OR_LISTING:
case TABLE:
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
case FONT:
if (attributes.contains(AttributeName.COLOR)
|| attributes.contains(AttributeName.FACE)
|| attributes.contains(AttributeName.SIZE)) {
err("HTML start tag \u201C"
+ name
+ "\u201D in a foreign namespace context.");
while (!isSpecialParentInForeign(stack[currentPtr])) {
pop();
}
if (!hasForeignInScope()) {
inForeign = false;
}
continue starttagloop;
}
// else fall thru
default:
if ("http://www.w3.org/2000/svg" == currNs) {
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterCamelCase(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
} else {
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
currNs, elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFosterNoScoping(
currNs, elementName, attributes);
}
attributes = null; // CPP
break starttagloop;
}
} // switch
} // foreignObject / annotation-xml
}
switch (mode) {
case IN_TABLE_BODY:
switch (group) {
case TR:
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_ROW;
attributes = null; // CPP
break starttagloop;
case TD_OR_TH:
err("\u201C" + name
+ "\u201D start tag in table body.");
clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot());
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TR,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_ROW;
continue;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
eltPos = findLastInTableScopeOrRootTbodyTheadTfoot();
if (eltPos == 0) {
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
} else {
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE;
continue;
}
default:
// fall through to IN_TABLE
}
case IN_ROW:
switch (group) {
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TR));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CELL;
insertMarker();
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
eltPos = findLastOrRoot(TreeBuilder.TR);
if (eltPos == 0) {
assert fragment;
err("No table row to close.");
break starttagloop;
}
clearStackBackTo(eltPos);
pop();
mode = IN_TABLE_BODY;
continue;
default:
// fall through to IN_TABLE
}
case IN_TABLE:
intableloop: for (;;) {
switch (group) {
case CAPTION:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
insertMarker();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_CAPTION;
attributes = null; // CPP
break starttagloop;
case COLGROUP:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_COLUMN_GROUP;
attributes = null; // CPP
break starttagloop;
case COL:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.COLGROUP,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_COLUMN_GROUP;
continue starttagloop;
case TBODY_OR_THEAD_OR_TFOOT:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE_BODY;
attributes = null; // CPP
break starttagloop;
case TR:
case TD_OR_TH:
clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE));
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
ElementName.TBODY,
HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_TABLE_BODY;
continue starttagloop;
case TABLE:
err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
generateImpliedEndTags();
// XXX is the next if dead code?
if (errorHandler != null && !isCurrent("table")) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case INPUT:
if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE))) {
break intableloop;
}
appendVoidElementToCurrent(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D.");
appendVoidFormToCurrent(attributes);
attributes = null; // CPP
break starttagloop;
}
default:
err("Start tag \u201C" + name
+ "\u201D seen in \u201Ctable\u201D.");
// fall through to IN_BODY
break intableloop;
}
}
case IN_CAPTION:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
err("Stray \u201C"
+ name
+ "\u201D start tag in \u201Ccaption\u201D.");
eltPos = findLastInTableScope("caption");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
break starttagloop;
}
generateImpliedEndTags();
if (errorHandler != null && currentPtr != eltPos) {
errNoCheck("Unclosed elements on stack.");
}
while (currentPtr >= eltPos) {
pop();
}
clearTheListOfActiveFormattingElementsUpToTheLastMarker();
mode = IN_TABLE;
continue;
default:
// fall through to IN_BODY
}
case IN_CELL:
switch (group) {
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
eltPos = findLastInTableScopeTdTh();
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
err("No cell to close.");
break starttagloop;
} else {
closeTheCell(eltPos);
continue;
}
default:
// fall through to IN_BODY
}
case FRAMESET_OK:
switch (group) {
case FRAMESET:
if (mode == FRAMESET_OK) {
if (currentPtr == 0 || stack[1].group != BODY) {
assert fragment;
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
} else {
err("\u201Cframeset\u201D start tag seen.");
detachFromParent(stack[1].node);
while (currentPtr > 0) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
}
} else {
err("Stray \u201Cframeset\u201D start tag.");
break starttagloop;
}
// NOT falling through!
case PRE_OR_LISTING:
case LI:
case DD_OR_DT:
case BUTTON:
case MARQUEE_OR_APPLET:
case OBJECT:
case TABLE:
case AREA_OR_WBR:
case BR:
case EMBED_OR_IMG:
case INPUT:
case KEYGEN:
case HR:
case TEXTAREA:
case XMP:
case IFRAME:
case SELECT:
if (mode == FRAMESET_OK
&& !(group == INPUT && Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString(
"hidden",
attributes.getValue(AttributeName.TYPE)))) {
framesetOk = false;
mode = IN_BODY;
}
// fall through to IN_BODY
default:
// fall through to IN_BODY
}
case IN_BODY:
inbodyloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case LINK_OR_BASEFONT_OR_BGSOUND:
case META:
case STYLE:
case SCRIPT:
case TITLE:
case COMMAND:
// Fall through to IN_HEAD
break inbodyloop;
case BODY:
err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open.");
if (addAttributesToBody(attributes)) {
attributes = null; // CPP
}
break starttagloop;
case P:
case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU:
case UL_OR_OL_OR_DL:
case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6:
implicitlyCloseP();
if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) {
err("Heading cannot be a child of another heading.");
pop();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FIELDSET:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
case PRE_OR_LISTING:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case FORM:
if (formPointer != null) {
err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag.");
break starttagloop;
} else {
implicitlyCloseP();
appendToCurrentNodeAndPushFormElementMayFoster(attributes);
attributes = null; // CPP
break starttagloop;
}
case LI:
case DD_OR_DT:
eltPos = currentPtr;
for (;;) {
StackNode<T> node = stack[eltPos]; // weak
// ref
if (node.group == group) { // LI or
// DD_OR_DT
generateImpliedEndTagsExceptFor(node.name);
if (errorHandler != null
&& eltPos != currentPtr) {
errNoCheck("Unclosed elements inside a list.");
}
while (currentPtr >= eltPos) {
pop();
}
break;
} else if (node.scoping
|| (node.special
&& node.name != "p"
&& node.name != "address" && node.name != "div")) {
break;
}
eltPos--;
}
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case PLAINTEXT:
implicitlyCloseP();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.PLAINTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case A:
int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a");
if (activeAPos != -1) {
err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element.");
StackNode<T> activeA = listOfActiveFormattingElements[activeAPos];
activeA.retain();
adoptionAgencyEndTag("a");
removeFromStack(activeA);
activeAPos = findInListOfActiveFormattingElements(activeA);
if (activeAPos != -1) {
removeFromListOfActiveFormattingElements(activeAPos);
}
activeA.release();
}
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U:
case FONT:
reconstructTheActiveFormattingElements();
maybeForgetEarlierDuplicateFormattingElement(elementName.name, attributes);
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case NOBR:
reconstructTheActiveFormattingElements();
if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) {
err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope.");
adoptionAgencyEndTag("nobr");
}
appendToCurrentNodeAndPushFormattingElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case BUTTON:
eltPos = findLastInScope(name);
if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) {
err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope.");
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent(name)) {
errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
continue starttagloop;
} else {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes,
formPointer);
attributes = null; // CPP
break starttagloop;
}
case OBJECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
insertMarker();
attributes = null; // CPP
break starttagloop;
case MARQUEE_OR_APPLET:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
insertMarker();
attributes = null; // CPP
break starttagloop;
case TABLE:
// The only quirk. Blame Hixie and
// Acid2.
if (!quirks) {
implicitlyCloseP();
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_TABLE;
attributes = null; // CPP
break starttagloop;
case BR:
case EMBED_OR_IMG:
case AREA_OR_WBR:
reconstructTheActiveFormattingElements();
// FALL THROUGH to PARAM_OR_SOURCE
case PARAM_OR_SOURCE:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case HR:
implicitlyCloseP();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case IMAGE:
err("Saw a start tag \u201Cimage\u201D.");
elementName = ElementName.IMG;
continue starttagloop;
case KEYGEN:
case INPUT:
reconstructTheActiveFormattingElements();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml", name,
attributes, formPointer);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case ISINDEX:
err("\u201Cisindex\u201D seen.");
if (formPointer != null) {
break starttagloop;
}
implicitlyCloseP();
HtmlAttributes formAttrs = new HtmlAttributes(0);
int actionIndex = attributes.getIndex(AttributeName.ACTION);
if (actionIndex > -1) {
formAttrs.addAttribute(
AttributeName.ACTION,
attributes.getValue(actionIndex)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
appendToCurrentNodeAndPushFormElementMayFoster(formAttrs);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.LABEL,
HtmlAttributes.EMPTY_ATTRIBUTES);
int promptIndex = attributes.getIndex(AttributeName.PROMPT);
if (promptIndex > -1) {
@Auto char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex));
appendCharacters(stack[currentPtr].node,
prompt, 0, prompt.length);
} else {
appendIsindexPrompt(stack[currentPtr].node);
}
HtmlAttributes inputAttributes = new HtmlAttributes(
0);
inputAttributes.addAttribute(
AttributeName.NAME,
Portability.newStringFromLiteral("isindex")
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
for (int i = 0; i < attributes.getLength(); i++) {
AttributeName attributeQName = attributes.getAttributeName(i);
if (AttributeName.NAME == attributeQName
|| AttributeName.PROMPT == attributeQName) {
attributes.releaseValue(i);
} else if (AttributeName.ACTION != attributeQName) {
inputAttributes.addAttribute(
attributeQName,
attributes.getValue(i)
// [NOCPP[
, XmlViolationPolicy.ALLOW
// ]NOCPP]
);
}
}
attributes.clearWithoutReleasingContents();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
"input", inputAttributes, formPointer);
pop(); // label
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
ElementName.HR,
HtmlAttributes.EMPTY_ATTRIBUTES);
pop(); // form
selfClosing = false;
// Portability.delete(formAttrs);
// Portability.delete(inputAttributes);
// Don't delete attributes, they are deleted
// later
break starttagloop;
case TEXTAREA:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
originalMode = mode;
mode = TEXT;
needToDropLF = true;
attributes = null; // CPP
break starttagloop;
case XMP:
implicitlyCloseP();
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (!scriptingEnabled) {
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
} else {
// fall through
}
case NOFRAMES:
case IFRAME:
case NOEMBED:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case SELECT:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
switch (mode) {
case IN_TABLE:
case IN_CAPTION:
case IN_COLUMN_GROUP:
case IN_TABLE_BODY:
case IN_ROW:
case IN_CELL:
mode = IN_SELECT_IN_TABLE;
break;
default:
mode = IN_SELECT;
break;
}
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
case OPTION:
/*
* If the stack of open elements has an option
* element in scope, then act as if an end tag
* with the tag name "option" had been seen.
*/
if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) {
optionendtagloop: for (;;) {
if (isCurrent("option")) {
pop();
break optionendtagloop;
}
eltPos = currentPtr;
for (;;) {
if (stack[eltPos].name == "option") {
generateImpliedEndTags();
if (errorHandler != null
&& !isCurrent("option")) {
errNoCheck("End tag \u201C"
+ name
+ "\u201D seen but there were unclosed elements.");
}
while (currentPtr >= eltPos) {
pop();
}
break optionendtagloop;
}
eltPos--;
}
}
}
/*
* Reconstruct the active formatting elements,
* if any.
*/
reconstructTheActiveFormattingElements();
/*
* Insert an HTML element for the token.
*/
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case RT_OR_RP:
/*
* If the stack of open elements has a ruby
* element in scope, then generate implied end
* tags. If the current node is not then a ruby
* element, this is a parse error; pop all the
* nodes from the current node up to the node
* immediately before the bottommost ruby
* element on the stack of open elements.
*
* Insert an HTML element for the token.
*/
eltPos = findLastInScope("ruby");
if (eltPos != NOT_FOUND_ON_STACK) {
generateImpliedEndTags();
}
if (eltPos != currentPtr) {
err("Unclosed children in \u201Cruby\u201D.");
while (currentPtr > eltPos) {
pop();
}
}
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case MATH:
reconstructTheActiveFormattingElements();
attributes.adjustForMath();
if (selfClosing) {
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1998/Math/MathML",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case SVG:
reconstructTheActiveFormattingElements();
attributes.adjustForSvg();
if (selfClosing) {
appendVoidElementToCurrentMayFosterCamelCase(
"http://www.w3.org/2000/svg",
elementName, attributes);
selfClosing = false;
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/2000/svg",
elementName, attributes);
inForeign = true;
}
attributes = null; // CPP
break starttagloop;
case CAPTION:
case COL:
case COLGROUP:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case FRAME:
case FRAMESET:
case HEAD:
err("Stray start tag \u201C" + name + "\u201D.");
break starttagloop;
case OUTPUT_OR_LABEL:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes, formPointer);
attributes = null; // CPP
break starttagloop;
default:
reconstructTheActiveFormattingElements();
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
}
}
case IN_HEAD:
inheadloop: for (;;) {
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BASE:
case COMMAND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
case LINK_OR_BASEFONT_OR_BGSOUND:
// Fall through to IN_HEAD_NOSCRIPT
break inheadloop;
case TITLE:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case NOSCRIPT:
if (scriptingEnabled) {
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
} else {
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_HEAD_NOSCRIPT;
}
attributes = null; // CPP
break starttagloop;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
/* Parse error. */
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
/* Ignore the token. */
break starttagloop;
default:
pop();
mode = AFTER_HEAD;
continue starttagloop;
}
}
case IN_HEAD_NOSCRIPT:
switch (group) {
case HTML:
// XXX did Hixie really mean to omit "base"
// here?
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case META:
checkMetaCharset(attributes);
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open.");
break starttagloop;
case NOSCRIPT:
err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open.");
break starttagloop;
default:
err("Bad start tag in \u201C" + name
+ "\u201D in \u201Chead\u201D.");
pop();
mode = IN_HEAD;
continue;
}
case IN_COLUMN_GROUP:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case COL:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
if (currentPtr == 0) {
assert fragment;
err("Garbage in \u201Ccolgroup\u201D fragment.");
break starttagloop;
}
pop();
mode = IN_TABLE;
continue;
}
case IN_SELECT_IN_TABLE:
switch (group) {
case CAPTION:
case TBODY_OR_THEAD_OR_TFOOT:
case TR:
case TD_OR_TH:
case TABLE:
err("\u201C"
+ name
+ "\u201D start tag with \u201Cselect\u201D open.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
default:
// fall through to IN_SELECT
}
case IN_SELECT:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case OPTION:
if (isCurrent("option")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case OPTGROUP:
if (isCurrent("option")) {
pop();
}
if (isCurrent("optgroup")) {
pop();
}
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case SELECT:
err("\u201Cselect\u201D start tag where end tag expected.");
eltPos = findLastInTableScope(name);
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
err("No \u201Cselect\u201D in table scope.");
break starttagloop;
} else {
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
break starttagloop;
}
case INPUT:
case TEXTAREA:
case KEYGEN:
err("\u201C"
+ name
+ "\u201D start tag seen in \u201Cselect\2201D.");
eltPos = findLastInTableScope("select");
if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) {
assert fragment;
break starttagloop;
}
while (currentPtr >= eltPos) {
pop();
}
resetTheInsertionMode();
continue;
case SCRIPT:
// XXX need to manage much more stuff
// here if
// supporting
// document.write()
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case IN_FRAMESET:
switch (group) {
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
attributes = null; // CPP
break starttagloop;
case FRAME:
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
attributes = null; // CPP
break starttagloop;
default:
// fall through to AFTER_FRAMESET
}
case AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case INITIAL:
/*
* Parse error.
*/
// [NOCPP[
switch (doctypeExpectation) {
case AUTO:
err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D.");
break;
case HTML:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D.");
break;
case HTML401_STRICT:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D.");
break;
case HTML401_TRANSITIONAL:
err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D.");
break;
case NO_DOCTYPE_ERRORS:
}
// ]NOCPP]
/*
*
* Set the document to quirks mode.
*/
documentModeInternal(DocumentMode.QUIRKS_MODE, null, null,
false);
/*
* Then, switch to the root element mode of the tree
* construction stage
*/
mode = BEFORE_HTML;
/*
* and reprocess the current token.
*/
continue;
case BEFORE_HTML:
switch (group) {
case HTML:
// optimize error check and streaming SAX by
// hoisting
// "html" handling here.
if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendHtmlElementToDocumentAndPush();
} else {
appendHtmlElementToDocumentAndPush(attributes);
}
// XXX application cache should fire here
mode = BEFORE_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Create an HTMLElement node with the tag name
* html, in the HTML namespace. Append it to the
* Document object.
*/
appendHtmlElementToDocumentAndPush();
/* Switch to the main mode */
mode = BEFORE_HEAD;
/*
* reprocess the current token.
*/
continue;
}
case BEFORE_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case HEAD:
/*
* A start tag whose tag name is "head"
*
* Create an element for the token.
*
* Set the head element pointer to this new element
* node.
*
* Append the new element to the current node and
* push it onto the stack of open elements.
*/
appendToCurrentNodeAndPushHeadElement(attributes);
/*
* Change the insertion mode to "in head".
*/
mode = IN_HEAD;
attributes = null; // CPP
break starttagloop;
default:
/*
* Any other start tag token
*
* Act as if a start tag token with the tag name
* "head" and no attributes had been seen,
*/
appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES);
mode = IN_HEAD;
/*
* then reprocess the current token.
*
* This will result in an empty head element being
* generated, with the current token being
* reprocessed in the "after head" insertion mode.
*/
continue;
}
case AFTER_HEAD:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case BODY:
if (attributes.getLength() == 0) {
// This has the right magic side effect
// that
// it
// makes attributes in SAX Tree mutable.
appendToCurrentNodeAndPushBodyElement();
} else {
appendToCurrentNodeAndPushBodyElement(attributes);
}
framesetOk = false;
mode = IN_BODY;
attributes = null; // CPP
break starttagloop;
case FRAMESET:
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
mode = IN_FRAMESET;
attributes = null; // CPP
break starttagloop;
case BASE:
err("\u201Cbase\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case LINK_OR_BASEFONT_OR_BGSOUND:
err("\u201Clink\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case META:
err("\u201Cmeta\u201D element outside \u201Chead\u201D.");
checkMetaCharset(attributes);
pushHeadPointerOntoStack();
appendVoidElementToCurrentMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
selfClosing = false;
pop(); // head
attributes = null; // CPP
break starttagloop;
case SCRIPT:
err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
case STYLE:
case NOFRAMES:
err("\u201C"
+ name
+ "\u201D element between \u201Chead\u201D and \u201Cbody\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RAWTEXT, elementName);
attributes = null; // CPP
break starttagloop;
case TITLE:
err("\u201Ctitle\u201D element outside \u201Chead\u201D.");
pushHeadPointerOntoStack();
appendToCurrentNodeAndPushElement(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.RCDATA, elementName);
attributes = null; // CPP
break starttagloop;
case HEAD:
err("Stray start tag \u201Chead\u201D.");
break starttagloop;
default:
appendToCurrentNodeAndPushBodyElement();
mode = FRAMESET_OK;
continue;
}
case AFTER_AFTER_BODY:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
fatal();
mode = framesetOk ? FRAMESET_OK : IN_BODY;
continue;
}
case AFTER_AFTER_FRAMESET:
switch (group) {
case HTML:
err("Stray \u201Chtml\u201D start tag.");
if (!fragment) {
addAttributesToHtml(attributes);
attributes = null; // CPP
}
break starttagloop;
case NOFRAMES:
appendToCurrentNodeAndPushElementMayFoster(
"http://www.w3.org/1999/xhtml",
elementName, attributes);
originalMode = mode;
mode = TEXT;
tokenizer.setStateAndEndTagExpectation(
Tokenizer.SCRIPT_DATA, elementName);
attributes = null; // CPP
break starttagloop;
default:
err("Stray \u201C" + name + "\u201D start tag.");
break starttagloop;
}
case TEXT:
assert false;
break starttagloop; // Avoid infinite loop if the assertion
// fails
}
}
if (needsPostProcessing && inForeign && !hasForeignInScope()) {
/*
* If, after doing so, the insertion mode is still "in foreign
* content", but there is no element in scope that has a namespace
* other than the HTML namespace, switch the insertion mode to the
* secondary insertion mode.
*/
inForeign = false;
}
if (errorHandler != null && selfClosing) {
errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag.");
}
if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) {
Portability.delete(attributes);
}
}
|
diff --git a/help-tool/src/java/org/sakaiproject/tool/help/ContentServlet.java b/help-tool/src/java/org/sakaiproject/tool/help/ContentServlet.java
index 071684c..1d2e37c 100644
--- a/help-tool/src/java/org/sakaiproject/tool/help/ContentServlet.java
+++ b/help-tool/src/java/org/sakaiproject/tool/help/ContentServlet.java
@@ -1,242 +1,242 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.tool.help;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.help.HelpManager;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.api.app.help.Resource;
import org.sakaiproject.component.cover.ComponentManager;
import org.apache.commons.lang.StringUtils;
/**
* Content Servlet serves help documents to document frame.
* @version $Id$
*/
public class ContentServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/** Our log (commons). */
private static Log M_log = LogFactory.getLog(ContentServlet.class);
private static final String DOC_ID = "docId";
private static final String TEXT_HTML = "text/html; charset=UTF-8";
private HelpManager helpManager;
private ServerConfigurationService serverConfigurationService;
/**
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
getHelpManager().initialize();
String docId = req.getParameter(DOC_ID);
if (docId == null) {
res.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
OutputStreamWriter writer = new OutputStreamWriter(res.getOutputStream(), "UTF-8");
try {
res.setContentType(TEXT_HTML);
URL url = null;
Resource resource = null;
resource = getHelpManager().getResourceByDocId(docId);
//Possibly a fileURL
if (resource == null && docId.indexOf('/') >= 0) {
if (M_log.isDebugEnabled())
M_log.debug("Adding new resource:"+docId);
resource = getHelpManager().createResource();
resource.setLocation("/"+docId);
resource.setDocId(docId);
- url = new URL(req.getScheme(),req.getLocalName(),req.getServerPort(),req.getContextPath()+"/"+docId);
+ url = new URL(req.getScheme(),req.getServerName(),req.getServerPort(),req.getContextPath()+"/"+docId);
//Can't save it without a category as is null
//getHelpManager().storeResource(resource);
}
if (resource != null)
{
String sakaiHomePath = getServerConfigurationService().getSakaiHomePath();
String localHelpPath = sakaiHomePath+getServerConfigurationService().getString("help.localpath","/help/");
File localFile = new File(localHelpPath+resource.getLocation());
boolean localFileIsFile = false;
String localFileCanonicalPath = localFile.getCanonicalPath();
if(localFileCanonicalPath.contains(localHelpPath) && localFile.isFile()) {
M_log.debug("Local help file overrides: "+resource.getLocation());
localFileIsFile = true;
}
if (!getHelpManager().getRestConfiguration().getOrganization()
.equalsIgnoreCase("sakai"))
{
writer.write(RestContentProvider.getTransformedDocument(
getServletContext(), getHelpManager(), resource));
} else {
if (resource.getLocation().startsWith("/"))
{
if (!"".equals(getHelpManager().getExternalLocation()))
{
url = new URL(getHelpManager().getExternalLocation()
+ resource.getLocation());
}
else
{
if(localFileIsFile) {
url = localFile.toURI().toURL();
}
else {
//If url hasn't been set yet, look it up in the classpath
if (url == null) {
url = HelpManager.class.getResource(resource.getLocation());
}
}
}
String defaultRepo = "/library/skin/";
String skinRepo = getServerConfigurationService().getString("skin.repo",defaultRepo);
String helpHeader = getServerConfigurationService().getString("help.header",null);
String helpFooter = getServerConfigurationService().getString("help.footer",null);
String resourceName = resource.getName();
if (resourceName == null) {
resourceName = "";
}
if (url == null) {
M_log.warn("Help document " + docId + " not found at: " + resource.getLocation());
} else {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
}
catch (ConnectException e){
M_log.info("ConnectException on " + url.getPath());
res.sendRedirect(resource.getLocation());
return;
}
try {
String sbuf;
while ((sbuf = br.readLine()) != null)
{
//Replacements because help wasn't written as a template
if (!skinRepo.equals(defaultRepo)) {
if (StringUtils.contains(sbuf,defaultRepo)) {
sbuf = StringUtils.replace(sbuf, defaultRepo, skinRepo + "/");
//Reset to only do one replacement
skinRepo=defaultRepo;
}
}
if (helpHeader != null) {
//Hopefully nobody writes <BODY>
if (StringUtils.contains(sbuf,"<body>")) {
sbuf = StringUtils.replace(sbuf, "<body>", "<body>"+helpHeader);
//Reset to only do one replacement
//Replace special variables
sbuf = StringUtils.replace(sbuf, "#ResourceBean.name", resourceName);
helpHeader = null;
}
}
if (helpFooter != null) {
if (StringUtils.contains(sbuf,"</body>")) {
sbuf = StringUtils.replace(sbuf, "</body>", helpFooter+"</body>");
sbuf = StringUtils.replace(sbuf, "#ResourceBean.name", resourceName);
//Reset to only do one replacement
helpFooter = null;
}
}
writer.write( sbuf );
writer.write( System.getProperty("line.separator") );
}
} finally {
br.close();
}
}
}
else
{
res.sendRedirect(resource.getLocation());
}
}
}
} finally {
try {
writer.flush();
} catch (IOException e) {
// ignore
}
writer.close();
}
}
/**
* get the component manager through cover
* @return help manager
*/
public HelpManager getHelpManager()
{
if (helpManager == null)
{
helpManager = (HelpManager) ComponentManager.get(HelpManager.class.getName());
return helpManager;
}
return helpManager;
}
/**
* get the component manager through cover
* @return serverconfigurationservicer
*/
public ServerConfigurationService getServerConfigurationService()
{
if (serverConfigurationService == null)
{
serverConfigurationService = (ServerConfigurationService) ComponentManager.get(ServerConfigurationService.class.getName());
return serverConfigurationService;
}
return serverConfigurationService;
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
getHelpManager().initialize();
String docId = req.getParameter(DOC_ID);
if (docId == null) {
res.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
OutputStreamWriter writer = new OutputStreamWriter(res.getOutputStream(), "UTF-8");
try {
res.setContentType(TEXT_HTML);
URL url = null;
Resource resource = null;
resource = getHelpManager().getResourceByDocId(docId);
//Possibly a fileURL
if (resource == null && docId.indexOf('/') >= 0) {
if (M_log.isDebugEnabled())
M_log.debug("Adding new resource:"+docId);
resource = getHelpManager().createResource();
resource.setLocation("/"+docId);
resource.setDocId(docId);
url = new URL(req.getScheme(),req.getLocalName(),req.getServerPort(),req.getContextPath()+"/"+docId);
//Can't save it without a category as is null
//getHelpManager().storeResource(resource);
}
if (resource != null)
{
String sakaiHomePath = getServerConfigurationService().getSakaiHomePath();
String localHelpPath = sakaiHomePath+getServerConfigurationService().getString("help.localpath","/help/");
File localFile = new File(localHelpPath+resource.getLocation());
boolean localFileIsFile = false;
String localFileCanonicalPath = localFile.getCanonicalPath();
if(localFileCanonicalPath.contains(localHelpPath) && localFile.isFile()) {
M_log.debug("Local help file overrides: "+resource.getLocation());
localFileIsFile = true;
}
if (!getHelpManager().getRestConfiguration().getOrganization()
.equalsIgnoreCase("sakai"))
{
writer.write(RestContentProvider.getTransformedDocument(
getServletContext(), getHelpManager(), resource));
} else {
if (resource.getLocation().startsWith("/"))
{
if (!"".equals(getHelpManager().getExternalLocation()))
{
url = new URL(getHelpManager().getExternalLocation()
+ resource.getLocation());
}
else
{
if(localFileIsFile) {
url = localFile.toURI().toURL();
}
else {
//If url hasn't been set yet, look it up in the classpath
if (url == null) {
url = HelpManager.class.getResource(resource.getLocation());
}
}
}
String defaultRepo = "/library/skin/";
String skinRepo = getServerConfigurationService().getString("skin.repo",defaultRepo);
String helpHeader = getServerConfigurationService().getString("help.header",null);
String helpFooter = getServerConfigurationService().getString("help.footer",null);
String resourceName = resource.getName();
if (resourceName == null) {
resourceName = "";
}
if (url == null) {
M_log.warn("Help document " + docId + " not found at: " + resource.getLocation());
} else {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
}
catch (ConnectException e){
M_log.info("ConnectException on " + url.getPath());
res.sendRedirect(resource.getLocation());
return;
}
try {
String sbuf;
while ((sbuf = br.readLine()) != null)
{
//Replacements because help wasn't written as a template
if (!skinRepo.equals(defaultRepo)) {
if (StringUtils.contains(sbuf,defaultRepo)) {
sbuf = StringUtils.replace(sbuf, defaultRepo, skinRepo + "/");
//Reset to only do one replacement
skinRepo=defaultRepo;
}
}
if (helpHeader != null) {
//Hopefully nobody writes <BODY>
if (StringUtils.contains(sbuf,"<body>")) {
sbuf = StringUtils.replace(sbuf, "<body>", "<body>"+helpHeader);
//Reset to only do one replacement
//Replace special variables
sbuf = StringUtils.replace(sbuf, "#ResourceBean.name", resourceName);
helpHeader = null;
}
}
if (helpFooter != null) {
if (StringUtils.contains(sbuf,"</body>")) {
sbuf = StringUtils.replace(sbuf, "</body>", helpFooter+"</body>");
sbuf = StringUtils.replace(sbuf, "#ResourceBean.name", resourceName);
//Reset to only do one replacement
helpFooter = null;
}
}
writer.write( sbuf );
writer.write( System.getProperty("line.separator") );
}
} finally {
br.close();
}
}
}
else
{
res.sendRedirect(resource.getLocation());
}
}
}
} finally {
try {
writer.flush();
} catch (IOException e) {
// ignore
}
writer.close();
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
getHelpManager().initialize();
String docId = req.getParameter(DOC_ID);
if (docId == null) {
res.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
OutputStreamWriter writer = new OutputStreamWriter(res.getOutputStream(), "UTF-8");
try {
res.setContentType(TEXT_HTML);
URL url = null;
Resource resource = null;
resource = getHelpManager().getResourceByDocId(docId);
//Possibly a fileURL
if (resource == null && docId.indexOf('/') >= 0) {
if (M_log.isDebugEnabled())
M_log.debug("Adding new resource:"+docId);
resource = getHelpManager().createResource();
resource.setLocation("/"+docId);
resource.setDocId(docId);
url = new URL(req.getScheme(),req.getServerName(),req.getServerPort(),req.getContextPath()+"/"+docId);
//Can't save it without a category as is null
//getHelpManager().storeResource(resource);
}
if (resource != null)
{
String sakaiHomePath = getServerConfigurationService().getSakaiHomePath();
String localHelpPath = sakaiHomePath+getServerConfigurationService().getString("help.localpath","/help/");
File localFile = new File(localHelpPath+resource.getLocation());
boolean localFileIsFile = false;
String localFileCanonicalPath = localFile.getCanonicalPath();
if(localFileCanonicalPath.contains(localHelpPath) && localFile.isFile()) {
M_log.debug("Local help file overrides: "+resource.getLocation());
localFileIsFile = true;
}
if (!getHelpManager().getRestConfiguration().getOrganization()
.equalsIgnoreCase("sakai"))
{
writer.write(RestContentProvider.getTransformedDocument(
getServletContext(), getHelpManager(), resource));
} else {
if (resource.getLocation().startsWith("/"))
{
if (!"".equals(getHelpManager().getExternalLocation()))
{
url = new URL(getHelpManager().getExternalLocation()
+ resource.getLocation());
}
else
{
if(localFileIsFile) {
url = localFile.toURI().toURL();
}
else {
//If url hasn't been set yet, look it up in the classpath
if (url == null) {
url = HelpManager.class.getResource(resource.getLocation());
}
}
}
String defaultRepo = "/library/skin/";
String skinRepo = getServerConfigurationService().getString("skin.repo",defaultRepo);
String helpHeader = getServerConfigurationService().getString("help.header",null);
String helpFooter = getServerConfigurationService().getString("help.footer",null);
String resourceName = resource.getName();
if (resourceName == null) {
resourceName = "";
}
if (url == null) {
M_log.warn("Help document " + docId + " not found at: " + resource.getLocation());
} else {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(url.openStream(),"UTF-8"));
}
catch (ConnectException e){
M_log.info("ConnectException on " + url.getPath());
res.sendRedirect(resource.getLocation());
return;
}
try {
String sbuf;
while ((sbuf = br.readLine()) != null)
{
//Replacements because help wasn't written as a template
if (!skinRepo.equals(defaultRepo)) {
if (StringUtils.contains(sbuf,defaultRepo)) {
sbuf = StringUtils.replace(sbuf, defaultRepo, skinRepo + "/");
//Reset to only do one replacement
skinRepo=defaultRepo;
}
}
if (helpHeader != null) {
//Hopefully nobody writes <BODY>
if (StringUtils.contains(sbuf,"<body>")) {
sbuf = StringUtils.replace(sbuf, "<body>", "<body>"+helpHeader);
//Reset to only do one replacement
//Replace special variables
sbuf = StringUtils.replace(sbuf, "#ResourceBean.name", resourceName);
helpHeader = null;
}
}
if (helpFooter != null) {
if (StringUtils.contains(sbuf,"</body>")) {
sbuf = StringUtils.replace(sbuf, "</body>", helpFooter+"</body>");
sbuf = StringUtils.replace(sbuf, "#ResourceBean.name", resourceName);
//Reset to only do one replacement
helpFooter = null;
}
}
writer.write( sbuf );
writer.write( System.getProperty("line.separator") );
}
} finally {
br.close();
}
}
}
else
{
res.sendRedirect(resource.getLocation());
}
}
}
} finally {
try {
writer.flush();
} catch (IOException e) {
// ignore
}
writer.close();
}
}
|
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/ui/PaneManager.java b/src/gwt/src/org/rstudio/studio/client/workbench/ui/PaneManager.java
index ad1caa0975..6a0d60c57b 100644
--- a/src/gwt/src/org/rstudio/studio/client/workbench/ui/PaneManager.java
+++ b/src/gwt/src/org/rstudio/studio/client/workbench/ui/PaneManager.java
@@ -1,508 +1,508 @@
/*
* PaneManager.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.ui;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import org.rstudio.core.client.Debug;
import org.rstudio.core.client.Triad;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.events.WindowStateChangeEvent;
import org.rstudio.core.client.layout.DualWindowLayoutPanel;
import org.rstudio.core.client.layout.LogicalWindow;
import org.rstudio.core.client.layout.WindowState;
import org.rstudio.core.client.theme.MinimizedModuleTabLayoutPanel;
import org.rstudio.core.client.theme.MinimizedWindowFrame;
import org.rstudio.core.client.theme.PrimaryWindowFrame;
import org.rstudio.core.client.theme.WindowFrame;
import org.rstudio.core.client.theme.res.ThemeResources;
import org.rstudio.core.client.widget.ToolbarButton;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ClientState;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.WorkbenchServerOperations;
import org.rstudio.studio.client.workbench.model.helper.IntStateValue;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.views.console.ConsoleInterruptButton;
import org.rstudio.studio.client.workbench.views.console.ConsolePane;
import org.rstudio.studio.client.workbench.views.output.find.FindOutputTab;
import org.rstudio.studio.client.workbench.views.source.SourceShim;
import java.util.ArrayList;
import java.util.HashMap;
/*
* TODO: Push client state when selected tab or layout changes
*/
public class PaneManager
{
public interface Binder extends CommandBinder<Commands, PaneManager> {}
public enum Tab {
History, Files, Plots, Packages, Help, VCS, Build,
Presentation, Environment, Viewer
}
class SelectedTabStateValue extends IntStateValue
{
SelectedTabStateValue(String name,
WorkbenchTabPanel tabPanel)
{
super("workbench-pane", name, ClientState.PROJECT_PERSISTENT,
session_.getSessionInfo().getClientState(), true);
tabPanel_ = tabPanel;
finishInit(session_.getSessionInfo().getClientState());
}
@Override
protected void onInit(Integer value)
{
if (value != null)
tabPanel_.selectTab(value);
}
@Override
protected Integer getValue() { return tabPanel_.getSelectedIndex(); }
private final WorkbenchTabPanel tabPanel_;
}
@Inject
public PaneManager(Provider<MainSplitPanel> pSplitPanel,
WorkbenchServerOperations server,
EventBus eventBus,
Session session,
Binder binder,
Commands commands,
UIPrefs uiPrefs,
@Named("Console") final Widget consolePane,
ConsoleInterruptButton consoleInterrupt,
SourceShim source,
@Named("History") final WorkbenchTab historyTab,
@Named("Files") final WorkbenchTab filesTab,
@Named("Plots") final WorkbenchTab plotsTab,
@Named("Packages") final WorkbenchTab packagesTab,
@Named("Help") final WorkbenchTab helpTab,
@Named("VCS") final WorkbenchTab vcsTab,
@Named("Build") final WorkbenchTab buildTab,
@Named("Presentation") final WorkbenchTab presentationTab,
@Named("Environment") final WorkbenchTab environmentTab,
@Named("Viewer") final WorkbenchTab viewerTab,
@Named("Compile PDF") final WorkbenchTab compilePdfTab,
@Named("Source Cpp") final WorkbenchTab sourceCppTab,
final FindOutputTab findOutputTab)
{
eventBus_ = eventBus;
session_ = session;
commands_ = commands;
consolePane_ = (ConsolePane)consolePane;
consoleInterrupt_ = consoleInterrupt;
source_ = source;
historyTab_ = historyTab;
filesTab_ = filesTab;
plotsTab_ = plotsTab;
packagesTab_ = packagesTab;
helpTab_ = helpTab;
vcsTab_ = vcsTab;
buildTab_ = buildTab;
presentationTab_ = presentationTab;
environmentTab_ = environmentTab;
viewerTab_ = viewerTab;
compilePdfTab_ = compilePdfTab;
findOutputTab_ = findOutputTab;
sourceCppTab_ = sourceCppTab;
binder.bind(commands, this);
PaneConfig config = validateConfig(uiPrefs.paneConfig().getValue());
initPanes(config);
panes_ = createPanes(config);
left_ = createSplitWindow(panes_.get(0), panes_.get(1), "left", 0.4);
right_ = createSplitWindow(panes_.get(2), panes_.get(3), "right", 0.6);
panel_ = pSplitPanel.get();
panel_.initialize(left_, right_);
if (session_.getSessionInfo().getSourceDocuments().length() == 0
&& sourceLogicalWindow_.getState() != WindowState.HIDE)
{
sourceLogicalWindow_.onWindowStateChange(
new WindowStateChangeEvent(WindowState.HIDE));
}
else if (session_.getSessionInfo().getSourceDocuments().length() > 0
&& sourceLogicalWindow_.getState() == WindowState.HIDE)
{
sourceLogicalWindow_.onWindowStateChange(
new WindowStateChangeEvent(WindowState.NORMAL));
}
uiPrefs.paneConfig().addValueChangeHandler(new ValueChangeHandler<PaneConfig>()
{
public void onValueChange(ValueChangeEvent<PaneConfig> evt)
{
- ArrayList<LogicalWindow> newPanes = createPanes(evt.getValue());
+ ArrayList<LogicalWindow> newPanes = createPanes(validateConfig(evt.getValue()));
panes_ = newPanes;
left_.replaceWindows(newPanes.get(0), newPanes.get(1));
right_.replaceWindows(newPanes.get(2), newPanes.get(3));
tabSet1TabPanel_.clear();
tabSet2TabPanel_.clear();
populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet1()),
tabSet1TabPanel_, tabSet1MinPanel_);
populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet2()),
tabSet2TabPanel_, tabSet2MinPanel_);
}
});
}
@Handler
public void onMaximizeConsole()
{
LogicalWindow consoleWindow = panesByName_.get("Console");
if (consoleWindow.getState() != WindowState.MAXIMIZE)
{
consoleWindow.onWindowStateChange(
new WindowStateChangeEvent(WindowState.MAXIMIZE));
}
}
private ArrayList<LogicalWindow> createPanes(PaneConfig config)
{
ArrayList<LogicalWindow> results = new ArrayList<LogicalWindow>();
JsArrayString panes = config.getPanes();
for (int i = 0; i < 4; i++)
{
results.add(panesByName_.get(panes.get(i)));
}
return results;
}
private void initPanes(PaneConfig config)
{
panesByName_ = new HashMap<String, LogicalWindow>();
panesByName_.put("Console", createConsole());
panesByName_.put("Source", createSource());
Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel> ts1 = createTabSet(
"TabSet1",
tabNamesToTabs(config.getTabSet1()));
panesByName_.put("TabSet1", ts1.first);
tabSet1TabPanel_ = ts1.second;
tabSet1MinPanel_ = ts1.third;
Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel> ts2 = createTabSet(
"TabSet2",
tabNamesToTabs(config.getTabSet2()));
panesByName_.put("TabSet2", ts2.first);
tabSet2TabPanel_ = ts2.second;
tabSet2MinPanel_ = ts2.third;
}
private ArrayList<Tab> tabNamesToTabs(JsArrayString tabNames)
{
ArrayList<Tab> tabList = new ArrayList<Tab>();
for (int j = 0; j < tabNames.length(); j++)
tabList.add(Enum.valueOf(Tab.class, tabNames.get(j)));
return tabList;
}
private PaneConfig validateConfig(PaneConfig config)
{
if (config == null)
config = PaneConfig.createDefault();
if (!config.validateAndAutoCorrect())
{
Debug.log("Pane config is not valid");
config = PaneConfig.createDefault();
}
return config;
}
public MainSplitPanel getPanel()
{
return panel_;
}
public WorkbenchTab getTab(Tab tab)
{
switch (tab)
{
case History:
return historyTab_;
case Files:
return filesTab_;
case Plots:
return plotsTab_;
case Packages:
return packagesTab_;
case Help:
return helpTab_;
case VCS:
return vcsTab_;
case Build:
return buildTab_;
case Presentation:
return presentationTab_;
case Environment:
return environmentTab_;
case Viewer:
return viewerTab_;
}
throw new IllegalArgumentException("Unknown tab");
}
public WorkbenchTab[] getAllTabs()
{
return new WorkbenchTab[] { historyTab_, filesTab_,
plotsTab_, packagesTab_, helpTab_,
vcsTab_, buildTab_, presentationTab_,
environmentTab_, viewerTab_};
}
public void activateTab(Tab tab)
{
tabToPanel_.get(tab).selectTab(tabToIndex_.get(tab));
}
public void activateTab(String tabName)
{
Tab tab = tabForName(tabName);
if (tab != null)
activateTab(tab);
}
public ConsolePane getConsole()
{
return consolePane_;
}
public WorkbenchTabPanel getOwnerTabPanel(Tab tab)
{
return tabToPanel_.get(tab);
}
public LogicalWindow getSourceLogicalWindow()
{
return sourceLogicalWindow_;
}
private DualWindowLayoutPanel createSplitWindow(LogicalWindow top,
LogicalWindow bottom,
String name,
double bottomDefaultPct)
{
return new DualWindowLayoutPanel(
eventBus_,
top,
bottom,
session_,
name,
WindowState.NORMAL,
(int) (Window.getClientHeight()*bottomDefaultPct));
}
private LogicalWindow createConsole()
{
PrimaryWindowFrame frame = new PrimaryWindowFrame("Console", null);
ToolbarButton goToWorkingDirButton =
commands_.goToWorkingDir().createToolbarButton();
goToWorkingDirButton.addStyleName(
ThemeResources.INSTANCE.themeStyles().windowFrameToolbarButton());
@SuppressWarnings("unused")
ConsoleTabPanel consoleTabPanel = new ConsoleTabPanel(frame,
consolePane_,
compilePdfTab_,
findOutputTab_,
sourceCppTab_,
eventBus_,
consoleInterrupt_,
goToWorkingDirButton);
return new LogicalWindow(frame, new MinimizedWindowFrame("Console"));
}
private LogicalWindow createSource()
{
WindowFrame sourceFrame = new WindowFrame();
sourceFrame.setFillWidget(source_.asWidget());
source_.forceLoad();
return sourceLogicalWindow_ = new LogicalWindow(
sourceFrame,
new MinimizedWindowFrame("Source"));
}
private
Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel>
createTabSet(String persisterName, ArrayList<Tab> tabs)
{
final WindowFrame frame = new WindowFrame();
final WorkbenchTabPanel tabPanel = new WorkbenchTabPanel(frame);
MinimizedModuleTabLayoutPanel minimized = new MinimizedModuleTabLayoutPanel();
populateTabPanel(tabs, tabPanel, minimized);
frame.setFillWidget(tabPanel);
minimized.addSelectionHandler(new SelectionHandler<Integer>()
{
public void onSelection(SelectionEvent<Integer> integerSelectionEvent)
{
int tab = integerSelectionEvent.getSelectedItem();
tabPanel.selectTab(tab);
}
});
tabPanel.addSelectionHandler(new SelectionHandler<Integer>()
{
public void onSelection(SelectionEvent<Integer> integerSelectionEvent)
{
session_.persistClientState();
}
});
new SelectedTabStateValue(persisterName, tabPanel);
return new Triad<LogicalWindow, WorkbenchTabPanel, MinimizedModuleTabLayoutPanel>(
new LogicalWindow(frame, minimized),
tabPanel,
minimized);
}
private void populateTabPanel(ArrayList<Tab> tabs,
WorkbenchTabPanel tabPanel,
MinimizedModuleTabLayoutPanel minimized)
{
ArrayList<WorkbenchTab> tabList = new ArrayList<WorkbenchTab>();
for (int i = 0; i < tabs.size(); i++)
{
Tab tab = tabs.get(i);
tabList.add(getTab(tab));
tabToPanel_.put(tab, tabPanel);
tabToIndex_.put(tab, i);
}
tabPanel.setTabs(tabList);
ArrayList<String> labels = new ArrayList<String>();
for (Tab tab : tabs)
{
if (!getTab(tab).isSuppressed())
labels.add(getTabLabel(tab));
}
minimized.setTabs(labels.toArray(new String[labels.size()]));
}
private String getTabLabel(Tab tab)
{
switch (tab)
{
case History:
return "History";
case Files:
return "Files";
case Plots:
return "Plots";
case Packages:
return "Packages";
case Help:
return "Help";
case VCS:
return getTab(tab).getTitle();
case Build:
return "Build";
case Presentation:
return getTab(tab).getTitle();
case Environment:
return "Environment";
case Viewer:
return "Viewer";
}
return "??";
}
private Tab tabForName(String name)
{
if (name.equalsIgnoreCase("history"))
return Tab.History;
if (name.equalsIgnoreCase("files"))
return Tab.Files;
if (name.equalsIgnoreCase("plots"))
return Tab.Plots;
if (name.equalsIgnoreCase("packages"))
return Tab.Packages;
if (name.equalsIgnoreCase("help"))
return Tab.Help;
if (name.equalsIgnoreCase("vcs"))
return Tab.VCS;
if (name.equalsIgnoreCase("build"))
return Tab.Build;
if (name.equalsIgnoreCase("presentation"))
return Tab.Presentation;
if (name.equalsIgnoreCase("environment"))
return Tab.Environment;
if (name.equalsIgnoreCase("viewer"))
return Tab.Viewer;
return null;
}
private final EventBus eventBus_;
private final Session session_;
private final Commands commands_;
private final FindOutputTab findOutputTab_;
private final WorkbenchTab compilePdfTab_;
private final WorkbenchTab sourceCppTab_;
private final ConsolePane consolePane_;
private final ConsoleInterruptButton consoleInterrupt_;
private final SourceShim source_;
private final WorkbenchTab historyTab_;
private final WorkbenchTab filesTab_;
private final WorkbenchTab plotsTab_;
private final WorkbenchTab packagesTab_;
private final WorkbenchTab helpTab_;
private final WorkbenchTab vcsTab_;
private final WorkbenchTab buildTab_;
private final WorkbenchTab presentationTab_;
private final WorkbenchTab environmentTab_;
private final WorkbenchTab viewerTab_;
private MainSplitPanel panel_;
private LogicalWindow sourceLogicalWindow_;
private final HashMap<Tab, WorkbenchTabPanel> tabToPanel_ =
new HashMap<Tab, WorkbenchTabPanel>();
private final HashMap<Tab, Integer> tabToIndex_ =
new HashMap<Tab, Integer>();
private HashMap<String, LogicalWindow> panesByName_;
private DualWindowLayoutPanel left_;
private DualWindowLayoutPanel right_;
private ArrayList<LogicalWindow> panes_;
private WorkbenchTabPanel tabSet1TabPanel_;
private MinimizedModuleTabLayoutPanel tabSet1MinPanel_;
private WorkbenchTabPanel tabSet2TabPanel_;
private MinimizedModuleTabLayoutPanel tabSet2MinPanel_;
}
| true | true | public PaneManager(Provider<MainSplitPanel> pSplitPanel,
WorkbenchServerOperations server,
EventBus eventBus,
Session session,
Binder binder,
Commands commands,
UIPrefs uiPrefs,
@Named("Console") final Widget consolePane,
ConsoleInterruptButton consoleInterrupt,
SourceShim source,
@Named("History") final WorkbenchTab historyTab,
@Named("Files") final WorkbenchTab filesTab,
@Named("Plots") final WorkbenchTab plotsTab,
@Named("Packages") final WorkbenchTab packagesTab,
@Named("Help") final WorkbenchTab helpTab,
@Named("VCS") final WorkbenchTab vcsTab,
@Named("Build") final WorkbenchTab buildTab,
@Named("Presentation") final WorkbenchTab presentationTab,
@Named("Environment") final WorkbenchTab environmentTab,
@Named("Viewer") final WorkbenchTab viewerTab,
@Named("Compile PDF") final WorkbenchTab compilePdfTab,
@Named("Source Cpp") final WorkbenchTab sourceCppTab,
final FindOutputTab findOutputTab)
{
eventBus_ = eventBus;
session_ = session;
commands_ = commands;
consolePane_ = (ConsolePane)consolePane;
consoleInterrupt_ = consoleInterrupt;
source_ = source;
historyTab_ = historyTab;
filesTab_ = filesTab;
plotsTab_ = plotsTab;
packagesTab_ = packagesTab;
helpTab_ = helpTab;
vcsTab_ = vcsTab;
buildTab_ = buildTab;
presentationTab_ = presentationTab;
environmentTab_ = environmentTab;
viewerTab_ = viewerTab;
compilePdfTab_ = compilePdfTab;
findOutputTab_ = findOutputTab;
sourceCppTab_ = sourceCppTab;
binder.bind(commands, this);
PaneConfig config = validateConfig(uiPrefs.paneConfig().getValue());
initPanes(config);
panes_ = createPanes(config);
left_ = createSplitWindow(panes_.get(0), panes_.get(1), "left", 0.4);
right_ = createSplitWindow(panes_.get(2), panes_.get(3), "right", 0.6);
panel_ = pSplitPanel.get();
panel_.initialize(left_, right_);
if (session_.getSessionInfo().getSourceDocuments().length() == 0
&& sourceLogicalWindow_.getState() != WindowState.HIDE)
{
sourceLogicalWindow_.onWindowStateChange(
new WindowStateChangeEvent(WindowState.HIDE));
}
else if (session_.getSessionInfo().getSourceDocuments().length() > 0
&& sourceLogicalWindow_.getState() == WindowState.HIDE)
{
sourceLogicalWindow_.onWindowStateChange(
new WindowStateChangeEvent(WindowState.NORMAL));
}
uiPrefs.paneConfig().addValueChangeHandler(new ValueChangeHandler<PaneConfig>()
{
public void onValueChange(ValueChangeEvent<PaneConfig> evt)
{
ArrayList<LogicalWindow> newPanes = createPanes(evt.getValue());
panes_ = newPanes;
left_.replaceWindows(newPanes.get(0), newPanes.get(1));
right_.replaceWindows(newPanes.get(2), newPanes.get(3));
tabSet1TabPanel_.clear();
tabSet2TabPanel_.clear();
populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet1()),
tabSet1TabPanel_, tabSet1MinPanel_);
populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet2()),
tabSet2TabPanel_, tabSet2MinPanel_);
}
});
}
| public PaneManager(Provider<MainSplitPanel> pSplitPanel,
WorkbenchServerOperations server,
EventBus eventBus,
Session session,
Binder binder,
Commands commands,
UIPrefs uiPrefs,
@Named("Console") final Widget consolePane,
ConsoleInterruptButton consoleInterrupt,
SourceShim source,
@Named("History") final WorkbenchTab historyTab,
@Named("Files") final WorkbenchTab filesTab,
@Named("Plots") final WorkbenchTab plotsTab,
@Named("Packages") final WorkbenchTab packagesTab,
@Named("Help") final WorkbenchTab helpTab,
@Named("VCS") final WorkbenchTab vcsTab,
@Named("Build") final WorkbenchTab buildTab,
@Named("Presentation") final WorkbenchTab presentationTab,
@Named("Environment") final WorkbenchTab environmentTab,
@Named("Viewer") final WorkbenchTab viewerTab,
@Named("Compile PDF") final WorkbenchTab compilePdfTab,
@Named("Source Cpp") final WorkbenchTab sourceCppTab,
final FindOutputTab findOutputTab)
{
eventBus_ = eventBus;
session_ = session;
commands_ = commands;
consolePane_ = (ConsolePane)consolePane;
consoleInterrupt_ = consoleInterrupt;
source_ = source;
historyTab_ = historyTab;
filesTab_ = filesTab;
plotsTab_ = plotsTab;
packagesTab_ = packagesTab;
helpTab_ = helpTab;
vcsTab_ = vcsTab;
buildTab_ = buildTab;
presentationTab_ = presentationTab;
environmentTab_ = environmentTab;
viewerTab_ = viewerTab;
compilePdfTab_ = compilePdfTab;
findOutputTab_ = findOutputTab;
sourceCppTab_ = sourceCppTab;
binder.bind(commands, this);
PaneConfig config = validateConfig(uiPrefs.paneConfig().getValue());
initPanes(config);
panes_ = createPanes(config);
left_ = createSplitWindow(panes_.get(0), panes_.get(1), "left", 0.4);
right_ = createSplitWindow(panes_.get(2), panes_.get(3), "right", 0.6);
panel_ = pSplitPanel.get();
panel_.initialize(left_, right_);
if (session_.getSessionInfo().getSourceDocuments().length() == 0
&& sourceLogicalWindow_.getState() != WindowState.HIDE)
{
sourceLogicalWindow_.onWindowStateChange(
new WindowStateChangeEvent(WindowState.HIDE));
}
else if (session_.getSessionInfo().getSourceDocuments().length() > 0
&& sourceLogicalWindow_.getState() == WindowState.HIDE)
{
sourceLogicalWindow_.onWindowStateChange(
new WindowStateChangeEvent(WindowState.NORMAL));
}
uiPrefs.paneConfig().addValueChangeHandler(new ValueChangeHandler<PaneConfig>()
{
public void onValueChange(ValueChangeEvent<PaneConfig> evt)
{
ArrayList<LogicalWindow> newPanes = createPanes(validateConfig(evt.getValue()));
panes_ = newPanes;
left_.replaceWindows(newPanes.get(0), newPanes.get(1));
right_.replaceWindows(newPanes.get(2), newPanes.get(3));
tabSet1TabPanel_.clear();
tabSet2TabPanel_.clear();
populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet1()),
tabSet1TabPanel_, tabSet1MinPanel_);
populateTabPanel(tabNamesToTabs(evt.getValue().getTabSet2()),
tabSet2TabPanel_, tabSet2MinPanel_);
}
});
}
|
diff --git a/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java b/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java
index 440eab70..ddbd5099 100644
--- a/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java
+++ b/src/main/java/com/laytonsmith/aliasengine/functions/Meta.java
@@ -1,496 +1,496 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.laytonsmith.aliasengine.functions;
import com.laytonsmith.aliasengine.api;
import com.laytonsmith.aliasengine.exceptions.CancelCommandException;
import com.laytonsmith.aliasengine.exceptions.ConfigRuntimeException;
import com.laytonsmith.aliasengine.Constructs.CArray;
import com.laytonsmith.aliasengine.Constructs.CString;
import com.laytonsmith.aliasengine.Constructs.CVoid;
import com.laytonsmith.aliasengine.Constructs.Construct;
import com.laytonsmith.aliasengine.Env;
import com.laytonsmith.aliasengine.GenericTreeNode;
import com.laytonsmith.aliasengine.Static;
import com.laytonsmith.aliasengine.functions.Exceptions.ExceptionType;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import java.util.logging.Level;
import net.minecraft.server.ServerConfigurationManager;
import org.bukkit.Bukkit;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* I'm So Meta, Even This Acronym
* @author Layton
*/
public class Meta {
public static String docs() {
return "These functions provide a way to run other commands";
}
@api
public static class runas implements Function {
public String getName() {
return "runas";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public Construct exec(int line_num, File f, final Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[1].val().substring(1);
if (args[0] instanceof CArray) {
CArray u = (CArray) args[0];
for (int i = 0; i < u.size(); i++) {
exec(line_num, f, env, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]});
}
return new CVoid(line_num, f);
}
if (args[0].val().equals("~op")) {
//Store their current op status
Boolean isOp = env.GetCommandSender().isOp();
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[1].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim());
}
}
//If they aren't op, op them now
if (!isOp) {
this.setOp(env.GetCommandSender(), true);
}
try {
Static.getServer().dispatchCommand(this.getOPCommandSender(env.GetCommandSender()), cmd);
} finally {
//If they just opped themselves, or deopped themselves in the command
//don't undo what they just did. Otherwise, set their op status back
//to their original status
- if(!cmd.equalsIgnoreCase("op " + env.GetPlayer().getName()) && !cmd.equalsIgnoreCase("deop " + env.GetPlayer().getName())){
+ if(env.GetPlayer() != null && !cmd.equalsIgnoreCase("op " + env.GetPlayer().getName()) && !cmd.equalsIgnoreCase("deop " + env.GetPlayer().getName())){
this.setOp(env.GetCommandSender(), isOp);
}
}
} else {
Player m = Static.getServer().getPlayer(args[0].val());
if (m != null && m.isOnline()) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
throw new ConfigRuntimeException("The player " + args[0].val() + " is not online",
ExceptionType.PlayerOfflineException, line_num, f);
}
}
return new CVoid(line_num, f);
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException, ExceptionType.PlayerOfflineException};
}
public String docs() {
return "void {player, command} Runs a command as a particular user. The special user '~op' is a user that runs as op. Be careful with this very powerful function."
+ " Commands cannot be run as an offline player. Returns void. If the first argument is an array of usernames, the command"
+ " will be run in the context of each user in the array.";
}
public boolean isRestricted() {
return true;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.0.1";
}
public Boolean runAsync() {
return false;
}
/**
* Set OP status for player without saving to ops.txt
*
* @param player
* @param value
*/
protected void setOp(CommandSender player, Boolean value) {
if (!(player instanceof Player) || player.isOp() == value) {
return;
}
try {
Server server = Bukkit.getServer();
Class serverClass = Class.forName("org.bukkit.craftbukkit.CraftServer", true, server.getClass().getClassLoader());
if (!server.getClass().isAssignableFrom(serverClass)) {
throw new IllegalStateException("Running server isn't CraftBukkit");
}
Field opSetField;
try {
opSetField = ServerConfigurationManager.class.getDeclaredField("operators");
} catch (NoSuchFieldException e){
opSetField = ServerConfigurationManager.class.getDeclaredField("h");
}
opSetField.setAccessible(true); // make field accessible for reflection
// Reflection magic
Set opSet = (Set) opSetField.get((ServerConfigurationManager) serverClass.getMethod("getHandle").invoke(server));
// since all Java objects pass by reference, we don't need to set field back to object
if (value) {
opSet.add(player.getName().toLowerCase());
} else {
opSet.remove(player.getName().toLowerCase());
}
player.recalculatePermissions();
} catch (ClassNotFoundException e) {
} catch (IllegalStateException e) {
} catch (Throwable e) {
Static.getLogger().log(Level.WARNING, "[CommandHelper]: Failed to OP player " + player.getName());
}
}
protected CommandSender getOPCommandSender(final CommandSender sender) {
if (sender.isOp()) {
return sender;
}
return (CommandSender) Proxy.newProxyInstance(sender.getClass().getClassLoader(),
new Class[] { (sender instanceof Player) ? Player.class : CommandSender.class },
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if ("isOp".equals(methodName) || "hasPermission".equals(methodName) || "isPermissionSet".equals(methodName)) {
return true;
} else {
return method.invoke(sender, args);
}
}
});
}
}
@api
public static class run implements Function {
public String getName() {
return "run";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public Construct exec(int line_num, File f, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[0].val() == null || args[0].val().length() <= 0 || args[0].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[0].val().substring(1);
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
}
//p.chat(cmd);
Static.getServer().dispatchCommand(env.GetCommandSender(), cmd);
return new CVoid(line_num, f);
}
public String docs() {
return "void {var1} Runs a command as the current player. Useful for running commands in a loop. Note that this accepts commands like from the "
+ "chat; with a forward slash in front.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.FormatException};
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.0.1";
}
public Boolean runAsync() {
return false;
}
}
@api
public static class g implements Function {
public String getName() {
return "g";
}
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
public Construct exec(int line_num, File f, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
for (int i = 0; i < args.length; i++) {
args[i].val();
}
return new CVoid(line_num, f);
}
public String docs() {
return "string {func1, [func2...]} Groups any number of functions together, and returns void. ";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.0.1";
}
public Boolean runAsync() {
return null;
}
}
@api
public static class p implements Function {
public String getName() {
return "p";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "mixed {c} Used internally by the compiler.";
}
public ExceptionType[] thrown() {
return null;
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.1.2";
}
public Boolean runAsync() {
return null;
}
public Construct exec(int line_num, File f, Env env, Construct... args) throws ConfigRuntimeException {
return Static.resolveConstruct(args[0].val(), line_num, f);
}
}
@api
public static class eval implements Function {
public String getName() {
return "eval";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "string {script_string} Executes arbitrary MScript. Note that this function is very experimental, and is subject to changing or "
+ "removal.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
public boolean isRestricted() {
return true;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.1.0";
}
public Construct exec(int line_num, File f, Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
return new CVoid(line_num, f);
}
//Doesn't matter, run out of state anyways
public Boolean runAsync() {
return null;
}
}
@api
public static class call_alias implements Function {
public String getName() {
return "call_alias";
}
public Integer[] numArgs() {
return new Integer[]{1};
}
public String docs() {
return "void {cmd} Allows a CommandHelper alias to be called from within another alias. Typically this is not possible, as"
+ " a script that runs \"/jail = /jail\" for instance, would simply be calling whatever plugin that actually"
+ " provides the jail functionality's /jail command. However, using this function makes the command loop back"
+ " to CommandHelper only.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{};
}
public boolean isRestricted() {
return false;
}
public void varList(IVariableList varList) {
}
public boolean preResolveVariables() {
return true;
}
public String since() {
return "3.2.0";
}
public Boolean runAsync() {
return null;
}
public Construct exec(int line_num, File f, Env env, Construct... args) throws ConfigRuntimeException {
Static.getAliasCore().removePlayerReference(env.GetCommandSender());
Static.getAliasCore().alias(args[0].val(), env.GetCommandSender(), null);
Static.getAliasCore().addPlayerReference(env.GetCommandSender());
return new CVoid(line_num, f);
}
}
@api public static class scriptas implements Function{
public String getName() {
return "scriptas";
}
public Integer[] numArgs() {
return new Integer[]{2};
}
public String docs() {
return "void {player, script} Runs the specified script in the context of a given player."
+ " A script that runs player() for instance, would return the specified player's name,"
+ " not the player running the command.";
}
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.PlayerOfflineException};
}
public boolean isRestricted() {
return true;
}
public boolean preResolveVariables() {
return false;
}
public String since() {
return "3.3.0";
}
public Boolean runAsync() {
return null;
}
public Construct exec(int line_num, File f, Env environment, Construct... args) throws ConfigRuntimeException {
Player p = Static.GetPlayer(args[0].val(), line_num, f);
CommandSender originalPlayer = environment.GetCommandSender();
environment.SetPlayer(p);
GenericTreeNode<Construct> tree = (GenericTreeNode<Construct>)environment.GetCustom("script_node");
environment.GetScript().eval(tree, environment);
environment.SetCommandSender(originalPlayer);
return new CVoid(line_num, f);
}
}
}
| true | true | public Construct exec(int line_num, File f, final Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[1].val().substring(1);
if (args[0] instanceof CArray) {
CArray u = (CArray) args[0];
for (int i = 0; i < u.size(); i++) {
exec(line_num, f, env, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]});
}
return new CVoid(line_num, f);
}
if (args[0].val().equals("~op")) {
//Store their current op status
Boolean isOp = env.GetCommandSender().isOp();
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[1].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim());
}
}
//If they aren't op, op them now
if (!isOp) {
this.setOp(env.GetCommandSender(), true);
}
try {
Static.getServer().dispatchCommand(this.getOPCommandSender(env.GetCommandSender()), cmd);
} finally {
//If they just opped themselves, or deopped themselves in the command
//don't undo what they just did. Otherwise, set their op status back
//to their original status
if(!cmd.equalsIgnoreCase("op " + env.GetPlayer().getName()) && !cmd.equalsIgnoreCase("deop " + env.GetPlayer().getName())){
this.setOp(env.GetCommandSender(), isOp);
}
}
} else {
Player m = Static.getServer().getPlayer(args[0].val());
if (m != null && m.isOnline()) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
throw new ConfigRuntimeException("The player " + args[0].val() + " is not online",
ExceptionType.PlayerOfflineException, line_num, f);
}
}
return new CVoid(line_num, f);
}
| public Construct exec(int line_num, File f, final Env env, Construct... args) throws CancelCommandException, ConfigRuntimeException {
if (args[1].val() == null || args[1].val().length() <= 0 || args[1].val().charAt(0) != '/') {
throw new ConfigRuntimeException("The first character of the command must be a forward slash (i.e. '/give')",
ExceptionType.FormatException, line_num, f);
}
String cmd = args[1].val().substring(1);
if (args[0] instanceof CArray) {
CArray u = (CArray) args[0];
for (int i = 0; i < u.size(); i++) {
exec(line_num, f, env, new Construct[]{new CString(u.get(i, line_num).val(), line_num, f), args[1]});
}
return new CVoid(line_num, f);
}
if (args[0].val().equals("~op")) {
//Store their current op status
Boolean isOp = env.GetCommandSender().isOp();
if ((Boolean) Static.getPreferences().getPreference("debug-mode")) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[1].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[1].val().trim());
}
}
//If they aren't op, op them now
if (!isOp) {
this.setOp(env.GetCommandSender(), true);
}
try {
Static.getServer().dispatchCommand(this.getOPCommandSender(env.GetCommandSender()), cmd);
} finally {
//If they just opped themselves, or deopped themselves in the command
//don't undo what they just did. Otherwise, set their op status back
//to their original status
if(env.GetPlayer() != null && !cmd.equalsIgnoreCase("op " + env.GetPlayer().getName()) && !cmd.equalsIgnoreCase("deop " + env.GetPlayer().getName())){
this.setOp(env.GetCommandSender(), isOp);
}
}
} else {
Player m = Static.getServer().getPlayer(args[0].val());
if (m != null && m.isOnline()) {
if (env.GetCommandSender() instanceof Player) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + env.GetPlayer().getName() + ": " + args[0].val().trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + args[0].val().trim());
}
//m.chat(cmd);
Static.getServer().dispatchCommand(m, cmd);
} else {
throw new ConfigRuntimeException("The player " + args[0].val() + " is not online",
ExceptionType.PlayerOfflineException, line_num, f);
}
}
return new CVoid(line_num, f);
}
|
diff --git a/src/main/java/com/zazzercode/doctorhere/models/hadoop/DoctorCountTool.java b/src/main/java/com/zazzercode/doctorhere/models/hadoop/DoctorCountTool.java
index 38b9a02..c571972 100644
--- a/src/main/java/com/zazzercode/doctorhere/models/hadoop/DoctorCountTool.java
+++ b/src/main/java/com/zazzercode/doctorhere/models/hadoop/DoctorCountTool.java
@@ -1,45 +1,46 @@
/**
*
*/
package com.zazzercode.doctorhere.models.hadoop;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.util.Tool;
/**
* responsible for triggering the map reduce job in Hadoop
* @author prayag
*
*/
public class DoctorCountTool extends Configured implements Tool{
@Override
public int run(String[] arg0) throws Exception {
JobConf jobConf = new JobConf(getConf(), DoctorCountTool.class);
jobConf.setJobName("DoctorCountTool");
//Setting configuration object with the Data Type of output Key and Value
jobConf.setOutputKeyClass(Text.class);
jobConf.setOutputValueClass(IntWritable.class);
jobConf.setMapperClass(DoctorMapper.class);
jobConf.setReducerClass(DoctorReducer.class);
//the hdfs input and output directory to be fetched from the command line
- FileInputFormat.addInputPath(jobConf, new Path("/tmp/wordcount/in"));
- FileOutputFormat.setOutputPath(jobConf, new Path("/tmp/wordcount/out"));
+ // add any aline to input.txt
+ FileInputFormat.addInputPath(jobConf, new Path("/home/prayag/input.txt"));
+ FileOutputFormat.setOutputPath(jobConf, new Path("/home/prayag/output"));
JobClient.runJob(jobConf);
return 0;
}
}
| true | true | public int run(String[] arg0) throws Exception {
JobConf jobConf = new JobConf(getConf(), DoctorCountTool.class);
jobConf.setJobName("DoctorCountTool");
//Setting configuration object with the Data Type of output Key and Value
jobConf.setOutputKeyClass(Text.class);
jobConf.setOutputValueClass(IntWritable.class);
jobConf.setMapperClass(DoctorMapper.class);
jobConf.setReducerClass(DoctorReducer.class);
//the hdfs input and output directory to be fetched from the command line
FileInputFormat.addInputPath(jobConf, new Path("/tmp/wordcount/in"));
FileOutputFormat.setOutputPath(jobConf, new Path("/tmp/wordcount/out"));
JobClient.runJob(jobConf);
return 0;
}
| public int run(String[] arg0) throws Exception {
JobConf jobConf = new JobConf(getConf(), DoctorCountTool.class);
jobConf.setJobName("DoctorCountTool");
//Setting configuration object with the Data Type of output Key and Value
jobConf.setOutputKeyClass(Text.class);
jobConf.setOutputValueClass(IntWritable.class);
jobConf.setMapperClass(DoctorMapper.class);
jobConf.setReducerClass(DoctorReducer.class);
//the hdfs input and output directory to be fetched from the command line
// add any aline to input.txt
FileInputFormat.addInputPath(jobConf, new Path("/home/prayag/input.txt"));
FileOutputFormat.setOutputPath(jobConf, new Path("/home/prayag/output"));
JobClient.runJob(jobConf);
return 0;
}
|
diff --git a/sandbox/src/org/springmodules/lucene/index/core/concurrent/ConcurrentLuceneIndexTemplate.java b/sandbox/src/org/springmodules/lucene/index/core/concurrent/ConcurrentLuceneIndexTemplate.java
index 5ff0920b..d5dd4064 100644
--- a/sandbox/src/org/springmodules/lucene/index/core/concurrent/ConcurrentLuceneIndexTemplate.java
+++ b/sandbox/src/org/springmodules/lucene/index/core/concurrent/ConcurrentLuceneIndexTemplate.java
@@ -1,93 +1,94 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springmodules.lucene.index.core.concurrent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.beans.factory.FactoryBean;
import org.springmodules.lucene.index.core.LuceneIndexTemplate;
/**
* This class is the dedicated proxy implementation of the LuceneIndexTemplate
* to manage concurrent calls on the index transparently.
*
* @author Thierry Templier
*/
public class ConcurrentLuceneIndexTemplate implements FactoryBean {
private LuceneChannel channel;
/**
* Set the channel used to manage concurrent calls on the index.
*/
public void setChannel(LuceneChannel channel) {
this.channel = channel;
}
/**
* Return the channel used to manage concurrent calls on the index.
*/
public LuceneChannel getChannel() {
return channel;
}
/**
* This method returns the dynamic proxy for the LuceneIndexTemplate
* interface.
*/
public Object getObject() throws Exception {
return (LuceneIndexTemplate) Proxy.newProxyInstance(
LuceneIndexTemplate.class.getClassLoader(),
new Class[] {LuceneIndexTemplate.class},
new ConcurentLuceneIndexTemplateInvocationHandler(channel));
}
public Class getObjectType() {
return LuceneIndexTemplate.class;
}
public boolean isSingleton() {
return true;
}
/**
* Invocation handler that creates a request from the called method,
* addes it in the channel and eventually waits for a response.
*/
private class ConcurentLuceneIndexTemplateInvocationHandler implements InvocationHandler {
private LuceneChannel channel;
public ConcurentLuceneIndexTemplateInvocationHandler(LuceneChannel channel) {
this.channel=channel;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LuceneChannelRequest element=new LuceneChannelRequest(
method.getName(),method.getParameterTypes(),method.getReturnType(),args);
if( method.getReturnType()==void.class ) {
channel.executeWithoutReturn(element);
return null;
} else {
- return channel.execute(element);
+ LuceneChannelResponse response=channel.execute(element);
+ return response.getMethodReturn();
}
}
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LuceneChannelRequest element=new LuceneChannelRequest(
method.getName(),method.getParameterTypes(),method.getReturnType(),args);
if( method.getReturnType()==void.class ) {
channel.executeWithoutReturn(element);
return null;
} else {
return channel.execute(element);
}
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
LuceneChannelRequest element=new LuceneChannelRequest(
method.getName(),method.getParameterTypes(),method.getReturnType(),args);
if( method.getReturnType()==void.class ) {
channel.executeWithoutReturn(element);
return null;
} else {
LuceneChannelResponse response=channel.execute(element);
return response.getMethodReturn();
}
}
|
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/FileDumpHelper.java b/apps/routerconsole/java/src/net/i2p/router/web/FileDumpHelper.java
index 99026be16..7bb1e99d0 100644
--- a/apps/routerconsole/java/src/net/i2p/router/web/FileDumpHelper.java
+++ b/apps/routerconsole/java/src/net/i2p/router/web/FileDumpHelper.java
@@ -1,190 +1,190 @@
package net.i2p.router.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.lang.ClassLoader;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import net.i2p.crypto.SHA256Generator;
import net.i2p.data.DataHelper;
import net.i2p.util.FileUtil;
/**
* Dump info on jars and wars
*
* @since 0.8.13
*/
public class FileDumpHelper extends HelperBase {
public String getFileSummary() {
StringBuilder buf = new StringBuilder(16*1024);
buf.append("<table><tr><th>File</th><th>Size</th><th>Date</th><th>SHA 256</th><th>Revision</th>" +
"<th>JDK</th><th>Built</th><th>By</th><th>Mods</th></tr>");
// jars added in wrapper.config
URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URL[] urls = urlClassLoader.getURLs();
List<File> flist = new ArrayList();
for (int i = 0; i < urls.length; i++) {
String p = urls[i].toString();
if (p.startsWith("file:") && p.endsWith(".jar")) {
p = p.substring(5);
if (!(p.startsWith(_context.getBaseDir().getAbsolutePath()) ||
p.startsWith(_context.getConfigDir().getAbsolutePath()))) {
flist.add(new File(p));
}
}
}
Collections.sort(flist);
for (File f : flist) {
dumpFile(buf, f);
}
// our jars
File dir = new File(_context.getBaseDir(), "lib");
dumpDir(buf, dir, ".jar");
// our wars
dir = new File(_context.getBaseDir(), "webapps");
dumpDir(buf, dir, ".war");
// plugins
File pluginDir = new File(_context.getConfigDir(), PluginUpdateHandler.PLUGIN_DIR);
File[] files = pluginDir.listFiles();
if (files != null) {
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
dir = new File(files[i], "lib");
dumpDir(buf, dir, ".jar");
dir = new File(files[i], "console/webapps");
dumpDir(buf, dir, ".war");
}
}
buf.append("</table>");
return buf.toString();
}
private static void dumpDir(StringBuilder buf, File dir, String suffix) {
File[] files = dir.listFiles();
if (files == null)
return;
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
if (files[i].getName().endsWith(suffix))
dumpFile(buf, files[i]);
}
}
private static void dumpFile(StringBuilder buf, File f) {
buf.append("<tr><td><b>").append(f.getAbsolutePath()).append("</b></td>" +
"<td align=\"right\">").append(f.length()).append("</td>" +
"<td>");
long mod = f.lastModified();
if (mod > 0)
buf.append((new Date(mod)).toString());
else
buf.append("<font color=\"red\">Not found</font>");
buf.append("</td><td align=\"center\">");
if (mod > 0 && !FileUtil.verifyZip(f))
buf.append("<font color=\"red\">CORRUPT</font><br>");
byte[] hash = sha256(f);
if (hash != null) {
byte[] hh = new byte[16];
System.arraycopy(hash, 0, hh, 0, 16);
buf.append("<tt>");
String p1 = DataHelper.toHexString(hh);
for (int i = p1.length(); i < 32; i++) {
buf.append('0');
}
buf.append(p1).append("</tt><br>");
System.arraycopy(hash, 16, hh, 0, 16);
buf.append("<tt>").append(DataHelper.toHexString(hh)).append("</tt>");
}
Attributes att = attributes(f);
if (att == null)
att = new Attributes();
buf.append("<td align=\"center\">");
String iv = getAtt(att, "Implementation-Version");
if (iv != null)
buf.append("<b>").append(iv).append("</b>");
String s = getAtt(att, "Base-Revision");
if (s != null && s.length() > 20) {
if (iv != null)
buf.append("<br>");
buf.append("<a href=\"http://stats.i2p/cgi-bin/viewmtn/revision/info/").append(s)
.append("\">" +
"<tt>").append(s.substring(0, 20)).append("</tt>" +
"<br>" +
"<tt>").append(s.substring(20)).append("</tt></a>");
}
buf.append("</td><td>");
s = getAtt(att, "Created-By");
if (s != null)
buf.append(s);
buf.append("</td><td>");
s = getAtt(att, "Build-Date");
if (s != null)
buf.append(s);
buf.append("</td><td align=\"center\">");
s = getAtt(att, "Built-By");
if (s != null)
buf.append(s);
buf.append("</td><td><font color=\"red\">");
s = getAtt(att, "Workspace-Changes");
if (s != null)
buf.append(s.replace(",", "<br>"));
- buf.append("</font></td>");
+ buf.append("</font></td></tr>\n");
}
private static byte[] sha256(File f) {
InputStream in = null;
try {
in = new FileInputStream(f);
MessageDigest md = SHA256Generator.getDigestInstance();
byte[] b = new byte[4096];
int cnt = 0;
while ((cnt = in.read(b)) >= 0) {
md.update(b, 0, cnt);
}
return md.digest();
} catch (IOException ioe) {
//ioe.printStackTrace();
return null;
} finally {
if (in != null) try { in.close(); } catch (IOException e) {}
}
}
private static Attributes attributes(File f) {
InputStream in = null;
try {
in = (new URL("jar:file:" + f.getAbsolutePath() + "!/META-INF/MANIFEST.MF")).openStream();
Manifest man = new Manifest(in);
return man.getMainAttributes();
} catch (IOException ioe) {
//ioe.printStackTrace();
return null;
} finally {
if (in != null) try { in.close(); } catch (IOException e) {}
}
}
private static String getAtt(Attributes atts, String s) {
String rv = atts.getValue(s);
if (rv != null)
rv = DataHelper.stripHTML(rv);
return rv;
}
}
| true | true | private static void dumpFile(StringBuilder buf, File f) {
buf.append("<tr><td><b>").append(f.getAbsolutePath()).append("</b></td>" +
"<td align=\"right\">").append(f.length()).append("</td>" +
"<td>");
long mod = f.lastModified();
if (mod > 0)
buf.append((new Date(mod)).toString());
else
buf.append("<font color=\"red\">Not found</font>");
buf.append("</td><td align=\"center\">");
if (mod > 0 && !FileUtil.verifyZip(f))
buf.append("<font color=\"red\">CORRUPT</font><br>");
byte[] hash = sha256(f);
if (hash != null) {
byte[] hh = new byte[16];
System.arraycopy(hash, 0, hh, 0, 16);
buf.append("<tt>");
String p1 = DataHelper.toHexString(hh);
for (int i = p1.length(); i < 32; i++) {
buf.append('0');
}
buf.append(p1).append("</tt><br>");
System.arraycopy(hash, 16, hh, 0, 16);
buf.append("<tt>").append(DataHelper.toHexString(hh)).append("</tt>");
}
Attributes att = attributes(f);
if (att == null)
att = new Attributes();
buf.append("<td align=\"center\">");
String iv = getAtt(att, "Implementation-Version");
if (iv != null)
buf.append("<b>").append(iv).append("</b>");
String s = getAtt(att, "Base-Revision");
if (s != null && s.length() > 20) {
if (iv != null)
buf.append("<br>");
buf.append("<a href=\"http://stats.i2p/cgi-bin/viewmtn/revision/info/").append(s)
.append("\">" +
"<tt>").append(s.substring(0, 20)).append("</tt>" +
"<br>" +
"<tt>").append(s.substring(20)).append("</tt></a>");
}
buf.append("</td><td>");
s = getAtt(att, "Created-By");
if (s != null)
buf.append(s);
buf.append("</td><td>");
s = getAtt(att, "Build-Date");
if (s != null)
buf.append(s);
buf.append("</td><td align=\"center\">");
s = getAtt(att, "Built-By");
if (s != null)
buf.append(s);
buf.append("</td><td><font color=\"red\">");
s = getAtt(att, "Workspace-Changes");
if (s != null)
buf.append(s.replace(",", "<br>"));
buf.append("</font></td>");
}
| private static void dumpFile(StringBuilder buf, File f) {
buf.append("<tr><td><b>").append(f.getAbsolutePath()).append("</b></td>" +
"<td align=\"right\">").append(f.length()).append("</td>" +
"<td>");
long mod = f.lastModified();
if (mod > 0)
buf.append((new Date(mod)).toString());
else
buf.append("<font color=\"red\">Not found</font>");
buf.append("</td><td align=\"center\">");
if (mod > 0 && !FileUtil.verifyZip(f))
buf.append("<font color=\"red\">CORRUPT</font><br>");
byte[] hash = sha256(f);
if (hash != null) {
byte[] hh = new byte[16];
System.arraycopy(hash, 0, hh, 0, 16);
buf.append("<tt>");
String p1 = DataHelper.toHexString(hh);
for (int i = p1.length(); i < 32; i++) {
buf.append('0');
}
buf.append(p1).append("</tt><br>");
System.arraycopy(hash, 16, hh, 0, 16);
buf.append("<tt>").append(DataHelper.toHexString(hh)).append("</tt>");
}
Attributes att = attributes(f);
if (att == null)
att = new Attributes();
buf.append("<td align=\"center\">");
String iv = getAtt(att, "Implementation-Version");
if (iv != null)
buf.append("<b>").append(iv).append("</b>");
String s = getAtt(att, "Base-Revision");
if (s != null && s.length() > 20) {
if (iv != null)
buf.append("<br>");
buf.append("<a href=\"http://stats.i2p/cgi-bin/viewmtn/revision/info/").append(s)
.append("\">" +
"<tt>").append(s.substring(0, 20)).append("</tt>" +
"<br>" +
"<tt>").append(s.substring(20)).append("</tt></a>");
}
buf.append("</td><td>");
s = getAtt(att, "Created-By");
if (s != null)
buf.append(s);
buf.append("</td><td>");
s = getAtt(att, "Build-Date");
if (s != null)
buf.append(s);
buf.append("</td><td align=\"center\">");
s = getAtt(att, "Built-By");
if (s != null)
buf.append(s);
buf.append("</td><td><font color=\"red\">");
s = getAtt(att, "Workspace-Changes");
if (s != null)
buf.append(s.replace(",", "<br>"));
buf.append("</font></td></tr>\n");
}
|
diff --git a/src/main/java/com/zack6849/superlogger/EventsHandler.java b/src/main/java/com/zack6849/superlogger/EventsHandler.java
index 917d175..65666cc 100644
--- a/src/main/java/com/zack6849/superlogger/EventsHandler.java
+++ b/src/main/java/com/zack6849/superlogger/EventsHandler.java
@@ -1,251 +1,251 @@
package com.zack6849.superlogger;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;
public class EventsHandler implements Listener {
public static main plugin;
public static boolean debug;
public static boolean LOG_COMMANDS;
public static boolean LOG_JOIN;
public static boolean LOG_CHAT;
public static boolean LOG_JOIN_IP;
public static boolean COMMAND_WHITELIST;
public static boolean LOG_KICK;
public static boolean LOG_QUIT ;
public static boolean LOG_DEATH;
public static boolean LOG_DEATH_LOCATION;
public static boolean LOG_DISALLOWED_CONNECTIONS;
public EventsHandler(main main) {
plugin = main;
debug = false;
LOG_COMMANDS = plugin.getConfig().getBoolean("log-commands");
LOG_JOIN = plugin.getConfig().getBoolean("log-join");
LOG_CHAT = plugin.getConfig().getBoolean("log-chat");
LOG_JOIN_IP = plugin.getConfig().getBoolean("log-ip");
COMMAND_WHITELIST = plugin.getConfig().getBoolean("use-command-whitelist");
LOG_KICK = plugin.getConfig().getBoolean("log-kick");
LOG_QUIT = plugin.getConfig().getBoolean("log-quit");
LOG_DEATH = plugin.getConfig().getBoolean("log-death");
LOG_DEATH_LOCATION = plugin.getConfig().getBoolean("log-death-location");
LOG_DISALLOWED_CONNECTIONS = plugin.getConfig().getBoolean("log-disallowed-connections");
}
public static void reload(){
LOG_COMMANDS = plugin.getConfig().getBoolean("log-commands");
LOG_JOIN = plugin.getConfig().getBoolean("log-join");
LOG_CHAT = plugin.getConfig().getBoolean("log-chat");
LOG_JOIN_IP = plugin.getConfig().getBoolean("log-ip");
COMMAND_WHITELIST = plugin.getConfig().getBoolean("use-command-whitelist");
LOG_KICK = plugin.getConfig().getBoolean("log-kick");
LOG_QUIT = plugin.getConfig().getBoolean("log-quit");
LOG_DEATH = plugin.getConfig().getBoolean("log-death");
LOG_DEATH_LOCATION = plugin.getConfig().getBoolean("log-death-location");
LOG_DISALLOWED_CONNECTIONS = plugin.getConfig().getBoolean("log-disallowed-connections");
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent e) {
debug("command event");
if (LOG_COMMANDS && ((main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.command")) || !main.permissions)) {
debug("logging commands");
String command = e.getMessage().split(" ")[0].replaceFirst("/", "");
if(plugin.getServer().getPluginCommand(command) == null && !plugin.getConfig().getBoolean("check-commands")){
return;
}
if (COMMAND_WHITELIST && isWhitelisted(e.getMessage())) {
debug("command whitelisting enabled and command is whitelisted");
if (!main.oldlog) {
debug("old logging disabled");
plugin.log(main.commands, main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
}
debug("logging to log.txt");
plugin.logToFile(main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
return;
}
debug("whitelist wasn't enabled.");
if (!main.oldlog) {
debug("old logging wasnt enabled");
plugin.log(main.commands, main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
}
debug("logging to main file");
plugin.logToFile(main.getTime() + "[COMMAND] " + e.getPlayer().getName() + " used command " + e.getMessage());
}
}
@EventHandler
public void onChat(AsyncPlayerChatEvent e) {
if (LOG_CHAT) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.chat")) {
if (!main.oldlog) {
plugin.log(main.chat, main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
}
plugin.logToFile(main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
return;
}
if (!main.oldlog) {
plugin.log(main.chat, main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
}
plugin.logToFile(main.getTime() + "[CHAT] <" + e.getPlayer().getName() + "> " + e.getMessage());
return;
}
}
@EventHandler
public void onJoin(PlayerJoinEvent e) {
if (LOG_JOIN) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.connection")) {
String log = main.getTime() + "[JOIN] " + e.getPlayer().getName() + " joined the server";
if (LOG_JOIN_IP) {
log += " from ip " + e.getPlayer().getAddress().toString().replaceFirst("/", "");
}
if (main.oldlog) {
//log to the main
plugin.logToFile(log);
}
plugin.logToAll(log);
return;
}
String log = main.getTime() + "[JOIN] " + e.getPlayer().getName() + " joined the server";
if (LOG_JOIN_IP) {
log += " from ip " + e.getPlayer().getAddress().toString().replaceFirst("/", "");
}
if (main.oldlog) {
plugin.logToFile(log);
}
plugin.log(main.connections, log);
}
}
@EventHandler
public void onKick(PlayerKickEvent e) {
if (LOG_KICK) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.connection")) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK]" + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
}
plugin.logToFile(main.getTime() + "[KICK] " + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
return;
}
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK]" + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
}
plugin.logToFile(main.getTime() + "[KICK] " + e.getPlayer().getName() + " was kicked from the server for " + e.getReason());
}
}
@EventHandler
public void onQuit(PlayerQuitEvent e) {
if (LOG_QUIT) {
if (main.permissions && !e.getPlayer().hasPermission("superlogger.bypass.connection")) {
plugin.logToFile(main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
}
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
return;
}
plugin.logToFile(main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
}
plugin.log(main.connections, main.getTime() + "[LEAVE] " + e.getPlayer().getName() + " left the server");
}
}
@EventHandler
public void onDeath(PlayerDeathEvent e) {
String info = main.getTime() + "[DEATH] " + e.getDeathMessage();
if (LOG_DEATH) {
if (main.permissions && !e.getEntity().hasPermission("superlogger.bypass.death")) {
if (LOG_DEATH_LOCATION) {
info += String.format(" at (%s,%s,%s) in world %s", e.getEntity().getLocation().getBlockX(), e.getEntity().getLocation().getBlockY(), e.getEntity().getLocation().getBlockZ(), e.getEntity().getWorld().getName());
}
if (main.oldlog) {
plugin.log(main.death, info);
}
plugin.logToFile(info);
return;
}
if (LOG_DEATH_LOCATION) {
info += String.format(" at (%s,%s,%s) in world %s", e.getEntity().getLocation().getBlockX(), e.getEntity().getLocation().getBlockY(), e.getEntity().getLocation().getBlockZ(), e.getEntity().getWorld().getName());
}
if (main.oldlog) {
plugin.log(main.death, info);
}
plugin.logToFile(info);
}
}
@EventHandler
- public void onDisalow(PlayerLoginEvent e) {
+ public void onDisallow(PlayerLoginEvent e) {
if (LOG_DISALLOWED_CONNECTIONS) {
if (!e.getResult().equals(PlayerLoginEvent.Result.ALLOWED)) {
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_BANNED)) {
plugin.logToFile(main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
}
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_WHITELIST)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
plugin.logToFile(main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_FULL)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
plugin.logToFile(main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_OTHER)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
plugin.logToFile(main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
}
}
}
public boolean isFiltered(String s) {
boolean flag = false;
String msg = s.split(" ")[0].toLowerCase().replaceFirst("/", "");
for (String s1 : main.blocked) {
if (msg.equalsIgnoreCase(s1)) {
flag = true;
break;
}
}
return flag;
}
public boolean isWhitelisted(String s) {
boolean flag = false;
String msg = s.split(" ")[0].toLowerCase().replaceFirst("/", "");
for (String s1 : main.whitelist) {
if (msg.equalsIgnoreCase(s1)) {
flag = true;
break;
}
}
return flag;
}
public static void debug(String s) {
if (debug) {
plugin.log.log(Level.FINEST, s);
Bukkit.broadcastMessage("[SUPERLOGGER] DEBUG: " + s);
}
}
}
| true | true | public void onDisalow(PlayerLoginEvent e) {
if (LOG_DISALLOWED_CONNECTIONS) {
if (!e.getResult().equals(PlayerLoginEvent.Result.ALLOWED)) {
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_BANNED)) {
plugin.logToFile(main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
}
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_WHITELIST)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
plugin.logToFile(main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_FULL)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
plugin.logToFile(main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_OTHER)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
plugin.logToFile(main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
}
}
}
| public void onDisallow(PlayerLoginEvent e) {
if (LOG_DISALLOWED_CONNECTIONS) {
if (!e.getResult().equals(PlayerLoginEvent.Result.ALLOWED)) {
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_BANNED)) {
plugin.logToFile(main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-BANNED] " + e.getPlayer().getName() + " was disconnected from the server because they are banned.");
}
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_WHITELIST)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
plugin.logToFile(main.getTime() + "[KICK-WHITELIST] " + e.getPlayer().getName() + " was disconnected for not being whitelisted.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_FULL)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
plugin.logToFile(main.getTime() + "[KICK-FULL SERVER] " + e.getPlayer().getName() + " was disconnected because the server is full.");
}
if (e.getResult().equals(PlayerLoginEvent.Result.KICK_OTHER)) {
if (!main.oldlog) {
plugin.log(main.connections, main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
plugin.logToFile(main.getTime() + "[KICK-UNKNOWN] " + e.getPlayer().getName() + " was disconnected for an unknown reason");
}
}
}
}
|
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/CalcNearBy.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/CalcNearBy.java
index bf436760..ec059d48 100644
--- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/CalcNearBy.java
+++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/CalcNearBy.java
@@ -1,414 +1,414 @@
/**
* This file is part of OSM2GpsMid
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* Copyright (C) 2007 Harald Mueller
* Copyright (C) 2007, 2008 Kai Krueger
*/
package de.ueller.osmToGpsMid;
import java.lang.Long;
import java.util.HashMap;
import de.ueller.osmToGpsMid.model.Entity;
import de.ueller.osmToGpsMid.model.Node;
import de.ueller.osmToGpsMid.model.Way;
import edu.wlu.cs.levy.CG.KDTree;
import edu.wlu.cs.levy.CG.KeyDuplicateException;
import edu.wlu.cs.levy.CG.KeySizeException;
public class CalcNearBy {
private int kdSize = 0; // Hack around the fact that KD-tree doesn't tell us its size
private static int kdWaysSize = 0;
private static KDTree nearByWays;
public CalcNearBy(OsmParser parser) {
KDTree nearByElements = getNearByElements(parser);
if (Configuration.getConfiguration().useHouseNumbers) {
nearByWays = getNearByWays(parser);
}
if (kdSize > 0) {
calcCityNearBy(parser, nearByElements);
calcWayIsIn(parser, nearByElements);
}
if (kdWaysSize > 0) {
calcWaysForHouseNumbers(parser, nearByWays);
}
}
// FIXME: this is a pretty crude and error-prone way to do this, rewrite to be better
// should use a better algorithm for findind the proper way
// GpsMid has a place where the nearest way to a destination is found,
// perhaps that can be used.
// sk750 April 2011: What you want to do with finding the closest way for a house number in Osm2GpsMid
// might be a mixture of closest point on a line in GpsMid
// and the traffic signal route node marking in Osm2GpsMid -
// though I this misses marking some route nodes
// because it doesn't look over tile boundaries for performance reasons.
//
// Plan:
// 1) get a bunch of nearby (by midpoint) named ways (maybe two dozen or so),
// 2) if addr:streetname matches to exactly one of the ways, mark that way as associated
// 3) order the ways by distance from the node to the closest point of the way
// 4) mark the nearest way as associated
// 5) maybe mark also one or two other nearest ways as associated, depending on .properties config
// (false nearby positives might be considered a lesser evil than not finding a housenumber)
// (the storage model currently doesn't allow for several way, so that would
// involve a change to storage or cloning of the node)
/*
maybe this is useful:
b/GpsMidGraph/de/ueller/midlet/gps/data/MoreMath.java
public static Node closestPointOnLine(Node node1, Node node2, Node offNode) {
// avoid division by zero if node1 and node2 are at the same coordinates
if (node1.radlat == node2.radlat && node1.radlon == node2.radlon) {
return new Node(node1);
}
float uX = node2.radlat - node1.radlat;
float uY = node2.radlon - node1.radlon;
float u = ( (offNode.radlat - node1.radlat) * uX + (offNode.radlon - node1.radlon) * uY) / (uX * uX + uY * uY);
if (u > 1.0) {
return new Node(node2);
} else if (u <= 0.0) {
return new Node(node1);
} else {
return new Node( (float)(node2.radlat * u + node1.radlat * (1.0 - u )), (float) (node2.radlon * u + node1.radlon * (1.0-u)), true);
}
}
}
*/
public long calcWayForHouseNumber(Entity n) {
- String streetName = n.getAttribute("addr:streetname");
+ String streetName = n.getAttribute("addr:street");
Node nearestWay = null;
try {
Node thisNode = null;
if (n instanceof Node) {
thisNode = (Node) n;
} else {
Way w = (Way) n;
thisNode = w.getMidPoint();
}
nearestWay = (Node) nearByWays.nearest(MyMath.latlon2XYZ(thisNode));
long maxDistanceTested = MyMath.dist(thisNode, nearestWay);
int retrieveN = 5;
int retrieveNforName = 5;
if (retrieveN > kdWaysSize) {
retrieveN = kdWaysSize;
}
if (retrieveNforName > kdWaysSize) {
retrieveNforName = kdWaysSize;
}
nearestWay = null;
long dist = 0;
Object [] nearWays = null;
if (false) {
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
// first look for matching street name
dist = 0;
nearWays = nearByWays.nearest(MyMath.latlon2XYZ(thisNode), retrieveNforName);
for (Object o : nearWays) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
if (other.getName() != null && streetName != null) {
//System.out.println ("comparing " + streetName + " to " + other.getName());
if (streetName.equals(other.getName())) {
nearestWay = other;
break;
}
}
}
if (nearestWay != null) {
//found a suitable Way, leaving loop
break;
}
if (retrieveN == kdWaysSize) {
/**
* We have checked all available ways and nothing was
* suitable, so abort with nearestWay == null;
*/
break;
}
maxDistanceTested = dist;
retrieveNforName = retrieveNforName * 5;
if (retrieveNforName > kdWaysSize) {
retrieveNforName = kdWaysSize;
}
}
}
if (nearestWay == null) {
nearestWay = (Node) nearByWays.nearest(MyMath.latlon2XYZ(thisNode));
maxDistanceTested = MyMath.dist(thisNode, nearestWay);
nearestWay = null;
retrieveN = 5;
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
dist = 0;
nearWays = nearByWays.nearest(MyMath.latlon2XYZ(thisNode), retrieveN);
// then look for other named ways
for (Object o : nearWays) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
//As the list returned by the kd-tree is sorted by distance,
//we can stop at the first found plus some (to match for street name)
if (dist < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
nearestWay = other;
break;
}
}
if (nearestWay != null) {
//found a suitable Way, leaving loop
break;
}
if (retrieveN == kdWaysSize) {
/**
* We have checked all available ways and nothing was
* suitable, so abort with nearestWay == null;
*/
break;
}
maxDistanceTested = dist;
retrieveN = retrieveN * 5;
if (retrieveN > kdWaysSize) {
retrieveN = kdWaysSize;
}
}
}
} catch (KeySizeException e) {
// Something must have gone horribly wrong here,
// This should never happen.
e.printStackTrace();
return 0;
}
if (nearestWay != null) {
return nearestWay.id;
}
return (long) 0;
}
/**
* @param parser
* @param nearByElements
*/
private void calcWayIsIn(OsmParser parser, KDTree nearByElements) {
for (Way w : parser.getWays()) {
if (w.isHighway() /*&& w.getIsIn() == null */) {
Node thisNode = w.getMidPoint();
if (thisNode == null) {
continue;
}
Node nearestPlace = null;
try {
nearestPlace = (Node) nearByElements.nearest(MyMath.latlon2XYZ(thisNode));
if (nearestPlace.getType(null) <= 5 && !(MyMath.dist(thisNode, nearestPlace) < Constants.MAX_DIST_CITY[nearestPlace.getType(null)])) {
long maxDistanceTested = MyMath.dist(thisNode, nearestPlace);
int retrieveN = 5;
if (retrieveN > kdSize) {
retrieveN = kdSize;
}
nearestPlace = null;
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
Object [] nearPlaces = nearByElements.nearest(MyMath.latlon2XYZ(thisNode), retrieveN);
long dist = 0;
for (Object o : nearPlaces) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
//As the list returned by the kd-tree is sorted by distance,
//we can stop at the first found
if (other.getType(null) <= 5 && dist < Constants.MAX_DIST_CITY[other.getType(null)]) {
nearestPlace = other;
break;
}
}
if (nearestPlace != null) {
//found a suitable Place, leaving loop
break;
}
if (retrieveN == kdSize) {
/**
* We have checked all available places and nothing was
* suitable, so abort with nearestPlace == null;
*/
break;
}
maxDistanceTested = dist;
retrieveN = retrieveN * 5;
if (retrieveN > kdSize) {
retrieveN = kdSize;
}
}
}
} catch (KeySizeException e) {
// Something must have gone horribly wrong here,
// This should never happen.
e.printStackTrace();
return;
}
if (nearestPlace != null) {
w.setAttribute("is_in", nearestPlace.getName());
w.nearBy = nearestPlace;
}
}
}
}
/**
* @param parser
* @param nearByElements
*/
private void calcWaysForHouseNumbers(OsmParser parser, KDTree nearByElements) {
int count = 0;
int ignoreCount = 0;
HashMap<Long, Way> wayHashMap = parser.getWayHashMap();
for (Node n : parser.getNodes()) {
if (n.hasHouseNumber()) {
long way = calcWayForHouseNumber((Entity) n);
//System.out.println ("Got id " + way + " for housenumber node " + n);
if (way != 0 && !n.containsKey("__wayid")) {
count++;
n.setAttribute("__wayid", Long.toString(way));
Way w = wayHashMap.get(way);
if (w != null) {
w.houseNumberAdd(n);
}
} else {
ignoreCount++;
}
}
}
System.out.println("info: accepted " + count + " non-relation housenumber-to-street connections");
System.out.println("info: ignored " + ignoreCount + " non-relation housenumber-to-street connections");
}
private void calcCityNearBy(OsmParser parser, KDTree nearByElements) {
//double [] latlonKey = new double[2];
for (Node n : parser.getNodes()) {
String place = n.getPlace();
if (place != null) {
Node nearestPlace = null;
int nneighbours = 10;
long nearesDist = Long.MAX_VALUE;
while ((nearestPlace == null)) {
nearesDist = Long.MAX_VALUE;
Object[] nearNodes = null;
if (kdSize < nneighbours) {
nneighbours = kdSize;
}
try {
nearNodes = nearByElements.nearest(
MyMath.latlon2XYZ(n), nneighbours);
} catch (IllegalArgumentException e) {
e.printStackTrace();
return;
} catch (KeySizeException e) {
e.printStackTrace();
return;
} catch (ClassCastException cce) {
System.out.println(nearNodes);
return;
}
for (Object otherO : nearNodes) {
Node other = (Node) otherO;
if ((n.getType(null) > other.getType(null)) && (other.getType(null) > 0)) {
long dist = MyMath.dist(n, other);
if (dist < nearesDist) {
nearesDist = dist;
nearestPlace = other;
}
}
}
if (nneighbours == kdSize) {
break;
}
nneighbours *= 5;
}
if (nearestPlace != null) {
n.nearBy = nearestPlace;
//n.nearByDist = nearesDist;
// System.out.println(n + " near " + n.nearBy);
}
}
}
}
private KDTree getNearByElements(OsmParser parser) {
System.out.println("Creating nearBy candidates");
KDTree kd = new KDTree(3);
//double [] latlonKey = new double[2];
for (Node n : parser.getNodes()) {
if (n.isPlace()) {
//latlonKey[0] = n.lat;
//latlonKey[1] = n.lon;
if (n.getName() == null || n.getName().trim().length() == 0) {
System.out.println("STRANGE: place without name, skipping: " + n);
System.out.println(" Please fix in OSM: " + n.toUrl());
continue;
}
try {
kd.insert(MyMath.latlon2XYZ(n), n);
kdSize++;
} catch (KeySizeException e) {
e.printStackTrace();
} catch (KeyDuplicateException e) {
System.out.println("KeyDuplication at " + n);
System.out.println(" Please fix in OSM: " + n.toUrl());
}
}
}
System.out.println("Found " + kdSize + " placenames");
return kd;
}
private KDTree getNearByWays(OsmParser parser) {
System.out.println("Creating nearBy way candidates");
KDTree kd = new KDTree(3);
//double [] latlonKey = new double[2];
for (Way w : parser.getWays()) {
if (w.isHighway() /*&& w.getIsIn() == null */) {
if (w.getName() == null || w.getName().trim().length() == 0) {
continue;
}
Node n = w.getMidPoint();
if (n == null) {
continue;
}
try {
// replace node's id with way id so
// we get the right id to add as tag
// causes problems
Node n2 = new Node();
n2.id = w.id;
// transfer coords to node
n2.lat = n.lat;
n2.lon = n.lon;
// System.out.println("way name: " + w.getName());
//n.setAttribute("name", w.getName());
// is this needed? suppose not
//n2.cloneTags(w);
//System.out.println("midpoint node: " + w.getName());
// FIXME: should find out about and eliminate duplicate warnings
kd.insert(MyMath.latlon2XYZ(n2), n2);
kdWaysSize++;
} catch (KeySizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyDuplicateException e) {
System.out.println("Warning: KeyDuplication bug at housenumber handling " + n.toUrl());
}
}
}
System.out.println("Found " + kdWaysSize + " waynames");
return kd;
}
}
| true | true | public long calcWayForHouseNumber(Entity n) {
String streetName = n.getAttribute("addr:streetname");
Node nearestWay = null;
try {
Node thisNode = null;
if (n instanceof Node) {
thisNode = (Node) n;
} else {
Way w = (Way) n;
thisNode = w.getMidPoint();
}
nearestWay = (Node) nearByWays.nearest(MyMath.latlon2XYZ(thisNode));
long maxDistanceTested = MyMath.dist(thisNode, nearestWay);
int retrieveN = 5;
int retrieveNforName = 5;
if (retrieveN > kdWaysSize) {
retrieveN = kdWaysSize;
}
if (retrieveNforName > kdWaysSize) {
retrieveNforName = kdWaysSize;
}
nearestWay = null;
long dist = 0;
Object [] nearWays = null;
if (false) {
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
// first look for matching street name
dist = 0;
nearWays = nearByWays.nearest(MyMath.latlon2XYZ(thisNode), retrieveNforName);
for (Object o : nearWays) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
if (other.getName() != null && streetName != null) {
//System.out.println ("comparing " + streetName + " to " + other.getName());
if (streetName.equals(other.getName())) {
nearestWay = other;
break;
}
}
}
if (nearestWay != null) {
//found a suitable Way, leaving loop
break;
}
if (retrieveN == kdWaysSize) {
/**
* We have checked all available ways and nothing was
* suitable, so abort with nearestWay == null;
*/
break;
}
maxDistanceTested = dist;
retrieveNforName = retrieveNforName * 5;
if (retrieveNforName > kdWaysSize) {
retrieveNforName = kdWaysSize;
}
}
}
if (nearestWay == null) {
nearestWay = (Node) nearByWays.nearest(MyMath.latlon2XYZ(thisNode));
maxDistanceTested = MyMath.dist(thisNode, nearestWay);
nearestWay = null;
retrieveN = 5;
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
dist = 0;
nearWays = nearByWays.nearest(MyMath.latlon2XYZ(thisNode), retrieveN);
// then look for other named ways
for (Object o : nearWays) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
//As the list returned by the kd-tree is sorted by distance,
//we can stop at the first found plus some (to match for street name)
if (dist < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
nearestWay = other;
break;
}
}
if (nearestWay != null) {
//found a suitable Way, leaving loop
break;
}
if (retrieveN == kdWaysSize) {
/**
* We have checked all available ways and nothing was
* suitable, so abort with nearestWay == null;
*/
break;
}
maxDistanceTested = dist;
retrieveN = retrieveN * 5;
if (retrieveN > kdWaysSize) {
retrieveN = kdWaysSize;
}
}
}
} catch (KeySizeException e) {
// Something must have gone horribly wrong here,
// This should never happen.
e.printStackTrace();
return 0;
}
if (nearestWay != null) {
return nearestWay.id;
}
return (long) 0;
}
| public long calcWayForHouseNumber(Entity n) {
String streetName = n.getAttribute("addr:street");
Node nearestWay = null;
try {
Node thisNode = null;
if (n instanceof Node) {
thisNode = (Node) n;
} else {
Way w = (Way) n;
thisNode = w.getMidPoint();
}
nearestWay = (Node) nearByWays.nearest(MyMath.latlon2XYZ(thisNode));
long maxDistanceTested = MyMath.dist(thisNode, nearestWay);
int retrieveN = 5;
int retrieveNforName = 5;
if (retrieveN > kdWaysSize) {
retrieveN = kdWaysSize;
}
if (retrieveNforName > kdWaysSize) {
retrieveNforName = kdWaysSize;
}
nearestWay = null;
long dist = 0;
Object [] nearWays = null;
if (false) {
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
// first look for matching street name
dist = 0;
nearWays = nearByWays.nearest(MyMath.latlon2XYZ(thisNode), retrieveNforName);
for (Object o : nearWays) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
if (other.getName() != null && streetName != null) {
//System.out.println ("comparing " + streetName + " to " + other.getName());
if (streetName.equals(other.getName())) {
nearestWay = other;
break;
}
}
}
if (nearestWay != null) {
//found a suitable Way, leaving loop
break;
}
if (retrieveN == kdWaysSize) {
/**
* We have checked all available ways and nothing was
* suitable, so abort with nearestWay == null;
*/
break;
}
maxDistanceTested = dist;
retrieveNforName = retrieveNforName * 5;
if (retrieveNforName > kdWaysSize) {
retrieveNforName = kdWaysSize;
}
}
}
if (nearestWay == null) {
nearestWay = (Node) nearByWays.nearest(MyMath.latlon2XYZ(thisNode));
maxDistanceTested = MyMath.dist(thisNode, nearestWay);
nearestWay = null;
retrieveN = 5;
while (maxDistanceTested < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
dist = 0;
nearWays = nearByWays.nearest(MyMath.latlon2XYZ(thisNode), retrieveN);
// then look for other named ways
for (Object o : nearWays) {
Node other = (Node) o;
dist = MyMath.dist(thisNode, other);
//As the list returned by the kd-tree is sorted by distance,
//we can stop at the first found plus some (to match for street name)
if (dist < Constants.MAX_DIST_CITY[Constants.NODE_PLACE_CITY]) {
nearestWay = other;
break;
}
}
if (nearestWay != null) {
//found a suitable Way, leaving loop
break;
}
if (retrieveN == kdWaysSize) {
/**
* We have checked all available ways and nothing was
* suitable, so abort with nearestWay == null;
*/
break;
}
maxDistanceTested = dist;
retrieveN = retrieveN * 5;
if (retrieveN > kdWaysSize) {
retrieveN = kdWaysSize;
}
}
}
} catch (KeySizeException e) {
// Something must have gone horribly wrong here,
// This should never happen.
e.printStackTrace();
return 0;
}
if (nearestWay != null) {
return nearestWay.id;
}
return (long) 0;
}
|
diff --git a/EventVerwaltung/src/Event.java b/EventVerwaltung/src/Event.java
index e921633..d3393a6 100644
--- a/EventVerwaltung/src/Event.java
+++ b/EventVerwaltung/src/Event.java
@@ -1,126 +1,126 @@
import java.util.ArrayList;
/**
* Java Applikation zur Verwaltung eines Events, welcher einen spezifischen Kuenstler, bzw. Kuenstlergruppe
* enthaelt. Zusaetzlich koennen verschiedene Ticketkategorien mit einer individuellen Anzahl und Preis
* definiert werden.
*
* @author Dave Kramer, Simon Schwarz
* @version 0.5
*/
public class Event
{
Kuenstler kuenstler;
Ticket ticket;
ArrayList<Ticket> alleTickets = new ArrayList<Ticket>();
//int ticketKategorien[];
public Event(String kuenstlerBezeichnung, int kuenstlerGage,
int ticketAnzahlKategorie1, int ticketPreisKategorie1,
int ticketAnzahlKategorie2, int ticketPreisKategorie2,
int ticketAnzahlKategorie3, int ticketPreisKategorie3)
{
int ticketKategorien[] = new int[]{1, 2, 3};
int ticketAnzahl[] = new int[]{ticketAnzahlKategorie1, ticketAnzahlKategorie2, ticketAnzahlKategorie3};
int ticketPreise[] = new int[]{ticketPreisKategorie1, ticketPreisKategorie2, ticketPreisKategorie3};
kuenstler = new Kuenstler(kuenstlerBezeichnung, kuenstlerGage);
for(int i = 0; i < ticketKategorien.length; i++)
{
ticket = new Ticket(ticketKategorien[i], ticketPreise[i], ticketAnzahl[i]);
alleTickets.add(ticket);
}
}
/**
* Erstellt einen neuen Event ohne Parameter. Tickets und Kuenstler koennen im Nachhinen mittels setter-Methoden gesetzt werden.
*/
public Event()
{
//Ich mache nichts
}
/**
* Erstellt einen neue Ticketkategorie sofern es noch nicht drei gibt
*
* @param kategorie Ticketkategorie
* @param preis Preis der Tickets in dieser Kategorie
* @param anzahl Anzahl vorhanden Tickets in der Kategorie
*/
public void setTicket(int kategorie,int preis, int anzahl)
{
if (alleTickets.size() < 3)
{
ticket = new Ticket(kategorie, preis, anzahl);
alleTickets.add(ticket);
}
else
{
System.out.println("Keine Ticketkategorien mehr einzurichten.(Max. 3)");
}
}
/**
* Methode um Tickets zu verkaufen, bzw. kaufen.
*
* @param anzahl Die gew�nschte Anzhal Tickets welche gekauft werden sollten
* @param kategorie Die gew�nschte Ticketkategorie
*/
public void kaufeTickets(int anzahl, int kategorie)
{
boolean vorhanden = false;
for(int i = 0; i < alleTickets.size(); i++)
{
Ticket tempTicket = alleTickets.get(i);
if(tempTicket.getTicketNr() == kategorie)
{
alleTickets.get(i).ticketVerkauf(anzahl);
vorhanden = true;
}
}
if(!vorhanden)
{
System.out.println("Die gewuenschte Kategorie hat noch keine Tickets");
}
}
/**
* Erstellt einen neuen Kuenstler oder Gruppe.
*
* @param bezeichnung Name der Gruppe, des Kuenstlers
* @param gage Verdienst des / der Kuenstler
*/
public void setKuenstler(String bezeichnung, int gage)
{
kuenstler = new Kuenstler(bezeichnung, gage);
}
public void outputEvent()
{
int ticketGesamtEinnahmen = 0;
if(kuenstler == null || ticket == null)
{
System.out.println("Es wurden noch nicht alle benoetigten Angaben eingetragen");
}
else
{
String outputString = "Kuenstler: " + kuenstler.getKuenstlerName() + ", Gage CHF " + kuenstler.getKuenstlerGage() + "\n";
for(Ticket ticket: alleTickets)
{
outputString += ticket.getTicketKategorieName() + ": " +
ticket.getTicketVerkauftAnzahl() + " von " + ticket.getTicketAnzahl() + " verkauft" +
- ", Einnahmen: CHF " + (ticket.getTicketVerkauftAnzahl() * ticket.getTicketAnzahl()) + "\n";
+ ", Einnahmen: CHF " + (ticket.getTicketVerkauftAnzahl() * ticket.getTicketPreis()) + "\n";
ticketGesamtEinnahmen += ticket.getTicketVerkauftAnzahl() * ticket.getTicketPreis();
}
outputString += "Gesamteinnahmen: " + ticketGesamtEinnahmen;
outputString += "\nGewinn: " + (ticketGesamtEinnahmen - kuenstler.getKuenstlerGage());
System.out.println(outputString);
}
}
}
| true | true | public void outputEvent()
{
int ticketGesamtEinnahmen = 0;
if(kuenstler == null || ticket == null)
{
System.out.println("Es wurden noch nicht alle benoetigten Angaben eingetragen");
}
else
{
String outputString = "Kuenstler: " + kuenstler.getKuenstlerName() + ", Gage CHF " + kuenstler.getKuenstlerGage() + "\n";
for(Ticket ticket: alleTickets)
{
outputString += ticket.getTicketKategorieName() + ": " +
ticket.getTicketVerkauftAnzahl() + " von " + ticket.getTicketAnzahl() + " verkauft" +
", Einnahmen: CHF " + (ticket.getTicketVerkauftAnzahl() * ticket.getTicketAnzahl()) + "\n";
ticketGesamtEinnahmen += ticket.getTicketVerkauftAnzahl() * ticket.getTicketPreis();
}
outputString += "Gesamteinnahmen: " + ticketGesamtEinnahmen;
outputString += "\nGewinn: " + (ticketGesamtEinnahmen - kuenstler.getKuenstlerGage());
System.out.println(outputString);
}
}
| public void outputEvent()
{
int ticketGesamtEinnahmen = 0;
if(kuenstler == null || ticket == null)
{
System.out.println("Es wurden noch nicht alle benoetigten Angaben eingetragen");
}
else
{
String outputString = "Kuenstler: " + kuenstler.getKuenstlerName() + ", Gage CHF " + kuenstler.getKuenstlerGage() + "\n";
for(Ticket ticket: alleTickets)
{
outputString += ticket.getTicketKategorieName() + ": " +
ticket.getTicketVerkauftAnzahl() + " von " + ticket.getTicketAnzahl() + " verkauft" +
", Einnahmen: CHF " + (ticket.getTicketVerkauftAnzahl() * ticket.getTicketPreis()) + "\n";
ticketGesamtEinnahmen += ticket.getTicketVerkauftAnzahl() * ticket.getTicketPreis();
}
outputString += "Gesamteinnahmen: " + ticketGesamtEinnahmen;
outputString += "\nGewinn: " + (ticketGesamtEinnahmen - kuenstler.getKuenstlerGage());
System.out.println(outputString);
}
}
|
diff --git a/SoarSuite/Tools/SoarJavaDebugger/src/modules/RHSBarChartView.java b/SoarSuite/Tools/SoarJavaDebugger/src/modules/RHSBarChartView.java
index 774fbd618..460a8e642 100644
--- a/SoarSuite/Tools/SoarJavaDebugger/src/modules/RHSBarChartView.java
+++ b/SoarSuite/Tools/SoarJavaDebugger/src/modules/RHSBarChartView.java
@@ -1,626 +1,626 @@
package modules;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import general.JavaElementXML;
import helpers.FormDataHelper;
import manager.Pane;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Text;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.experimental.chart.swt.ChartComposite;
import debugger.MainFrame;
import dialogs.PropertiesDialog;
import doc.Document;
import sml.Agent;
import sml.Kernel;
import sml.smlAgentEventId;
public class RHSBarChartView extends AbstractUpdateView implements Kernel.AgentEventInterface, Kernel.RhsFunctionInterface {
public RHSBarChartView()
{
}
protected String chartTitle = new String();
@Override
public void init(MainFrame frame, Document doc, Pane parentPane) {
if (chartTitle.length() <= 0) {
chartTitle = getModuleBaseName();
}
super.init(frame, doc, parentPane);
}
@Override
public String getModuleBaseName() {
return "rhs_bar_chart_view";
}
// Assume this may be empty! (no function is registered)
protected String rhsFunName = new String();
int rhsCallback = -1;
protected boolean debugMessages = true;
@Override
public void showProperties() {
PropertiesDialog.Property properties[] = new PropertiesDialog.Property[4] ;
properties[0] = new PropertiesDialog.IntProperty("Update automatically every n'th decision (0 => none)", m_UpdateEveryNthDecision) ;
properties[1] = new PropertiesDialog.StringProperty("Name of RHS function to use to update this window", rhsFunName) ;
properties[2] = new PropertiesDialog.StringProperty("Chart title", chartTitle) ;
properties[3] = new PropertiesDialog.BooleanProperty("Debug messages", debugMessages) ;
boolean ok = PropertiesDialog.showDialog(m_Frame, "Properties", properties) ;
if (ok) {
m_UpdateEveryNthDecision = ((PropertiesDialog.IntProperty)properties[0]).getValue() ;
chartTitle = ((PropertiesDialog.StringProperty)properties[2]).getValue() ;
chart.setTitle(chartTitle);
- properties[3] = new PropertiesDialog.BooleanProperty("Debug messages", debugMessages) ;
+ debugMessages = ((PropertiesDialog.BooleanProperty)properties[3]).getValue() ;
// TODO: abstractify some of this code, it is repeated in many of the new RHS widgets
if (this.getAgentFocus() != null)
{
// Make sure we're getting the events to match the new settings
this.unregisterForAgentEvents(this.getAgentFocus()) ;
this.registerForAgentEvents(this.getAgentFocus()) ;
}
String tempRHSFunName = ((PropertiesDialog.StringProperty)properties[1]).getValue() ;
tempRHSFunName = tempRHSFunName.trim();
// Make sure new one is different than old one and not zero length string
if (tempRHSFunName.length() <= 0 || tempRHSFunName.equals(rhsFunName)) {
return;
}
// BUGBUG: There can potentially other RHS function widgets with clashing RHS functions.
// This situation is managed in RHSFunTextView but the scope is limited to that tree of widgets.
// There needs to be some kind of RHS function management for all widgets using them.
Agent agent = m_Frame.getAgentFocus() ;
if (agent == null) {
return;
}
// Try and register this, message and return if failure
Kernel kernel = agent.GetKernel();
int tempRHSCallback = kernel.AddRhsFunction(tempRHSFunName, this, null);
// TODO: Verify that error check here is correct, and fix registerForAgentEvents
// BUGBUG: remove true
if (tempRHSCallback <= 0) {
// failed to register callback
MessageBox errorDialog = new MessageBox(this.m_Frame.getShell(), SWT.ICON_ERROR | SWT.OK);
errorDialog.setMessage("Failed to change RHS function name \"" + tempRHSFunName + "\".");
errorDialog.open();
return;
}
// unregister old rhs fun
boolean registerOK = true ;
if (rhsCallback != -1)
registerOK = kernel.RemoveRhsFunction(rhsCallback);
rhsCallback = -1;
// save new one
rhsFunName = tempRHSFunName;
rhsCallback = tempRHSCallback;
if (!registerOK)
throw new IllegalStateException("Problem unregistering for events") ;
} // Careful, returns in the previous block!
}
class OrderedString implements Comparable<OrderedString> {
OrderedString(String string) {
this.string = new String(string);
this.value = new Integer(0);
}
OrderedString(String string, int value) {
this.string = new String(string);
this.value = new Integer(value);
}
OrderedString(OrderedString ov) {
this.string = new String(ov.string);
this.value = new Integer(ov.value);
}
public String string;
public Integer value;
// This is backwards because descending iterator is a java 1.6 feature
public int compareTo(OrderedString other) {
return this.value - other.value;
}
public boolean equals(Object obj) {
OrderedString orderedString;
try {
orderedString = (OrderedString)obj;
} catch (ClassCastException e) {
return super.equals(obj);
}
return this.string.equals(orderedString.string);
}
public int hashCode() {
return this.string.hashCode();
}
}
// category -> series -> value
HashMap<String, HashMap<String, Double> > categoryToSeriesMap = new HashMap<String, HashMap<String, Double> >();
TreeSet<OrderedString> categoryOrderSet = new TreeSet<OrderedString>();
TreeSet<OrderedString> seriesOrderSet = new TreeSet<OrderedString>();
public String rhsFunctionHandler(int eventID, Object data,
String agentName, String functionName, String argument) {
// Syntax:
// |--- commandLine --------------------|
// exec <rhs_function_name> <command> [<args>]
// exec <rhs_function_name> addvalue <category> <category-order> <series> <series-order> <value>
String[] commandLine = argument.split("\\s+");
if (commandLine.length < 1) {
return m_Name + ":" + functionName + ": no command";
}
if (commandLine[0].equals("--clear")) {
this.onInitSoar();
return debugMessages ? m_Name + ":" + functionName + ": cleared" : null;
} else if (commandLine[0].equals("addvalue")) {
if (commandLine.length != 6) {
return m_Name + ":" + functionName + ": addvalue requires <category> <category-order> <series> <series-order> <value>";
}
int catOrder = 0;
try {
catOrder = Integer.parseInt(commandLine[2]);
} catch (NumberFormatException e) {
return m_Name + ":" + functionName + ": addvalue: parsing failed for <category-order> argument";
}
int serOrder = 0;
try {
serOrder = Integer.parseInt(commandLine[4]);
} catch (NumberFormatException e) {
return m_Name + ":" + functionName + ": addvalue: parsing failed for <series-order> argument";
}
double value = 0;
try {
value = Double.parseDouble(commandLine[5]);
} catch (NumberFormatException e) {
return m_Name + ":" + functionName + ": addvalue: parsing failed for <value> argument";
}
updateData(commandLine[1], catOrder, commandLine[3], serOrder, value);
return debugMessages ? m_Name + ":" + functionName + ": Graph updated." : null;
}
return m_Name + ":" + functionName + ": unknown command: " + commandLine[0];
}
private void updateData(String category, int categoryOrder, String series, int seriesOrder, double value) {
if (!categoryToSeriesMap.containsKey(category)) {
HashMap<String, Double> seriesToValueMap = new HashMap<String, Double>();
categoryToSeriesMap.put(category, seriesToValueMap);
categoryOrderSet.add(new OrderedString(category, categoryOrder));
}
HashMap<String, Double> seriesToValueMap = categoryToSeriesMap.get(category);
seriesToValueMap.put(series, value);
seriesOrderSet.add(new OrderedString(series, seriesOrder));
}
@Override
protected void registerForAgentEvents(Agent agent)
{
super.registerForAgentEvents(agent);
if (rhsFunName.length() <= 0) {
return;
}
if (agent == null)
return ;
Kernel kernel = agent.GetKernel();
rhsCallback = kernel.AddRhsFunction(rhsFunName, this, null);
if (rhsCallback <= 0) {
// failed to register callback
rhsCallback = -1;
rhsFunName = "";
throw new IllegalStateException("Problem registering for events") ;
}
}
@Override
protected void unregisterForAgentEvents(Agent agent)
{
super.unregisterForAgentEvents(agent);
if (agent == null)
return ;
boolean ok = true ;
Kernel kernel = agent.GetKernel();
if (rhsCallback != -1)
ok = kernel.RemoveRhsFunction(rhsCallback);
rhsFunName = "";
rhsCallback = -1;
if (!ok)
throw new IllegalStateException("Problem unregistering for events") ;
}
@Override
public boolean find(String text, boolean searchDown, boolean matchCase,
boolean wrap, boolean searchHiddenText) {
return false;
}
@Override
public void copy() {
}
@Override
public void displayText(String text) {
}
int rhsFunInitSoarHandler = -1;
@Override
protected void registerForViewAgentEvents(Agent agent) {
rhsFunInitSoarHandler = agent.GetKernel().RegisterForAgentEvent(smlAgentEventId.smlEVENT_AFTER_AGENT_REINITIALIZED, this, this) ;
}
@Override
protected boolean unregisterForViewAgentEvents(Agent agent) {
if (agent == null)
return true;
boolean ok = true;
if (rhsFunInitSoarHandler != -1)
ok = agent.GetKernel().UnregisterForAgentEvent(rhsFunInitSoarHandler);
rhsFunInitSoarHandler = -1;
return ok;
}
@Override
protected void clearViewAgentEvents() {
rhsFunInitSoarHandler = -1;
}
ChartComposite frame;
JFreeChart chart;
DefaultCategoryDataset dataset;
Composite rhsBarChartContainer;
Label rightClickLabel;
@Override
protected void createDisplayControl(Composite parent) {
rhsBarChartContainer = new Composite(parent, SWT.NULL);
FormData attachFull = FormDataHelper.anchorFull(0) ;
rhsBarChartContainer.setLayoutData(attachFull);
{
GridLayout gl = new GridLayout();
gl.numColumns = 1;
gl.verticalSpacing = 0;
gl.marginHeight = 0;
gl.marginWidth = 0;
rhsBarChartContainer.setLayout(gl);
}
dataset = new DefaultCategoryDataset();
// create the chart...
chart = ChartFactory.createBarChart(
chartTitle, // chart title
"Category", // domain axis label
"Value", // range axis label
dataset, // data
PlotOrientation.HORIZONTAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
frame = new ChartComposite(rhsBarChartContainer, SWT.NONE, chart, true);
{
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
frame.setLayoutData(gd);
}
frame.pack();
rightClickLabel = new Label(rhsBarChartContainer, SWT.NONE);
rightClickLabel.setText("Right click here to access chart properties and remove window...");
{
GridData gd = new GridData(SWT.FILL, SWT.NONE, true, false);
rightClickLabel.setLayoutData(gd);
}
createContextMenu(rightClickLabel) ;
}
@Override
public org.eclipse.swt.graphics.Color getBackgroundColor() {
return getMainFrame().getDisplay().getSystemColor(SWT.COLOR_CYAN) ;
}
@Override
protected Control getDisplayControl() {
return rhsBarChartContainer;
}
@Override
protected void restoreContent(JavaElementXML element) {
// TODO Auto-generated method stub
}
@Override
protected void storeContent(JavaElementXML element) {
// TODO Auto-generated method stub
}
private void updateChart() {
// TODO: explore processing only changes instead of the entire data each update
// for each category
Iterator<OrderedString> catIter = this.categoryOrderSet.iterator();
while (catIter.hasNext()) {
String category = catIter.next().string;
// for each series
HashMap<String, Double> seriesToValueMap = categoryToSeriesMap.get(category);
Iterator<OrderedString> serIter = this.seriesOrderSet.iterator();
while (serIter.hasNext()) {
String series = serIter.next().string;
// add/set value (add seems to work)
dataset.addValue(seriesToValueMap.get(series), series, category);
}
}
}
@Override
protected void updateNow() {
// If Soar is running in the UI thread we can make
// the update directly.
if (!Document.kDocInOwnThread)
{
updateChart();
return ;
}
// Have to make update in the UI thread.
// Callback comes in the document thread.
Display.getDefault().asyncExec(new Runnable() {
public void run() {
updateChart();
}
}) ;
}
@Override
public void clearDisplay() {
categoryToSeriesMap.clear();
categoryOrderSet.clear();
seriesOrderSet.clear();
// If Soar is running in the UI thread we can make
// the update directly.
if (!Document.kDocInOwnThread)
{
dataset.clear();
return ;
}
// Have to make update in the UI thread.
// Callback comes in the document thread.
Display.getDefault().asyncExec(new Runnable() {
public void run() {
dataset.clear();
}
}) ;
}
public void onInitSoar() {
clearDisplay();
}
@Override
public void agentEventHandler(int eventID, Object data, String agentName)
{
// Note: We need to check the agent names match because although this is called an agentEventHandler it's
// an event registered with the kernel -- so it's sent to all listeners, not just the agent that is reinitializing.
if (eventID == smlAgentEventId.smlEVENT_AFTER_AGENT_REINITIALIZED.swigValue()) {
onInitSoar();
updateNow() ;
}
}
/************************************************************************
*
* Converts this object into an XML representation.
*
*************************************************************************/
@Override
public JavaElementXML convertToXML(String title, boolean storeContent) {
JavaElementXML element = new JavaElementXML(title) ;
// It's useful to record the class name to uniquely identify the type
// of object being stored at this point in the XML tree.
Class cl = this.getClass() ;
element.addAttribute(JavaElementXML.kClassAttribute, cl.getName()) ;
if (m_Name == null)
throw new IllegalStateException("We've created a view with no name -- very bad") ;
// Store this object's properties.
element.addAttribute("Name", m_Name) ;
element.addAttribute("UpdateOnStop", Boolean.toString(m_UpdateOnStop)) ;
element.addAttribute("UpdateEveryNthDecision", Integer.toString(m_UpdateEveryNthDecision)) ;
element.addAttribute("RHSFunctionName", rhsFunName) ;
element.addAttribute("ChartTitle", chartTitle) ;
element.addAttribute("DebugMessages", Boolean.toString(debugMessages)) ;
if (storeContent)
storeContent(element) ;
element.addChildElement(this.m_Logger.convertToXML("Logger")) ;
return element ;
}
/************************************************************************
*
* Rebuild the object from an XML representation.
*
* @param frame The top level window that owns this window
* @param doc The document we're rebuilding
* @param parent The pane window that owns this view
* @param element The XML representation of this command
*
*************************************************************************/
@Override
public void loadFromXML(MainFrame frame, Document doc, Pane parent,
JavaElementXML element) throws Exception {
setValues(frame, doc, parent) ;
m_Name = element.getAttribute("Name") ;
m_UpdateOnStop = element.getAttributeBooleanDefault("UpdateOnStop", true) ;
m_UpdateEveryNthDecision = element.getAttributeIntDefault("UpdateEveryNthDecision", 0) ;
rhsFunName = element.getAttribute("RHSFunctionName");
chartTitle = element.getAttribute("ChartTitle");
debugMessages = element.getAttributeBooleanDefault("DebugMessages", true);
if (rhsFunName == null) {
rhsFunName = new String();
}
if (chartTitle == null) {
chartTitle = new String();
}
JavaElementXML log = element.findChildByName("Logger") ;
if (log != null)
this.m_Logger.loadFromXML(doc, log) ;
// Register that this module's name is in use
frame.registerViewName(m_Name, this) ;
// Actually create the window
init(frame, doc, parent) ;
// Restore the text we saved (if we chose to save it)
restoreContent(element) ;
}
}
/*
Test code:
sp {propose*init
(state <s> ^superstate nil
-^name)
-->
(<s> ^operator <o> +)
(<o> ^name init)
}
sp {apply*init
(state <s> ^operator.name init)
-->
(<s> ^name test)
}
sp {propose*update
(state <s> ^name test
-^toggle on)
-->
(<s> ^operator <o> +)
(<o> ^name update)
}
sp {apply*update
(state <s> ^operator.name update)
-->
(<s> ^toggle on)
(write (crlf) (exec graph |addvalue category1 1 series1 1 0.5|))
(write (crlf) (exec graph |addvalue category2 2 series1 1 0.7|))
(write (crlf) (exec graph |addvalue category3 3 series1 1 0.1|))
(write (crlf) (exec graph |addvalue category1 1 series2 2 0.2|))
(write (crlf) (exec graph |addvalue category2 2 series2 2 0.4|))
(write (crlf) (exec graph |addvalue category3 3 series2 2 0.8|))
}
sp {propose*update2
(state <s> ^name test
^toggle on)
-->
(<s> ^operator <o> +)
(<o> ^name update2)
}
sp {apply*update2
(state <s> ^operator.name update2)
-->
(<s> ^toggle on -)
(write (crlf) (exec graph |addvalue category1 1 series1 1 0.1|))
(write (crlf) (exec graph |addvalue category2 2 series1 1 0.2|))
(write (crlf) (exec graph |addvalue category3 3 series1 1 0.3|))
(write (crlf) (exec graph |addvalue category1 1 series2 2 0.6|))
(write (crlf) (exec graph |addvalue category2 2 series2 2 0.2|))
(write (crlf) (exec graph |addvalue category3 3 series2 2 0.5|))
}
*/
| true | true | public void showProperties() {
PropertiesDialog.Property properties[] = new PropertiesDialog.Property[4] ;
properties[0] = new PropertiesDialog.IntProperty("Update automatically every n'th decision (0 => none)", m_UpdateEveryNthDecision) ;
properties[1] = new PropertiesDialog.StringProperty("Name of RHS function to use to update this window", rhsFunName) ;
properties[2] = new PropertiesDialog.StringProperty("Chart title", chartTitle) ;
properties[3] = new PropertiesDialog.BooleanProperty("Debug messages", debugMessages) ;
boolean ok = PropertiesDialog.showDialog(m_Frame, "Properties", properties) ;
if (ok) {
m_UpdateEveryNthDecision = ((PropertiesDialog.IntProperty)properties[0]).getValue() ;
chartTitle = ((PropertiesDialog.StringProperty)properties[2]).getValue() ;
chart.setTitle(chartTitle);
properties[3] = new PropertiesDialog.BooleanProperty("Debug messages", debugMessages) ;
// TODO: abstractify some of this code, it is repeated in many of the new RHS widgets
if (this.getAgentFocus() != null)
{
// Make sure we're getting the events to match the new settings
this.unregisterForAgentEvents(this.getAgentFocus()) ;
this.registerForAgentEvents(this.getAgentFocus()) ;
}
String tempRHSFunName = ((PropertiesDialog.StringProperty)properties[1]).getValue() ;
tempRHSFunName = tempRHSFunName.trim();
// Make sure new one is different than old one and not zero length string
if (tempRHSFunName.length() <= 0 || tempRHSFunName.equals(rhsFunName)) {
return;
}
// BUGBUG: There can potentially other RHS function widgets with clashing RHS functions.
// This situation is managed in RHSFunTextView but the scope is limited to that tree of widgets.
// There needs to be some kind of RHS function management for all widgets using them.
Agent agent = m_Frame.getAgentFocus() ;
if (agent == null) {
return;
}
// Try and register this, message and return if failure
Kernel kernel = agent.GetKernel();
int tempRHSCallback = kernel.AddRhsFunction(tempRHSFunName, this, null);
// TODO: Verify that error check here is correct, and fix registerForAgentEvents
// BUGBUG: remove true
if (tempRHSCallback <= 0) {
// failed to register callback
MessageBox errorDialog = new MessageBox(this.m_Frame.getShell(), SWT.ICON_ERROR | SWT.OK);
errorDialog.setMessage("Failed to change RHS function name \"" + tempRHSFunName + "\".");
errorDialog.open();
return;
}
// unregister old rhs fun
boolean registerOK = true ;
if (rhsCallback != -1)
registerOK = kernel.RemoveRhsFunction(rhsCallback);
rhsCallback = -1;
// save new one
rhsFunName = tempRHSFunName;
rhsCallback = tempRHSCallback;
if (!registerOK)
throw new IllegalStateException("Problem unregistering for events") ;
} // Careful, returns in the previous block!
}
| public void showProperties() {
PropertiesDialog.Property properties[] = new PropertiesDialog.Property[4] ;
properties[0] = new PropertiesDialog.IntProperty("Update automatically every n'th decision (0 => none)", m_UpdateEveryNthDecision) ;
properties[1] = new PropertiesDialog.StringProperty("Name of RHS function to use to update this window", rhsFunName) ;
properties[2] = new PropertiesDialog.StringProperty("Chart title", chartTitle) ;
properties[3] = new PropertiesDialog.BooleanProperty("Debug messages", debugMessages) ;
boolean ok = PropertiesDialog.showDialog(m_Frame, "Properties", properties) ;
if (ok) {
m_UpdateEveryNthDecision = ((PropertiesDialog.IntProperty)properties[0]).getValue() ;
chartTitle = ((PropertiesDialog.StringProperty)properties[2]).getValue() ;
chart.setTitle(chartTitle);
debugMessages = ((PropertiesDialog.BooleanProperty)properties[3]).getValue() ;
// TODO: abstractify some of this code, it is repeated in many of the new RHS widgets
if (this.getAgentFocus() != null)
{
// Make sure we're getting the events to match the new settings
this.unregisterForAgentEvents(this.getAgentFocus()) ;
this.registerForAgentEvents(this.getAgentFocus()) ;
}
String tempRHSFunName = ((PropertiesDialog.StringProperty)properties[1]).getValue() ;
tempRHSFunName = tempRHSFunName.trim();
// Make sure new one is different than old one and not zero length string
if (tempRHSFunName.length() <= 0 || tempRHSFunName.equals(rhsFunName)) {
return;
}
// BUGBUG: There can potentially other RHS function widgets with clashing RHS functions.
// This situation is managed in RHSFunTextView but the scope is limited to that tree of widgets.
// There needs to be some kind of RHS function management for all widgets using them.
Agent agent = m_Frame.getAgentFocus() ;
if (agent == null) {
return;
}
// Try and register this, message and return if failure
Kernel kernel = agent.GetKernel();
int tempRHSCallback = kernel.AddRhsFunction(tempRHSFunName, this, null);
// TODO: Verify that error check here is correct, and fix registerForAgentEvents
// BUGBUG: remove true
if (tempRHSCallback <= 0) {
// failed to register callback
MessageBox errorDialog = new MessageBox(this.m_Frame.getShell(), SWT.ICON_ERROR | SWT.OK);
errorDialog.setMessage("Failed to change RHS function name \"" + tempRHSFunName + "\".");
errorDialog.open();
return;
}
// unregister old rhs fun
boolean registerOK = true ;
if (rhsCallback != -1)
registerOK = kernel.RemoveRhsFunction(rhsCallback);
rhsCallback = -1;
// save new one
rhsFunName = tempRHSFunName;
rhsCallback = tempRHSCallback;
if (!registerOK)
throw new IllegalStateException("Problem unregistering for events") ;
} // Careful, returns in the previous block!
}
|
diff --git a/src/uk/ac/cam/db538/dexter/dex/DexClass.java b/src/uk/ac/cam/db538/dexter/dex/DexClass.java
index d9f0e6ce..89d6d847 100644
--- a/src/uk/ac/cam/db538/dexter/dex/DexClass.java
+++ b/src/uk/ac/cam/db538/dexter/dex/DexClass.java
@@ -1,235 +1,234 @@
package uk.ac.cam.db538.dexter.dex;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import lombok.Getter;
import lombok.val;
import org.jf.dexlib.AnnotationDirectoryItem;
import org.jf.dexlib.AnnotationDirectoryItem.FieldAnnotation;
import org.jf.dexlib.AnnotationDirectoryItem.MethodAnnotation;
import org.jf.dexlib.AnnotationDirectoryItem.ParameterAnnotation;
import org.jf.dexlib.AnnotationItem;
import org.jf.dexlib.AnnotationSetItem;
import org.jf.dexlib.ClassDataItem;
import org.jf.dexlib.ClassDataItem.EncodedField;
import org.jf.dexlib.ClassDataItem.EncodedMethod;
import org.jf.dexlib.ClassDefItem;
import org.jf.dexlib.ClassDefItem.StaticFieldInitializer;
import org.jf.dexlib.DexFile;
import org.jf.dexlib.EncodedValue.EncodedValue;
import uk.ac.cam.db538.dexter.dex.field.DexInstanceField;
import uk.ac.cam.db538.dexter.dex.field.DexStaticField;
import uk.ac.cam.db538.dexter.dex.method.DexMethod;
import uk.ac.cam.db538.dexter.dex.type.DexClassType;
import uk.ac.cam.db538.dexter.hierarchy.BaseClassDefinition;
import uk.ac.cam.db538.dexter.hierarchy.ClassDefinition;
public class DexClass {
@Getter private final Dex parentFile;
@Getter private final BaseClassDefinition classDef;
private final List<DexMethod> _methods;
@Getter private final List<DexMethod> methods;
private final List<DexInstanceField> _instanceFields;
@Getter private final List<DexInstanceField> instanceFields;
private final List<DexStaticField> _staticFields;
@Getter private final List<DexStaticField> staticFields;
private final List<DexAnnotation> _annotations;
@Getter private final List<DexAnnotation> annotations;
@Getter private final String sourceFile;
public DexClass(Dex parent, BaseClassDefinition classDef, String sourceFile) {
this.parentFile = parent;
this.classDef = classDef;
this._methods = new ArrayList<DexMethod>();
this.methods = Collections.unmodifiableList(this._methods);
this._instanceFields = new ArrayList<DexInstanceField>();
this.instanceFields = Collections.unmodifiableList(this._instanceFields);
this._staticFields = new ArrayList<DexStaticField>();
this.staticFields = Collections.unmodifiableList(this._staticFields);
this._annotations = new ArrayList<DexAnnotation>();
this.annotations = Collections.unmodifiableList(this._annotations);
this.sourceFile = sourceFile;
}
public DexClass(Dex parent, ClassDefItem clsItem) {
this(parent,
init_FindClassDefinition(parent, clsItem),
DexUtils.parseString(clsItem.getSourceFile()));
val annotationDirectory = clsItem.getAnnotations();
this._annotations.addAll(init_ParseAnnotations(parent, annotationDirectory));
val clsData = clsItem.getClassData();
if (clsData != null) {
// static fields
for (val sfieldItem : clsData.getStaticFields())
this._staticFields.add(new DexStaticField(this, clsItem, sfieldItem, annotationDirectory));
// instance fields
for (val ifieldItem : clsData.getInstanceFields())
this._instanceFields.add(new DexInstanceField(this, ifieldItem, annotationDirectory));
// methods
for (val methodItem : clsData.getDirectMethods())
this._methods.add(new DexMethod(this, methodItem, annotationDirectory));
}
}
private static BaseClassDefinition init_FindClassDefinition(Dex parent, ClassDefItem clsItem) {
val hierarchy = parent.getHierarchy();
val clsType = DexClassType.parse(clsItem.getClassType().getTypeDescriptor(),
hierarchy.getTypeCache());
return hierarchy.getBaseClassDefinition(clsType);
}
private static List<DexAnnotation> init_ParseAnnotations(Dex parent, AnnotationDirectoryItem annoDir) {
if (annoDir == null)
return Collections.emptyList();
else
return DexAnnotation.parseAll(annoDir.getClassAnnotations(), parent.getTypeCache());
}
public List<DexClassType> getInterfaceTypes() {
if (classDef instanceof ClassDefinition) {
val ifaceDefs = ((ClassDefinition) classDef).getInterfaces();
if (ifaceDefs.isEmpty())
return Collections.emptyList();
val list = new ArrayList<DexClassType>(ifaceDefs.size());
for (val ifaceDef : ifaceDefs)
list.add(ifaceDef.getType());
return list;
} else
return Collections.emptyList();
}
public void addAnnotation(DexAnnotation anno) {
this._annotations.add(anno);
}
public void instrument(DexInstrumentationCache cache) {
// System.out.println("Instrumenting class " + this.classDef.getType().getPrettyName());
//
// for (val method : this._methods)
// method.instrument(cache);
//
// this.addAnnotation(new DexAnnotation(
// parentFile.getAuxiliaryDex().getAnno_InternalClass().getType(),
// AnnotationVisibility.RUNTIME));
}
public void writeToFile(DexFile outFile, DexAssemblingCache cache) {
System.out.println("Assembling class " + this.classDef.getType().getPrettyName());
val classAnnotations = this.getAnnotations();
val asmClassType = cache.getType(classDef.getType());
val asmSuperType = cache.getType(classDef.getSuperclass().getType());
val asmAccessFlags = DexUtils.assembleAccessFlags(classDef.getAccessFlags());
val asmInterfaces = cache.getTypeList(getInterfaceTypes());
val asmSourceFile = cache.getStringConstant(sourceFile);
val asmClassAnnotations = new ArrayList<AnnotationItem>(classAnnotations.size());
for (val anno : classAnnotations)
asmClassAnnotations.add(anno.writeToFile(outFile, cache));
val asmMethodAnnotations = new ArrayList<MethodAnnotation>(_methods.size());
for (val method : _methods) {
val methodAnno = method.assembleAnnotations(outFile, cache);
if (methodAnno != null)
asmMethodAnnotations.add(methodAnno);
}
val asmFieldAnnotations = new ArrayList<FieldAnnotation>(_instanceFields.size() + _staticFields.size());
for (val field : _instanceFields) {
val fieldAnno = field.assembleAnnotations(outFile, cache);
if (fieldAnno != null)
asmFieldAnnotations.add(fieldAnno);
}
for (val field : _staticFields) {
val fieldAnno = field.assembleAnnotations(outFile, cache);
if (fieldAnno != null)
asmFieldAnnotations.add(fieldAnno);
}
val asmParamAnnotations = new ArrayList<ParameterAnnotation>(_methods.size());
for (val method : _methods) {
val paramAnno = method.assembleParameterAnnotations(outFile, cache);
if (paramAnno != null)
asmParamAnnotations.add(paramAnno);
}
AnnotationSetItem asmClassAnnotationSet = null;
if (asmClassAnnotations.size() > 0)
asmClassAnnotationSet = AnnotationSetItem.internAnnotationSetItem(
outFile,
asmClassAnnotations);
AnnotationDirectoryItem asmAnnotations = null;
if (asmClassAnnotationSet!= null || asmFieldAnnotations.size() != 0 ||
asmMethodAnnotations.size() != 0 || asmParamAnnotations.size() != 0) {
asmAnnotations = AnnotationDirectoryItem.internAnnotationDirectoryItem(
outFile,
asmClassAnnotationSet,
asmFieldAnnotations,
asmMethodAnnotations,
asmParamAnnotations);
}
val asmStaticFields = new LinkedList<EncodedField>();
val asmInstanceFields = new LinkedList<EncodedField>();
val asmDirectMethods = new LinkedList<EncodedMethod>();
val asmVirtualMethods = new LinkedList<EncodedMethod>();
val staticFieldInitializers = new LinkedList<StaticFieldInitializer>();
for (val field : _staticFields) {
EncodedField outField = field.writeToFile(outFile, cache);
asmStaticFields.add(outField);
EncodedValue initialValue = field.getInitialValue();
- if (initialValue != null) {
+ if (initialValue != null)
initialValue = DexUtils.cloneEncodedValue(initialValue, cache);
- staticFieldInitializers.add(new StaticFieldInitializer(initialValue, outField));
- }
+ staticFieldInitializers.add(new StaticFieldInitializer(initialValue, outField));
}
for (val field : _instanceFields)
asmInstanceFields.add(field.writeToFile(outFile, cache));
for (val method : _methods) {
if (method.getMethodDef().isVirtual())
asmVirtualMethods.add(method.writeToFile(outFile, cache));
else
asmDirectMethods.add(method.writeToFile(outFile, cache));
}
val classData = ClassDataItem.internClassDataItem(
outFile,
asmStaticFields,
asmInstanceFields,
asmDirectMethods,
asmVirtualMethods);
ClassDefItem.internClassDefItem(
outFile, asmClassType, asmAccessFlags, asmSuperType,
asmInterfaces, asmSourceFile, asmAnnotations,
classData, staticFieldInitializers);
}
}
| false | true | public void writeToFile(DexFile outFile, DexAssemblingCache cache) {
System.out.println("Assembling class " + this.classDef.getType().getPrettyName());
val classAnnotations = this.getAnnotations();
val asmClassType = cache.getType(classDef.getType());
val asmSuperType = cache.getType(classDef.getSuperclass().getType());
val asmAccessFlags = DexUtils.assembleAccessFlags(classDef.getAccessFlags());
val asmInterfaces = cache.getTypeList(getInterfaceTypes());
val asmSourceFile = cache.getStringConstant(sourceFile);
val asmClassAnnotations = new ArrayList<AnnotationItem>(classAnnotations.size());
for (val anno : classAnnotations)
asmClassAnnotations.add(anno.writeToFile(outFile, cache));
val asmMethodAnnotations = new ArrayList<MethodAnnotation>(_methods.size());
for (val method : _methods) {
val methodAnno = method.assembleAnnotations(outFile, cache);
if (methodAnno != null)
asmMethodAnnotations.add(methodAnno);
}
val asmFieldAnnotations = new ArrayList<FieldAnnotation>(_instanceFields.size() + _staticFields.size());
for (val field : _instanceFields) {
val fieldAnno = field.assembleAnnotations(outFile, cache);
if (fieldAnno != null)
asmFieldAnnotations.add(fieldAnno);
}
for (val field : _staticFields) {
val fieldAnno = field.assembleAnnotations(outFile, cache);
if (fieldAnno != null)
asmFieldAnnotations.add(fieldAnno);
}
val asmParamAnnotations = new ArrayList<ParameterAnnotation>(_methods.size());
for (val method : _methods) {
val paramAnno = method.assembleParameterAnnotations(outFile, cache);
if (paramAnno != null)
asmParamAnnotations.add(paramAnno);
}
AnnotationSetItem asmClassAnnotationSet = null;
if (asmClassAnnotations.size() > 0)
asmClassAnnotationSet = AnnotationSetItem.internAnnotationSetItem(
outFile,
asmClassAnnotations);
AnnotationDirectoryItem asmAnnotations = null;
if (asmClassAnnotationSet!= null || asmFieldAnnotations.size() != 0 ||
asmMethodAnnotations.size() != 0 || asmParamAnnotations.size() != 0) {
asmAnnotations = AnnotationDirectoryItem.internAnnotationDirectoryItem(
outFile,
asmClassAnnotationSet,
asmFieldAnnotations,
asmMethodAnnotations,
asmParamAnnotations);
}
val asmStaticFields = new LinkedList<EncodedField>();
val asmInstanceFields = new LinkedList<EncodedField>();
val asmDirectMethods = new LinkedList<EncodedMethod>();
val asmVirtualMethods = new LinkedList<EncodedMethod>();
val staticFieldInitializers = new LinkedList<StaticFieldInitializer>();
for (val field : _staticFields) {
EncodedField outField = field.writeToFile(outFile, cache);
asmStaticFields.add(outField);
EncodedValue initialValue = field.getInitialValue();
if (initialValue != null) {
initialValue = DexUtils.cloneEncodedValue(initialValue, cache);
staticFieldInitializers.add(new StaticFieldInitializer(initialValue, outField));
}
}
for (val field : _instanceFields)
asmInstanceFields.add(field.writeToFile(outFile, cache));
for (val method : _methods) {
if (method.getMethodDef().isVirtual())
asmVirtualMethods.add(method.writeToFile(outFile, cache));
else
asmDirectMethods.add(method.writeToFile(outFile, cache));
}
val classData = ClassDataItem.internClassDataItem(
outFile,
asmStaticFields,
asmInstanceFields,
asmDirectMethods,
asmVirtualMethods);
ClassDefItem.internClassDefItem(
outFile, asmClassType, asmAccessFlags, asmSuperType,
asmInterfaces, asmSourceFile, asmAnnotations,
classData, staticFieldInitializers);
}
| public void writeToFile(DexFile outFile, DexAssemblingCache cache) {
System.out.println("Assembling class " + this.classDef.getType().getPrettyName());
val classAnnotations = this.getAnnotations();
val asmClassType = cache.getType(classDef.getType());
val asmSuperType = cache.getType(classDef.getSuperclass().getType());
val asmAccessFlags = DexUtils.assembleAccessFlags(classDef.getAccessFlags());
val asmInterfaces = cache.getTypeList(getInterfaceTypes());
val asmSourceFile = cache.getStringConstant(sourceFile);
val asmClassAnnotations = new ArrayList<AnnotationItem>(classAnnotations.size());
for (val anno : classAnnotations)
asmClassAnnotations.add(anno.writeToFile(outFile, cache));
val asmMethodAnnotations = new ArrayList<MethodAnnotation>(_methods.size());
for (val method : _methods) {
val methodAnno = method.assembleAnnotations(outFile, cache);
if (methodAnno != null)
asmMethodAnnotations.add(methodAnno);
}
val asmFieldAnnotations = new ArrayList<FieldAnnotation>(_instanceFields.size() + _staticFields.size());
for (val field : _instanceFields) {
val fieldAnno = field.assembleAnnotations(outFile, cache);
if (fieldAnno != null)
asmFieldAnnotations.add(fieldAnno);
}
for (val field : _staticFields) {
val fieldAnno = field.assembleAnnotations(outFile, cache);
if (fieldAnno != null)
asmFieldAnnotations.add(fieldAnno);
}
val asmParamAnnotations = new ArrayList<ParameterAnnotation>(_methods.size());
for (val method : _methods) {
val paramAnno = method.assembleParameterAnnotations(outFile, cache);
if (paramAnno != null)
asmParamAnnotations.add(paramAnno);
}
AnnotationSetItem asmClassAnnotationSet = null;
if (asmClassAnnotations.size() > 0)
asmClassAnnotationSet = AnnotationSetItem.internAnnotationSetItem(
outFile,
asmClassAnnotations);
AnnotationDirectoryItem asmAnnotations = null;
if (asmClassAnnotationSet!= null || asmFieldAnnotations.size() != 0 ||
asmMethodAnnotations.size() != 0 || asmParamAnnotations.size() != 0) {
asmAnnotations = AnnotationDirectoryItem.internAnnotationDirectoryItem(
outFile,
asmClassAnnotationSet,
asmFieldAnnotations,
asmMethodAnnotations,
asmParamAnnotations);
}
val asmStaticFields = new LinkedList<EncodedField>();
val asmInstanceFields = new LinkedList<EncodedField>();
val asmDirectMethods = new LinkedList<EncodedMethod>();
val asmVirtualMethods = new LinkedList<EncodedMethod>();
val staticFieldInitializers = new LinkedList<StaticFieldInitializer>();
for (val field : _staticFields) {
EncodedField outField = field.writeToFile(outFile, cache);
asmStaticFields.add(outField);
EncodedValue initialValue = field.getInitialValue();
if (initialValue != null)
initialValue = DexUtils.cloneEncodedValue(initialValue, cache);
staticFieldInitializers.add(new StaticFieldInitializer(initialValue, outField));
}
for (val field : _instanceFields)
asmInstanceFields.add(field.writeToFile(outFile, cache));
for (val method : _methods) {
if (method.getMethodDef().isVirtual())
asmVirtualMethods.add(method.writeToFile(outFile, cache));
else
asmDirectMethods.add(method.writeToFile(outFile, cache));
}
val classData = ClassDataItem.internClassDataItem(
outFile,
asmStaticFields,
asmInstanceFields,
asmDirectMethods,
asmVirtualMethods);
ClassDefItem.internClassDefItem(
outFile, asmClassType, asmAccessFlags, asmSuperType,
asmInterfaces, asmSourceFile, asmAnnotations,
classData, staticFieldInitializers);
}
|
diff --git a/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java b/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java
index 725a50b..24996b4 100644
--- a/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java
+++ b/src/org/eclipse/core/tests/internal/mapping/ChangeValidationTest.java
@@ -1,220 +1,221 @@
/*******************************************************************************
* Copyright (c) 2006 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.core.tests.internal.mapping;
import java.util.*;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.resources.*;
import org.eclipse.core.resources.mapping.*;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.tests.resources.ResourceTest;
/**
* Tests for change validation
*/
public class ChangeValidationTest extends ResourceTest {
private IResourceChangeDescriptionFactory factory;
private IProject project;
public static Test suite() {
return new TestSuite(ChangeValidationTest.class);
}
private void assertStatusEqual(IStatus status, String[] expectedMessages) {
List actualMessages = new ArrayList();
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
String message = getModelMessage(children[i]);
if (message != null)
actualMessages.add(message);
}
} else {
String message = getModelMessage(status);
if (message != null)
actualMessages.add(message);
}
if (expectedMessages.length < actualMessages.size()) {
for (Iterator iter = actualMessages.iterator(); iter.hasNext();) {
String actual = (String) iter.next();
boolean found = false;
for (int i = 0; i < expectedMessages.length; i++) {
String expected = expectedMessages[i];
- if (actual.equals(expected))
+ if (actual.equals(expected)) {
found = true;
- break;
+ break;
+ }
}
if (!found)
fail("Unexpected message returned: " + actual);
}
} else {
for (int i = 0; i < expectedMessages.length; i++) {
String string = expectedMessages[i];
if (!actualMessages.contains(string)) {
fail("Expect message missing: " + string);
}
}
}
}
private IResourceChangeDescriptionFactory createEmptyChangeDescription() {
return ResourceChangeValidator.getValidator().createDeltaFactory();
}
/*
* Only return the message of the status if it
* came from our test model provider
*/
private String getModelMessage(IStatus status) {
if (status instanceof ModelStatus) {
ModelStatus ms = (ModelStatus) status;
String id = ms.getModelProviderId();
if (id.equals(TestModelProvider.ID))
return status.getMessage();
}
return null;
}
protected void setUp() throws Exception {
TestModelProvider.enabled = true;
super.setUp();
project = getWorkspace().getRoot().getProject("Project");
IResource[] before = buildResources(project, new String[] {"c/", "c/b/", "c/a/", "c/x", "c/b/y", "c/b/z"});
ensureExistsInWorkspace(before, true);
assertExistsInWorkspace(before);
factory = createEmptyChangeDescription();
}
protected void tearDown() throws Exception {
TestModelProvider.enabled = false;
super.tearDown();
}
public void testCopyReplaceDeletedFolder() {
// Copy folder to replace a deleted folder
final IResource folder = project.findMember("c/b/");
IFolder destination = project.getFolder("/c/a/");
factory.delete(destination);
factory.copy(folder, destination.getFullPath());
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, folder),});
}
public void testFileChanges() {
factory.change((IFile) project.findMember("c/x"));
factory.change((IFile) project.findMember("c/b/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.CHANGED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.CHANGED, project.findMember("c/b/y"))});
}
public void testFileCopy() {
factory.copy(project.findMember("c/x"), new Path("c/x2"));
factory.copy(project.findMember("c/b/y"), new Path("c/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.COPIED, project.findMember("c/b/y"))});
}
public void testFileCreate() {
IFile file = project.getFile("file");
factory.create(file);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.ADDED, file)});
}
public void testFileInFolderCreate() {
IFolder folder = project.getFolder("folder");
IFile file = folder.getFile("file");
factory.create(folder);
factory.create(file);
IStatus status = validateChange(factory);
//this isn't very accurate, but ChangeDescription doesn't currently record recursive creates
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.ADDED, folder)});
}
public void testFileDeletion() {
factory.delete(project.findMember("c/x"));
factory.delete(project.findMember("c/b/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project.findMember("c/b/y"))});
}
public void testFileMoves() {
factory.move(project.findMember("c/x"), new Path("c/x2"));
factory.move(project.findMember("c/b/y"), new Path("c/y"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, project.findMember("c/x")), ChangeDescription.getMessageFor(ChangeDescription.MOVED, project.findMember("c/b/y"))});
}
public void testFolderCopy() {
final IResource folder = project.findMember("c/b/");
factory.copy(folder, new Path("c/d"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, folder),});
}
public void testFolderDeletion() {
final IResource folder = project.findMember("c/b/");
factory.delete(folder);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project.findMember("c/b")),});
}
public void testFolderMove() {
final IResource folder = project.findMember("c/b/");
factory.move(folder, new Path("c/d"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, folder),});
}
public void testMoveReplaceDeletedFolder() {
// Move to replace a deleted folder
final IResource folder = project.findMember("c/b/");
IFolder destination = project.getFolder("/c/a/");
factory.delete(destination);
factory.move(folder, destination.getFullPath());
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, folder),});
}
public void testProjectClose() {
factory.close(project);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.CLOSED, project)});
}
public void testProjectCopy() {
// A project copy
factory.copy(project, new Path("MovedProject"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.COPIED, project)});
}
public void testProjectDeletion() {
// A project deletion
factory.delete(project);
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.REMOVED, project)});
}
public void testProjectMove() {
factory.move(project, new Path("MovedProject"));
IStatus status = validateChange(factory);
assertStatusEqual(status, new String[] {ChangeDescription.getMessageFor(ChangeDescription.MOVED, project)});
}
private IStatus validateChange(IResourceChangeDescriptionFactory factory) {
return ResourceChangeValidator.getValidator().validateChange(factory.getDelta(), getMonitor());
}
}
| false | true | private void assertStatusEqual(IStatus status, String[] expectedMessages) {
List actualMessages = new ArrayList();
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
String message = getModelMessage(children[i]);
if (message != null)
actualMessages.add(message);
}
} else {
String message = getModelMessage(status);
if (message != null)
actualMessages.add(message);
}
if (expectedMessages.length < actualMessages.size()) {
for (Iterator iter = actualMessages.iterator(); iter.hasNext();) {
String actual = (String) iter.next();
boolean found = false;
for (int i = 0; i < expectedMessages.length; i++) {
String expected = expectedMessages[i];
if (actual.equals(expected))
found = true;
break;
}
if (!found)
fail("Unexpected message returned: " + actual);
}
} else {
for (int i = 0; i < expectedMessages.length; i++) {
String string = expectedMessages[i];
if (!actualMessages.contains(string)) {
fail("Expect message missing: " + string);
}
}
}
}
| private void assertStatusEqual(IStatus status, String[] expectedMessages) {
List actualMessages = new ArrayList();
if (status.isMultiStatus()) {
IStatus[] children = status.getChildren();
for (int i = 0; i < children.length; i++) {
String message = getModelMessage(children[i]);
if (message != null)
actualMessages.add(message);
}
} else {
String message = getModelMessage(status);
if (message != null)
actualMessages.add(message);
}
if (expectedMessages.length < actualMessages.size()) {
for (Iterator iter = actualMessages.iterator(); iter.hasNext();) {
String actual = (String) iter.next();
boolean found = false;
for (int i = 0; i < expectedMessages.length; i++) {
String expected = expectedMessages[i];
if (actual.equals(expected)) {
found = true;
break;
}
}
if (!found)
fail("Unexpected message returned: " + actual);
}
} else {
for (int i = 0; i < expectedMessages.length; i++) {
String string = expectedMessages[i];
if (!actualMessages.contains(string)) {
fail("Expect message missing: " + string);
}
}
}
}
|
diff --git a/src/main/java/org/spoutcraft/launcher/MD5Utils.java b/src/main/java/org/spoutcraft/launcher/MD5Utils.java
index 44e0b97..aebbb5c 100644
--- a/src/main/java/org/spoutcraft/launcher/MD5Utils.java
+++ b/src/main/java/org/spoutcraft/launcher/MD5Utils.java
@@ -1,38 +1,41 @@
package org.spoutcraft.launcher;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.spoutcraft.launcher.config.YAMLProcessor;
public class MD5Utils {
public static String getMD5(File file){
try {
- return DigestUtils.md5Hex(new FileInputStream(file));
+ FileInputStream fis = new FileInputStream(file);
+ String md5 = DigestUtils.md5Hex(fis);
+ fis.close();
+ return md5;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String getMD5(FileType type) {
return getMD5(type, MinecraftYML.getLatestMinecraftVersion());
}
@SuppressWarnings("unchecked")
public static String getMD5(FileType type, String version) {
YAMLProcessor config = MinecraftYML.getMinecraftYML();
Map<String, Map<String, String>> builds = (Map<String, Map<String, String>>) config.getProperty("versions");
if (builds.containsKey(version)) {
Map<String, String> files = builds.get(version);
return files.get(type.name());
}
return null;
}
}
| true | true | public static String getMD5(File file){
try {
return DigestUtils.md5Hex(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
| public static String getMD5(File file){
try {
FileInputStream fis = new FileInputStream(file);
String md5 = DigestUtils.md5Hex(fis);
fis.close();
return md5;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.