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/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java
index 8af5b13ef..9218b4ffe 100644
--- a/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java
+++ b/openjpa-kernel/src/main/java/org/apache/openjpa/conf/OpenJPAConfigurationImpl.java
@@ -1,1422 +1,1421 @@
/*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.conf;
import java.util.Collection;
import java.util.HashSet;
import org.apache.openjpa.datacache.ConcurrentDataCache;
import org.apache.openjpa.datacache.ConcurrentQueryCache;
import org.apache.openjpa.datacache.DataCacheManager;
import org.apache.openjpa.datacache.DataCacheManagerImpl;
import org.apache.openjpa.ee.ManagedRuntime;
import org.apache.openjpa.event.OrphanedKeyAction;
import org.apache.openjpa.event.RemoteCommitEventManager;
import org.apache.openjpa.event.RemoteCommitProvider;
import org.apache.openjpa.kernel.AutoClear;
import org.apache.openjpa.kernel.BrokerImpl;
import org.apache.openjpa.kernel.ConnectionRetainModes;
import org.apache.openjpa.kernel.InverseManager;
import org.apache.openjpa.kernel.LockLevels;
import org.apache.openjpa.kernel.LockManager;
import org.apache.openjpa.kernel.QueryFlushModes;
import org.apache.openjpa.kernel.RestoreState;
import org.apache.openjpa.kernel.SavepointManager;
import org.apache.openjpa.kernel.Seq;
import org.apache.openjpa.kernel.exps.AggregateListener;
import org.apache.openjpa.kernel.exps.FilterListener;
import org.apache.openjpa.lib.conf.BooleanValue;
import org.apache.openjpa.lib.conf.ConfigurationImpl;
import org.apache.openjpa.lib.conf.Configurations;
import org.apache.openjpa.lib.conf.IntValue;
import org.apache.openjpa.lib.conf.ObjectValue;
import org.apache.openjpa.lib.conf.PluginListValue;
import org.apache.openjpa.lib.conf.PluginValue;
import org.apache.openjpa.lib.conf.StringListValue;
import org.apache.openjpa.lib.conf.StringValue;
import org.apache.openjpa.lib.log.Log;
import org.apache.openjpa.lib.util.Localizer;
import org.apache.openjpa.meta.MetaDataFactory;
import org.apache.openjpa.meta.MetaDataRepository;
import org.apache.openjpa.util.ClassResolver;
import org.apache.openjpa.util.ImplHelper;
import org.apache.openjpa.util.ProxyManager;
/**
* Implementation of the {@link OpenJPAConfiguration} interface.
* On construction, the class will attempt to locate a default properties
* file called <code>openjpa.properties</code> located at any top level token
* of the CLASSPATH. See the {@link ConfigurationImpl} class description
* for details.
*
* @see ConfigurationImpl
* @author Marc Prud'hommeaux
* @author Abe White
*/
public class OpenJPAConfigurationImpl
extends ConfigurationImpl
implements OpenJPAConfiguration {
private static final Localizer _loc = Localizer.forPackage
(OpenJPAConfigurationImpl.class);
// cached state; some of this is created in getter methods, so make
// protected in case subclasses want to access without creating
protected MetaDataRepository metaRepos = null;
protected RemoteCommitEventManager remoteEventManager = null;
// openjpa properties
public ObjectValue classResolverPlugin;
public ObjectValue brokerPlugin;
public ObjectValue dataCachePlugin;
public ObjectValue dataCacheManagerPlugin;
public IntValue dataCacheTimeout;
public ObjectValue queryCachePlugin;
public BooleanValue dynamicDataStructs;
public ObjectValue managedRuntimePlugin;
public BooleanValue transactionMode;
public IntValue connectionRetainMode;
public IntValue fetchBatchSize;
public StringListValue fetchGroups;
public IntValue flushBeforeQueries;
public IntValue lockTimeout;
public IntValue readLockLevel;
public IntValue writeLockLevel;
public ObjectValue seqPlugin;
public PluginListValue filterListenerPlugins;
public PluginListValue aggregateListenerPlugins;
public BooleanValue retryClassRegistration;
public ObjectValue proxyManagerPlugin;
public StringValue connectionUserName;
public StringValue connectionPassword;
public StringValue connectionURL;
public StringValue connectionDriverName;
public ObjectValue connectionFactory;
public StringValue connectionFactoryName;
public StringValue connectionProperties;
public StringValue connectionFactoryProperties;
public BooleanValue connectionFactoryMode;
public StringValue connection2UserName;
public StringValue connection2Password;
public StringValue connection2URL;
public StringValue connection2DriverName;
public StringValue connection2Properties;
public ObjectValue connectionFactory2;
public StringValue connectionFactory2Name;
public StringValue connectionFactory2Properties;
public BooleanValue optimistic;
public IntValue autoClear;
public BooleanValue retainState;
public IntValue restoreState;
public ObjectValue detachStatePlugin;
public BooleanValue ignoreChanges;
public BooleanValue nontransactionalRead;
public BooleanValue nontransactionalWrite;
public BooleanValue multithreaded;
public StringValue mapping;
public PluginValue metaFactoryPlugin;
public ObjectValue lockManagerPlugin;
public ObjectValue inverseManagerPlugin;
public ObjectValue savepointManagerPlugin;
public ObjectValue orphanedKeyPlugin;
public ObjectValue compatibilityPlugin;
// custom values
public BrokerFactoryValue brokerFactoryPlugin;
public RemoteCommitProviderValue remoteProviderPlugin;
public AutoDetachValue autoDetach;
private Collection supportedOptions = new HashSet(33);
private String spec = null;
private final StoreFacadeTypeRegistry _storeFacadeRegistry =
new StoreFacadeTypeRegistry();
/**
* Default constructor. Attempts to load default properties.
*/
public OpenJPAConfigurationImpl() {
this(true);
}
/**
* Constructor.
*
* @param loadDefaults whether to attempt to load the default
* <code>openjpa.properties</code> resource
*/
public OpenJPAConfigurationImpl(boolean loadDefaults) {
this(true, loadDefaults);
}
/**
* Constructor.
*
* @param derivations whether to apply product derivations
* @param loadDefaults whether to attempt to load the default
* <code>openjpa.properties</code> resource
*/
public OpenJPAConfigurationImpl(boolean derivations, boolean loadDefaults) {
super(false);
String[] aliases;
// setup super's log factory plugin
logFactoryPlugin.setProperty("Log");
logFactoryPlugin
.setAlias("openjpa", "org.apache.openjpa.lib.log.LogFactoryImpl");
aliases = logFactoryPlugin.getAliases();
logFactoryPlugin.setDefault(aliases[0]);
logFactoryPlugin.setString(aliases[0]);
classResolverPlugin =
addPlugin("ClassResolver", true);
aliases = new String[]{
"default", "org.apache.openjpa.util.ClassResolverImpl",
// deprecated alias
"spec", "org.apache.openjpa.util.ClassResolverImpl",
};
classResolverPlugin.setAliases(aliases);
classResolverPlugin.setDefault(aliases[0]);
classResolverPlugin.setString(aliases[0]);
classResolverPlugin.setInstantiatingGetter("getClassResolverInstance");
brokerFactoryPlugin = new BrokerFactoryValue();
addValue(brokerFactoryPlugin);
brokerPlugin = addPlugin("BrokerImpl", false);
aliases = new String[]{ "default", BrokerImpl.class.getName() };
brokerPlugin.setAliases(aliases);
brokerPlugin.setDefault(aliases[0]);
brokerPlugin.setString(aliases[0]);
dataCacheManagerPlugin =
addPlugin("DataCacheManager", true);
aliases = new String[]{
"default", DataCacheManagerImpl.class.getName(),
};
dataCacheManagerPlugin.setAliases(aliases);
dataCacheManagerPlugin.setDefault(aliases[0]);
dataCacheManagerPlugin.setString(aliases[0]);
dataCacheManagerPlugin.setInstantiatingGetter("getDataCacheManager");
dataCachePlugin = addPlugin("DataCache", false);
aliases = new String[]{
"false", null,
"true", ConcurrentDataCache.class.getName(),
"concurrent", ConcurrentDataCache.class.getName(),
};
dataCachePlugin.setAliases(aliases);
dataCachePlugin.setDefault(aliases[0]);
dataCachePlugin.setString(aliases[0]);
dataCacheTimeout = addInt("DataCacheTimeout");
dataCacheTimeout.setDefault("-1");
dataCacheTimeout.set(-1);
queryCachePlugin = addPlugin("QueryCache", true);
aliases = new String[]{
"true", ConcurrentQueryCache.class.getName(),
"concurrent", ConcurrentQueryCache.class.getName(),
"false", null,
};
queryCachePlugin.setAliases(aliases);
queryCachePlugin.setDefault(aliases[0]);
queryCachePlugin.setString(aliases[0]);
dynamicDataStructs =
addBoolean("DynamicDataStructs");
dynamicDataStructs.setDefault("false");
dynamicDataStructs.set(false);
lockManagerPlugin = addPlugin("LockManager", false);
aliases = new String[]{
"none", "org.apache.openjpa.kernel.NoneLockManager",
"version", "org.apache.openjpa.kernel.VersionLockManager",
};
lockManagerPlugin.setAliases(aliases);
lockManagerPlugin.setDefault(aliases[0]);
lockManagerPlugin.setString(aliases[0]);
inverseManagerPlugin =
addPlugin("InverseManager", false);
aliases = new String[]{
"false", null,
"true", "org.apache.openjpa.kernel.InverseManager",
};
inverseManagerPlugin.setAliases(aliases);
inverseManagerPlugin.setDefault(aliases[0]);
inverseManagerPlugin.setString(aliases[0]);
savepointManagerPlugin =
addPlugin("SavepointManager", true);
aliases = new String[]{
"in-mem", "org.apache.openjpa.kernel.InMemorySavepointManager",
};
savepointManagerPlugin.setAliases(aliases);
savepointManagerPlugin.setDefault(aliases[0]);
savepointManagerPlugin.setString(aliases[0]);
savepointManagerPlugin.setInstantiatingGetter
("getSavepointManagerInstance");
orphanedKeyPlugin =
addPlugin("OrphanedKeyAction", true);
aliases = new String[]{
"log", "org.apache.openjpa.event.LogOrphanedKeyAction",
"exception", "org.apache.openjpa.event.ExceptionOrphanedKeyAction",
"none", "org.apache.openjpa.event.NoneOrphanedKeyAction",
};
orphanedKeyPlugin.setAliases(aliases);
orphanedKeyPlugin.setDefault(aliases[0]);
orphanedKeyPlugin.setString(aliases[0]);
orphanedKeyPlugin.setInstantiatingGetter
("getOrphanedKeyActionInstance");
remoteProviderPlugin = new RemoteCommitProviderValue();
addValue(remoteProviderPlugin);
transactionMode = addBoolean("TransactionMode");
aliases = new String[]{
"local", "false",
"managed", "true",
};
transactionMode.setAliases(aliases);
transactionMode.setDefault(aliases[0]);
managedRuntimePlugin =
addPlugin("ManagedRuntime", true);
aliases = new String[]{
"auto", "org.apache.openjpa.ee.AutomaticManagedRuntime",
"jndi", "org.apache.openjpa.ee.JNDIManagedRuntime",
"invocation", "org.apache.openjpa.ee.InvocationManagedRuntime",
};
managedRuntimePlugin.setAliases(aliases);
managedRuntimePlugin.setDefault(aliases[0]);
managedRuntimePlugin.setString(aliases[0]);
managedRuntimePlugin.setInstantiatingGetter
("getManagedRuntimeInstance");
proxyManagerPlugin = addPlugin("ProxyManager", true);
aliases = new String[]{ "default",
"org.apache.openjpa.util.ProxyManagerImpl" };
proxyManagerPlugin.setAliases(aliases);
proxyManagerPlugin.setDefault(aliases[0]);
proxyManagerPlugin.setString(aliases[0]);
proxyManagerPlugin.setInstantiatingGetter("getProxyManagerInstance");
mapping = addString("Mapping");
- metaFactoryPlugin =
- addPlugin("MetaDataFactory", false);
+ metaFactoryPlugin = addPlugin("MetaDataFactory", false);
connectionFactory = addObject("ConnectionFactory");
connectionFactory.setInstantiatingGetter("getConnectionFactory");
connectionFactory2 = addObject("ConnectionFactory2");
connectionFactory2.setInstantiatingGetter("getConnectionFactory2");
connectionUserName = addString("ConnectionUserName");
connectionPassword = addString("ConnectionPassword");
connectionURL = addString("ConnectionURL");
connectionDriverName =
addString("ConnectionDriverName");
connectionFactoryName =
addString("ConnectionFactoryName");
connectionProperties =
addString("ConnectionProperties");
connectionFactoryProperties = addString("ConnectionFactoryProperties");
connection2UserName =
addString("Connection2UserName");
connection2Password =
addString("Connection2Password");
connection2URL = addString("Connection2URL");
connection2DriverName =
addString("Connection2DriverName");
connection2Properties =
addString("Connection2Properties");
connectionFactory2Properties = addString(
"ConnectionFactory2Properties");
connectionFactory2Name =
addString("ConnectionFactory2Name");
connectionFactoryMode =
addBoolean("ConnectionFactoryMode");
aliases = new String[]{
"local", "false",
"managed", "true",
};
connectionFactoryMode.setAliases(aliases);
connectionFactoryMode.setDefault(aliases[0]);
optimistic = addBoolean("Optimistic");
optimistic.setDefault("true");
optimistic.set(true);
autoClear = addInt("AutoClear");
aliases = new String[]{
"datastore", String.valueOf(AutoClear.CLEAR_DATASTORE),
"all", String.valueOf(AutoClear.CLEAR_ALL),
};
autoClear.setAliases(aliases);
autoClear.setDefault(aliases[0]);
autoClear.set(AutoClear.CLEAR_DATASTORE);
retainState = addBoolean("RetainState");
retainState.setDefault("true");
retainState.set(true);
restoreState = addInt("RestoreState");
aliases = new String[]{
"none", String.valueOf(RestoreState.RESTORE_NONE),
"false", String.valueOf(RestoreState.RESTORE_NONE),
"immutable", String.valueOf(RestoreState.RESTORE_IMMUTABLE),
// "true" for compat with jdo RestoreValues
"true", String.valueOf(RestoreState.RESTORE_IMMUTABLE),
"all", String.valueOf(RestoreState.RESTORE_ALL),
};
restoreState.setAliases(aliases);
restoreState.setDefault(aliases[0]);
restoreState.set(RestoreState.RESTORE_IMMUTABLE);
autoDetach = new AutoDetachValue();
addValue(autoDetach);
detachStatePlugin = addPlugin("DetachState", true);
aliases = new String[]{
"loaded", DetachOptions.Loaded.class.getName(),
"fgs", DetachOptions.FetchGroups.class.getName(),
"all", DetachOptions.All.class.getName(),
};
detachStatePlugin.setAliases(aliases);
detachStatePlugin.setDefault(aliases[0]);
detachStatePlugin.setString(aliases[0]);
detachStatePlugin.setInstantiatingGetter("getDetachStateInstance");
ignoreChanges = addBoolean("IgnoreChanges");
nontransactionalRead =
addBoolean("NontransactionalRead");
nontransactionalRead.setDefault("true");
nontransactionalRead.set(true);
nontransactionalWrite =
addBoolean("NontransactionalWrite");
multithreaded = addBoolean("Multithreaded");
fetchBatchSize = addInt("FetchBatchSize");
fetchBatchSize.setDefault("-1");
fetchBatchSize.set(-1);
fetchGroups = addStringList("FetchGroups");
fetchGroups.setDefault("default");
fetchGroups.set(new String[]{ "default" });
flushBeforeQueries = addInt("FlushBeforeQueries");
aliases = new String[]{
"true", String.valueOf(QueryFlushModes.FLUSH_TRUE),
"false", String.valueOf(QueryFlushModes.FLUSH_FALSE),
"with-connection", String.valueOf
(QueryFlushModes.FLUSH_WITH_CONNECTION),
};
flushBeforeQueries.setAliases(aliases);
flushBeforeQueries.setDefault(aliases[0]);
flushBeforeQueries.set(QueryFlushModes.FLUSH_TRUE);
lockTimeout = addInt("LockTimeout");
lockTimeout.setDefault("-1");
lockTimeout.set(-1);
readLockLevel = addInt("ReadLockLevel");
aliases = new String[]{
"read", String.valueOf(LockLevels.LOCK_READ),
"write", String.valueOf(LockLevels.LOCK_WRITE),
"none", String.valueOf(LockLevels.LOCK_NONE),
};
readLockLevel.setAliases(aliases);
readLockLevel.setDefault(aliases[0]);
readLockLevel.set(LockLevels.LOCK_READ);
writeLockLevel = addInt("WriteLockLevel");
aliases = new String[]{
"read", String.valueOf(LockLevels.LOCK_READ),
"write", String.valueOf(LockLevels.LOCK_WRITE),
"none", String.valueOf(LockLevels.LOCK_NONE),
};
writeLockLevel.setAliases(aliases);
writeLockLevel.setDefault(aliases[1]);
writeLockLevel.set(LockLevels.LOCK_WRITE);
seqPlugin = new SeqValue("Sequence");
seqPlugin.setInstantiatingGetter("getSequenceInstance");
addValue(seqPlugin);
connectionRetainMode =
addInt("ConnectionRetainMode");
aliases = new String[]{
"on-demand",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_DEMAND),
"transaction",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_TRANS),
"always",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_ALWAYS),
// deprecated
"persistence-manager",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_ALWAYS),
};
connectionRetainMode.setAliases(aliases);
connectionRetainMode.setDefault(aliases[0]);
connectionRetainMode.setAliasListComprehensive(true);
connectionRetainMode.set(ConnectionRetainModes.CONN_RETAIN_DEMAND);
filterListenerPlugins =
addPluginList("FilterListeners");
filterListenerPlugins.setInstantiatingGetter
("getFilterListenerInstances");
aggregateListenerPlugins =
addPluginList("AggregateListeners");
aggregateListenerPlugins.setInstantiatingGetter
("getAggregateListenerInstances");
retryClassRegistration =
addBoolean("RetryClassRegistration");
compatibilityPlugin =
addPlugin("Compatibility", true);
aliases = new String[]{ "default", Compatibility.class.getName() };
compatibilityPlugin.setAliases(aliases);
compatibilityPlugin.setDefault(aliases[0]);
compatibilityPlugin.setString(aliases[0]);
compatibilityPlugin.setInstantiatingGetter("getCompatibilityInstance");
// initialize supported options that some runtimes may not support
supportedOptions.add(OPTION_NONTRANS_READ);
supportedOptions.add(OPTION_OPTIMISTIC);
supportedOptions.add(OPTION_ID_APPLICATION);
supportedOptions.add(OPTION_ID_DATASTORE);
supportedOptions.add(OPTION_TYPE_COLLECTION);
supportedOptions.add(OPTION_TYPE_MAP);
supportedOptions.add(OPTION_TYPE_ARRAY);
supportedOptions.add(OPTION_NULL_CONTAINER);
supportedOptions.add(OPTION_EMBEDDED_RELATION);
supportedOptions.add(OPTION_EMBEDDED_COLLECTION_RELATION);
supportedOptions.add(OPTION_EMBEDDED_MAP_RELATION);
supportedOptions.add(OPTION_INC_FLUSH);
supportedOptions.add(OPTION_VALUE_AUTOASSIGN);
supportedOptions.add(OPTION_VALUE_INCREMENT);
supportedOptions.add(OPTION_DATASTORE_CONNECTION);
if (derivations)
ProductDerivations.beforeConfigurationLoad(this);
if (loadDefaults)
loadDefaults();
}
public String getProductName() {
return "openjpa";
}
public Collection supportedOptions() {
return supportedOptions;
}
public String getSpecification() {
return spec;
}
public boolean setSpecification(String spec) {
if (spec == null)
return false;
if (this.spec != null) {
if (!this.spec.equals(spec)
&& getConfigurationLog().isWarnEnabled())
getConfigurationLog().warn(_loc.get("diff-specs", this.spec,
spec));
return false;
}
this.spec = spec;
ProductDerivations.afterSpecificationSet(this);
return true;
}
public void setClassResolver(String classResolver) {
assertNotReadOnly();
classResolverPlugin.setString(classResolver);
}
public String getClassResolver() {
return classResolverPlugin.getString();
}
public void setClassResolver(ClassResolver classResolver) {
assertNotReadOnly();
classResolverPlugin.set(classResolver);
}
public ClassResolver getClassResolverInstance() {
if (classResolverPlugin.get() == null)
classResolverPlugin.instantiate(ClassResolver.class, this);
return (ClassResolver) classResolverPlugin.get();
}
public void setBrokerFactory(String factory) {
assertNotReadOnly();
brokerFactoryPlugin.setString(factory);
}
public String getBrokerFactory() {
return brokerFactoryPlugin.getString();
}
public void setBrokerImpl(String broker) {
assertNotReadOnly();
brokerPlugin.setString(broker);
}
public String getBrokerImpl() {
return brokerPlugin.getString();
}
public BrokerImpl newBrokerInstance(String user, String pass) {
BrokerImpl broker = (BrokerImpl) brokerPlugin.instantiate
(BrokerImpl.class, this);
if (broker != null)
broker.setAuthentication(user, pass);
return broker;
}
public void setDataCacheManager(String mgr) {
assertNotReadOnly();
dataCacheManagerPlugin.setString(mgr);
}
public String getDataCacheManager() {
return dataCacheManagerPlugin.getString();
}
public void setDataCacheManager(DataCacheManager dcm) {
assertNotReadOnly();
if (dcm != null)
dcm.initialize(this, dataCachePlugin, queryCachePlugin);
dataCacheManagerPlugin.set(dcm);
}
public DataCacheManager getDataCacheManagerInstance() {
DataCacheManager dcm = (DataCacheManager) dataCacheManagerPlugin.get();
if (dcm == null) {
dcm = (DataCacheManager) dataCacheManagerPlugin.instantiate
(DataCacheManager.class, this);
dcm.initialize(this, dataCachePlugin, queryCachePlugin);
}
return dcm;
}
public void setDataCache(String dataCache) {
assertNotReadOnly();
dataCachePlugin.setString(dataCache);
}
public String getDataCache() {
return dataCachePlugin.getString();
}
public void setDataCacheTimeout(int dataCacheTimeout) {
assertNotReadOnly();
this.dataCacheTimeout.set(dataCacheTimeout);
}
public void setDataCacheTimeout(Integer dataCacheTimeout) {
if (dataCacheTimeout != null)
setDataCacheTimeout(dataCacheTimeout.intValue());
}
public int getDataCacheTimeout() {
return dataCacheTimeout.get();
}
public void setQueryCache(String queryCache) {
assertNotReadOnly();
queryCachePlugin.setString(queryCache);
}
public String getQueryCache() {
return queryCachePlugin.getString();
}
public boolean getDynamicDataStructs() {
return dynamicDataStructs.get();
}
public void setDynamicDataStructs(boolean dynamic) {
dynamicDataStructs.set(dynamic);
}
public void setDynamicDataStructs(Boolean dynamic) {
setDynamicDataStructs(dynamic.booleanValue());
}
public void setLockManager(String lockManager) {
assertNotReadOnly();
lockManagerPlugin.setString(lockManager);
}
public String getLockManager() {
return lockManagerPlugin.getString();
}
public LockManager newLockManagerInstance() {
// don't validate plugin properties on instantiation because it
// is likely that back ends will override defaults with their
// own subclasses with new properties
return (LockManager) lockManagerPlugin.instantiate(LockManager.class,
this, false);
}
public void setInverseManager(String inverseManager) {
assertNotReadOnly();
inverseManagerPlugin.setString(inverseManager);
}
public String getInverseManager() {
return inverseManagerPlugin.getString();
}
public InverseManager newInverseManagerInstance() {
return (InverseManager) inverseManagerPlugin.instantiate
(InverseManager.class, this);
}
public void setSavepointManager(String savepointManager) {
assertNotReadOnly();
savepointManagerPlugin.setString(savepointManager);
}
public String getSavepointManager() {
return savepointManagerPlugin.getString();
}
public SavepointManager getSavepointManagerInstance() {
if (savepointManagerPlugin.get() == null)
savepointManagerPlugin.instantiate(SavepointManager.class, this);
return (SavepointManager) savepointManagerPlugin.get();
}
public void setOrphanedKeyAction(String action) {
assertNotReadOnly();
orphanedKeyPlugin.setString(action);
}
public String getOrphanedKeyAction() {
return orphanedKeyPlugin.getString();
}
public OrphanedKeyAction getOrphanedKeyActionInstance() {
if (orphanedKeyPlugin.get() == null)
orphanedKeyPlugin.instantiate(OrphanedKeyAction.class, this);
return (OrphanedKeyAction) orphanedKeyPlugin.get();
}
public void setOrphanedKeyAction(OrphanedKeyAction action) {
assertNotReadOnly();
orphanedKeyPlugin.set(action);
}
public void setRemoteCommitProvider(String remoteCommitProvider) {
assertNotReadOnly();
remoteProviderPlugin.setString(remoteCommitProvider);
}
public String getRemoteCommitProvider() {
return remoteProviderPlugin.getString();
}
public RemoteCommitProvider newRemoteCommitProviderInstance() {
return remoteProviderPlugin.instantiateProvider(this);
}
public void setRemoteCommitEventManager
(RemoteCommitEventManager remoteEventManager) {
assertNotReadOnly();
this.remoteEventManager = remoteEventManager;
remoteProviderPlugin.configureEventManager(remoteEventManager);
}
public RemoteCommitEventManager getRemoteCommitEventManager() {
if (remoteEventManager == null) {
remoteEventManager = new RemoteCommitEventManager(this);
remoteProviderPlugin.configureEventManager(remoteEventManager);
}
return remoteEventManager;
}
public void setTransactionMode(String transactionMode) {
assertNotReadOnly();
this.transactionMode.setString(transactionMode);
}
public String getTransactionMode() {
return transactionMode.getString();
}
public void setTransactionModeManaged(boolean managed) {
assertNotReadOnly();
transactionMode.set(managed);
}
public boolean isTransactionModeManaged() {
return transactionMode.get();
}
public void setManagedRuntime(String managedRuntime) {
assertNotReadOnly();
managedRuntimePlugin.setString(managedRuntime);
}
public String getManagedRuntime() {
return managedRuntimePlugin.getString();
}
public void setManagedRuntime(ManagedRuntime managedRuntime) {
assertNotReadOnly();
managedRuntimePlugin.set(managedRuntime);
}
public ManagedRuntime getManagedRuntimeInstance() {
if (managedRuntimePlugin.get() == null)
managedRuntimePlugin.instantiate(ManagedRuntime.class, this);
return (ManagedRuntime) managedRuntimePlugin.get();
}
public void setProxyManager(String proxyManager) {
assertNotReadOnly();
proxyManagerPlugin.setString(proxyManager);
}
public String getProxyManager() {
return proxyManagerPlugin.getString();
}
public void setProxyManager(ProxyManager proxyManager) {
assertNotReadOnly();
proxyManagerPlugin.set(proxyManager);
}
public ProxyManager getProxyManagerInstance() {
if (proxyManagerPlugin.get() == null)
proxyManagerPlugin.instantiate(ProxyManager.class, this);
return (ProxyManager) proxyManagerPlugin.get();
}
public void setMapping(String mapping) {
assertNotReadOnly();
this.mapping.setString(mapping);
}
public String getMapping() {
return mapping.getString();
}
public void setMetaDataFactory(String meta) {
assertNotReadOnly();
this.metaFactoryPlugin.setString(meta);
}
public String getMetaDataFactory() {
return metaFactoryPlugin.getString();
}
public MetaDataFactory newMetaDataFactoryInstance() {
return (MetaDataFactory) metaFactoryPlugin.instantiate
(MetaDataFactory.class, this);
}
public void setMetaDataRepository(MetaDataRepository meta) {
assertNotReadOnly();
metaRepos = meta;
}
public MetaDataRepository getMetaDataRepository() {
if (metaRepos == null)
metaRepos = new MetaDataRepository(this);
return metaRepos;
}
public void setConnectionUserName(String connectionUserName) {
assertNotReadOnly();
this.connectionUserName.setString(connectionUserName);
}
public String getConnectionUserName() {
return connectionUserName.getString();
}
public void setConnectionPassword(String connectionPassword) {
assertNotReadOnly();
this.connectionPassword.setString(connectionPassword);
}
public String getConnectionPassword() {
return connectionPassword.getString();
}
public void setConnectionURL(String connectionURL) {
assertNotReadOnly();
this.connectionURL.setString(connectionURL);
}
public String getConnectionURL() {
return connectionURL.getString();
}
public void setConnectionDriverName(String driverName) {
assertNotReadOnly();
this.connectionDriverName.setString(driverName);
}
public String getConnectionDriverName() {
return connectionDriverName.getString();
}
public void setConnectionProperties(String connectionProperties) {
assertNotReadOnly();
this.connectionProperties.setString(connectionProperties);
}
public String getConnectionProperties() {
return connectionProperties.getString();
}
public void setConnectionFactoryProperties
(String connectionFactoryProperties) {
assertNotReadOnly();
this.connectionFactoryProperties.setString(connectionFactoryProperties);
}
public String getConnectionFactoryProperties() {
return connectionFactoryProperties.getString();
}
public String getConnectionFactoryMode() {
return connectionFactoryMode.getString();
}
public void setConnectionFactoryMode(String mode) {
assertNotReadOnly();
connectionFactoryMode.setString(mode);
}
public boolean isConnectionFactoryModeManaged() {
return connectionFactoryMode.get();
}
public void setConnectionFactoryModeManaged(boolean managed) {
assertNotReadOnly();
connectionFactoryMode.set(managed);
}
public void setConnectionFactoryName(String connectionFactoryName) {
assertNotReadOnly();
this.connectionFactoryName.setString(connectionFactoryName);
}
public String getConnectionFactoryName() {
return connectionFactoryName.getString();
}
public void setConnectionFactory(Object factory) {
assertNotReadOnly();
connectionFactory.set(factory);
}
public Object getConnectionFactory() {
if (connectionFactory.get() == null)
connectionFactory.set(lookupConnectionFactory
(getConnectionFactoryName()), true);
return connectionFactory.get();
}
/**
* Lookup the connection factory at the given name.
*/
private Object lookupConnectionFactory(String name) {
if (name == null || name.trim().length() == 0)
return null;
return Configurations.lookup(name);
}
public void setConnection2UserName(String connection2UserName) {
assertNotReadOnly();
this.connection2UserName.setString(connection2UserName);
}
public String getConnection2UserName() {
return connection2UserName.getString();
}
public void setConnection2Password(String connection2Password) {
assertNotReadOnly();
this.connection2Password.setString(connection2Password);
}
public String getConnection2Password() {
return connection2Password.getString();
}
public void setConnection2URL(String connection2URL) {
assertNotReadOnly();
this.connection2URL.setString(connection2URL);
}
public String getConnection2URL() {
return connection2URL.getString();
}
public void setConnection2DriverName(String driverName) {
assertNotReadOnly();
this.connection2DriverName.setString(driverName);
}
public String getConnection2DriverName() {
return connection2DriverName.getString();
}
public void setConnection2Properties(String connection2Properties) {
assertNotReadOnly();
this.connection2Properties.setString(connection2Properties);
}
public String getConnection2Properties() {
return connection2Properties.getString();
}
public void setConnectionFactory2Properties
(String connectionFactory2Properties) {
assertNotReadOnly();
this.connectionFactory2Properties.setString
(connectionFactory2Properties);
}
public String getConnectionFactory2Properties() {
return connectionFactory2Properties.getString();
}
public void setConnectionFactory2Name(String connectionFactory2Name) {
assertNotReadOnly();
this.connectionFactory2Name.setString(connectionFactory2Name);
}
public String getConnectionFactory2Name() {
return connectionFactory2Name.getString();
}
public void setConnectionFactory2(Object factory) {
assertNotReadOnly();
connectionFactory2.set(factory);
}
public Object getConnectionFactory2() {
if (connectionFactory2.get() == null)
connectionFactory2.set(lookupConnectionFactory
(getConnectionFactory2Name()), false);
return connectionFactory2.get();
}
public void setOptimistic(boolean optimistic) {
assertNotReadOnly();
this.optimistic.set(optimistic);
}
public void setOptimistic(Boolean optimistic) {
if (optimistic != null)
setOptimistic(optimistic.booleanValue());
}
public boolean getOptimistic() {
return optimistic.get();
}
public void setAutoClear(String clear) {
assertNotReadOnly();
autoClear.setString(clear);
}
public String getAutoClear() {
return autoClear.getString();
}
public void setAutoClear(int clear) {
assertNotReadOnly();
autoClear.set(clear);
}
public int getAutoClearConstant() {
return autoClear.get();
}
public void setRetainState(boolean retainState) {
assertNotReadOnly();
this.retainState.set(retainState);
}
public void setRetainState(Boolean retainState) {
if (retainState != null)
setRetainState(retainState.booleanValue());
}
public boolean getRetainState() {
return retainState.get();
}
public void setRestoreState(String restoreState) {
assertNotReadOnly();
this.restoreState.setString(restoreState);
}
public String getRestoreState() {
return restoreState.getString();
}
public void setRestoreState(int restoreState) {
assertNotReadOnly();
this.restoreState.set(restoreState);
}
public int getRestoreStateConstant() {
return restoreState.get();
}
public void setAutoDetach(String autoDetach) {
assertNotReadOnly();
this.autoDetach.setString(autoDetach);
}
public String getAutoDetach() {
return autoDetach.getString();
}
public void setAutoDetach(int autoDetachFlags) {
autoDetach.set(autoDetachFlags);
}
public int getAutoDetachConstant() {
return autoDetach.get();
}
public void setDetachState(String detachState) {
assertNotReadOnly();
detachStatePlugin.setString(detachState);
}
public String getDetachState() {
return detachStatePlugin.getString();
}
public void setDetachState(DetachOptions detachState) {
assertNotReadOnly();
detachStatePlugin.set(detachState);
}
public DetachOptions getDetachStateInstance() {
if (detachStatePlugin.get() == null)
detachStatePlugin.instantiate(DetachOptions.class, this);
return (DetachOptions) detachStatePlugin.get();
}
public void setIgnoreChanges(boolean ignoreChanges) {
assertNotReadOnly();
this.ignoreChanges.set(ignoreChanges);
}
public void setIgnoreChanges(Boolean ignoreChanges) {
if (ignoreChanges != null)
setIgnoreChanges(ignoreChanges.booleanValue());
}
public boolean getIgnoreChanges() {
return ignoreChanges.get();
}
public void setNontransactionalRead(boolean nontransactionalRead) {
assertNotReadOnly();
this.nontransactionalRead.set(nontransactionalRead);
}
public void setNontransactionalRead(Boolean nontransactionalRead) {
if (nontransactionalRead != null)
setNontransactionalRead(nontransactionalRead.booleanValue());
}
public boolean getNontransactionalRead() {
return nontransactionalRead.get();
}
public void setNontransactionalWrite(boolean nontransactionalWrite) {
assertNotReadOnly();
this.nontransactionalWrite.set(nontransactionalWrite);
}
public void setNontransactionalWrite(Boolean nontransactionalWrite) {
if (nontransactionalWrite != null)
setNontransactionalWrite(nontransactionalWrite.booleanValue());
}
public boolean getNontransactionalWrite() {
return nontransactionalWrite.get();
}
public void setMultithreaded(boolean multithreaded) {
assertNotReadOnly();
this.multithreaded.set(multithreaded);
}
public void setMultithreaded(Boolean multithreaded) {
if (multithreaded != null)
setMultithreaded(multithreaded.booleanValue());
}
public boolean getMultithreaded() {
return multithreaded.get();
}
public void setFetchBatchSize(int fetchBatchSize) {
assertNotReadOnly();
this.fetchBatchSize.set(fetchBatchSize);
}
public void setFetchBatchSize(Integer fetchBatchSize) {
if (fetchBatchSize != null)
setFetchBatchSize(fetchBatchSize.intValue());
}
public int getFetchBatchSize() {
return fetchBatchSize.get();
}
public void setFetchGroups(String fetchGroups) {
assertNotReadOnly();
this.fetchGroups.setString(fetchGroups);
}
public String getFetchGroups() {
return fetchGroups.getString();
}
public String[] getFetchGroupsList() {
return fetchGroups.get();
}
public void setFetchGroups(String[] fetchGroups) {
this.fetchGroups.set(fetchGroups);
}
public void setFlushBeforeQueries(String flush) {
assertNotReadOnly();
flushBeforeQueries.setString(flush);
}
public String getFlushBeforeQueries() {
return flushBeforeQueries.getString();
}
public void setFlushBeforeQueries(int flush) {
assertNotReadOnly();
flushBeforeQueries.set(flush);
}
public int getFlushBeforeQueriesConstant() {
return flushBeforeQueries.get();
}
public void setLockTimeout(int timeout) {
assertNotReadOnly();
lockTimeout.set(timeout);
}
public void setLockTimeout(Integer timeout) {
if (timeout != null)
setLockTimeout(timeout.intValue());
}
public int getLockTimeout() {
return lockTimeout.get();
}
public void setReadLockLevel(String level) {
assertNotReadOnly();
readLockLevel.setString(level);
}
public String getReadLockLevel() {
return readLockLevel.getString();
}
public void setReadLockLevel(int level) {
assertNotReadOnly();
readLockLevel.set(level);
}
public int getReadLockLevelConstant() {
return readLockLevel.get();
}
public void setWriteLockLevel(String level) {
assertNotReadOnly();
writeLockLevel.setString(level);
}
public String getWriteLockLevel() {
return writeLockLevel.getString();
}
public void setWriteLockLevel(int level) {
assertNotReadOnly();
writeLockLevel.set(level);
}
public int getWriteLockLevelConstant() {
return writeLockLevel.get();
}
public void setSequence(String sequence) {
assertNotReadOnly();
seqPlugin.setString(sequence);
}
public String getSequence() {
return seqPlugin.getString();
}
public void setSequence(Seq seq) {
assertNotReadOnly();
seqPlugin.set(seq);
}
public Seq getSequenceInstance() {
if (seqPlugin.get() == null)
seqPlugin.instantiate(Seq.class, this);
return (Seq) seqPlugin.get();
}
public void setConnectionRetainMode(String connectionRetainMode) {
assertNotReadOnly();
this.connectionRetainMode.setString(connectionRetainMode);
}
public String getConnectionRetainMode() {
return connectionRetainMode.getString();
}
public void setConnectionRetainMode(int connectionRetainMode) {
assertNotReadOnly();
this.connectionRetainMode.set(connectionRetainMode);
}
public int getConnectionRetainModeConstant() {
return connectionRetainMode.get();
}
public void setFilterListeners(String filterListeners) {
assertNotReadOnly();
filterListenerPlugins.setString(filterListeners);
}
public String getFilterListeners() {
return filterListenerPlugins.getString();
}
public void setFilterListeners(FilterListener[] listeners) {
assertNotReadOnly();
filterListenerPlugins.set(listeners);
}
public FilterListener[] getFilterListenerInstances() {
if (filterListenerPlugins.get() == null)
filterListenerPlugins.instantiate(FilterListener.class, this);
return (FilterListener[]) filterListenerPlugins.get();
}
public void setAggregateListeners(String aggregateListeners) {
assertNotReadOnly();
aggregateListenerPlugins.setString(aggregateListeners);
}
public String getAggregateListeners() {
return aggregateListenerPlugins.getString();
}
public void setAggregateListeners(AggregateListener[] listeners) {
assertNotReadOnly();
aggregateListenerPlugins.set(listeners);
}
public AggregateListener[] getAggregateListenerInstances() {
if (aggregateListenerPlugins.get() == null)
aggregateListenerPlugins.instantiate(AggregateListener.class, this);
return (AggregateListener[]) aggregateListenerPlugins.get();
}
public void setRetryClassRegistration(boolean retry) {
assertNotReadOnly();
retryClassRegistration.set(retry);
}
public void setRetryClassRegistration(Boolean retry) {
if (retry != null)
setRetryClassRegistration(retry.booleanValue());
}
public boolean getRetryClassRegistration() {
return retryClassRegistration.get();
}
public String getCompatibility() {
return compatibilityPlugin.getString();
}
public void setCompatibility(String compatibility) {
compatibilityPlugin.setString(compatibility);
}
public Compatibility getCompatibilityInstance() {
if (compatibilityPlugin.get() == null)
compatibilityPlugin.instantiate(Compatibility.class, this);
return (Compatibility) compatibilityPlugin.get();
}
public void instantiateAll() {
super.instantiateAll();
// instantiate singletons without values
getRemoteCommitEventManager();
getMetaDataRepository();
}
public void close() {
ImplHelper.close(remoteEventManager);
ImplHelper.close(metaRepos);
super.close();
ProductDerivations.afterClose(this);
}
public Log getConfigurationLog() {
return getLog(LOG_RUNTIME);
}
public StoreFacadeTypeRegistry getStoreFacadeTypeRegistry() {
return _storeFacadeRegistry;
}
}
| true | true | public OpenJPAConfigurationImpl(boolean derivations, boolean loadDefaults) {
super(false);
String[] aliases;
// setup super's log factory plugin
logFactoryPlugin.setProperty("Log");
logFactoryPlugin
.setAlias("openjpa", "org.apache.openjpa.lib.log.LogFactoryImpl");
aliases = logFactoryPlugin.getAliases();
logFactoryPlugin.setDefault(aliases[0]);
logFactoryPlugin.setString(aliases[0]);
classResolverPlugin =
addPlugin("ClassResolver", true);
aliases = new String[]{
"default", "org.apache.openjpa.util.ClassResolverImpl",
// deprecated alias
"spec", "org.apache.openjpa.util.ClassResolverImpl",
};
classResolverPlugin.setAliases(aliases);
classResolverPlugin.setDefault(aliases[0]);
classResolverPlugin.setString(aliases[0]);
classResolverPlugin.setInstantiatingGetter("getClassResolverInstance");
brokerFactoryPlugin = new BrokerFactoryValue();
addValue(brokerFactoryPlugin);
brokerPlugin = addPlugin("BrokerImpl", false);
aliases = new String[]{ "default", BrokerImpl.class.getName() };
brokerPlugin.setAliases(aliases);
brokerPlugin.setDefault(aliases[0]);
brokerPlugin.setString(aliases[0]);
dataCacheManagerPlugin =
addPlugin("DataCacheManager", true);
aliases = new String[]{
"default", DataCacheManagerImpl.class.getName(),
};
dataCacheManagerPlugin.setAliases(aliases);
dataCacheManagerPlugin.setDefault(aliases[0]);
dataCacheManagerPlugin.setString(aliases[0]);
dataCacheManagerPlugin.setInstantiatingGetter("getDataCacheManager");
dataCachePlugin = addPlugin("DataCache", false);
aliases = new String[]{
"false", null,
"true", ConcurrentDataCache.class.getName(),
"concurrent", ConcurrentDataCache.class.getName(),
};
dataCachePlugin.setAliases(aliases);
dataCachePlugin.setDefault(aliases[0]);
dataCachePlugin.setString(aliases[0]);
dataCacheTimeout = addInt("DataCacheTimeout");
dataCacheTimeout.setDefault("-1");
dataCacheTimeout.set(-1);
queryCachePlugin = addPlugin("QueryCache", true);
aliases = new String[]{
"true", ConcurrentQueryCache.class.getName(),
"concurrent", ConcurrentQueryCache.class.getName(),
"false", null,
};
queryCachePlugin.setAliases(aliases);
queryCachePlugin.setDefault(aliases[0]);
queryCachePlugin.setString(aliases[0]);
dynamicDataStructs =
addBoolean("DynamicDataStructs");
dynamicDataStructs.setDefault("false");
dynamicDataStructs.set(false);
lockManagerPlugin = addPlugin("LockManager", false);
aliases = new String[]{
"none", "org.apache.openjpa.kernel.NoneLockManager",
"version", "org.apache.openjpa.kernel.VersionLockManager",
};
lockManagerPlugin.setAliases(aliases);
lockManagerPlugin.setDefault(aliases[0]);
lockManagerPlugin.setString(aliases[0]);
inverseManagerPlugin =
addPlugin("InverseManager", false);
aliases = new String[]{
"false", null,
"true", "org.apache.openjpa.kernel.InverseManager",
};
inverseManagerPlugin.setAliases(aliases);
inverseManagerPlugin.setDefault(aliases[0]);
inverseManagerPlugin.setString(aliases[0]);
savepointManagerPlugin =
addPlugin("SavepointManager", true);
aliases = new String[]{
"in-mem", "org.apache.openjpa.kernel.InMemorySavepointManager",
};
savepointManagerPlugin.setAliases(aliases);
savepointManagerPlugin.setDefault(aliases[0]);
savepointManagerPlugin.setString(aliases[0]);
savepointManagerPlugin.setInstantiatingGetter
("getSavepointManagerInstance");
orphanedKeyPlugin =
addPlugin("OrphanedKeyAction", true);
aliases = new String[]{
"log", "org.apache.openjpa.event.LogOrphanedKeyAction",
"exception", "org.apache.openjpa.event.ExceptionOrphanedKeyAction",
"none", "org.apache.openjpa.event.NoneOrphanedKeyAction",
};
orphanedKeyPlugin.setAliases(aliases);
orphanedKeyPlugin.setDefault(aliases[0]);
orphanedKeyPlugin.setString(aliases[0]);
orphanedKeyPlugin.setInstantiatingGetter
("getOrphanedKeyActionInstance");
remoteProviderPlugin = new RemoteCommitProviderValue();
addValue(remoteProviderPlugin);
transactionMode = addBoolean("TransactionMode");
aliases = new String[]{
"local", "false",
"managed", "true",
};
transactionMode.setAliases(aliases);
transactionMode.setDefault(aliases[0]);
managedRuntimePlugin =
addPlugin("ManagedRuntime", true);
aliases = new String[]{
"auto", "org.apache.openjpa.ee.AutomaticManagedRuntime",
"jndi", "org.apache.openjpa.ee.JNDIManagedRuntime",
"invocation", "org.apache.openjpa.ee.InvocationManagedRuntime",
};
managedRuntimePlugin.setAliases(aliases);
managedRuntimePlugin.setDefault(aliases[0]);
managedRuntimePlugin.setString(aliases[0]);
managedRuntimePlugin.setInstantiatingGetter
("getManagedRuntimeInstance");
proxyManagerPlugin = addPlugin("ProxyManager", true);
aliases = new String[]{ "default",
"org.apache.openjpa.util.ProxyManagerImpl" };
proxyManagerPlugin.setAliases(aliases);
proxyManagerPlugin.setDefault(aliases[0]);
proxyManagerPlugin.setString(aliases[0]);
proxyManagerPlugin.setInstantiatingGetter("getProxyManagerInstance");
mapping = addString("Mapping");
metaFactoryPlugin =
addPlugin("MetaDataFactory", false);
connectionFactory = addObject("ConnectionFactory");
connectionFactory.setInstantiatingGetter("getConnectionFactory");
connectionFactory2 = addObject("ConnectionFactory2");
connectionFactory2.setInstantiatingGetter("getConnectionFactory2");
connectionUserName = addString("ConnectionUserName");
connectionPassword = addString("ConnectionPassword");
connectionURL = addString("ConnectionURL");
connectionDriverName =
addString("ConnectionDriverName");
connectionFactoryName =
addString("ConnectionFactoryName");
connectionProperties =
addString("ConnectionProperties");
connectionFactoryProperties = addString("ConnectionFactoryProperties");
connection2UserName =
addString("Connection2UserName");
connection2Password =
addString("Connection2Password");
connection2URL = addString("Connection2URL");
connection2DriverName =
addString("Connection2DriverName");
connection2Properties =
addString("Connection2Properties");
connectionFactory2Properties = addString(
"ConnectionFactory2Properties");
connectionFactory2Name =
addString("ConnectionFactory2Name");
connectionFactoryMode =
addBoolean("ConnectionFactoryMode");
aliases = new String[]{
"local", "false",
"managed", "true",
};
connectionFactoryMode.setAliases(aliases);
connectionFactoryMode.setDefault(aliases[0]);
optimistic = addBoolean("Optimistic");
optimistic.setDefault("true");
optimistic.set(true);
autoClear = addInt("AutoClear");
aliases = new String[]{
"datastore", String.valueOf(AutoClear.CLEAR_DATASTORE),
"all", String.valueOf(AutoClear.CLEAR_ALL),
};
autoClear.setAliases(aliases);
autoClear.setDefault(aliases[0]);
autoClear.set(AutoClear.CLEAR_DATASTORE);
retainState = addBoolean("RetainState");
retainState.setDefault("true");
retainState.set(true);
restoreState = addInt("RestoreState");
aliases = new String[]{
"none", String.valueOf(RestoreState.RESTORE_NONE),
"false", String.valueOf(RestoreState.RESTORE_NONE),
"immutable", String.valueOf(RestoreState.RESTORE_IMMUTABLE),
// "true" for compat with jdo RestoreValues
"true", String.valueOf(RestoreState.RESTORE_IMMUTABLE),
"all", String.valueOf(RestoreState.RESTORE_ALL),
};
restoreState.setAliases(aliases);
restoreState.setDefault(aliases[0]);
restoreState.set(RestoreState.RESTORE_IMMUTABLE);
autoDetach = new AutoDetachValue();
addValue(autoDetach);
detachStatePlugin = addPlugin("DetachState", true);
aliases = new String[]{
"loaded", DetachOptions.Loaded.class.getName(),
"fgs", DetachOptions.FetchGroups.class.getName(),
"all", DetachOptions.All.class.getName(),
};
detachStatePlugin.setAliases(aliases);
detachStatePlugin.setDefault(aliases[0]);
detachStatePlugin.setString(aliases[0]);
detachStatePlugin.setInstantiatingGetter("getDetachStateInstance");
ignoreChanges = addBoolean("IgnoreChanges");
nontransactionalRead =
addBoolean("NontransactionalRead");
nontransactionalRead.setDefault("true");
nontransactionalRead.set(true);
nontransactionalWrite =
addBoolean("NontransactionalWrite");
multithreaded = addBoolean("Multithreaded");
fetchBatchSize = addInt("FetchBatchSize");
fetchBatchSize.setDefault("-1");
fetchBatchSize.set(-1);
fetchGroups = addStringList("FetchGroups");
fetchGroups.setDefault("default");
fetchGroups.set(new String[]{ "default" });
flushBeforeQueries = addInt("FlushBeforeQueries");
aliases = new String[]{
"true", String.valueOf(QueryFlushModes.FLUSH_TRUE),
"false", String.valueOf(QueryFlushModes.FLUSH_FALSE),
"with-connection", String.valueOf
(QueryFlushModes.FLUSH_WITH_CONNECTION),
};
flushBeforeQueries.setAliases(aliases);
flushBeforeQueries.setDefault(aliases[0]);
flushBeforeQueries.set(QueryFlushModes.FLUSH_TRUE);
lockTimeout = addInt("LockTimeout");
lockTimeout.setDefault("-1");
lockTimeout.set(-1);
readLockLevel = addInt("ReadLockLevel");
aliases = new String[]{
"read", String.valueOf(LockLevels.LOCK_READ),
"write", String.valueOf(LockLevels.LOCK_WRITE),
"none", String.valueOf(LockLevels.LOCK_NONE),
};
readLockLevel.setAliases(aliases);
readLockLevel.setDefault(aliases[0]);
readLockLevel.set(LockLevels.LOCK_READ);
writeLockLevel = addInt("WriteLockLevel");
aliases = new String[]{
"read", String.valueOf(LockLevels.LOCK_READ),
"write", String.valueOf(LockLevels.LOCK_WRITE),
"none", String.valueOf(LockLevels.LOCK_NONE),
};
writeLockLevel.setAliases(aliases);
writeLockLevel.setDefault(aliases[1]);
writeLockLevel.set(LockLevels.LOCK_WRITE);
seqPlugin = new SeqValue("Sequence");
seqPlugin.setInstantiatingGetter("getSequenceInstance");
addValue(seqPlugin);
connectionRetainMode =
addInt("ConnectionRetainMode");
aliases = new String[]{
"on-demand",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_DEMAND),
"transaction",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_TRANS),
"always",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_ALWAYS),
// deprecated
"persistence-manager",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_ALWAYS),
};
connectionRetainMode.setAliases(aliases);
connectionRetainMode.setDefault(aliases[0]);
connectionRetainMode.setAliasListComprehensive(true);
connectionRetainMode.set(ConnectionRetainModes.CONN_RETAIN_DEMAND);
filterListenerPlugins =
addPluginList("FilterListeners");
filterListenerPlugins.setInstantiatingGetter
("getFilterListenerInstances");
aggregateListenerPlugins =
addPluginList("AggregateListeners");
aggregateListenerPlugins.setInstantiatingGetter
("getAggregateListenerInstances");
retryClassRegistration =
addBoolean("RetryClassRegistration");
compatibilityPlugin =
addPlugin("Compatibility", true);
aliases = new String[]{ "default", Compatibility.class.getName() };
compatibilityPlugin.setAliases(aliases);
compatibilityPlugin.setDefault(aliases[0]);
compatibilityPlugin.setString(aliases[0]);
compatibilityPlugin.setInstantiatingGetter("getCompatibilityInstance");
// initialize supported options that some runtimes may not support
supportedOptions.add(OPTION_NONTRANS_READ);
supportedOptions.add(OPTION_OPTIMISTIC);
supportedOptions.add(OPTION_ID_APPLICATION);
supportedOptions.add(OPTION_ID_DATASTORE);
supportedOptions.add(OPTION_TYPE_COLLECTION);
supportedOptions.add(OPTION_TYPE_MAP);
supportedOptions.add(OPTION_TYPE_ARRAY);
supportedOptions.add(OPTION_NULL_CONTAINER);
supportedOptions.add(OPTION_EMBEDDED_RELATION);
supportedOptions.add(OPTION_EMBEDDED_COLLECTION_RELATION);
supportedOptions.add(OPTION_EMBEDDED_MAP_RELATION);
supportedOptions.add(OPTION_INC_FLUSH);
supportedOptions.add(OPTION_VALUE_AUTOASSIGN);
supportedOptions.add(OPTION_VALUE_INCREMENT);
supportedOptions.add(OPTION_DATASTORE_CONNECTION);
if (derivations)
ProductDerivations.beforeConfigurationLoad(this);
if (loadDefaults)
loadDefaults();
}
| public OpenJPAConfigurationImpl(boolean derivations, boolean loadDefaults) {
super(false);
String[] aliases;
// setup super's log factory plugin
logFactoryPlugin.setProperty("Log");
logFactoryPlugin
.setAlias("openjpa", "org.apache.openjpa.lib.log.LogFactoryImpl");
aliases = logFactoryPlugin.getAliases();
logFactoryPlugin.setDefault(aliases[0]);
logFactoryPlugin.setString(aliases[0]);
classResolverPlugin =
addPlugin("ClassResolver", true);
aliases = new String[]{
"default", "org.apache.openjpa.util.ClassResolverImpl",
// deprecated alias
"spec", "org.apache.openjpa.util.ClassResolverImpl",
};
classResolverPlugin.setAliases(aliases);
classResolverPlugin.setDefault(aliases[0]);
classResolverPlugin.setString(aliases[0]);
classResolverPlugin.setInstantiatingGetter("getClassResolverInstance");
brokerFactoryPlugin = new BrokerFactoryValue();
addValue(brokerFactoryPlugin);
brokerPlugin = addPlugin("BrokerImpl", false);
aliases = new String[]{ "default", BrokerImpl.class.getName() };
brokerPlugin.setAliases(aliases);
brokerPlugin.setDefault(aliases[0]);
brokerPlugin.setString(aliases[0]);
dataCacheManagerPlugin =
addPlugin("DataCacheManager", true);
aliases = new String[]{
"default", DataCacheManagerImpl.class.getName(),
};
dataCacheManagerPlugin.setAliases(aliases);
dataCacheManagerPlugin.setDefault(aliases[0]);
dataCacheManagerPlugin.setString(aliases[0]);
dataCacheManagerPlugin.setInstantiatingGetter("getDataCacheManager");
dataCachePlugin = addPlugin("DataCache", false);
aliases = new String[]{
"false", null,
"true", ConcurrentDataCache.class.getName(),
"concurrent", ConcurrentDataCache.class.getName(),
};
dataCachePlugin.setAliases(aliases);
dataCachePlugin.setDefault(aliases[0]);
dataCachePlugin.setString(aliases[0]);
dataCacheTimeout = addInt("DataCacheTimeout");
dataCacheTimeout.setDefault("-1");
dataCacheTimeout.set(-1);
queryCachePlugin = addPlugin("QueryCache", true);
aliases = new String[]{
"true", ConcurrentQueryCache.class.getName(),
"concurrent", ConcurrentQueryCache.class.getName(),
"false", null,
};
queryCachePlugin.setAliases(aliases);
queryCachePlugin.setDefault(aliases[0]);
queryCachePlugin.setString(aliases[0]);
dynamicDataStructs =
addBoolean("DynamicDataStructs");
dynamicDataStructs.setDefault("false");
dynamicDataStructs.set(false);
lockManagerPlugin = addPlugin("LockManager", false);
aliases = new String[]{
"none", "org.apache.openjpa.kernel.NoneLockManager",
"version", "org.apache.openjpa.kernel.VersionLockManager",
};
lockManagerPlugin.setAliases(aliases);
lockManagerPlugin.setDefault(aliases[0]);
lockManagerPlugin.setString(aliases[0]);
inverseManagerPlugin =
addPlugin("InverseManager", false);
aliases = new String[]{
"false", null,
"true", "org.apache.openjpa.kernel.InverseManager",
};
inverseManagerPlugin.setAliases(aliases);
inverseManagerPlugin.setDefault(aliases[0]);
inverseManagerPlugin.setString(aliases[0]);
savepointManagerPlugin =
addPlugin("SavepointManager", true);
aliases = new String[]{
"in-mem", "org.apache.openjpa.kernel.InMemorySavepointManager",
};
savepointManagerPlugin.setAliases(aliases);
savepointManagerPlugin.setDefault(aliases[0]);
savepointManagerPlugin.setString(aliases[0]);
savepointManagerPlugin.setInstantiatingGetter
("getSavepointManagerInstance");
orphanedKeyPlugin =
addPlugin("OrphanedKeyAction", true);
aliases = new String[]{
"log", "org.apache.openjpa.event.LogOrphanedKeyAction",
"exception", "org.apache.openjpa.event.ExceptionOrphanedKeyAction",
"none", "org.apache.openjpa.event.NoneOrphanedKeyAction",
};
orphanedKeyPlugin.setAliases(aliases);
orphanedKeyPlugin.setDefault(aliases[0]);
orphanedKeyPlugin.setString(aliases[0]);
orphanedKeyPlugin.setInstantiatingGetter
("getOrphanedKeyActionInstance");
remoteProviderPlugin = new RemoteCommitProviderValue();
addValue(remoteProviderPlugin);
transactionMode = addBoolean("TransactionMode");
aliases = new String[]{
"local", "false",
"managed", "true",
};
transactionMode.setAliases(aliases);
transactionMode.setDefault(aliases[0]);
managedRuntimePlugin =
addPlugin("ManagedRuntime", true);
aliases = new String[]{
"auto", "org.apache.openjpa.ee.AutomaticManagedRuntime",
"jndi", "org.apache.openjpa.ee.JNDIManagedRuntime",
"invocation", "org.apache.openjpa.ee.InvocationManagedRuntime",
};
managedRuntimePlugin.setAliases(aliases);
managedRuntimePlugin.setDefault(aliases[0]);
managedRuntimePlugin.setString(aliases[0]);
managedRuntimePlugin.setInstantiatingGetter
("getManagedRuntimeInstance");
proxyManagerPlugin = addPlugin("ProxyManager", true);
aliases = new String[]{ "default",
"org.apache.openjpa.util.ProxyManagerImpl" };
proxyManagerPlugin.setAliases(aliases);
proxyManagerPlugin.setDefault(aliases[0]);
proxyManagerPlugin.setString(aliases[0]);
proxyManagerPlugin.setInstantiatingGetter("getProxyManagerInstance");
mapping = addString("Mapping");
metaFactoryPlugin = addPlugin("MetaDataFactory", false);
connectionFactory = addObject("ConnectionFactory");
connectionFactory.setInstantiatingGetter("getConnectionFactory");
connectionFactory2 = addObject("ConnectionFactory2");
connectionFactory2.setInstantiatingGetter("getConnectionFactory2");
connectionUserName = addString("ConnectionUserName");
connectionPassword = addString("ConnectionPassword");
connectionURL = addString("ConnectionURL");
connectionDriverName =
addString("ConnectionDriverName");
connectionFactoryName =
addString("ConnectionFactoryName");
connectionProperties =
addString("ConnectionProperties");
connectionFactoryProperties = addString("ConnectionFactoryProperties");
connection2UserName =
addString("Connection2UserName");
connection2Password =
addString("Connection2Password");
connection2URL = addString("Connection2URL");
connection2DriverName =
addString("Connection2DriverName");
connection2Properties =
addString("Connection2Properties");
connectionFactory2Properties = addString(
"ConnectionFactory2Properties");
connectionFactory2Name =
addString("ConnectionFactory2Name");
connectionFactoryMode =
addBoolean("ConnectionFactoryMode");
aliases = new String[]{
"local", "false",
"managed", "true",
};
connectionFactoryMode.setAliases(aliases);
connectionFactoryMode.setDefault(aliases[0]);
optimistic = addBoolean("Optimistic");
optimistic.setDefault("true");
optimistic.set(true);
autoClear = addInt("AutoClear");
aliases = new String[]{
"datastore", String.valueOf(AutoClear.CLEAR_DATASTORE),
"all", String.valueOf(AutoClear.CLEAR_ALL),
};
autoClear.setAliases(aliases);
autoClear.setDefault(aliases[0]);
autoClear.set(AutoClear.CLEAR_DATASTORE);
retainState = addBoolean("RetainState");
retainState.setDefault("true");
retainState.set(true);
restoreState = addInt("RestoreState");
aliases = new String[]{
"none", String.valueOf(RestoreState.RESTORE_NONE),
"false", String.valueOf(RestoreState.RESTORE_NONE),
"immutable", String.valueOf(RestoreState.RESTORE_IMMUTABLE),
// "true" for compat with jdo RestoreValues
"true", String.valueOf(RestoreState.RESTORE_IMMUTABLE),
"all", String.valueOf(RestoreState.RESTORE_ALL),
};
restoreState.setAliases(aliases);
restoreState.setDefault(aliases[0]);
restoreState.set(RestoreState.RESTORE_IMMUTABLE);
autoDetach = new AutoDetachValue();
addValue(autoDetach);
detachStatePlugin = addPlugin("DetachState", true);
aliases = new String[]{
"loaded", DetachOptions.Loaded.class.getName(),
"fgs", DetachOptions.FetchGroups.class.getName(),
"all", DetachOptions.All.class.getName(),
};
detachStatePlugin.setAliases(aliases);
detachStatePlugin.setDefault(aliases[0]);
detachStatePlugin.setString(aliases[0]);
detachStatePlugin.setInstantiatingGetter("getDetachStateInstance");
ignoreChanges = addBoolean("IgnoreChanges");
nontransactionalRead =
addBoolean("NontransactionalRead");
nontransactionalRead.setDefault("true");
nontransactionalRead.set(true);
nontransactionalWrite =
addBoolean("NontransactionalWrite");
multithreaded = addBoolean("Multithreaded");
fetchBatchSize = addInt("FetchBatchSize");
fetchBatchSize.setDefault("-1");
fetchBatchSize.set(-1);
fetchGroups = addStringList("FetchGroups");
fetchGroups.setDefault("default");
fetchGroups.set(new String[]{ "default" });
flushBeforeQueries = addInt("FlushBeforeQueries");
aliases = new String[]{
"true", String.valueOf(QueryFlushModes.FLUSH_TRUE),
"false", String.valueOf(QueryFlushModes.FLUSH_FALSE),
"with-connection", String.valueOf
(QueryFlushModes.FLUSH_WITH_CONNECTION),
};
flushBeforeQueries.setAliases(aliases);
flushBeforeQueries.setDefault(aliases[0]);
flushBeforeQueries.set(QueryFlushModes.FLUSH_TRUE);
lockTimeout = addInt("LockTimeout");
lockTimeout.setDefault("-1");
lockTimeout.set(-1);
readLockLevel = addInt("ReadLockLevel");
aliases = new String[]{
"read", String.valueOf(LockLevels.LOCK_READ),
"write", String.valueOf(LockLevels.LOCK_WRITE),
"none", String.valueOf(LockLevels.LOCK_NONE),
};
readLockLevel.setAliases(aliases);
readLockLevel.setDefault(aliases[0]);
readLockLevel.set(LockLevels.LOCK_READ);
writeLockLevel = addInt("WriteLockLevel");
aliases = new String[]{
"read", String.valueOf(LockLevels.LOCK_READ),
"write", String.valueOf(LockLevels.LOCK_WRITE),
"none", String.valueOf(LockLevels.LOCK_NONE),
};
writeLockLevel.setAliases(aliases);
writeLockLevel.setDefault(aliases[1]);
writeLockLevel.set(LockLevels.LOCK_WRITE);
seqPlugin = new SeqValue("Sequence");
seqPlugin.setInstantiatingGetter("getSequenceInstance");
addValue(seqPlugin);
connectionRetainMode =
addInt("ConnectionRetainMode");
aliases = new String[]{
"on-demand",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_DEMAND),
"transaction",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_TRANS),
"always",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_ALWAYS),
// deprecated
"persistence-manager",
String.valueOf(ConnectionRetainModes.CONN_RETAIN_ALWAYS),
};
connectionRetainMode.setAliases(aliases);
connectionRetainMode.setDefault(aliases[0]);
connectionRetainMode.setAliasListComprehensive(true);
connectionRetainMode.set(ConnectionRetainModes.CONN_RETAIN_DEMAND);
filterListenerPlugins =
addPluginList("FilterListeners");
filterListenerPlugins.setInstantiatingGetter
("getFilterListenerInstances");
aggregateListenerPlugins =
addPluginList("AggregateListeners");
aggregateListenerPlugins.setInstantiatingGetter
("getAggregateListenerInstances");
retryClassRegistration =
addBoolean("RetryClassRegistration");
compatibilityPlugin =
addPlugin("Compatibility", true);
aliases = new String[]{ "default", Compatibility.class.getName() };
compatibilityPlugin.setAliases(aliases);
compatibilityPlugin.setDefault(aliases[0]);
compatibilityPlugin.setString(aliases[0]);
compatibilityPlugin.setInstantiatingGetter("getCompatibilityInstance");
// initialize supported options that some runtimes may not support
supportedOptions.add(OPTION_NONTRANS_READ);
supportedOptions.add(OPTION_OPTIMISTIC);
supportedOptions.add(OPTION_ID_APPLICATION);
supportedOptions.add(OPTION_ID_DATASTORE);
supportedOptions.add(OPTION_TYPE_COLLECTION);
supportedOptions.add(OPTION_TYPE_MAP);
supportedOptions.add(OPTION_TYPE_ARRAY);
supportedOptions.add(OPTION_NULL_CONTAINER);
supportedOptions.add(OPTION_EMBEDDED_RELATION);
supportedOptions.add(OPTION_EMBEDDED_COLLECTION_RELATION);
supportedOptions.add(OPTION_EMBEDDED_MAP_RELATION);
supportedOptions.add(OPTION_INC_FLUSH);
supportedOptions.add(OPTION_VALUE_AUTOASSIGN);
supportedOptions.add(OPTION_VALUE_INCREMENT);
supportedOptions.add(OPTION_DATASTORE_CONNECTION);
if (derivations)
ProductDerivations.beforeConfigurationLoad(this);
if (loadDefaults)
loadDefaults();
}
|
diff --git a/src/jpcsp/graphics/RE/software/RendererTemplate.java b/src/jpcsp/graphics/RE/software/RendererTemplate.java
index c9343691..7ad8530f 100644
--- a/src/jpcsp/graphics/RE/software/RendererTemplate.java
+++ b/src/jpcsp/graphics/RE/software/RendererTemplate.java
@@ -1,1776 +1,1776 @@
/*
This file is part of jpcsp.
Jpcsp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jpcsp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.graphics.RE.software;
import static jpcsp.graphics.GeCommands.LMODE_SEPARATE_SPECULAR_COLOR;
import static jpcsp.graphics.GeCommands.SOP_REPLACE_STENCIL_VALUE;
import static jpcsp.graphics.GeCommands.TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888;
import static jpcsp.graphics.RE.software.PixelColor.addComponent;
import static jpcsp.graphics.RE.software.PixelColor.doubleColor;
import static jpcsp.graphics.RE.software.PixelColor.ONE;
import static jpcsp.graphics.RE.software.PixelColor.ZERO;
import static jpcsp.graphics.RE.software.PixelColor.absBGR;
import static jpcsp.graphics.RE.software.PixelColor.add;
import static jpcsp.graphics.RE.software.PixelColor.addBGR;
import static jpcsp.graphics.RE.software.PixelColor.combineComponent;
import static jpcsp.graphics.RE.software.PixelColor.doubleComponent;
import static jpcsp.graphics.RE.software.PixelColor.getAlpha;
import static jpcsp.graphics.RE.software.PixelColor.getBlue;
import static jpcsp.graphics.RE.software.PixelColor.getColor;
import static jpcsp.graphics.RE.software.PixelColor.getColorBGR;
import static jpcsp.graphics.RE.software.PixelColor.getGreen;
import static jpcsp.graphics.RE.software.PixelColor.getRed;
import static jpcsp.graphics.RE.software.PixelColor.maxBGR;
import static jpcsp.graphics.RE.software.PixelColor.minBGR;
import static jpcsp.graphics.RE.software.PixelColor.multiply;
import static jpcsp.graphics.RE.software.PixelColor.multiplyBGR;
import static jpcsp.graphics.RE.software.PixelColor.multiplyComponent;
import static jpcsp.graphics.RE.software.PixelColor.setAlpha;
import static jpcsp.graphics.RE.software.PixelColor.setBGR;
import static jpcsp.graphics.RE.software.PixelColor.substractBGR;
import static jpcsp.graphics.RE.software.PixelColor.substractComponent;
import static jpcsp.util.Utilities.pixelToTexel;
import static jpcsp.util.Utilities.wrap;
import static jpcsp.util.Utilities.clamp;
import static jpcsp.util.Utilities.dot3;
import static jpcsp.util.Utilities.max;
import static jpcsp.util.Utilities.min;
import static jpcsp.util.Utilities.normalize3;
import static jpcsp.util.Utilities.round;
import jpcsp.graphics.GeCommands;
import jpcsp.graphics.VideoEngine;
import jpcsp.graphics.RE.software.Rasterizer.Range;
import jpcsp.util.DurationStatistics;
/**
* @author gid15
*
*/
public class RendererTemplate {
public static boolean hasMemInt;
public static boolean needSourceDepthRead;
public static boolean needDestinationDepthRead;
public static boolean needDepthWrite;
public static boolean needTextureUV;
public static boolean simpleTextureUV;
public static boolean swapTextureUV;
public static boolean needScissoringX;
public static boolean needScissoringY;
public static boolean transform2D;
public static boolean clearMode;
public static boolean clearModeColor;
public static boolean clearModeStencil;
public static boolean clearModeDepth;
public static int nearZ;
public static int farZ;
public static boolean colorTestFlagEnabled;
public static int colorTestFunc;
public static boolean alphaTestFlagEnabled;
public static int alphaFunc;
public static int alphaRef;
public static boolean stencilTestFlagEnabled;
public static int stencilFunc;
public static int stencilRef;
public static int stencilOpFail;
public static int stencilOpZFail;
public static int stencilOpZPass;
public static boolean depthTestFlagEnabled;
public static int depthFunc;
public static boolean blendFlagEnabled;
public static int blendEquation;
public static int blendSrc;
public static int blendDst;
public static int sfix;
public static int dfix;
public static boolean colorLogicOpFlagEnabled;
public static int logicOp;
public static int colorMask;
public static boolean depthMask;
public static boolean textureFlagEnabled;
public static boolean useVertexTexture;
public static boolean lightingFlagEnabled;
public static boolean sameVertexColor;
public static boolean setVertexPrimaryColor;
public static boolean primaryColorSetGlobally;
public static boolean isTriangle;
public static boolean matFlagAmbient;
public static boolean matFlagDiffuse;
public static boolean matFlagSpecular;
public static boolean useVertexColor;
public static boolean textureColorDoubled;
public static int lightMode;
public static int texMapMode;
public static int texProjMapMode;
public static float texTranslateX;
public static float texTranslateY;
public static float texScaleX;
public static float texScaleY;
public static int texWrapS;
public static int texWrapT;
public static int textureFunc;
public static boolean textureAlphaUsed;
public static int psm;
public static int texMagFilter;
public static boolean needTextureWrapU;
public static boolean needTextureWrapV;
public static boolean needSourceDepthClamp;
public static boolean isLogTraceEnabled;
public static boolean collectStatistics;
public static boolean ditherFlagEnabled;
private static final boolean resampleTextureForMag = true;
private static DurationStatistics statistics;
public RendererTemplate() {
if (collectStatistics) {
if (statistics == null) {
statistics = new DurationStatistics(String.format("Duration %s", getClass().getName()));
}
}
}
public static boolean isRendererWriterNative(int[] memInt, int psm) {
return memInt != null && psm == GeCommands.TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888;
}
public DurationStatistics getStatistics() {
return statistics;
}
public void render(final BasePrimitiveRenderer renderer) {
doRender(renderer);
}
private static void doRenderStart(final BasePrimitiveRenderer renderer) {
if (isLogTraceEnabled) {
final PrimitiveState prim = renderer.prim;
String comment;
if (isTriangle) {
if (transform2D) {
comment = "Triangle doRender 2D";
} else {
comment = "Triangle doRender 3D";
}
} else {
if (transform2D) {
comment = "Sprite doRender 2D";
} else {
comment = "Sprite doRender 3D";
}
}
VideoEngine.log.trace(String.format("%s (%d,%d)-(%d,%d) skip=%d", comment, prim.pxMin, prim.pyMin, prim.pxMax, prim.pyMax, renderer.imageWriterSkipEOL));
}
renderer.preRender();
if (collectStatistics) {
if (isTriangle) {
if (transform2D) {
RESoftware.triangleRender2DStatistics.start();
} else {
RESoftware.triangleRender3DStatistics.start();
}
} else {
RESoftware.spriteRenderStatistics.start();
}
statistics.start();
}
}
private static void doRenderEnd(final BasePrimitiveRenderer renderer) {
if (collectStatistics) {
statistics.end();
if (isTriangle) {
if (transform2D) {
RESoftware.triangleRender2DStatistics.end();
} else {
RESoftware.triangleRender3DStatistics.end();
}
} else {
RESoftware.spriteRenderStatistics.end();
}
}
renderer.postRender();
}
private static IRandomTextureAccess resampleTexture(final BasePrimitiveRenderer renderer) {
IRandomTextureAccess textureAccess = renderer.textureAccess;
renderer.prim.needResample = false;
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
if (texMagFilter == GeCommands.TFLT_LINEAR) {
final PrimitiveState prim = renderer.prim;
if (needTextureUV && simpleTextureUV && transform2D) {
if (renderer.cachedTexture != null) {
if (Math.abs(prim.uStep) != 1f || Math.abs(prim.vStep) != 1f) {
prim.resampleFactorWidth = 1f / Math.abs(prim.uStep);
prim.resampleFactorHeight = 1f / Math.abs(prim.vStep);
if (renderer.cachedTexture.canResample(prim.resampleFactorWidth, prim.resampleFactorHeight)) {
prim.needResample = true;
prim.uStart *= prim.resampleFactorWidth;
prim.vStart *= prim.resampleFactorHeight;
prim.uStep = prim.uStep < 0f ? -1f : 1f;
prim.vStep = prim.vStep < 0f ? -1f : 1f;
} else if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Cannot resample with factors %f, %f", prim.resampleFactorWidth, prim.resampleFactorHeight));
}
}
}
} else {
if (resampleTextureForMag && !transform2D && renderer.cachedTexture != null) {
prim.resampleFactorWidth = 2f;
prim.resampleFactorHeight = 2f;
prim.needResample = renderer.cachedTexture.canResample(prim.resampleFactorWidth, prim.resampleFactorHeight);
}
}
}
}
return textureAccess;
}
private static void doRender(final BasePrimitiveRenderer renderer) {
final PixelState pixel = renderer.pixel;
final PrimitiveState prim = renderer.prim;
final IRendererWriter rendererWriter = renderer.rendererWriter;
final Lighting lighting = renderer.lighting;
IRandomTextureAccess textureAccess = resampleTexture(renderer);
doRenderStart(renderer);
int stencilRefAlpha = 0;
if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) {
if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) {
// Prepare stencilRef as a ready-to-use alpha value
stencilRefAlpha = renderer.stencilRef << 24;
}
}
int stencilRefMasked = renderer.stencilRef & renderer.stencilMask;
int notColorMask = 0xFFFFFFFF;
if (!clearMode && colorMask != 0x00000000) {
notColorMask = ~renderer.colorMask;
}
int alpha, a, b, g, r;
int textureWidthMask = renderer.textureWidth - 1;
int textureHeightMask = renderer.textureHeight - 1;
float textureWidthFloat = renderer.textureWidth;
float textureHeightFloat = renderer.textureHeight;
final int alphaRef = renderer.alphaRef;
final int primSourceDepth = (int) prim.p2z;
float u = prim.uStart;
float v = prim.vStart;
ColorDepth colorDepth = new ColorDepth();
PrimarySecondaryColors colors = new PrimarySecondaryColors();
Range range = null;
Rasterizer rasterizer = null;
float t1uw = 0f;
float t1vw = 0f;
float t2uw = 0f;
float t2vw = 0f;
float t3uw = 0f;
float t3vw = 0f;
if (isTriangle) {
if (transform2D) {
t1uw = prim.t1u;
t1vw = prim.t1v;
t2uw = prim.t2u;
t2vw = prim.t2v;
t3uw = prim.t3u;
t3vw = prim.t3v;
} else {
t1uw = prim.t1u * prim.p1wInverted;
t1vw = prim.t1v * prim.p1wInverted;
t2uw = prim.t2u * prim.p2wInverted;
t2vw = prim.t2v * prim.p2wInverted;
t3uw = prim.t3u * prim.p3wInverted;
t3vw = prim.t3v * prim.p3wInverted;
}
range = new Range();
// No need to use a Rasterizer when rendering very small area.
// The overhead of the Rasterizer would lead to slower rendering.
if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) {
rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax);
rasterizer.setY(prim.pyMin);
}
}
int fbIndex = 0;
int depthIndex = 0;
int depthOffset = 0;
final int[] memInt = renderer.memInt;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex = renderer.fbAddress >> 2;
depthIndex = renderer.depthAddress >> 2;
depthOffset = (renderer.depthAddress >> 1) & 1;
}
// Use local variables instead of "pixel" members.
// The Java JIT is then producing a slightly faster code.
int sourceColor = 0;
int sourceDepth = 0;
int destinationColor = 0;
int destinationDepth = 0;
int primaryColor = renderer.primaryColor;
int secondaryColor = 0;
float pixelU = 0f;
float pixelV = 0f;
boolean needResample = prim.needResample;
for (int y = prim.pyMin; y <= prim.pyMax; y++) {
int startX = prim.pxMin;
int endX = prim.pxMax;
if (isTriangle && rasterizer != null) {
rasterizer.getNextRange(range);
startX = max(range.xMin, startX);
endX = min(range.xMax, endX);
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, y));
}
}
if (isTriangle && startX > endX) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL);
}
} else {
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v = prim.vStart;
} else {
u = prim.uStart;
}
}
if (isTriangle) {
int startSkip = startX - prim.pxMin;
if (startSkip > 0) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += startSkip;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += startSkip;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(startSkip, startSkip);
}
if (simpleTextureUV) {
if (swapTextureUV) {
v += startSkip * prim.vStep;
} else {
u += startSkip * prim.uStep;
}
}
}
prim.computeTriangleWeights(pixel, startX, y);
}
for (int x = startX; x <= endX; x++) {
// Use a dummy "do { } while (false);" loop to allow to exit
// quickly from the pixel rendering when a filter does not pass.
// When a filter does not pass, the following is executed:
// rendererWriter.skip(1, 1); // Skip the pixel
// continue;
do {
//
// Test if the pixel is inside the triangle
//
if (isTriangle && !pixel.isInsideTriangle()) {
// Pixel not inside triangle, skip the pixel
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, y, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
//
// Start rendering the pixel
//
if (transform2D) {
pixel.newPixel2D();
} else {
pixel.newPixel3D();
}
//
// ScissorTest (performed as soon as the pixel screen coordinates are available)
//
if (transform2D) {
if (needScissoringX && needScissoringY) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2 && y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringX) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringY) {
if (!(y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel source depth
//
if (needSourceDepthRead) {
if (isTriangle) {
sourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z));
} else {
sourceDepth = primSourceDepth;
}
}
//
// ScissorDepthTest (performed as soon as the pixel source depth is available)
//
if (!transform2D && !clearMode && needSourceDepthRead) {
if (nearZ != 0x0000 || farZ != 0xFFFF) {
if (sourceDepth < renderer.nearZ || sourceDepth > renderer.farZ) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel destination color and depth
//
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
destinationColor = memInt[fbIndex];
if (needDestinationDepthRead) {
if (depthOffset == 0) {
destinationDepth = memInt[depthIndex] & 0x0000FFFF;
} else {
destinationDepth = memInt[depthIndex] >>> 16;
}
}
} else {
rendererWriter.readCurrent(colorDepth);
destinationColor = colorDepth.color;
if (needDestinationDepthRead) {
destinationDepth = colorDepth.depth;
}
}
//
// StencilTest (performed as soon as destination color is known)
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilFunc) {
case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
// Nothing to do
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES:
if ((getAlpha(destinationColor) & renderer.stencilMask) != stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS:
if ((getAlpha(destinationColor) & renderer.stencilMask) == stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS:
if ((getAlpha(destinationColor) & renderer.stencilMask) >= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) > stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER:
if ((getAlpha(destinationColor) & renderer.stencilMask) <= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) < stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// DepthTest (performed as soon as depths are known, but after the stencil test)
//
if (depthTestFlagEnabled && !clearMode) {
switch (depthFunc) {
case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL:
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL:
// No filter required
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL:
if (sourceDepth != destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL:
if (sourceDepth == destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS:
if (sourceDepth >= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL:
if (sourceDepth > destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER:
if (sourceDepth <= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL:
if (sourceDepth < destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// Primary color
//
if (setVertexPrimaryColor) {
if (isTriangle) {
if (sameVertexColor) {
primaryColor = pixel.c3;
} else {
primaryColor = pixel.getTriangleColorWeightedValue();
}
}
}
//
// Material Flags
//
if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) {
if (matFlagAmbient) {
pixel.materialAmbient = primaryColor;
}
if (matFlagDiffuse) {
pixel.materialDiffuse = primaryColor;
}
if (matFlagSpecular) {
pixel.materialSpecular = primaryColor;
}
}
//
// Lighting
//
if (lightingFlagEnabled && !transform2D) {
lighting.applyLighting(colors, pixel);
primaryColor = colors.primaryColor;
secondaryColor = colors.secondaryColor;
}
//
// Pixel texture U,V
//
if (needTextureUV) {
if (simpleTextureUV) {
pixelU = u;
pixelV = v;
} else {
// Compute the mapped texture u,v coordinates
// based on the Barycentric coordinates.
pixelU = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw);
pixelV = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw);
if (!transform2D) {
// In 3D, apply a perspective correction by weighting
// the coordinates by their "w" value. See
// http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted);
pixelU *= weightInverted;
pixelV *= weightInverted;
}
}
}
//
// Texture
//
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
//
// TextureMapping
//
if (!transform2D) {
switch (texMapMode) {
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (texScaleX != 1f) {
pixelU *= renderer.texScaleX;
}
if (texTranslateX != 0f) {
pixelU += renderer.texTranslateX;
}
if (texScaleY != 1f) {
pixelV *= renderer.texScaleY;
}
if (texTranslateY != 0f) {
pixelV += renderer.texTranslateY;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
switch (texProjMapMode) {
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION:
final float[] V = pixel.getV();
pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
float tu = pixelU;
float tv = pixelV;
pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12];
pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13];
//pixelQ = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
final float[] normalizedN = pixel.getNormalizedN();
pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
final float[] N = pixel.getN();
pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
// Implementation based on shader.vert/ApplyTexture:
//
// vec3 Nn = normalize(N);
// vec3 Ve = vec3(gl_ModelViewMatrix * V);
// float k = gl_FrontMaterial.shininess;
// vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w;
// vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w;
// float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k);
// float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k);
// T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0);
//
final float[] Ve = new float[3];
final float[] Ne = new float[3];
final float[] Lu = new float[3];
final float[] Lv = new float[3];
pixel.getVe(Ve);
pixel.getNormalizedNe(Ne);
for (int i = 0; i < 3; i++) {
Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3];
Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3];
}
float Pu;
if (renderer.envMapDiffuseLightU) {
normalize3(Lu, Lu);
Pu = dot3(Ne, Lu);
} else {
Lu[2] += 1f;
normalize3(Lu, Lu);
Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess);
}
float Pv;
if (renderer.envMapDiffuseLightV) {
normalize3(Lv, Lv);
Pv = dot3(Ne, Lv);
} else {
Lv[2] += 1f;
normalize3(Lv, Lv);
Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess);
}
pixelU = (Pu + 1f) * 0.5f;
pixelV = (Pv + 1f) * 0.5f;
//pixelQ = 1f;
break;
}
}
//
// Texture resampling (as late as possible)
//
if (texMagFilter == GeCommands.TFLT_LINEAR) {
if (needResample) {
// Perform the resampling as late as possible.
// We might be lucky that all the pixel are eliminated
// by the depth or stencil tests. In which case,
// we don't need to resample.
textureAccess = renderer.cachedTexture.resample(prim.resampleFactorWidth, prim.resampleFactorHeight);
textureWidthMask = textureAccess.getWidth() - 1;
textureHeightMask = textureAccess.getHeight() - 1;
textureWidthFloat = textureAccess.getWidth();
textureHeightFloat = textureAccess.getHeight();
needResample = false;
}
}
//
// TextureWrap
//
if (needTextureWrapU) {
switch (texWrapS) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelU = wrap(pixelU, textureWidthMask);
} else {
pixelU = wrap(pixelU);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelU = clamp(pixelU, 0f, textureWidthMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelU = clamp(pixelU, 0f, 0.99999f);
}
break;
}
}
if (needTextureWrapV) {
switch (texWrapT) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelV = wrap(pixelV, textureHeightMask);
} else {
pixelV = wrap(pixelV);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelV = clamp(pixelV, 0f, textureHeightMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelV = clamp(pixelV, 0f, 0.99999f);
}
break;
}
}
//
// TextureReader
//
if (transform2D) {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV));
} else {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat));
}
//
// TextureFunction
//
switch (textureFunc) {
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE:
if (textureAlphaUsed) {
sourceColor = multiply(sourceColor, primaryColor);
} else {
sourceColor = multiply(sourceColor | 0xFF000000, primaryColor);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL:
if (textureAlphaUsed) {
alpha = getAlpha(sourceColor);
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), getBlue(sourceColor), alpha);
g = combineComponent(getGreen(primaryColor), getGreen(sourceColor), alpha);
r = combineComponent(getRed(primaryColor), getRed(sourceColor), alpha);
sourceColor = getColor(a, b, g, r);
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
} else {
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE:
if (!textureAlphaUsed) {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
sourceColor = setAlpha(addBGR(sourceColor, primaryColor), a);
} else {
sourceColor = add(sourceColor & 0x00FFFFFF, primaryColor);
}
break;
}
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = doubleColor(sourceColor);
secondaryColor = doubleColor(secondaryColor);
} else {
sourceColor = doubleColor(sourceColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(sourceColor, secondaryColor);
}
} else {
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
primaryColor = doubleColor(primaryColor);
secondaryColor = doubleColor(secondaryColor);
} else if (!primaryColorSetGlobally) {
primaryColor = doubleColor(primaryColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(primaryColor, secondaryColor);
} else {
sourceColor = primaryColor;
}
}
//
// ColorTest
//
if (colorTestFlagEnabled && !clearMode) {
switch (colorTestFunc) {
case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES:
if ((sourceColor & renderer.colorTestMsk) != renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS:
if ((sourceColor & renderer.colorTestMsk) == renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// AlphaTest
//
if (alphaTestFlagEnabled && !clearMode) {
switch (alphaFunc) {
case GeCommands.ATST_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.ATST_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ATST_PASS_PIXEL_IF_MATCHES:
if (getAlpha(sourceColor) != alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS:
if (getAlpha(sourceColor) == alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS:
if (getAlpha(sourceColor) >= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
// No test if alphaRef==0xFF
if (RendererTemplate.alphaRef < 0xFF) {
if (getAlpha(sourceColor) > alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER:
if (getAlpha(sourceColor) <= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
// No test if alphaRef==0x00
if (RendererTemplate.alphaRef > 0x00) {
if (getAlpha(sourceColor) < alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
}
}
//
// AlphaBlend
//
if (blendFlagEnabled && !clearMode) {
int filteredSrc;
int filteredDst;
switch (blendEquation) {
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD:
if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) {
// Nothing to do, this is a NOP
} else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) {
sourceColor = PixelColor.add(sourceColor, destinationColor & 0x00FFFFFF);
} else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) {
// This is the most common case and can be optimized
int srcAlpha = sourceColor >>> 24;
if (srcAlpha == ZERO) {
// Set color of destination
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else if (srcAlpha == ONE) {
// Nothing to change
} else {
int oneMinusSrcAlpha = ONE - srcAlpha;
filteredSrc = multiplyBGR(sourceColor, srcAlpha, srcAlpha, srcAlpha);
filteredDst = multiplyBGR(destinationColor, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha);
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
} else {
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredSrc, filteredDst));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredDst, filteredSrc));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, minBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, maxBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, absBGR(sourceColor, destinationColor));
break;
}
}
if (ditherFlagEnabled) {
int ditherValue = renderer.ditherMatrix[((y & 0x3) << 2) + (x & 0x3)];
if (ditherValue > 0) {
b = addComponent(getBlue(sourceColor), ditherValue);
g = addComponent(getGreen(sourceColor), ditherValue);
r = addComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
} else if (ditherValue < 0) {
ditherValue = -ditherValue;
b = substractComponent(getBlue(sourceColor), ditherValue);
g = substractComponent(getGreen(sourceColor), ditherValue);
r = substractComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
}
}
//
// StencilOpZPass
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilOpZPass) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
break;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
sourceColor &= 0x00FFFFFF;
break;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
sourceColor &= 0x00FFFFFF;
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | stencilRefAlpha;
}
break;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | ((~destinationColor) & 0xFF000000);
break;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
}
} else if (!clearMode) {
// Write the alpha/stencil value to the frame buffer
// only when the stencil test is enabled
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
//
// ColorLogicalOperation
//
if (colorLogicOpFlagEnabled && !clearMode) {
switch (logicOp) {
case GeCommands.LOP_CLEAR:
sourceColor = ZERO;
break;
case GeCommands.LOP_AND:
sourceColor &= destinationColor;
break;
case GeCommands.LOP_REVERSE_AND:
sourceColor &= (~destinationColor);
break;
case GeCommands.LOP_COPY:
// This is a NOP
break;
case GeCommands.LOP_INVERTED_AND:
sourceColor = (~sourceColor) & destinationColor;
break;
case GeCommands.LOP_NO_OPERATION:
sourceColor = destinationColor;
break;
case GeCommands.LOP_EXLUSIVE_OR:
sourceColor ^= destinationColor;
break;
case GeCommands.LOP_OR:
sourceColor |= destinationColor;
break;
case GeCommands.LOP_NEGATED_OR:
sourceColor = ~(sourceColor | destinationColor);
break;
case GeCommands.LOP_EQUIVALENCE:
sourceColor = ~(sourceColor ^ destinationColor);
break;
case GeCommands.LOP_INVERTED:
sourceColor = ~destinationColor;
break;
case GeCommands.LOP_REVERSE_OR:
sourceColor |= (~destinationColor);
break;
case GeCommands.LOP_INVERTED_COPY:
sourceColor = ~sourceColor;
break;
case GeCommands.LOP_INVERTED_OR:
sourceColor = (~sourceColor) | destinationColor;
break;
case GeCommands.LOP_NEGATED_AND:
sourceColor = ~(sourceColor & destinationColor);
break;
case GeCommands.LOP_SET:
sourceColor = 0xFFFFFFFF;
break;
}
}
//
// ColorMask
//
if (clearMode) {
if (clearModeColor) {
if (!clearModeStencil) {
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
} else {
if (clearModeStencil) {
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else {
sourceColor = destinationColor;
}
}
} else {
if (colorMask != 0x00000000) {
- sourceColor = (sourceColor & notColorMask) | (destinationColor & colorMask);
+ sourceColor = (sourceColor & notColorMask) | (destinationColor & renderer.colorMask);
}
}
//
// DepthMask
//
if (needDepthWrite) {
if (clearMode) {
if (!clearModeDepth) {
sourceDepth = destinationDepth;
}
} else if (!depthTestFlagEnabled) {
// Depth writes are disabled when the depth test is not enabled.
sourceDepth = destinationDepth;
} else if (!depthMask) {
sourceDepth = destinationDepth;
}
}
//
// Filter passed
//
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (needDepthWrite && needSourceDepthClamp) {
// Clamp between 0 and 65535
sourceDepth = Math.max(0, Math.min(sourceDepth, 65535));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
memInt[fbIndex] = sourceColor;
fbIndex++;
if (needDepthWrite) {
if (depthOffset == 0) {
memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (sourceDepth & 0x0000FFFF);
depthOffset = 1;
} else {
memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (sourceDepth << 16);
depthIndex++;
depthOffset = 0;
}
} else if (needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
if (needDepthWrite) {
colorDepth.color = sourceColor;
colorDepth.depth = sourceDepth;
rendererWriter.writeNext(colorDepth);
} else {
rendererWriter.writeNextColor(sourceColor);
}
}
} while (false);
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v += prim.vStep;
} else {
u += prim.uStep;
}
}
if (isTriangle) {
prim.deltaXTriangleWeigths(pixel);
}
}
int skip = prim.pxMax - endX;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += skip + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += skip + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL);
}
}
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
u += prim.uStep;
} else {
v += prim.vStep;
}
}
}
doRenderEnd(renderer);
}
protected static int stencilOpFail(int destination, int stencilRefAlpha) {
int alpha;
switch (stencilOpFail) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
return destination;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
return destination & 0x00FFFFFF;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
return destination & 0x00FFFFFF;
}
return (destination & 0x00FFFFFF) | stencilRefAlpha;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
return destination ^ 0xFF000000;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
}
return destination;
}
protected static int stencilOpZFail(int destination, int stencilRefAlpha) {
int alpha;
switch (stencilOpZFail) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
return destination;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
return destination & 0x00FFFFFF;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
return destination & 0x00FFFFFF;
}
return (destination & 0x00FFFFFF) | stencilRefAlpha;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
return destination ^ 0xFF000000;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
}
return destination;
}
protected static int blendSrc(int source, int destination, int fix) {
int alpha;
switch (blendSrc) {
case GeCommands.ALPHA_SOURCE_COLOR:
return source;
case GeCommands.ALPHA_ONE_MINUS_SOURCE_COLOR:
return 0xFFFFFFFF - source;
case GeCommands.ALPHA_SOURCE_ALPHA:
alpha = getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA:
alpha = ONE - getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DESTINATION_ALPHA:
alpha = getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DESTINATION_ALPHA:
alpha = ONE - getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_SOURCE_ALPHA:
alpha = doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_SOURCE_ALPHA:
alpha = ONE - doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_DESTINATION_ALPHA:
alpha = doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_DESTINATION_ALPHA:
alpha = ONE - doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_FIX:
return fix;
}
return source;
}
protected static int blendDst(int source, int destination, int fix) {
int alpha;
switch (blendDst) {
case GeCommands.ALPHA_DESTINATION_COLOR:
return destination;
case GeCommands.ALPHA_ONE_MINUS_DESTINATION_COLOR:
return 0xFFFFFFFF - destination;
case GeCommands.ALPHA_SOURCE_ALPHA:
alpha = getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA:
alpha = ONE - getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DESTINATION_ALPHA:
alpha = getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DESTINATION_ALPHA:
alpha = ONE - getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_SOURCE_ALPHA:
alpha = doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_SOURCE_ALPHA:
alpha = ONE - doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_DESTINATION_ALPHA:
alpha = doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_DESTINATION_ALPHA:
alpha = ONE - doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_FIX:
return fix;
}
return destination;
}
}
| true | true | private static void doRender(final BasePrimitiveRenderer renderer) {
final PixelState pixel = renderer.pixel;
final PrimitiveState prim = renderer.prim;
final IRendererWriter rendererWriter = renderer.rendererWriter;
final Lighting lighting = renderer.lighting;
IRandomTextureAccess textureAccess = resampleTexture(renderer);
doRenderStart(renderer);
int stencilRefAlpha = 0;
if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) {
if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) {
// Prepare stencilRef as a ready-to-use alpha value
stencilRefAlpha = renderer.stencilRef << 24;
}
}
int stencilRefMasked = renderer.stencilRef & renderer.stencilMask;
int notColorMask = 0xFFFFFFFF;
if (!clearMode && colorMask != 0x00000000) {
notColorMask = ~renderer.colorMask;
}
int alpha, a, b, g, r;
int textureWidthMask = renderer.textureWidth - 1;
int textureHeightMask = renderer.textureHeight - 1;
float textureWidthFloat = renderer.textureWidth;
float textureHeightFloat = renderer.textureHeight;
final int alphaRef = renderer.alphaRef;
final int primSourceDepth = (int) prim.p2z;
float u = prim.uStart;
float v = prim.vStart;
ColorDepth colorDepth = new ColorDepth();
PrimarySecondaryColors colors = new PrimarySecondaryColors();
Range range = null;
Rasterizer rasterizer = null;
float t1uw = 0f;
float t1vw = 0f;
float t2uw = 0f;
float t2vw = 0f;
float t3uw = 0f;
float t3vw = 0f;
if (isTriangle) {
if (transform2D) {
t1uw = prim.t1u;
t1vw = prim.t1v;
t2uw = prim.t2u;
t2vw = prim.t2v;
t3uw = prim.t3u;
t3vw = prim.t3v;
} else {
t1uw = prim.t1u * prim.p1wInverted;
t1vw = prim.t1v * prim.p1wInverted;
t2uw = prim.t2u * prim.p2wInverted;
t2vw = prim.t2v * prim.p2wInverted;
t3uw = prim.t3u * prim.p3wInverted;
t3vw = prim.t3v * prim.p3wInverted;
}
range = new Range();
// No need to use a Rasterizer when rendering very small area.
// The overhead of the Rasterizer would lead to slower rendering.
if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) {
rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax);
rasterizer.setY(prim.pyMin);
}
}
int fbIndex = 0;
int depthIndex = 0;
int depthOffset = 0;
final int[] memInt = renderer.memInt;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex = renderer.fbAddress >> 2;
depthIndex = renderer.depthAddress >> 2;
depthOffset = (renderer.depthAddress >> 1) & 1;
}
// Use local variables instead of "pixel" members.
// The Java JIT is then producing a slightly faster code.
int sourceColor = 0;
int sourceDepth = 0;
int destinationColor = 0;
int destinationDepth = 0;
int primaryColor = renderer.primaryColor;
int secondaryColor = 0;
float pixelU = 0f;
float pixelV = 0f;
boolean needResample = prim.needResample;
for (int y = prim.pyMin; y <= prim.pyMax; y++) {
int startX = prim.pxMin;
int endX = prim.pxMax;
if (isTriangle && rasterizer != null) {
rasterizer.getNextRange(range);
startX = max(range.xMin, startX);
endX = min(range.xMax, endX);
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, y));
}
}
if (isTriangle && startX > endX) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL);
}
} else {
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v = prim.vStart;
} else {
u = prim.uStart;
}
}
if (isTriangle) {
int startSkip = startX - prim.pxMin;
if (startSkip > 0) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += startSkip;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += startSkip;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(startSkip, startSkip);
}
if (simpleTextureUV) {
if (swapTextureUV) {
v += startSkip * prim.vStep;
} else {
u += startSkip * prim.uStep;
}
}
}
prim.computeTriangleWeights(pixel, startX, y);
}
for (int x = startX; x <= endX; x++) {
// Use a dummy "do { } while (false);" loop to allow to exit
// quickly from the pixel rendering when a filter does not pass.
// When a filter does not pass, the following is executed:
// rendererWriter.skip(1, 1); // Skip the pixel
// continue;
do {
//
// Test if the pixel is inside the triangle
//
if (isTriangle && !pixel.isInsideTriangle()) {
// Pixel not inside triangle, skip the pixel
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, y, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
//
// Start rendering the pixel
//
if (transform2D) {
pixel.newPixel2D();
} else {
pixel.newPixel3D();
}
//
// ScissorTest (performed as soon as the pixel screen coordinates are available)
//
if (transform2D) {
if (needScissoringX && needScissoringY) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2 && y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringX) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringY) {
if (!(y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel source depth
//
if (needSourceDepthRead) {
if (isTriangle) {
sourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z));
} else {
sourceDepth = primSourceDepth;
}
}
//
// ScissorDepthTest (performed as soon as the pixel source depth is available)
//
if (!transform2D && !clearMode && needSourceDepthRead) {
if (nearZ != 0x0000 || farZ != 0xFFFF) {
if (sourceDepth < renderer.nearZ || sourceDepth > renderer.farZ) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel destination color and depth
//
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
destinationColor = memInt[fbIndex];
if (needDestinationDepthRead) {
if (depthOffset == 0) {
destinationDepth = memInt[depthIndex] & 0x0000FFFF;
} else {
destinationDepth = memInt[depthIndex] >>> 16;
}
}
} else {
rendererWriter.readCurrent(colorDepth);
destinationColor = colorDepth.color;
if (needDestinationDepthRead) {
destinationDepth = colorDepth.depth;
}
}
//
// StencilTest (performed as soon as destination color is known)
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilFunc) {
case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
// Nothing to do
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES:
if ((getAlpha(destinationColor) & renderer.stencilMask) != stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS:
if ((getAlpha(destinationColor) & renderer.stencilMask) == stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS:
if ((getAlpha(destinationColor) & renderer.stencilMask) >= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) > stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER:
if ((getAlpha(destinationColor) & renderer.stencilMask) <= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) < stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// DepthTest (performed as soon as depths are known, but after the stencil test)
//
if (depthTestFlagEnabled && !clearMode) {
switch (depthFunc) {
case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL:
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL:
// No filter required
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL:
if (sourceDepth != destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL:
if (sourceDepth == destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS:
if (sourceDepth >= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL:
if (sourceDepth > destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER:
if (sourceDepth <= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL:
if (sourceDepth < destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// Primary color
//
if (setVertexPrimaryColor) {
if (isTriangle) {
if (sameVertexColor) {
primaryColor = pixel.c3;
} else {
primaryColor = pixel.getTriangleColorWeightedValue();
}
}
}
//
// Material Flags
//
if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) {
if (matFlagAmbient) {
pixel.materialAmbient = primaryColor;
}
if (matFlagDiffuse) {
pixel.materialDiffuse = primaryColor;
}
if (matFlagSpecular) {
pixel.materialSpecular = primaryColor;
}
}
//
// Lighting
//
if (lightingFlagEnabled && !transform2D) {
lighting.applyLighting(colors, pixel);
primaryColor = colors.primaryColor;
secondaryColor = colors.secondaryColor;
}
//
// Pixel texture U,V
//
if (needTextureUV) {
if (simpleTextureUV) {
pixelU = u;
pixelV = v;
} else {
// Compute the mapped texture u,v coordinates
// based on the Barycentric coordinates.
pixelU = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw);
pixelV = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw);
if (!transform2D) {
// In 3D, apply a perspective correction by weighting
// the coordinates by their "w" value. See
// http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted);
pixelU *= weightInverted;
pixelV *= weightInverted;
}
}
}
//
// Texture
//
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
//
// TextureMapping
//
if (!transform2D) {
switch (texMapMode) {
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (texScaleX != 1f) {
pixelU *= renderer.texScaleX;
}
if (texTranslateX != 0f) {
pixelU += renderer.texTranslateX;
}
if (texScaleY != 1f) {
pixelV *= renderer.texScaleY;
}
if (texTranslateY != 0f) {
pixelV += renderer.texTranslateY;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
switch (texProjMapMode) {
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION:
final float[] V = pixel.getV();
pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
float tu = pixelU;
float tv = pixelV;
pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12];
pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13];
//pixelQ = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
final float[] normalizedN = pixel.getNormalizedN();
pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
final float[] N = pixel.getN();
pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
// Implementation based on shader.vert/ApplyTexture:
//
// vec3 Nn = normalize(N);
// vec3 Ve = vec3(gl_ModelViewMatrix * V);
// float k = gl_FrontMaterial.shininess;
// vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w;
// vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w;
// float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k);
// float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k);
// T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0);
//
final float[] Ve = new float[3];
final float[] Ne = new float[3];
final float[] Lu = new float[3];
final float[] Lv = new float[3];
pixel.getVe(Ve);
pixel.getNormalizedNe(Ne);
for (int i = 0; i < 3; i++) {
Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3];
Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3];
}
float Pu;
if (renderer.envMapDiffuseLightU) {
normalize3(Lu, Lu);
Pu = dot3(Ne, Lu);
} else {
Lu[2] += 1f;
normalize3(Lu, Lu);
Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess);
}
float Pv;
if (renderer.envMapDiffuseLightV) {
normalize3(Lv, Lv);
Pv = dot3(Ne, Lv);
} else {
Lv[2] += 1f;
normalize3(Lv, Lv);
Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess);
}
pixelU = (Pu + 1f) * 0.5f;
pixelV = (Pv + 1f) * 0.5f;
//pixelQ = 1f;
break;
}
}
//
// Texture resampling (as late as possible)
//
if (texMagFilter == GeCommands.TFLT_LINEAR) {
if (needResample) {
// Perform the resampling as late as possible.
// We might be lucky that all the pixel are eliminated
// by the depth or stencil tests. In which case,
// we don't need to resample.
textureAccess = renderer.cachedTexture.resample(prim.resampleFactorWidth, prim.resampleFactorHeight);
textureWidthMask = textureAccess.getWidth() - 1;
textureHeightMask = textureAccess.getHeight() - 1;
textureWidthFloat = textureAccess.getWidth();
textureHeightFloat = textureAccess.getHeight();
needResample = false;
}
}
//
// TextureWrap
//
if (needTextureWrapU) {
switch (texWrapS) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelU = wrap(pixelU, textureWidthMask);
} else {
pixelU = wrap(pixelU);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelU = clamp(pixelU, 0f, textureWidthMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelU = clamp(pixelU, 0f, 0.99999f);
}
break;
}
}
if (needTextureWrapV) {
switch (texWrapT) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelV = wrap(pixelV, textureHeightMask);
} else {
pixelV = wrap(pixelV);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelV = clamp(pixelV, 0f, textureHeightMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelV = clamp(pixelV, 0f, 0.99999f);
}
break;
}
}
//
// TextureReader
//
if (transform2D) {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV));
} else {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat));
}
//
// TextureFunction
//
switch (textureFunc) {
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE:
if (textureAlphaUsed) {
sourceColor = multiply(sourceColor, primaryColor);
} else {
sourceColor = multiply(sourceColor | 0xFF000000, primaryColor);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL:
if (textureAlphaUsed) {
alpha = getAlpha(sourceColor);
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), getBlue(sourceColor), alpha);
g = combineComponent(getGreen(primaryColor), getGreen(sourceColor), alpha);
r = combineComponent(getRed(primaryColor), getRed(sourceColor), alpha);
sourceColor = getColor(a, b, g, r);
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
} else {
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE:
if (!textureAlphaUsed) {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
sourceColor = setAlpha(addBGR(sourceColor, primaryColor), a);
} else {
sourceColor = add(sourceColor & 0x00FFFFFF, primaryColor);
}
break;
}
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = doubleColor(sourceColor);
secondaryColor = doubleColor(secondaryColor);
} else {
sourceColor = doubleColor(sourceColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(sourceColor, secondaryColor);
}
} else {
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
primaryColor = doubleColor(primaryColor);
secondaryColor = doubleColor(secondaryColor);
} else if (!primaryColorSetGlobally) {
primaryColor = doubleColor(primaryColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(primaryColor, secondaryColor);
} else {
sourceColor = primaryColor;
}
}
//
// ColorTest
//
if (colorTestFlagEnabled && !clearMode) {
switch (colorTestFunc) {
case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES:
if ((sourceColor & renderer.colorTestMsk) != renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS:
if ((sourceColor & renderer.colorTestMsk) == renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// AlphaTest
//
if (alphaTestFlagEnabled && !clearMode) {
switch (alphaFunc) {
case GeCommands.ATST_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.ATST_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ATST_PASS_PIXEL_IF_MATCHES:
if (getAlpha(sourceColor) != alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS:
if (getAlpha(sourceColor) == alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS:
if (getAlpha(sourceColor) >= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
// No test if alphaRef==0xFF
if (RendererTemplate.alphaRef < 0xFF) {
if (getAlpha(sourceColor) > alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER:
if (getAlpha(sourceColor) <= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
// No test if alphaRef==0x00
if (RendererTemplate.alphaRef > 0x00) {
if (getAlpha(sourceColor) < alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
}
}
//
// AlphaBlend
//
if (blendFlagEnabled && !clearMode) {
int filteredSrc;
int filteredDst;
switch (blendEquation) {
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD:
if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) {
// Nothing to do, this is a NOP
} else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) {
sourceColor = PixelColor.add(sourceColor, destinationColor & 0x00FFFFFF);
} else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) {
// This is the most common case and can be optimized
int srcAlpha = sourceColor >>> 24;
if (srcAlpha == ZERO) {
// Set color of destination
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else if (srcAlpha == ONE) {
// Nothing to change
} else {
int oneMinusSrcAlpha = ONE - srcAlpha;
filteredSrc = multiplyBGR(sourceColor, srcAlpha, srcAlpha, srcAlpha);
filteredDst = multiplyBGR(destinationColor, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha);
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
} else {
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredSrc, filteredDst));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredDst, filteredSrc));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, minBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, maxBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, absBGR(sourceColor, destinationColor));
break;
}
}
if (ditherFlagEnabled) {
int ditherValue = renderer.ditherMatrix[((y & 0x3) << 2) + (x & 0x3)];
if (ditherValue > 0) {
b = addComponent(getBlue(sourceColor), ditherValue);
g = addComponent(getGreen(sourceColor), ditherValue);
r = addComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
} else if (ditherValue < 0) {
ditherValue = -ditherValue;
b = substractComponent(getBlue(sourceColor), ditherValue);
g = substractComponent(getGreen(sourceColor), ditherValue);
r = substractComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
}
}
//
// StencilOpZPass
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilOpZPass) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
break;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
sourceColor &= 0x00FFFFFF;
break;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
sourceColor &= 0x00FFFFFF;
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | stencilRefAlpha;
}
break;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | ((~destinationColor) & 0xFF000000);
break;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
}
} else if (!clearMode) {
// Write the alpha/stencil value to the frame buffer
// only when the stencil test is enabled
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
//
// ColorLogicalOperation
//
if (colorLogicOpFlagEnabled && !clearMode) {
switch (logicOp) {
case GeCommands.LOP_CLEAR:
sourceColor = ZERO;
break;
case GeCommands.LOP_AND:
sourceColor &= destinationColor;
break;
case GeCommands.LOP_REVERSE_AND:
sourceColor &= (~destinationColor);
break;
case GeCommands.LOP_COPY:
// This is a NOP
break;
case GeCommands.LOP_INVERTED_AND:
sourceColor = (~sourceColor) & destinationColor;
break;
case GeCommands.LOP_NO_OPERATION:
sourceColor = destinationColor;
break;
case GeCommands.LOP_EXLUSIVE_OR:
sourceColor ^= destinationColor;
break;
case GeCommands.LOP_OR:
sourceColor |= destinationColor;
break;
case GeCommands.LOP_NEGATED_OR:
sourceColor = ~(sourceColor | destinationColor);
break;
case GeCommands.LOP_EQUIVALENCE:
sourceColor = ~(sourceColor ^ destinationColor);
break;
case GeCommands.LOP_INVERTED:
sourceColor = ~destinationColor;
break;
case GeCommands.LOP_REVERSE_OR:
sourceColor |= (~destinationColor);
break;
case GeCommands.LOP_INVERTED_COPY:
sourceColor = ~sourceColor;
break;
case GeCommands.LOP_INVERTED_OR:
sourceColor = (~sourceColor) | destinationColor;
break;
case GeCommands.LOP_NEGATED_AND:
sourceColor = ~(sourceColor & destinationColor);
break;
case GeCommands.LOP_SET:
sourceColor = 0xFFFFFFFF;
break;
}
}
//
// ColorMask
//
if (clearMode) {
if (clearModeColor) {
if (!clearModeStencil) {
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
} else {
if (clearModeStencil) {
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else {
sourceColor = destinationColor;
}
}
} else {
if (colorMask != 0x00000000) {
sourceColor = (sourceColor & notColorMask) | (destinationColor & colorMask);
}
}
//
// DepthMask
//
if (needDepthWrite) {
if (clearMode) {
if (!clearModeDepth) {
sourceDepth = destinationDepth;
}
} else if (!depthTestFlagEnabled) {
// Depth writes are disabled when the depth test is not enabled.
sourceDepth = destinationDepth;
} else if (!depthMask) {
sourceDepth = destinationDepth;
}
}
//
// Filter passed
//
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (needDepthWrite && needSourceDepthClamp) {
// Clamp between 0 and 65535
sourceDepth = Math.max(0, Math.min(sourceDepth, 65535));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
memInt[fbIndex] = sourceColor;
fbIndex++;
if (needDepthWrite) {
if (depthOffset == 0) {
memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (sourceDepth & 0x0000FFFF);
depthOffset = 1;
} else {
memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (sourceDepth << 16);
depthIndex++;
depthOffset = 0;
}
} else if (needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
if (needDepthWrite) {
colorDepth.color = sourceColor;
colorDepth.depth = sourceDepth;
rendererWriter.writeNext(colorDepth);
} else {
rendererWriter.writeNextColor(sourceColor);
}
}
} while (false);
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v += prim.vStep;
} else {
u += prim.uStep;
}
}
if (isTriangle) {
prim.deltaXTriangleWeigths(pixel);
}
}
int skip = prim.pxMax - endX;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += skip + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += skip + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL);
}
}
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
u += prim.uStep;
} else {
v += prim.vStep;
}
}
}
doRenderEnd(renderer);
}
| private static void doRender(final BasePrimitiveRenderer renderer) {
final PixelState pixel = renderer.pixel;
final PrimitiveState prim = renderer.prim;
final IRendererWriter rendererWriter = renderer.rendererWriter;
final Lighting lighting = renderer.lighting;
IRandomTextureAccess textureAccess = resampleTexture(renderer);
doRenderStart(renderer);
int stencilRefAlpha = 0;
if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) {
if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) {
// Prepare stencilRef as a ready-to-use alpha value
stencilRefAlpha = renderer.stencilRef << 24;
}
}
int stencilRefMasked = renderer.stencilRef & renderer.stencilMask;
int notColorMask = 0xFFFFFFFF;
if (!clearMode && colorMask != 0x00000000) {
notColorMask = ~renderer.colorMask;
}
int alpha, a, b, g, r;
int textureWidthMask = renderer.textureWidth - 1;
int textureHeightMask = renderer.textureHeight - 1;
float textureWidthFloat = renderer.textureWidth;
float textureHeightFloat = renderer.textureHeight;
final int alphaRef = renderer.alphaRef;
final int primSourceDepth = (int) prim.p2z;
float u = prim.uStart;
float v = prim.vStart;
ColorDepth colorDepth = new ColorDepth();
PrimarySecondaryColors colors = new PrimarySecondaryColors();
Range range = null;
Rasterizer rasterizer = null;
float t1uw = 0f;
float t1vw = 0f;
float t2uw = 0f;
float t2vw = 0f;
float t3uw = 0f;
float t3vw = 0f;
if (isTriangle) {
if (transform2D) {
t1uw = prim.t1u;
t1vw = prim.t1v;
t2uw = prim.t2u;
t2vw = prim.t2v;
t3uw = prim.t3u;
t3vw = prim.t3v;
} else {
t1uw = prim.t1u * prim.p1wInverted;
t1vw = prim.t1v * prim.p1wInverted;
t2uw = prim.t2u * prim.p2wInverted;
t2vw = prim.t2v * prim.p2wInverted;
t3uw = prim.t3u * prim.p3wInverted;
t3vw = prim.t3v * prim.p3wInverted;
}
range = new Range();
// No need to use a Rasterizer when rendering very small area.
// The overhead of the Rasterizer would lead to slower rendering.
if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) {
rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax);
rasterizer.setY(prim.pyMin);
}
}
int fbIndex = 0;
int depthIndex = 0;
int depthOffset = 0;
final int[] memInt = renderer.memInt;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex = renderer.fbAddress >> 2;
depthIndex = renderer.depthAddress >> 2;
depthOffset = (renderer.depthAddress >> 1) & 1;
}
// Use local variables instead of "pixel" members.
// The Java JIT is then producing a slightly faster code.
int sourceColor = 0;
int sourceDepth = 0;
int destinationColor = 0;
int destinationDepth = 0;
int primaryColor = renderer.primaryColor;
int secondaryColor = 0;
float pixelU = 0f;
float pixelV = 0f;
boolean needResample = prim.needResample;
for (int y = prim.pyMin; y <= prim.pyMax; y++) {
int startX = prim.pxMin;
int endX = prim.pxMax;
if (isTriangle && rasterizer != null) {
rasterizer.getNextRange(range);
startX = max(range.xMin, startX);
endX = min(range.xMax, endX);
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, y));
}
}
if (isTriangle && startX > endX) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL);
}
} else {
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v = prim.vStart;
} else {
u = prim.uStart;
}
}
if (isTriangle) {
int startSkip = startX - prim.pxMin;
if (startSkip > 0) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += startSkip;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += startSkip;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(startSkip, startSkip);
}
if (simpleTextureUV) {
if (swapTextureUV) {
v += startSkip * prim.vStep;
} else {
u += startSkip * prim.uStep;
}
}
}
prim.computeTriangleWeights(pixel, startX, y);
}
for (int x = startX; x <= endX; x++) {
// Use a dummy "do { } while (false);" loop to allow to exit
// quickly from the pixel rendering when a filter does not pass.
// When a filter does not pass, the following is executed:
// rendererWriter.skip(1, 1); // Skip the pixel
// continue;
do {
//
// Test if the pixel is inside the triangle
//
if (isTriangle && !pixel.isInsideTriangle()) {
// Pixel not inside triangle, skip the pixel
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, y, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
//
// Start rendering the pixel
//
if (transform2D) {
pixel.newPixel2D();
} else {
pixel.newPixel3D();
}
//
// ScissorTest (performed as soon as the pixel screen coordinates are available)
//
if (transform2D) {
if (needScissoringX && needScissoringY) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2 && y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringX) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringY) {
if (!(y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel source depth
//
if (needSourceDepthRead) {
if (isTriangle) {
sourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z));
} else {
sourceDepth = primSourceDepth;
}
}
//
// ScissorDepthTest (performed as soon as the pixel source depth is available)
//
if (!transform2D && !clearMode && needSourceDepthRead) {
if (nearZ != 0x0000 || farZ != 0xFFFF) {
if (sourceDepth < renderer.nearZ || sourceDepth > renderer.farZ) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel destination color and depth
//
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
destinationColor = memInt[fbIndex];
if (needDestinationDepthRead) {
if (depthOffset == 0) {
destinationDepth = memInt[depthIndex] & 0x0000FFFF;
} else {
destinationDepth = memInt[depthIndex] >>> 16;
}
}
} else {
rendererWriter.readCurrent(colorDepth);
destinationColor = colorDepth.color;
if (needDestinationDepthRead) {
destinationDepth = colorDepth.depth;
}
}
//
// StencilTest (performed as soon as destination color is known)
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilFunc) {
case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
// Nothing to do
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES:
if ((getAlpha(destinationColor) & renderer.stencilMask) != stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS:
if ((getAlpha(destinationColor) & renderer.stencilMask) == stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS:
if ((getAlpha(destinationColor) & renderer.stencilMask) >= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) > stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER:
if ((getAlpha(destinationColor) & renderer.stencilMask) <= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) < stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// DepthTest (performed as soon as depths are known, but after the stencil test)
//
if (depthTestFlagEnabled && !clearMode) {
switch (depthFunc) {
case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL:
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL:
// No filter required
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL:
if (sourceDepth != destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL:
if (sourceDepth == destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS:
if (sourceDepth >= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL:
if (sourceDepth > destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER:
if (sourceDepth <= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL:
if (sourceDepth < destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// Primary color
//
if (setVertexPrimaryColor) {
if (isTriangle) {
if (sameVertexColor) {
primaryColor = pixel.c3;
} else {
primaryColor = pixel.getTriangleColorWeightedValue();
}
}
}
//
// Material Flags
//
if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) {
if (matFlagAmbient) {
pixel.materialAmbient = primaryColor;
}
if (matFlagDiffuse) {
pixel.materialDiffuse = primaryColor;
}
if (matFlagSpecular) {
pixel.materialSpecular = primaryColor;
}
}
//
// Lighting
//
if (lightingFlagEnabled && !transform2D) {
lighting.applyLighting(colors, pixel);
primaryColor = colors.primaryColor;
secondaryColor = colors.secondaryColor;
}
//
// Pixel texture U,V
//
if (needTextureUV) {
if (simpleTextureUV) {
pixelU = u;
pixelV = v;
} else {
// Compute the mapped texture u,v coordinates
// based on the Barycentric coordinates.
pixelU = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw);
pixelV = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw);
if (!transform2D) {
// In 3D, apply a perspective correction by weighting
// the coordinates by their "w" value. See
// http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted);
pixelU *= weightInverted;
pixelV *= weightInverted;
}
}
}
//
// Texture
//
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
//
// TextureMapping
//
if (!transform2D) {
switch (texMapMode) {
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (texScaleX != 1f) {
pixelU *= renderer.texScaleX;
}
if (texTranslateX != 0f) {
pixelU += renderer.texTranslateX;
}
if (texScaleY != 1f) {
pixelV *= renderer.texScaleY;
}
if (texTranslateY != 0f) {
pixelV += renderer.texTranslateY;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
switch (texProjMapMode) {
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION:
final float[] V = pixel.getV();
pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
float tu = pixelU;
float tv = pixelV;
pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12];
pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13];
//pixelQ = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
final float[] normalizedN = pixel.getNormalizedN();
pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
final float[] N = pixel.getN();
pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
// Implementation based on shader.vert/ApplyTexture:
//
// vec3 Nn = normalize(N);
// vec3 Ve = vec3(gl_ModelViewMatrix * V);
// float k = gl_FrontMaterial.shininess;
// vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w;
// vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w;
// float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k);
// float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k);
// T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0);
//
final float[] Ve = new float[3];
final float[] Ne = new float[3];
final float[] Lu = new float[3];
final float[] Lv = new float[3];
pixel.getVe(Ve);
pixel.getNormalizedNe(Ne);
for (int i = 0; i < 3; i++) {
Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3];
Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3];
}
float Pu;
if (renderer.envMapDiffuseLightU) {
normalize3(Lu, Lu);
Pu = dot3(Ne, Lu);
} else {
Lu[2] += 1f;
normalize3(Lu, Lu);
Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess);
}
float Pv;
if (renderer.envMapDiffuseLightV) {
normalize3(Lv, Lv);
Pv = dot3(Ne, Lv);
} else {
Lv[2] += 1f;
normalize3(Lv, Lv);
Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess);
}
pixelU = (Pu + 1f) * 0.5f;
pixelV = (Pv + 1f) * 0.5f;
//pixelQ = 1f;
break;
}
}
//
// Texture resampling (as late as possible)
//
if (texMagFilter == GeCommands.TFLT_LINEAR) {
if (needResample) {
// Perform the resampling as late as possible.
// We might be lucky that all the pixel are eliminated
// by the depth or stencil tests. In which case,
// we don't need to resample.
textureAccess = renderer.cachedTexture.resample(prim.resampleFactorWidth, prim.resampleFactorHeight);
textureWidthMask = textureAccess.getWidth() - 1;
textureHeightMask = textureAccess.getHeight() - 1;
textureWidthFloat = textureAccess.getWidth();
textureHeightFloat = textureAccess.getHeight();
needResample = false;
}
}
//
// TextureWrap
//
if (needTextureWrapU) {
switch (texWrapS) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelU = wrap(pixelU, textureWidthMask);
} else {
pixelU = wrap(pixelU);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelU = clamp(pixelU, 0f, textureWidthMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelU = clamp(pixelU, 0f, 0.99999f);
}
break;
}
}
if (needTextureWrapV) {
switch (texWrapT) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelV = wrap(pixelV, textureHeightMask);
} else {
pixelV = wrap(pixelV);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelV = clamp(pixelV, 0f, textureHeightMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelV = clamp(pixelV, 0f, 0.99999f);
}
break;
}
}
//
// TextureReader
//
if (transform2D) {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV));
} else {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat));
}
//
// TextureFunction
//
switch (textureFunc) {
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE:
if (textureAlphaUsed) {
sourceColor = multiply(sourceColor, primaryColor);
} else {
sourceColor = multiply(sourceColor | 0xFF000000, primaryColor);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL:
if (textureAlphaUsed) {
alpha = getAlpha(sourceColor);
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), getBlue(sourceColor), alpha);
g = combineComponent(getGreen(primaryColor), getGreen(sourceColor), alpha);
r = combineComponent(getRed(primaryColor), getRed(sourceColor), alpha);
sourceColor = getColor(a, b, g, r);
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
} else {
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE:
if (!textureAlphaUsed) {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
sourceColor = setAlpha(addBGR(sourceColor, primaryColor), a);
} else {
sourceColor = add(sourceColor & 0x00FFFFFF, primaryColor);
}
break;
}
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = doubleColor(sourceColor);
secondaryColor = doubleColor(secondaryColor);
} else {
sourceColor = doubleColor(sourceColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(sourceColor, secondaryColor);
}
} else {
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
primaryColor = doubleColor(primaryColor);
secondaryColor = doubleColor(secondaryColor);
} else if (!primaryColorSetGlobally) {
primaryColor = doubleColor(primaryColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(primaryColor, secondaryColor);
} else {
sourceColor = primaryColor;
}
}
//
// ColorTest
//
if (colorTestFlagEnabled && !clearMode) {
switch (colorTestFunc) {
case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES:
if ((sourceColor & renderer.colorTestMsk) != renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS:
if ((sourceColor & renderer.colorTestMsk) == renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// AlphaTest
//
if (alphaTestFlagEnabled && !clearMode) {
switch (alphaFunc) {
case GeCommands.ATST_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.ATST_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ATST_PASS_PIXEL_IF_MATCHES:
if (getAlpha(sourceColor) != alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS:
if (getAlpha(sourceColor) == alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS:
if (getAlpha(sourceColor) >= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
// No test if alphaRef==0xFF
if (RendererTemplate.alphaRef < 0xFF) {
if (getAlpha(sourceColor) > alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER:
if (getAlpha(sourceColor) <= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
// No test if alphaRef==0x00
if (RendererTemplate.alphaRef > 0x00) {
if (getAlpha(sourceColor) < alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
}
}
//
// AlphaBlend
//
if (blendFlagEnabled && !clearMode) {
int filteredSrc;
int filteredDst;
switch (blendEquation) {
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD:
if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) {
// Nothing to do, this is a NOP
} else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) {
sourceColor = PixelColor.add(sourceColor, destinationColor & 0x00FFFFFF);
} else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) {
// This is the most common case and can be optimized
int srcAlpha = sourceColor >>> 24;
if (srcAlpha == ZERO) {
// Set color of destination
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else if (srcAlpha == ONE) {
// Nothing to change
} else {
int oneMinusSrcAlpha = ONE - srcAlpha;
filteredSrc = multiplyBGR(sourceColor, srcAlpha, srcAlpha, srcAlpha);
filteredDst = multiplyBGR(destinationColor, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha);
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
} else {
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredSrc, filteredDst));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredDst, filteredSrc));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, minBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, maxBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, absBGR(sourceColor, destinationColor));
break;
}
}
if (ditherFlagEnabled) {
int ditherValue = renderer.ditherMatrix[((y & 0x3) << 2) + (x & 0x3)];
if (ditherValue > 0) {
b = addComponent(getBlue(sourceColor), ditherValue);
g = addComponent(getGreen(sourceColor), ditherValue);
r = addComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
} else if (ditherValue < 0) {
ditherValue = -ditherValue;
b = substractComponent(getBlue(sourceColor), ditherValue);
g = substractComponent(getGreen(sourceColor), ditherValue);
r = substractComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
}
}
//
// StencilOpZPass
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilOpZPass) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
break;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
sourceColor &= 0x00FFFFFF;
break;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
sourceColor &= 0x00FFFFFF;
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | stencilRefAlpha;
}
break;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | ((~destinationColor) & 0xFF000000);
break;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
}
} else if (!clearMode) {
// Write the alpha/stencil value to the frame buffer
// only when the stencil test is enabled
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
//
// ColorLogicalOperation
//
if (colorLogicOpFlagEnabled && !clearMode) {
switch (logicOp) {
case GeCommands.LOP_CLEAR:
sourceColor = ZERO;
break;
case GeCommands.LOP_AND:
sourceColor &= destinationColor;
break;
case GeCommands.LOP_REVERSE_AND:
sourceColor &= (~destinationColor);
break;
case GeCommands.LOP_COPY:
// This is a NOP
break;
case GeCommands.LOP_INVERTED_AND:
sourceColor = (~sourceColor) & destinationColor;
break;
case GeCommands.LOP_NO_OPERATION:
sourceColor = destinationColor;
break;
case GeCommands.LOP_EXLUSIVE_OR:
sourceColor ^= destinationColor;
break;
case GeCommands.LOP_OR:
sourceColor |= destinationColor;
break;
case GeCommands.LOP_NEGATED_OR:
sourceColor = ~(sourceColor | destinationColor);
break;
case GeCommands.LOP_EQUIVALENCE:
sourceColor = ~(sourceColor ^ destinationColor);
break;
case GeCommands.LOP_INVERTED:
sourceColor = ~destinationColor;
break;
case GeCommands.LOP_REVERSE_OR:
sourceColor |= (~destinationColor);
break;
case GeCommands.LOP_INVERTED_COPY:
sourceColor = ~sourceColor;
break;
case GeCommands.LOP_INVERTED_OR:
sourceColor = (~sourceColor) | destinationColor;
break;
case GeCommands.LOP_NEGATED_AND:
sourceColor = ~(sourceColor & destinationColor);
break;
case GeCommands.LOP_SET:
sourceColor = 0xFFFFFFFF;
break;
}
}
//
// ColorMask
//
if (clearMode) {
if (clearModeColor) {
if (!clearModeStencil) {
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
} else {
if (clearModeStencil) {
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else {
sourceColor = destinationColor;
}
}
} else {
if (colorMask != 0x00000000) {
sourceColor = (sourceColor & notColorMask) | (destinationColor & renderer.colorMask);
}
}
//
// DepthMask
//
if (needDepthWrite) {
if (clearMode) {
if (!clearModeDepth) {
sourceDepth = destinationDepth;
}
} else if (!depthTestFlagEnabled) {
// Depth writes are disabled when the depth test is not enabled.
sourceDepth = destinationDepth;
} else if (!depthMask) {
sourceDepth = destinationDepth;
}
}
//
// Filter passed
//
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (needDepthWrite && needSourceDepthClamp) {
// Clamp between 0 and 65535
sourceDepth = Math.max(0, Math.min(sourceDepth, 65535));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
memInt[fbIndex] = sourceColor;
fbIndex++;
if (needDepthWrite) {
if (depthOffset == 0) {
memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (sourceDepth & 0x0000FFFF);
depthOffset = 1;
} else {
memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (sourceDepth << 16);
depthIndex++;
depthOffset = 0;
}
} else if (needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
if (needDepthWrite) {
colorDepth.color = sourceColor;
colorDepth.depth = sourceDepth;
rendererWriter.writeNext(colorDepth);
} else {
rendererWriter.writeNextColor(sourceColor);
}
}
} while (false);
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v += prim.vStep;
} else {
u += prim.uStep;
}
}
if (isTriangle) {
prim.deltaXTriangleWeigths(pixel);
}
}
int skip = prim.pxMax - endX;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += skip + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += skip + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL);
}
}
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
u += prim.uStep;
} else {
v += prim.vStep;
}
}
}
doRenderEnd(renderer);
}
|
diff --git a/core/src/main/java/hudson/ExtensionList.java b/core/src/main/java/hudson/ExtensionList.java
index a667e630d..5e519928d 100644
--- a/core/src/main/java/hudson/ExtensionList.java
+++ b/core/src/main/java/hudson/ExtensionList.java
@@ -1,274 +1,274 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc.
*
* 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 hudson;
import hudson.init.InitMilestone;
import hudson.model.Hudson;
import hudson.util.DescriptorList;
import hudson.util.Memoizer;
import hudson.util.Iterators;
import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.util.Comparator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Retains the known extension instances for the given type 'T'.
*
* <p>
* Extensions are loaded lazily on demand and automatically by using {@link ExtensionFinder}, but this
* class also provides a mechanism to provide compatibility with the older {@link DescriptorList}-based
* manual registration,
*
* <p>
* All {@link ExtensionList} instances should be owned by {@link Hudson}, even though
* extension points can be defined by anyone on any type. Use {@link Hudson#getExtensionList(Class)}
* and {@link Hudson#getDescriptorList(Class)} to obtain the instances.
*
* @param <T>
* Type of the extension point. This class holds instances of the subtypes of 'T'.
*
* @author Kohsuke Kawaguchi
* @since 1.286
* @see Hudson#getExtensionList(Class)
* @see Hudson#getDescriptorList(Class)
*/
public class ExtensionList<T> extends AbstractList<T> {
public final Hudson hudson;
public final Class<T> extensionType;
/**
* Once discovered, extensions are retained here.
*/
@CopyOnWrite
private volatile List<T> extensions;
/**
* Place to store manually registered instances with the per-Hudson scope.
* {@link CopyOnWriteArrayList} is used here to support concurrent iterations and mutation.
*/
private final CopyOnWriteArrayList<T> legacyInstances;
protected ExtensionList(Hudson hudson, Class<T> extensionType) {
this(hudson,extensionType,new CopyOnWriteArrayList<T>());
}
/**
*
* @param legacyStore
* Place to store manually registered instances. The version of the constructor that
* omits this uses a new {@link Vector}, making the storage lifespan tied to the life of {@link ExtensionList}.
* If the manually registered instances are scoped to VM level, the caller should pass in a static list.
*/
protected ExtensionList(Hudson hudson, Class<T> extensionType, CopyOnWriteArrayList<T> legacyStore) {
this.hudson = hudson;
this.extensionType = extensionType;
this.legacyInstances = legacyStore;
}
/**
* Looks for the extension instance of the given type (subclasses excluded),
* or return null.
*/
public <U extends T> U get(Class<U> type) {
for (T ext : this)
if(ext.getClass()==type)
return type.cast(ext);
return null;
}
@Override
public Iterator<T> iterator() {
// we need to intercept mutation, so for now don't allow Iterator.remove
return Iterators.readOnly(ensureLoaded().iterator());
}
public T get(int index) {
return ensureLoaded().get(index);
}
public int size() {
return ensureLoaded().size();
}
@Override
public synchronized boolean remove(Object o) {
legacyInstances.remove(o);
if(extensions!=null) {
List<T> r = new ArrayList<T>(extensions);
r.remove(o);
extensions = sort(r);
}
return true;
}
@Override
public synchronized T remove(int index) {
T t = get(index);
remove(t);
return t;
}
/**
* Write access will put the instance into a legacy store.
*
* @deprecated since 2009-02-23.
* Prefer automatic registration.
*/
@Override
public synchronized boolean add(T t) {
legacyInstances.add(t);
// if we've already filled extensions, add it
if(extensions!=null) {
List<T> r = new ArrayList<T>(extensions);
r.add(t);
extensions = sort(r);
}
return true;
}
@Override
public void add(int index, T element) {
add(element);
}
/**
* Used to bind extension to URLs by their class names.
*
* @since 1.349
*/
public T getDynamic(String className) {
for (T t : this)
if (t.getClass().getName().equals(className))
return t;
return null;
}
/**
* Returns {@link ExtensionFinder}s used to search for the extension instances.
*/
protected Iterable<? extends ExtensionFinder> finders() {
return hudson.getExtensionList(ExtensionFinder.class);
}
private List<T> ensureLoaded() {
if(extensions!=null)
return extensions; // already loaded
if(Hudson.getInstance().getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED)<0)
return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible
synchronized (this) {
if(extensions==null) {
List<T> r = load();
r.addAll(legacyInstances);
extensions = sort(r);
}
return extensions;
}
}
/**
* Loads all the extensions.
*/
protected List<T> load() {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE,"Loading ExtensionList: "+extensionType, new Throwable());
List<T> r = new ArrayList<T>();
for (ExtensionFinder finder : finders())
r.addAll(finder.findExtensions(extensionType, hudson));
return r;
}
/**
* If the {@link ExtensionList} implementation requires sorting extensions,
* override this method to do so.
*
* <p>
* The implementation should copy a list, do a sort, and return the new instance.
*/
protected List<T> sort(List<T> r) {
r = new ArrayList<T>(r);
Collections.sort(r,new Comparator<T>() {
public int compare(T lhs, T rhs) {
Extension el = lhs.getClass().getAnnotation(Extension.class);
Extension er = rhs.getClass().getAnnotation(Extension.class);
// Extension used to be Retention.SOURCE, and we may also end up loading extensions from other places
// like Plexus that don't have any annotations, so we need to be defensive
double l = el!=null ? el.ordinal() : 0;
double r = er!=null ? er.ordinal() : 0;
if(l>r) return -1;
if(l<r) return 1;
return 0;
}
});
return r;
}
public static <T> ExtensionList<T> create(Hudson hudson, Class<T> type) {
if(type==ExtensionFinder.class)
return new ExtensionList<T>(hudson,type) {
/**
- * If this ExtensionList is searching for ExtensionFinders, calling hudosn.getExtensionList
+ * If this ExtensionList is searching for ExtensionFinders, calling hudson.getExtensionList
* results in infinite recursion.
*/
@Override
protected Iterable<? extends ExtensionFinder> finders() {
return Collections.singleton(new ExtensionFinder.Sezpoz());
}
};
if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null)
return new ExtensionList<T>(hudson,type);
else {
return new ExtensionList<T>(hudson,type,staticLegacyInstances.get(type));
}
}
/**
* Places to store static-scope legacy instances.
*/
private static final Memoizer<Class,CopyOnWriteArrayList> staticLegacyInstances = new Memoizer<Class,CopyOnWriteArrayList>() {
public CopyOnWriteArrayList compute(Class key) {
return new CopyOnWriteArrayList();
}
};
/**
* Exposed for the test harness to clear all legacy extension instances.
*/
public static void clearLegacyInstances() {
staticLegacyInstances.clear();
}
private static final Logger LOGGER = Logger.getLogger(ExtensionList.class.getName());
}
| true | true | public static <T> ExtensionList<T> create(Hudson hudson, Class<T> type) {
if(type==ExtensionFinder.class)
return new ExtensionList<T>(hudson,type) {
/**
* If this ExtensionList is searching for ExtensionFinders, calling hudosn.getExtensionList
* results in infinite recursion.
*/
@Override
protected Iterable<? extends ExtensionFinder> finders() {
return Collections.singleton(new ExtensionFinder.Sezpoz());
}
};
if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null)
return new ExtensionList<T>(hudson,type);
else {
return new ExtensionList<T>(hudson,type,staticLegacyInstances.get(type));
}
}
| public static <T> ExtensionList<T> create(Hudson hudson, Class<T> type) {
if(type==ExtensionFinder.class)
return new ExtensionList<T>(hudson,type) {
/**
* If this ExtensionList is searching for ExtensionFinders, calling hudson.getExtensionList
* results in infinite recursion.
*/
@Override
protected Iterable<? extends ExtensionFinder> finders() {
return Collections.singleton(new ExtensionFinder.Sezpoz());
}
};
if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null)
return new ExtensionList<T>(hudson,type);
else {
return new ExtensionList<T>(hudson,type,staticLegacyInstances.get(type));
}
}
|
diff --git a/src/com/ichi2/anki/Image.java b/src/com/ichi2/anki/Image.java
index fc9317ef..db22d951 100644
--- a/src/com/ichi2/anki/Image.java
+++ b/src/com/ichi2/anki/Image.java
@@ -1,44 +1,45 @@
/***************************************************************************************
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import android.util.Log;
/**
* Class used to display and handle correctly images
*/
public class Image {
/**
* Tag for logging messages
*/
private static final String TAG = "AnkiDroid";
/**
*
* @param deckFilename Deck's filename whose images are going to be load
* @param content HTML content of a card's side (question or answer)
* @return content Modified content in order to display correctly the images
*/
public static String loadImages(String deckFilename, String content)
{
Log.i(TAG, "Image - loadImages, filename = " + deckFilename);
String imagePath = deckFilename.replace(".anki", ".media/");
Log.i(TAG, "Image path = " + imagePath);
- return content.replaceAll("<img src=\"", "<img src=\"" + "content://com.ichi2.anki" + imagePath);
+ content = content.replace("<img src=\"", "<img src=\"" + "content://com.ichi2.anki" + imagePath);
+ return content.replace("<img src=\"" + "content://com.ichi2.anki" + imagePath + "http://", "<img src=\"http://");
}
}
| true | true | public static String loadImages(String deckFilename, String content)
{
Log.i(TAG, "Image - loadImages, filename = " + deckFilename);
String imagePath = deckFilename.replace(".anki", ".media/");
Log.i(TAG, "Image path = " + imagePath);
return content.replaceAll("<img src=\"", "<img src=\"" + "content://com.ichi2.anki" + imagePath);
}
| public static String loadImages(String deckFilename, String content)
{
Log.i(TAG, "Image - loadImages, filename = " + deckFilename);
String imagePath = deckFilename.replace(".anki", ".media/");
Log.i(TAG, "Image path = " + imagePath);
content = content.replace("<img src=\"", "<img src=\"" + "content://com.ichi2.anki" + imagePath);
return content.replace("<img src=\"" + "content://com.ichi2.anki" + imagePath + "http://", "<img src=\"http://");
}
|
diff --git a/dexlib/src/main/java/org/jf/dexlib/Item.java b/dexlib/src/main/java/org/jf/dexlib/Item.java
index 825ec28..e301f8b 100644
--- a/dexlib/src/main/java/org/jf/dexlib/Item.java
+++ b/dexlib/src/main/java/org/jf/dexlib/Item.java
@@ -1,186 +1,186 @@
/*
* [The "BSD licence"]
* Copyright (c) 2009 Ben Gruver
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib;
import org.jf.dexlib.Util.AnnotatedOutput;
import org.jf.dexlib.Util.Input;
import org.jf.dexlib.Util.AlignmentUtils;
public abstract class Item<T extends Item> implements Comparable<T> {
/**
* The offset of this item in the dex file, or -1 if not known
*/
private int offset = -1;
/**
* The index of this item in the containing section, or -1 if not known
*/
private int index = -1;
/**
* The DexFile that this item is associatedr with
*/
protected final DexFile dexFile;
/**
* The constructor that is used when reading in a <code>DexFile</code>
* @param dexFile the <code>DexFile</code> that this item is associated with
*/
protected Item(DexFile dexFile) {
this.dexFile = dexFile;
}
/**
* Read in the item from the given input stream, and initialize the index
* @param in the <code>Input</code> object to read from
* @param index the index within the containing section of the item being read in
* @param readContext a <code>ReadContext</code> object to hold information that is
* only needed while reading in a file
*/
protected void readFrom(Input in, int index, ReadContext readContext) {
assert in.getCursor() % getItemType().ItemAlignment == 0:"The Input cursor is not aligned";
this.offset = in.getCursor();
this.index = index;
this.readItem(in, readContext);
}
/**
* Place the item at the given offset and index, and return the offset of the byte following this item
* @param offset The offset to place the item at
* @param index The index of the item within the containing section
* @return The offset of the byte following this item
*/
protected int placeAt(int offset, int index) {
assert offset % getItemType().ItemAlignment == 0:"The offset is not aligned";
assert !dexFile.getInplace() || (offset == this.offset && this.index == index);
this.offset = offset;
this.index = index;
return this.placeItem(offset);
}
/**
* Write and annotate this item to the output stream
* @param out The output stream to write and annotate to
*/
protected void writeTo(AnnotatedOutput out) {
assert out.getCursor() % getItemType().ItemAlignment == 0:"The Output cursor is not aligned";
if (out.getCursor() != offset) {
throw new RuntimeException("Item was placed at offset 0x" + Integer.toHexString(offset) +
- "but is being written to offset 0x" + Integer.toHexString(out.getCursor()));
+ " but is being written to offset 0x" + Integer.toHexString(out.getCursor()));
}
if (out.annotates()) {
out.annotate(0, "[0x" + Integer.toHexString(index) + "] " + this.getItemType().TypeName);
}
out.indent();
writeItem(out);
out.deindent();
}
/**
* Returns a human readable form of this item
* @return a human readable form of this item
*/
public String toString() {
return getConciseIdentity();
}
/**
* The method in the concrete item subclass that actually reads in the data for the item
*
* The logic in this method can assume that the given Input object is valid and is
* aligned as neccessary.
*
* This method is for internal use only
* @param in the <code>Input</code> object to read from
* @param readContext a <code>ReadContext</code> object to hold information that is
* only needed while reading in a file
*/
protected abstract void readItem(Input in, ReadContext readContext);
/**
* The method should finalize the layout of the item and return the offset of the byte
* immediately following the item.
*
* The implementation of this method can assume that the offset argument has already been
* aligned based on the item's alignment requirements
*
* This method is for internal use only
* @param offset the (pre-aligned) offset to place the item at
* @return the size of the item, in bytes
*/
protected abstract int placeItem(int offset);
/**
* The method in the concrete item subclass that actually writes and annotates the data
* for the item.
*
* The logic in this method can assume that the given Output object is valid and is
* aligned as neccessary
*
* @param out The <code>AnnotatedOutput</code> object to write/annotate to
*/
protected abstract void writeItem(AnnotatedOutput out);
/**
* @return An ItemType enum that represents the item type of this item
*/
public abstract ItemType getItemType();
/**
* @return A concise (human-readable) string value that conveys the identity of this item
*/
public abstract String getConciseIdentity();
/**
* @return the offset in the dex file where this item is located
*/
public int getOffset() {
return offset;
}
/**
* @return the index of this item within the item's containing section
*/
public int getIndex() {
return index;
}
/**
* @return the <code>DexFile</code> that contains this item
*/
public DexFile getDexFile() {
return dexFile;
}
}
| true | true | protected void writeTo(AnnotatedOutput out) {
assert out.getCursor() % getItemType().ItemAlignment == 0:"The Output cursor is not aligned";
if (out.getCursor() != offset) {
throw new RuntimeException("Item was placed at offset 0x" + Integer.toHexString(offset) +
"but is being written to offset 0x" + Integer.toHexString(out.getCursor()));
}
if (out.annotates()) {
out.annotate(0, "[0x" + Integer.toHexString(index) + "] " + this.getItemType().TypeName);
}
out.indent();
writeItem(out);
out.deindent();
}
| protected void writeTo(AnnotatedOutput out) {
assert out.getCursor() % getItemType().ItemAlignment == 0:"The Output cursor is not aligned";
if (out.getCursor() != offset) {
throw new RuntimeException("Item was placed at offset 0x" + Integer.toHexString(offset) +
" but is being written to offset 0x" + Integer.toHexString(out.getCursor()));
}
if (out.annotates()) {
out.annotate(0, "[0x" + Integer.toHexString(index) + "] " + this.getItemType().TypeName);
}
out.indent();
writeItem(out);
out.deindent();
}
|
diff --git a/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling/src/main/java/org/nuxeo/ecm/platform/pictures/tiles/api/imageresource/DocumentImageResource.java b/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling/src/main/java/org/nuxeo/ecm/platform/pictures/tiles/api/imageresource/DocumentImageResource.java
index 0130f910e..d3867e0f4 100644
--- a/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling/src/main/java/org/nuxeo/ecm/platform/pictures/tiles/api/imageresource/DocumentImageResource.java
+++ b/nuxeo-platform-imaging-tiling/nuxeo-platform-imaging-tiling/src/main/java/org/nuxeo/ecm/platform/pictures/tiles/api/imageresource/DocumentImageResource.java
@@ -1,99 +1,102 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Nuxeo - initial API and implementation
*
* $Id$
*
*/
package org.nuxeo.ecm.platform.pictures.tiles.api.imageresource;
import java.util.Calendar;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.model.PropertyException;
/**
*
* DocumentModel based implementation of ImageResource
* Support clean digest and modification date to have a clean invalidation system.
*
*
* @author tiry
*
*/
public class DocumentImageResource implements ImageResource {
/**
*
*/
private static final long serialVersionUID = 1L;
protected Blob blob = null;
protected String hash = null;
protected Calendar modified = null;
protected DocumentModel doc = null;
protected String xPath = null;
protected String fileName = null;
public DocumentImageResource(DocumentModel doc, String xPath) {
this.doc = doc;
this.xPath = xPath;
}
protected String getEscapedxPath(String xPath) {
String clean = xPath.replace(":", "_");
clean = clean.replace("/", "_");
return clean;
}
protected void compute() throws PropertyException, ClientException {
blob = (Blob) doc.getProperty(xPath).getValue();
modified = (Calendar) doc.getProperty("dublincore", "modified");
hash = blob.getDigest();
if (hash == null) {
hash = doc.getRepositoryName() + "_" + doc.getId() + "_"
+ getEscapedxPath(xPath);
+ if (modified != null) {
+ hash = hash + "_" + modified.getTimeInMillis();
+ }
}
}
public Blob getBlob() throws ClientException {
if (blob == null)
compute();
if (fileName!=null)
blob.setFilename(fileName);
return blob;
}
public String getHash() throws ClientException {
if (hash == null)
compute();
return hash;
}
public Calendar getModificationDate() throws ClientException {
if (modified == null)
compute();
return modified;
}
public void setFileName(String name) {
this.fileName=name;
}
}
| true | true | protected void compute() throws PropertyException, ClientException {
blob = (Blob) doc.getProperty(xPath).getValue();
modified = (Calendar) doc.getProperty("dublincore", "modified");
hash = blob.getDigest();
if (hash == null) {
hash = doc.getRepositoryName() + "_" + doc.getId() + "_"
+ getEscapedxPath(xPath);
}
}
| protected void compute() throws PropertyException, ClientException {
blob = (Blob) doc.getProperty(xPath).getValue();
modified = (Calendar) doc.getProperty("dublincore", "modified");
hash = blob.getDigest();
if (hash == null) {
hash = doc.getRepositoryName() + "_" + doc.getId() + "_"
+ getEscapedxPath(xPath);
if (modified != null) {
hash = hash + "_" + modified.getTimeInMillis();
}
}
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
index 099a2cb3..6e08e1de 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
@@ -1,682 +1,679 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2003 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.javadoc;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.Scope;
import com.puppycrawl.tools.checkstyle.api.ScopeUtils;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.Utils;
import com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import org.apache.regexp.RE;
/**
* <p>
* Checks the Javadoc of a method or constructor.
* By default, does not check for unused throws.
* To allow documented <code>java.lang.RuntimeException</code>s
* that are not declared, set property allowUndeclaredRTE to true.
* The scope to verify is specified using the {@link Scope} class and
* defaults to {@link Scope#PRIVATE}. To verify another scope,
* set property scope to one of the {@link Scope} constants.
* </p>
* <p>
* Error messages about parameters for which no param tags are
* present can be suppressed by defining property
* <code>allowMissingParamTags</code>.
* Error messages about exceptions which are declared to be thrown,
* but for which no throws tag is present can be suppressed by
* defining property <code>allowMissingThrowsTags</code>.
* Error messages about methods which return non-void but for
* which no return tag is present can be suppressed by defining
* property <code>allowMissingReturnTag</code>.
* </p>
* <p>
* An example of how to configure the check is:
* </p>
* <pre>
* <module name="JavadocMethod"/>
* </pre>
* <p> An example of how to configure the check to check to allow
* documentation of undeclared RuntimeExceptions
* and for the {@link Scope#PUBLIC} scope, while ignoring any missing
* param tags is:
*</p>
* <pre>
* <module name="JavadocMethod">
* <property name="scope" value="public"/>
* <property name="allowUndeclaredRTE" value="true"/>
* <property name="allowMissingParamTags" value="true"/>
* </module>
* </pre>
*
* @author Oliver Burn
* @author Rick Giles
* @author o_sukhodoslky
* @version 1.1
*/
public class JavadocMethodCheck
extends AbstractTypeAwareCheck
{
/** the pattern to match Javadoc tags that take an argument **/
private static final String MATCH_JAVADOC_ARG_PAT =
"@(throws|exception|param)\\s+(\\S+)\\s+\\S";
/** compiled regexp to match Javadoc tags that take an argument **/
private static final RE MATCH_JAVADOC_ARG =
Utils.createRE(MATCH_JAVADOC_ARG_PAT);
/**
* the pattern to match the first line of a multi-line Javadoc
* tag that takes an argument.
**/
private static final String MATCH_JAVADOC_ARG_MULTILINE_START_PAT =
"@(throws|exception|param)\\s+(\\S+)\\s*$";
/** compiled regexp to match first part of multilineJavadoc tags **/
private static final RE MATCH_JAVADOC_ARG_MULTILINE_START =
Utils.createRE(MATCH_JAVADOC_ARG_MULTILINE_START_PAT);
/** the pattern that looks for a continuation of the comment **/
private static final String MATCH_JAVADOC_MULTILINE_CONT_PAT =
"(\\*/|@|[^\\s\\*])";
/** compiled regexp to look for a continuation of the comment **/
private static final RE MATCH_JAVADOC_MULTILINE_CONT =
Utils.createRE(MATCH_JAVADOC_MULTILINE_CONT_PAT);
/** Multiline finished at end of comment **/
private static final String END_JAVADOC = "*/";
/** Multiline finished at next Javadoc **/
private static final String NEXT_TAG = "@";
/** the pattern to match Javadoc tags with no argument **/
private static final String MATCH_JAVADOC_NOARG_PAT =
"@(return|see)\\s+\\S";
/** compiled regexp to match Javadoc tags with no argument **/
private static final RE MATCH_JAVADOC_NOARG =
Utils.createRE(MATCH_JAVADOC_NOARG_PAT);
/**
* the pattern to match the first line of a multi-line Javadoc
* tag that takes no argument.
**/
private static final String MATCH_JAVADOC_NOARG_MULTILINE_START_PAT =
"@(return|see)\\s*$";
/** compiled regexp to match first part of multilineJavadoc tags **/
private static final RE MATCH_JAVADOC_NOARG_MULTILINE_START =
Utils.createRE(MATCH_JAVADOC_NOARG_MULTILINE_START_PAT);
/** the pattern to match Javadoc tags with no argument and {} **/
private static final String MATCH_JAVADOC_NOARG_CURLY_PAT =
"\\{\\s*@(inheritDoc)\\s*\\}";
/** compiled regexp to match Javadoc tags with no argument and {} **/
private static final RE MATCH_JAVADOC_NOARG_CURLY =
Utils.createRE(MATCH_JAVADOC_NOARG_CURLY_PAT);
/** the visibility scope where Javadoc comments are checked **/
private Scope mScope = Scope.PRIVATE;
/**
* controls whether to allow documented exceptions that
* are not declared if they are a subclass of
* java.lang.RuntimeException.
**/
private boolean mAllowUndeclaredRTE = false;
/**
* controls whether to allow documented exceptions that
* are subclass of one of declared exception.
* Defaults to false (backward compatibility).
**/
private boolean mAllowThrowsTagsForSubclasses = false;
/**
* controls whether to ignore errors when a method has parameters
* but does not have matching param tags in the javadoc.
* Defaults to false.
**/
private boolean mAllowMissingParamTags = false;
/**
* controls whether to ignore errors when a method declares that
* it throws exceptions but does not have matching throws tags
* in the javadoc. Defaults to false.
**/
private boolean mAllowMissingThrowsTags = false;
/**
* controls whether to ignore errors when a method returns
* non-void type but does not have a return tag in the javadoc.
* Defaults to false.
**/
private boolean mAllowMissingReturnTag = false;
/**
* Set the scope.
* @param aFrom a <code>String</code> value
*/
public void setScope(String aFrom)
{
mScope = Scope.getInstance(aFrom);
}
/**
* controls whether to allow documented exceptions that
* are not declared if they are a subclass of
* java.lang.RuntimeException.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowUndeclaredRTE(boolean aFlag)
{
mAllowUndeclaredRTE = aFlag;
}
/**
* controls whether to allow documented exception that
* are subclass of one of declared exceptions.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowThrowsTagsForSubclasses(boolean aFlag)
{
mAllowThrowsTagsForSubclasses = aFlag;
}
/**
* controls whether to allow a method which has parameters
* to omit matching param tags in the javadoc.
* Defaults to false.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingParamTags(boolean aFlag)
{
mAllowMissingParamTags = aFlag;
}
/**
* controls whether to allow a method which declares that
* it throws exceptions to omit matching throws tags
* in the javadoc. Defaults to false.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingThrowsTags(boolean aFlag)
{
mAllowMissingThrowsTags = aFlag;
}
/**
* controls whether to allow a method which returns
* non-void type to omit the return tag in the javadoc.
* Defaults to false.
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingReturnTag(boolean aFlag)
{
mAllowMissingReturnTag = aFlag;
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getDefaultTokens()
{
return new int[] {
TokenTypes.PACKAGE_DEF,
TokenTypes.IMPORT,
TokenTypes.METHOD_DEF,
TokenTypes.CTOR_DEF,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getAcceptableTokens()
{
return new int[] {
TokenTypes.METHOD_DEF,
TokenTypes.CTOR_DEF,
};
}
/** @see com.puppycrawl.tools.checkstyle.api.Check */
public int[] getRequiredTokens()
{
return new int[] {
TokenTypes.PACKAGE_DEF,
TokenTypes.IMPORT,
};
}
/**
* Checks Javadoc comments for a method or constructor.
* @param aAST the tree node for the method or constructor.
*/
protected final void processAST(DetailAST aAST)
{
final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS);
final Scope declaredScope = ScopeUtils.getScopeFromMods(mods);
final Scope targetScope =
ScopeUtils.inInterfaceBlock(aAST)
? Scope.PUBLIC
: declaredScope;
if (targetScope.isIn(mScope)) {
final Scope surroundingScope =
ScopeUtils.getSurroundingScope(aAST);
if (surroundingScope.isIn(mScope)) {
final FileContents contents = getFileContents();
final String[] cmt =
contents.getJavadocBefore(aAST.getLineNo());
if (cmt == null) {
log(aAST.getLineNo(),
aAST.getColumnNo(),
"javadoc.missing");
}
else {
checkComment(aAST, cmt);
}
}
}
}
/**
* Checks the Javadoc for a method.
* @param aAST the token for the method
* @param aComment the Javadoc comment
*/
private void checkComment(DetailAST aAST, String[] aComment)
{
final List tags = getMethodTags(aComment, aAST.getLineNo() - 1);
// Check for only one @see tag
if ((tags.size() != 1)
|| !((JavadocTag) tags.get(0)).isSeeOrInheritDocTag())
{
checkParamTags(tags, getParameters(aAST));
checkThrowsTags(tags, getThrows(aAST));
if (isFunction(aAST)) {
checkReturnTag(tags, aAST.getLineNo());
}
// Dump out all unused tags
final Iterator it = tags.iterator();
while (it.hasNext()) {
final JavadocTag jt = (JavadocTag) it.next();
if (!jt.isSeeOrInheritDocTag()) {
log(jt.getLineNo(), "javadoc.unusedTagGeneral");
}
}
}
}
/**
* Returns the tags in a javadoc comment. Only finds throws, exception,
* param, return and see tags.
* @return the tags found
* @param aLines the Javadoc comment
* @param aLastLineNo the line number of the last line in the Javadoc
* comment
**/
private List getMethodTags(String[] aLines, int aLastLineNo)
{
final List tags = new ArrayList();
int currentLine = aLastLineNo - aLines.length;
for (int i = 0; i < aLines.length; i++) {
currentLine++;
if (MATCH_JAVADOC_ARG.match(aLines[i])) {
tags.add(new JavadocTag(currentLine,
MATCH_JAVADOC_ARG.getParen(1),
MATCH_JAVADOC_ARG.getParen(2)));
}
else if (MATCH_JAVADOC_NOARG.match(aLines[i])) {
tags.add(new JavadocTag(currentLine,
MATCH_JAVADOC_NOARG.getParen(1)));
}
else if (MATCH_JAVADOC_NOARG_CURLY.match(aLines[i])) {
tags.add(new JavadocTag(currentLine,
MATCH_JAVADOC_NOARG_CURLY.getParen(1)));
}
else if (MATCH_JAVADOC_ARG_MULTILINE_START.match(aLines[i])) {
final String p1 = MATCH_JAVADOC_ARG_MULTILINE_START.getParen(1);
final String p2 = MATCH_JAVADOC_ARG_MULTILINE_START.getParen(2);
// Look for the rest of the comment if all we saw was
// the tag and the name. Stop when we see '*/' (end of
// Javadoc, '@' (start of next tag), or anything that's
// not whitespace or '*' characters.
int remIndex = i + 1;
while (remIndex < aLines.length) {
if (MATCH_JAVADOC_MULTILINE_CONT.match(aLines[remIndex])) {
remIndex = aLines.length;
String lFin = MATCH_JAVADOC_MULTILINE_CONT.getParen(1);
if (!lFin.equals(NEXT_TAG)
&& !lFin.equals(END_JAVADOC))
{
tags.add(new JavadocTag(currentLine, p1, p2));
}
}
remIndex++;
}
}
else if (MATCH_JAVADOC_NOARG_MULTILINE_START.match(aLines[i])) {
final String p1 =
MATCH_JAVADOC_NOARG_MULTILINE_START.getParen(1);
// Look for the rest of the comment if all we saw was
// the tag and the name. Stop when we see '*/' (end of
// Javadoc, '@' (start of next tag), or anything that's
// not whitespace or '*' characters.
int remIndex = i + 1;
while (remIndex < aLines.length) {
if (MATCH_JAVADOC_MULTILINE_CONT.match(aLines[remIndex])) {
remIndex = aLines.length;
String lFin = MATCH_JAVADOC_MULTILINE_CONT.getParen(1);
if (!lFin.equals(NEXT_TAG)
&& !lFin.equals(END_JAVADOC))
{
tags.add(new JavadocTag(currentLine, p1));
}
}
remIndex++;
}
}
}
return tags;
}
/**
* Computes the parameter nodes for a method.
* @param aAST the method node.
* @return the list of parameter nodes for aAST.
**/
private List getParameters(DetailAST aAST)
{
final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
final List retVal = new ArrayList();
DetailAST child = (DetailAST) params.getFirstChild();
while (child != null) {
if (child.getType() == TokenTypes.PARAMETER_DEF) {
final DetailAST ident = child.findFirstToken(TokenTypes.IDENT);
retVal.add(ident);
}
child = (DetailAST) child.getNextSibling();
}
return retVal;
}
/**
* Computes the exception nodes for a method.
* @param aAST the method node.
* @return the list of exception nodes for aAST.
**/
private List getThrows(DetailAST aAST)
{
final List retVal = new ArrayList();
final DetailAST throwsAST =
aAST.findFirstToken(TokenTypes.LITERAL_THROWS);
if (throwsAST != null) {
DetailAST child = (DetailAST) throwsAST.getFirstChild();
while (child != null) {
if ((child.getType() == TokenTypes.IDENT)
|| (child.getType() == TokenTypes.DOT))
{
final ExceptionInfo ei =
new ExceptionInfo(FullIdent.createFullIdent(child));
retVal.add(ei);
}
child = (DetailAST) child.getNextSibling();
}
}
return retVal;
}
/**
* Checks a set of tags for matching parameters.
* @param aTags the tags to check
* @param aParams the list of parameters to check
**/
private void checkParamTags(List aTags, List aParams)
{
// Loop over the tags, checking to see they exist in the params.
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isParamTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching param
boolean found = false;
final Iterator paramIt = aParams.iterator();
while (paramIt.hasNext()) {
final DetailAST param = (DetailAST) paramIt.next();
if (param.getText().equals(tag.getArg1())) {
found = true;
paramIt.remove();
break;
}
}
// Handle extra JavadocTag
if (!found) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@param", tag.getArg1());
}
}
// Now dump out all parameters without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingParamTags) {
final Iterator paramIt = aParams.iterator();
while (paramIt.hasNext()) {
final DetailAST param = (DetailAST) paramIt.next();
log(param.getLineNo(), param.getColumnNo(),
"javadoc.expectedTag", "@param", param.getText());
}
}
}
/**
* Checks whether a method is a function.
* @param aAST the method node.
* @return whether the method is a function.
**/
private boolean isFunction(DetailAST aAST)
{
boolean retVal = false;
if (aAST.getType() == TokenTypes.METHOD_DEF) {
final DetailAST typeAST = aAST.findFirstToken(TokenTypes.TYPE);
if ((typeAST != null)
&& (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) == null))
{
retVal = true;
}
}
return retVal;
}
/**
* Checks for only one return tag. All return tags will be removed from the
* supplied list.
* @param aTags the tags to check
* @param aLineNo the line number of the expected tag
**/
private void checkReturnTag(List aTags, int aLineNo)
{
// Loop over tags finding return tags. After the first one, report an
// error.
boolean found = false;
final ListIterator it = aTags.listIterator();
while (it.hasNext()) {
final JavadocTag jt = (JavadocTag) it.next();
if (jt.isReturnTag()) {
if (found) {
log(jt.getLineNo(), "javadoc.return.duplicate");
}
found = true;
it.remove();
}
}
// Handle there being no @return tags :- unless
// the user has chosen to suppress these problems
if (!found && !mAllowMissingReturnTag) {
log(aLineNo, "javadoc.return.expected");
}
}
/**
* Checks a set of tags for matching throws.
* @param aTags the tags to check
* @param aThrows the throws to check
**/
private void checkThrowsTags(List aTags, List aThrows)
{
// Loop over the tags, checking to see they exist in the throws.
final Set foundThrows = new HashSet(); //used for performance only
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
boolean found = foundThrows.contains(documentedEx);
Class documentedClass = null;
boolean classLoaded = false;
final ListIterator throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
final FullIdent fi = ei.getName();
final String declaredEx = fi.getText();
if (isSameType(declaredEx, documentedEx)) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
found = isSubclass(documentedClass, ei.getClazz());
-// if (found) {
-// ei.setFound();
-// }
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
reqd = !isUnchecked(documentedClass);
}
if (reqd) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@throws", tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags) {
final ListIterator throwIt = aThrows.listIterator();
while (throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
if (!ei.isFound()) {
final FullIdent fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag", "@throws", fi.getText());
}
}
}
}
/**
* Tries to load class for throws tag. Logs error if unable.
* @param aTag name of class which we try to load.
* @return <code>Class</code> for the tag.
*/
private Class loadClassForTag(JavadocTag aTag)
{
Class clazz = resolveClass(aTag.getArg1());
if (clazz == null) {
log(aTag.getLineNo(), "javadoc.classInfo",
"@throws", aTag.getArg1());
}
return clazz;
}
/**
* Logs error if unable to load class information.
* @param aIdent class name for which we can no load class.
*/
protected final void logLoadError(FullIdent aIdent)
{
log(aIdent.getLineNo(), "javadoc.classInfo", "@throws",
aIdent.getText());
}
/** Stores useful information about declared exception. */
class ExceptionInfo extends ClassInfo
{
/** does the exception have throws tag associated with. */
private boolean mFound;
/**
* Creates new instance for <code>FullIdent</code>.
* @param aIdent <code>FullIdent</code> of the exception
*/
ExceptionInfo(FullIdent aIdent)
{
super(aIdent);
}
/** Mark that the exception has associated throws tag */
final void setFound()
{
mFound = true;
}
/** @return whether the exception has throws tag associated with */
final boolean isFound()
{
return mFound;
}
}
}
| true | true | private void checkThrowsTags(List aTags, List aThrows)
{
// Loop over the tags, checking to see they exist in the throws.
final Set foundThrows = new HashSet(); //used for performance only
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
boolean found = foundThrows.contains(documentedEx);
Class documentedClass = null;
boolean classLoaded = false;
final ListIterator throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
final FullIdent fi = ei.getName();
final String declaredEx = fi.getText();
if (isSameType(declaredEx, documentedEx)) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
found = isSubclass(documentedClass, ei.getClazz());
// if (found) {
// ei.setFound();
// }
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
reqd = !isUnchecked(documentedClass);
}
if (reqd) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@throws", tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags) {
final ListIterator throwIt = aThrows.listIterator();
while (throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
if (!ei.isFound()) {
final FullIdent fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag", "@throws", fi.getText());
}
}
}
}
| private void checkThrowsTags(List aTags, List aThrows)
{
// Loop over the tags, checking to see they exist in the throws.
final Set foundThrows = new HashSet(); //used for performance only
final ListIterator tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = (JavadocTag) tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
boolean found = foundThrows.contains(documentedEx);
Class documentedClass = null;
boolean classLoaded = false;
final ListIterator throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
final FullIdent fi = ei.getName();
final String declaredEx = fi.getText();
if (isSameType(declaredEx, documentedEx)) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
found = isSubclass(documentedClass, ei.getClazz());
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
if (!classLoaded) {
documentedClass = loadClassForTag(tag);
classLoaded = true;
}
reqd = !isUnchecked(documentedClass);
}
if (reqd) {
log(tag.getLineNo(), "javadoc.unusedTag",
"@throws", tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags) {
final ListIterator throwIt = aThrows.listIterator();
while (throwIt.hasNext()) {
final ExceptionInfo ei = (ExceptionInfo) throwIt.next();
if (!ei.isFound()) {
final FullIdent fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag", "@throws", fi.getText());
}
}
}
}
|
diff --git a/Notes2Google/src/de/mbaaba/notes/NotesCalendarEntry.java b/Notes2Google/src/de/mbaaba/notes/NotesCalendarEntry.java
index ac649b0..9783254 100644
--- a/Notes2Google/src/de/mbaaba/notes/NotesCalendarEntry.java
+++ b/Notes2Google/src/de/mbaaba/notes/NotesCalendarEntry.java
@@ -1,111 +1,112 @@
/* --------------------------------------------------------------------------
* @author Hauke Walden
* @created 28.06.2011
* Copyright 2011 by Hauke Walden
* All rights reserved.
* --------------------------------------------------------------------------
*/
package de.mbaaba.notes;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import lotus.domino.DateTime;
import lotus.domino.Item;
import lotus.domino.NotesException;
import de.mbaaba.calendar.CalendarEntry;
import de.mbaaba.calendar.ICalendarEntry;
import de.mbaaba.calendar.ItemNotFoundException;
import de.mbaaba.calendar.Person;
import de.mbaaba.calendar.PersonFactory;
import de.mbaaba.calendar.PersonFactory.CalendarType;
public class NotesCalendarEntry extends CalendarEntry {
private boolean confidential;
public NotesCalendarEntry(ICalendarEntry aCalendarEntry) {
super(aCalendarEntry);
}
public NotesCalendarEntry() {
}
public void mapItem(Item aItem) throws NotesException {
String itemName = aItem.getName().toLowerCase();
// System.out.println(itemName + " = " + aItem.getDateTimeValue() + " "
// + aItem.getValueString());
if (itemName.equals("subject")) {
setSubject(aItem.getValueString());
} else if (itemName.equals("body")) {
setBody(aItem.getValueString());
} else if (itemName.equals("chair")) {
try {
List<Person> findPerson = PersonFactory.findPerson(CalendarType.Notes, aItem.getValueString());
if ((findPerson != null) && (findPerson.size() > 0)) {
setChair(findPerson.get(0));
}
} catch (ItemNotFoundException e) {
// chair not found in DB
}
} else if (itemName.equals("location")) {
setLocation(aItem.getValueString());
} else if (itemName.equals("room")) {
setRoom(aItem.getValueString());
} else if (itemName.equals("orgconfidential")) {
setConfidential(aItem.getValueString().equals("1"));
} else if (itemName.equals("startdatetime")) {
Vector<?> dates = aItem.getValueDateTimeArray();
for (Object object : dates) {
Date javaDate = ((DateTime) object).toJavaDate();
addStartDate(javaDate);
}
} else if (itemName.equals("enddatetime")) {
Vector<?> dates = aItem.getValueDateTimeArray();
for (Object object : dates) {
Date javaDate = ((DateTime) object).toJavaDate();
addEndDate(javaDate);
}
} else if (itemName.equals("$alarmoffset")) {
// DateTime thisAlarmOffset = aItem.getDateTimeValue();
- // TODO: alarms
+ // TODO: 5: Handle alarm settings
+ // http://github.com/hwacookie/CalendarSyncTool/issues/issue/5
} else if (itemName.equals("originalmodtime")) {
setLastModified(aItem.getDateTimeValue().toJavaDate());
} else if (itemName.equals("requiredattendees") || itemName.equals("optionalattendees")) {
try {
if (aItem.getValues() != null) {
Vector<?> v = aItem.getValues();
for (Object object : v) {
String s = object.toString();
if (s.matches(".+@.+")) {
addAttendee(s, itemName);
}
}
}
} catch (NotesException e) {
}
} else {
// System.out.println(itemName+" = "+aItem.getDateTimeValue()+" "+aItem.getValueString());
}
}
public boolean isConfidential() {
return confidential;
}
public void setConfidential(boolean confidential) {
this.confidential = confidential;
}
@Override
public String toString() {
String s = super.toString();
s = s + "---------------------------------------------\n";
s = s + "is confidential: " + isConfidential() + "\n";
return s;
}
}
| true | true | public void mapItem(Item aItem) throws NotesException {
String itemName = aItem.getName().toLowerCase();
// System.out.println(itemName + " = " + aItem.getDateTimeValue() + " "
// + aItem.getValueString());
if (itemName.equals("subject")) {
setSubject(aItem.getValueString());
} else if (itemName.equals("body")) {
setBody(aItem.getValueString());
} else if (itemName.equals("chair")) {
try {
List<Person> findPerson = PersonFactory.findPerson(CalendarType.Notes, aItem.getValueString());
if ((findPerson != null) && (findPerson.size() > 0)) {
setChair(findPerson.get(0));
}
} catch (ItemNotFoundException e) {
// chair not found in DB
}
} else if (itemName.equals("location")) {
setLocation(aItem.getValueString());
} else if (itemName.equals("room")) {
setRoom(aItem.getValueString());
} else if (itemName.equals("orgconfidential")) {
setConfidential(aItem.getValueString().equals("1"));
} else if (itemName.equals("startdatetime")) {
Vector<?> dates = aItem.getValueDateTimeArray();
for (Object object : dates) {
Date javaDate = ((DateTime) object).toJavaDate();
addStartDate(javaDate);
}
} else if (itemName.equals("enddatetime")) {
Vector<?> dates = aItem.getValueDateTimeArray();
for (Object object : dates) {
Date javaDate = ((DateTime) object).toJavaDate();
addEndDate(javaDate);
}
} else if (itemName.equals("$alarmoffset")) {
// DateTime thisAlarmOffset = aItem.getDateTimeValue();
// TODO: alarms
} else if (itemName.equals("originalmodtime")) {
setLastModified(aItem.getDateTimeValue().toJavaDate());
} else if (itemName.equals("requiredattendees") || itemName.equals("optionalattendees")) {
try {
if (aItem.getValues() != null) {
Vector<?> v = aItem.getValues();
for (Object object : v) {
String s = object.toString();
if (s.matches(".+@.+")) {
addAttendee(s, itemName);
}
}
}
} catch (NotesException e) {
}
} else {
// System.out.println(itemName+" = "+aItem.getDateTimeValue()+" "+aItem.getValueString());
}
}
| public void mapItem(Item aItem) throws NotesException {
String itemName = aItem.getName().toLowerCase();
// System.out.println(itemName + " = " + aItem.getDateTimeValue() + " "
// + aItem.getValueString());
if (itemName.equals("subject")) {
setSubject(aItem.getValueString());
} else if (itemName.equals("body")) {
setBody(aItem.getValueString());
} else if (itemName.equals("chair")) {
try {
List<Person> findPerson = PersonFactory.findPerson(CalendarType.Notes, aItem.getValueString());
if ((findPerson != null) && (findPerson.size() > 0)) {
setChair(findPerson.get(0));
}
} catch (ItemNotFoundException e) {
// chair not found in DB
}
} else if (itemName.equals("location")) {
setLocation(aItem.getValueString());
} else if (itemName.equals("room")) {
setRoom(aItem.getValueString());
} else if (itemName.equals("orgconfidential")) {
setConfidential(aItem.getValueString().equals("1"));
} else if (itemName.equals("startdatetime")) {
Vector<?> dates = aItem.getValueDateTimeArray();
for (Object object : dates) {
Date javaDate = ((DateTime) object).toJavaDate();
addStartDate(javaDate);
}
} else if (itemName.equals("enddatetime")) {
Vector<?> dates = aItem.getValueDateTimeArray();
for (Object object : dates) {
Date javaDate = ((DateTime) object).toJavaDate();
addEndDate(javaDate);
}
} else if (itemName.equals("$alarmoffset")) {
// DateTime thisAlarmOffset = aItem.getDateTimeValue();
// TODO: 5: Handle alarm settings
// http://github.com/hwacookie/CalendarSyncTool/issues/issue/5
} else if (itemName.equals("originalmodtime")) {
setLastModified(aItem.getDateTimeValue().toJavaDate());
} else if (itemName.equals("requiredattendees") || itemName.equals("optionalattendees")) {
try {
if (aItem.getValues() != null) {
Vector<?> v = aItem.getValues();
for (Object object : v) {
String s = object.toString();
if (s.matches(".+@.+")) {
addAttendee(s, itemName);
}
}
}
} catch (NotesException e) {
}
} else {
// System.out.println(itemName+" = "+aItem.getDateTimeValue()+" "+aItem.getValueString());
}
}
|
diff --git a/src/jivko/brain/movement/Command.java b/src/jivko/brain/movement/Command.java
index 8fff480..8409395 100644
--- a/src/jivko/brain/movement/Command.java
+++ b/src/jivko/brain/movement/Command.java
@@ -1,265 +1,267 @@
package jivko.brain.movement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static jivko.brain.movement.CommandsCenter.XML_DOM_ATTRIBUTE_MAX;
import static jivko.brain.movement.CommandsCenter.XML_DOM_ATTRIBUTE_MIN;
import static jivko.brain.movement.CommandsCenter.XML_DOM_ATTRIBUTE_NAME;
import static jivko.brain.movement.CommandsCenter.XML_DOM_ATTRIBUTE_PORT;
import static jivko.brain.movement.CommandsCenter.XML_DOM_ATTRIBUTE_VAL;
import static jivko.brain.movement.CommandsCenter.XML_DOM_NODE_COMMAND;
import jivko.util.ComPort;
import jivko.util.HexUtils;
import jivko.util.OsUtils;
import jivko.util.Tree;
/**
*
* @author Sergii Smehov (smehov.com)
*/
public class Command extends jivko.util.Tree implements Cloneable {
private static final String DEFAULT_PORT_NAME = "/dev/ttyACM0";
private static final int DEFAULT_PORT_SPEED = 9600;
private static final String COMMAND_SPEED_PREFIX = "T";
public static final int DEFAULT_COMMAND_SPEED = 200;
public static final double DEFAULT_COMMAND_SPEED_KOEF = 1.2;
private static final int DEFAULT_COMMAND_DURATION = 1500;
private static Random rand = new Random();
public Command() {
}
public Command(String name) {
this.name = name;
}
public Command(String name, String value) {
this(name);
setValue(value);
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
private String name;
private Integer min;
private Integer max;
private Integer value;
private String port;
private Integer duration = DEFAULT_COMMAND_DURATION;
private Integer speed = DEFAULT_COMMAND_SPEED;
private String command;
private static Map<String, ComPort> openedPorts = new HashMap<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public Integer getMin() {
return min;
}
public void setMin(String min) {
if (min != null && !"".equals(min)) {
this.min = Integer.parseInt(min);
}
}
public Integer getMax() {
return max;
}
public void setMax(String max) {
if (max != null && !"".equals(max)) {
this.max = Integer.parseInt(max);
}
}
public Integer getValue() {
return value;
}
public void setValue(String value) {
if (value != null && !"".equals(value)) {
this.value = Integer.parseInt(value);
}
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public Integer getDuration() {
return duration;
}
public void setDuration(String duration) {
if (duration != null && !"".equals(duration)) {
this.duration = Integer.parseInt(duration);
}
}
public Integer getSpeed() {
return speed;
}
public void setSpeed(String speed) {
if (speed != null && !"".equals(speed)) {
this.speed = Integer.parseInt(speed);
}
}
public void addPort(String portName) throws Exception {
//this work only for unix
if (OsUtils.isUnix()) {
//if port is not opened yet
if (openedPorts.get(port) == null) {
ComPort newPort = new ComPort(portName, DEFAULT_PORT_SPEED);
openedPorts.put(port, newPort);
}
}
}
public boolean isHardcoded() {
return command.split("#").length > 2;
}
public boolean isUsbCommand() {
return port.contains("USB");
}
public void compile() throws Exception {
//System.err.println("before:" + command);
if (port == null || "".equals(port))
port = DEFAULT_PORT_NAME;
addPort(port);
if (!isHardcoded()) {
if (command == null || "".equals(command))
return;
if (!command.contains("xxx")) {
throw new Exception("Wrong command format -no xxx");
}
Integer val;
if (value != null) {
val = value;
if (min == null && max == null) {
if (isUsbCommand()) {
- String bytes = HexUtils.hexStringToByteArrayString(val.toString());
- command = command.replaceAll("xxx", bytes);
+ //String bytes = HexUtils.hexStringToByteArrayString(val.toString());
+ char ch = (char)(val.intValue());
+ String s = "" + ch;
+ command = command.replaceAll("xxx", s);
} else {
command = command.replaceAll("xxx", val.toString());
}
}
} else {
if (min == null || max == null)
throw new Exception("Command: " + name + ": if now val preset at least min or max should be!");
}
if (!isUsbCommand()) {
command += COMMAND_SPEED_PREFIX + speed.toString();
}
}
command += "\r\n";
//System.err.println("after:" + command);
}
public void print() {
print("");
}
public void print(String identity) {
System.out.println(identity + XML_DOM_ATTRIBUTE_NAME + ": "+ getName());
System.out.println(identity + XML_DOM_ATTRIBUTE_MAX + ": "+ getMax());
System.out.println(identity + XML_DOM_ATTRIBUTE_MIN + ": "+ getMin());
System.out.println(identity + XML_DOM_ATTRIBUTE_PORT + ": "+ getPort());
System.out.println(identity + XML_DOM_ATTRIBUTE_VAL + ": "+ getValue());
System.out.println(identity + XML_DOM_NODE_COMMAND + ": "+ getCommand());
identity = identity + " ";
List<Tree> chNodes = getNodes();
for (Tree t : chNodes) {
((Command)t).print(identity);
}
}
public void execute() throws Exception {
System.out.println("Executing command: " + getName());
if (command != null && !"".equals(command)) {
String commandSaved = command;
if (!isUsbCommand()) {
if (!isHardcoded()) {
Integer newVal = value;
if (min != null && max != null) {
newVal = min + rand.nextInt(max - min);
}
command = command.replaceAll("xxx", newVal.toString());
int newSpeed = CommandSpeedDeterminator.getReccomendSpeed(this, newVal);
int idx = command.indexOf('T');
command = command.substring(0, idx+1);
command += newSpeed;
}
command += "\r\n";
}
//print();
//this work only for unix
if (OsUtils.isUnix()) {
ComPort comPort = openedPorts.get(port);
if (isUsbCommand()) {
comPort.writeCharByChar(command, 10);
} else {
comPort.write(command);
}
}
command = commandSaved;
}
for (Tree t : getNodes()) {
((Command)t).execute();
}
}
}
| true | true | public void compile() throws Exception {
//System.err.println("before:" + command);
if (port == null || "".equals(port))
port = DEFAULT_PORT_NAME;
addPort(port);
if (!isHardcoded()) {
if (command == null || "".equals(command))
return;
if (!command.contains("xxx")) {
throw new Exception("Wrong command format -no xxx");
}
Integer val;
if (value != null) {
val = value;
if (min == null && max == null) {
if (isUsbCommand()) {
String bytes = HexUtils.hexStringToByteArrayString(val.toString());
command = command.replaceAll("xxx", bytes);
} else {
command = command.replaceAll("xxx", val.toString());
}
}
} else {
if (min == null || max == null)
throw new Exception("Command: " + name + ": if now val preset at least min or max should be!");
}
if (!isUsbCommand()) {
command += COMMAND_SPEED_PREFIX + speed.toString();
}
}
command += "\r\n";
//System.err.println("after:" + command);
}
| public void compile() throws Exception {
//System.err.println("before:" + command);
if (port == null || "".equals(port))
port = DEFAULT_PORT_NAME;
addPort(port);
if (!isHardcoded()) {
if (command == null || "".equals(command))
return;
if (!command.contains("xxx")) {
throw new Exception("Wrong command format -no xxx");
}
Integer val;
if (value != null) {
val = value;
if (min == null && max == null) {
if (isUsbCommand()) {
//String bytes = HexUtils.hexStringToByteArrayString(val.toString());
char ch = (char)(val.intValue());
String s = "" + ch;
command = command.replaceAll("xxx", s);
} else {
command = command.replaceAll("xxx", val.toString());
}
}
} else {
if (min == null || max == null)
throw new Exception("Command: " + name + ": if now val preset at least min or max should be!");
}
if (!isUsbCommand()) {
command += COMMAND_SPEED_PREFIX + speed.toString();
}
}
command += "\r\n";
//System.err.println("after:" + command);
}
|
diff --git a/jetty/src/main/java/org/mortbay/io/nio/NIOBuffer.java b/jetty/src/main/java/org/mortbay/io/nio/NIOBuffer.java
index f33bb8c47..c6a947e8d 100644
--- a/jetty/src/main/java/org/mortbay/io/nio/NIOBuffer.java
+++ b/jetty/src/main/java/org/mortbay/io/nio/NIOBuffer.java
@@ -1,301 +1,305 @@
// ========================================================================
// Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.mortbay.io.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import org.mortbay.io.AbstractBuffer;
import org.mortbay.io.Buffer;
/* ------------------------------------------------------------------------------- */
/**
*
* @author gregw
*/
public class NIOBuffer extends AbstractBuffer
{
public final static boolean
DIRECT=true,
INDIRECT=false;
protected ByteBuffer _buf;
private ReadableByteChannel _in;
private InputStream _inStream;
private WritableByteChannel _out;
private OutputStream _outStream;
public NIOBuffer(int size, boolean direct)
{
super(READWRITE,NON_VOLATILE);
_buf = direct
?ByteBuffer.allocateDirect(size)
:ByteBuffer.allocate(size);
_buf.position(0);
_buf.limit(_buf.capacity());
}
/**
* @param file
*/
public NIOBuffer(File file) throws IOException
{
super(READONLY,NON_VOLATILE);
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
_buf = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
setGetIndex(0);
setPutIndex((int)file.length());
_access=IMMUTABLE;
}
public byte[] array()
{
if (!_buf.hasArray())
return null;
return _buf.array();
}
public int capacity()
{
return _buf.capacity();
}
public byte peek(int position)
{
return _buf.get(position);
}
public int peek(int index, byte[] b, int offset, int length)
{
int l = length;
if (index+l > capacity())
l=capacity()-index;
if (l <= 0)
return -1;
try
{
_buf.position(index);
_buf.get(b,offset,l);
}
finally
{
_buf.position(0);
}
return l;
}
public void poke(int position, byte b)
{
if (isReadOnly()) throw new IllegalStateException(__READONLY);
_buf.put(position,b);
}
public int poke(int index, Buffer src)
{
if (isReadOnly()) throw new IllegalStateException(__READONLY);
byte[] array=src.array();
if (array!=null)
{
int length = poke(index,array,src.getIndex(),src.length());
return length;
}
else
{
Buffer src_buf=src.buffer();
if (src_buf instanceof NIOBuffer)
{
ByteBuffer src_bytebuf = ((NIOBuffer)src_buf)._buf;
if (src_bytebuf==_buf)
src_bytebuf=_buf.duplicate();
try
{
_buf.position(index);
int space = _buf.remaining();
int length=src.length();
if (length>space)
length=space;
src_bytebuf.position(src.getIndex());
src_bytebuf.limit(src.getIndex()+length);
_buf.put(src_bytebuf);
return length;
}
finally
{
_buf.position(0);
src_bytebuf.limit(src_bytebuf.capacity());
src_bytebuf.position(0);
}
}
else
return super.poke(index,src);
}
}
public int poke(int index, byte[] b, int offset, int length)
{
if (isReadOnly()) throw new IllegalStateException(__READONLY);
try
{
_buf.position(index);
int space=_buf.remaining();
if (length>space)
length=space;
if (length>0)
_buf.put(b,offset,length);
return length;
}
finally
{
_buf.position(0);
}
}
public ByteBuffer getByteBuffer()
{
return _buf;
}
public void setByteBuffer(ByteBuffer buf)
{
this._buf = buf;
}
/* ------------------------------------------------------------ */
public int readFrom(InputStream in, int max) throws IOException
{
if (_in==null || !_in.isOpen() || in!=_inStream)
{
_in=Channels.newChannel(in);
_inStream=in;
}
if (max<0 || max>space())
max=space();
int p = putIndex();
try
{
int len=0, total=0, available=max;
+ int loop=0;
while (total<max)
{
_buf.position(p);
_buf.limit(p+available);
len=_in.read(_buf);
if (len<0)
{
_in=null;
_inStream=in;
break;
}
else if (len>0)
{
p += len;
total += len;
available -= len;
setPutIndex(p);
+ loop=0;
}
+ else if (loop++>1)
+ break;
if (in.available()<=0)
break;
}
if (len<0 && total==0)
return -1;
return total;
}
catch(IOException e)
{
_in=null;
_inStream=in;
throw e;
}
finally
{
if (_in!=null && !_in.isOpen())
{
_in=null;
_inStream=in;
}
_buf.position(0);
_buf.limit(_buf.capacity());
}
}
/* ------------------------------------------------------------ */
public void writeTo(OutputStream out) throws IOException
{
if (_out==null || !_out.isOpen() || _out!=_outStream)
{
_out=Channels.newChannel(out);
_outStream=out;
}
try
{
int loop=0;
while(hasContent() && _out.isOpen())
{
_buf.position(getIndex());
_buf.limit(putIndex());
int len=_out.write(_buf);
if (len<0)
break;
else if (len>0)
{
skip(len);
loop=0;
}
else if (loop++>1)
break;
}
}
catch(IOException e)
{
_out=null;
_outStream=null;
throw e;
}
finally
{
if (_out!=null && !_out.isOpen())
{
_out=null;
_outStream=null;
}
_buf.position(0);
_buf.limit(_buf.capacity());
}
}
}
| false | true | public int readFrom(InputStream in, int max) throws IOException
{
if (_in==null || !_in.isOpen() || in!=_inStream)
{
_in=Channels.newChannel(in);
_inStream=in;
}
if (max<0 || max>space())
max=space();
int p = putIndex();
try
{
int len=0, total=0, available=max;
while (total<max)
{
_buf.position(p);
_buf.limit(p+available);
len=_in.read(_buf);
if (len<0)
{
_in=null;
_inStream=in;
break;
}
else if (len>0)
{
p += len;
total += len;
available -= len;
setPutIndex(p);
}
if (in.available()<=0)
break;
}
if (len<0 && total==0)
return -1;
return total;
}
catch(IOException e)
{
_in=null;
_inStream=in;
throw e;
}
finally
{
if (_in!=null && !_in.isOpen())
{
_in=null;
_inStream=in;
}
_buf.position(0);
_buf.limit(_buf.capacity());
}
}
| public int readFrom(InputStream in, int max) throws IOException
{
if (_in==null || !_in.isOpen() || in!=_inStream)
{
_in=Channels.newChannel(in);
_inStream=in;
}
if (max<0 || max>space())
max=space();
int p = putIndex();
try
{
int len=0, total=0, available=max;
int loop=0;
while (total<max)
{
_buf.position(p);
_buf.limit(p+available);
len=_in.read(_buf);
if (len<0)
{
_in=null;
_inStream=in;
break;
}
else if (len>0)
{
p += len;
total += len;
available -= len;
setPutIndex(p);
loop=0;
}
else if (loop++>1)
break;
if (in.available()<=0)
break;
}
if (len<0 && total==0)
return -1;
return total;
}
catch(IOException e)
{
_in=null;
_inStream=in;
throw e;
}
finally
{
if (_in!=null && !_in.isOpen())
{
_in=null;
_inStream=in;
}
_buf.position(0);
_buf.limit(_buf.capacity());
}
}
|
diff --git a/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/ServicesAcquisitionStorage.java b/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/ServicesAcquisitionStorage.java
index 75fe4c86..49551723 100644
--- a/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/ServicesAcquisitionStorage.java
+++ b/cspi-services/src/main/java/org/collectionspace/chain/csp/persistence/services/ServicesAcquisitionStorage.java
@@ -1,17 +1,17 @@
package org.collectionspace.chain.csp.persistence.services;
import java.io.IOException;
import org.collectionspace.chain.util.jxj.InvalidJXJException;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.helper.persistence.ContextualisedStorage;
import org.dom4j.DocumentException;
public class ServicesAcquisitionStorage extends GenericRecordStorage implements ContextualisedStorage {
public ServicesAcquisitionStorage(ServicesConnection conn) throws InvalidJXJException, DocumentException, IOException {
super(conn,"acquisition.jxj","acquisition","acquisitions",
"acquisitions_common","acquisitions-common-list/acquisition-list-item",
- new String[]{"acquReferenceNum"},null);
+ new String[]{"AcquisitionReferenceNumber"},new String[]{"acquReferenceNum"});
}
}
| true | true | public ServicesAcquisitionStorage(ServicesConnection conn) throws InvalidJXJException, DocumentException, IOException {
super(conn,"acquisition.jxj","acquisition","acquisitions",
"acquisitions_common","acquisitions-common-list/acquisition-list-item",
new String[]{"acquReferenceNum"},null);
}
| public ServicesAcquisitionStorage(ServicesConnection conn) throws InvalidJXJException, DocumentException, IOException {
super(conn,"acquisition.jxj","acquisition","acquisitions",
"acquisitions_common","acquisitions-common-list/acquisition-list-item",
new String[]{"AcquisitionReferenceNumber"},new String[]{"acquReferenceNum"});
}
|
diff --git a/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java b/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java
index 789ef754..b1761333 100644
--- a/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java
+++ b/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java
@@ -1,394 +1,394 @@
package org.cishell.utilities;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
// TODO: Fix this class.
public class DateUtilities {
public static final String MONTH_DAY_YEAR_DATE_FORMAT =
"Month-Day-Year Date Format";
public static final String DAY_MONTH_YEAR_DATE_FORMAT =
"Day-Month-Year Date Format";
public final static double AVERAGE_MILLIS_PER_MONTH =
(365.24 * 24 * 60 * 60 * 1000 / 12);
// TODO: Is this actually necessary?
public static Date[] generateDaysBetweenDates(Date startDate, Date endDate) {
GregorianCalendar startDateCalendar =
new GregorianCalendar(startDate.getYear() + 1900,
startDate.getMonth(),
startDate.getDate());
GregorianCalendar endDateCalendar =
new GregorianCalendar(endDate.getYear() + 1900,
endDate.getMonth(),
endDate.getDate());
// Return an empty set of days (Dates) if the start date is actually AFTER
// the end date.
if (startDateCalendar.getTimeInMillis() > endDateCalendar.getTimeInMillis())
return new Date [0];
// There is at least one day between the provided start and end dates (dates
// themselves included).
ArrayList workingDaysBetweenDates = new ArrayList();
GregorianCalendar currentCalendarForDateThatWeAreCalculating =
(GregorianCalendar)startDateCalendar.clone();
final Date actualEndDateAccordingToCalendar = endDateCalendar.getTime();
boolean shouldKeepGeneratingDaysBetweenDates = true;
// This is the meat of the Date generation.
while (shouldKeepGeneratingDaysBetweenDates) {
// Get the current calculated date.
Date currentCalculatedDate =
currentCalendarForDateThatWeAreCalculating.getTime();
// Add the current date that we are calculating.
workingDaysBetweenDates.add(currentCalculatedDate);
// Move the current calendar for the date that we are calculating
// forward in time a day.
currentCalendarForDateThatWeAreCalculating.add(Calendar.DATE, 1);
// Should we stop now?
if ((currentCalculatedDate.getYear() ==
actualEndDateAccordingToCalendar.getYear()) &&
(currentCalculatedDate.getMonth() ==
actualEndDateAccordingToCalendar.getMonth()) &&
(currentCalculatedDate.getDate() ==
actualEndDateAccordingToCalendar.getDate()))
{
shouldKeepGeneratingDaysBetweenDates = false;
}
}
Date[] finalDaysBetweenDates = new Date [workingDaysBetweenDates.size()];
return (Date[])workingDaysBetweenDates.toArray(finalDaysBetweenDates);
}
public static int calculateDaysBetween(Date[] dateSet) {
return dateSet.length;
}
public static int calculateDaysBetween(Date startDate, Date endDate) {
FAQCalendar startDateCalendar = new FAQCalendar(startDate.getYear(),
startDate.getMonth(),
startDate.getDate());
FAQCalendar endDateCalendar = new FAQCalendar(endDate.getYear(),
endDate.getMonth(),
endDate.getDate());
return (int) startDateCalendar.diffDayPeriods(endDateCalendar);
}
public static int calculateMonthsBetween(Date startDate, Date endDate) {
int roundedMonthsBetween = (int)Math.round
((endDate.getTime() - startDate.getTime()) / AVERAGE_MILLIS_PER_MONTH);
if (roundedMonthsBetween > 0) {
return roundedMonthsBetween;
}
else {
// HACK(?): There must be at least one month between
// (even if they're both the same month).
return 1;
}
}
// Assumes dateSet is sorted from earliest to latest.
public static Date[] getNewYearsDatesFromDateSet(Date[] dateSet) {
ArrayList workingNewYearsDates = new ArrayList();
// Return an empty set if there are no dates.
if (dateSet.length == 0)
return new Date [0];
// If the first date is not a new year's date, add a new year's date for
// that date's year.
if ((dateSet[0].getMonth() != 0) || (dateSet[0].getDate() != 1))
workingNewYearsDates.add(new Date(dateSet[0].getYear(), 0, 1));
// Find each date that has the month and day of 1-1 (well, 0-1 because Date
// is stupid).
for (int ii = 0; ii < dateSet.length; ii++) {
if ((dateSet[ii].getMonth() == 0) && (dateSet[ii].getDate() == 1))
workingNewYearsDates.add(dateSet[ii]);
}
Date[] finalNewYearsDates = new Date [workingNewYearsDates.size()];
return (Date[])workingNewYearsDates.toArray(finalNewYearsDates);
}
public static Date[] generateNewYearsDatesBetweenDates(Date startDate,
Date endDate)
{
final int startDateYear = startDate.getYear();
final int endDateYear = endDate.getYear();
// The number of years between the two years (inclusive).
final int numYearsBetween = ((endDateYear - startDateYear) + 1);
// Return an empty array if the start date is after the end date.
if (numYearsBetween == 0)
return new Date[] { };
Date[] newYearsDatesBetween = new Date [numYearsBetween];
for (int ii = 0; ii < numYearsBetween; ii++)
newYearsDatesBetween[ii] = new Date((startDateYear + ii), 0, 1);
return newYearsDatesBetween;
}
// TODO: This could also REALLY be improved.
public static Date[] generateFirstOfTheMonthDatesBetweenDates(Date[] dateSet) {
ArrayList workingFirstOfTheMonthDates = new ArrayList();
// Find each date that has the day of 1.
for (int ii = 0; ii < dateSet.length; ii++) {
if (dateSet[ii].getDate() == 1)
workingFirstOfTheMonthDates.add(dateSet[ii]);
}
Date[] finalFirstOfTheMonthDates =
new Date [workingFirstOfTheMonthDates.size()];
return (Date[])workingFirstOfTheMonthDates.toArray
(finalFirstOfTheMonthDates);
}
public static Date[] generateFirstOfTheMonthDatesBetweenDates(Date startDate,
Date endDate)
{
Date[] allDaysBetweenDates = generateDaysBetweenDates(startDate, endDate);
return generateFirstOfTheMonthDatesBetweenDates(allDaysBetweenDates);
}
//TODO: These should be sorted so the first format checked is the most likely format, etc...
private static final DateFormat[] MONTH_DAY_YEAR_DATE_FORMATS = {
new SimpleDateFormat("MM-d-yy"),
new SimpleDateFormat("MM-d-yyyy"),
new SimpleDateFormat("MM-dd-yy"),
new SimpleDateFormat("MM-dd-yyyy"),
new SimpleDateFormat("MM/d/yy"),
new SimpleDateFormat("MM/dd/yy"),
new SimpleDateFormat("MM/d/yyyy"),
new SimpleDateFormat("MMM/dd/yyyy"),
new SimpleDateFormat("MMM-d-yy"),
new SimpleDateFormat("MMM-d-yyyy"),
new SimpleDateFormat("MMM-dd-yy"),
new SimpleDateFormat("MMM-dd-yyyy"),
new SimpleDateFormat("MMM/d/yy"),
new SimpleDateFormat("MMM/dd/yy"),
new SimpleDateFormat("MMM/d/yyyy"),
new SimpleDateFormat("MMM/dd/yyyy"),
new SimpleDateFormat("yyyy"),
DateFormat.getDateInstance(DateFormat.SHORT),
DateFormat.getDateInstance(DateFormat.MEDIUM),
DateFormat.getDateInstance(DateFormat.LONG),
};
private static final DateFormat[] DAY_MONTH_YEAR_DATE_FORMATS = {
DateFormat.getDateInstance(DateFormat.FULL),
new SimpleDateFormat("d-MM-yy"),
new SimpleDateFormat("d-MM-yyyy"),
new SimpleDateFormat("dd-MM-yy"),
new SimpleDateFormat("dd-MM-yyyy"),
new SimpleDateFormat("d/MM/yy"),
new SimpleDateFormat("dd/MM/yy"),
new SimpleDateFormat("d/MM/yyyy"),
new SimpleDateFormat("dd/MMM/yyyy"),
new SimpleDateFormat("d-MMM-yy"),
new SimpleDateFormat("d-MMM-yyyy"),
new SimpleDateFormat("dd-MMM-yy"),
new SimpleDateFormat("dd-MMM-yyyy"),
new SimpleDateFormat("d/MMM/yy"),
new SimpleDateFormat("dd/MMM/yy"),
new SimpleDateFormat("d/MMM/yyyy"),
new SimpleDateFormat("dd/MMM/yyyy"),
new SimpleDateFormat("yyyy"),
DateFormat.getDateInstance(DateFormat.SHORT),
DateFormat.getDateInstance(DateFormat.MEDIUM),
DateFormat.getDateInstance(DateFormat.LONG),
};
public static Date parseDate(String dateString) throws ParseException {
return parseDate(dateString, true);
}
public static Date parseDate(String dateString, boolean fixYear)
throws ParseException {
return (parseDate(dateString, MONTH_DAY_YEAR_DATE_FORMATS, fixYear));
}
public static Date parseDate(String dateString, String suggestedDateFormat)
throws ParseException {
return parseDate(dateString, suggestedDateFormat, true);
}
public static Date parseDate(
String dateString, String suggestedDateFormat, boolean fixYear)
throws ParseException {
if (MONTH_DAY_YEAR_DATE_FORMAT.equals(suggestedDateFormat)) {
return parseDate(dateString, MONTH_DAY_YEAR_DATE_FORMATS, fixYear);
} else if (DAY_MONTH_YEAR_DATE_FORMAT.equals(suggestedDateFormat)) {
return parseDate(dateString, DAY_MONTH_YEAR_DATE_FORMATS, fixYear);
} else {
DateFormat[] dateFormats = new DateFormat[] {
new SimpleDateFormat(suggestedDateFormat)
};
return parseDate(dateString, dateFormats, fixYear);
}
}
public static Date parseDate(String dateString, DateFormat[] dateFormats)
throws ParseException {
return parseDate(dateString, dateFormats, true);
}
public static Date parseDate(
String dateString, DateFormat[] dateFormats, boolean fixYear)
throws ParseException {
for (int ii = 0; ii < dateFormats.length; ii++) {
try {
DateFormat format = dateFormats[ii];
format.setLenient(false);
Date date = format.parse(dateString);
if (fixYear && (date.getYear() < 1900)) {
date.setYear(date.getYear() + 1900);
}
return date;
}
catch (ParseException dateParseException) {
continue;
}
}
String exceptionMessage = "Could not parse the field " +
"'" + dateString + "'" +
" as a date.";
throw new ParseException(exceptionMessage, 0);
}
public static Date interpretObjectAsDate(Object object)
throws ParseException {
return interpretObjectAsDate(object, "");
}
public static Date interpretObjectAsDate(Object object, String dateFormat)
throws ParseException {
return interpretObjectAsDate(object, dateFormat, true);
}
public static Date interpretObjectAsDate(
Object object, String dateFormat, boolean fixYear)
throws ParseException {
final String EMPTY_DATE_MESSAGE = "An empty date was found.";
String objectAsString = object.toString();
// TODO: These if's are a result of a "bug" in Prefuse's.
// CSV Table Reader, which interprets a column as being an array type
// if it has empty cells.
if (object instanceof Date) {
return (Date)object;
}
else if (object instanceof short[]) {
short[] year = (short[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Short[]) {
Short[] year = (Short[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof int[]) {
int[] year = (int[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Integer[]) {
Integer[] year = (Integer[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = year.toString();
}
}
else if (object instanceof long[]) {
long[] year = (long[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Long[]) {
Long[] year = (Long[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof String[]) {
String[] year = (String[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = year[0];
}
}
- return parseDate(objectAsString, dateFormat, fixYear);
+ return parseDate(objectAsString.trim(), dateFormat, fixYear);
}
private static Date fixDateYear(Date date) {
if (date.getYear() < 1900) {
Date fixedDate = (Date)date.clone();
fixedDate.setYear(date.getYear() + 1900);
return fixedDate;
} else {
return date;
}
}
}
| true | true | public static Date interpretObjectAsDate(
Object object, String dateFormat, boolean fixYear)
throws ParseException {
final String EMPTY_DATE_MESSAGE = "An empty date was found.";
String objectAsString = object.toString();
// TODO: These if's are a result of a "bug" in Prefuse's.
// CSV Table Reader, which interprets a column as being an array type
// if it has empty cells.
if (object instanceof Date) {
return (Date)object;
}
else if (object instanceof short[]) {
short[] year = (short[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Short[]) {
Short[] year = (Short[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof int[]) {
int[] year = (int[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Integer[]) {
Integer[] year = (Integer[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = year.toString();
}
}
else if (object instanceof long[]) {
long[] year = (long[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Long[]) {
Long[] year = (Long[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof String[]) {
String[] year = (String[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = year[0];
}
}
return parseDate(objectAsString, dateFormat, fixYear);
}
| public static Date interpretObjectAsDate(
Object object, String dateFormat, boolean fixYear)
throws ParseException {
final String EMPTY_DATE_MESSAGE = "An empty date was found.";
String objectAsString = object.toString();
// TODO: These if's are a result of a "bug" in Prefuse's.
// CSV Table Reader, which interprets a column as being an array type
// if it has empty cells.
if (object instanceof Date) {
return (Date)object;
}
else if (object instanceof short[]) {
short[] year = (short[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Short[]) {
Short[] year = (Short[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof int[]) {
int[] year = (int[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Integer[]) {
Integer[] year = (Integer[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = year.toString();
}
}
else if (object instanceof long[]) {
long[] year = (long[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof Long[]) {
Long[] year = (Long[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = "" + year[0];
}
}
else if (object instanceof String[]) {
String[] year = (String[])object;
if (year.length == 0) {
throw new ParseException(EMPTY_DATE_MESSAGE, 0);
}
else {
objectAsString = year[0];
}
}
return parseDate(objectAsString.trim(), dateFormat, fixYear);
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java
index e27871757..b5d3afa96 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/templates/NameTagHandler.java
@@ -1,61 +1,62 @@
/*
* 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.shindig.gadgets.templates;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.google.inject.Inject;
/**
* TagHandler for the <os:Name person="..."/> tag.
*/
public class NameTagHandler extends AbstractTagHandler {
static final String TAG_NAME = "Name";
static final String PERSON_ATTR = "person";
@Inject
public NameTagHandler() {
super(TagHandler.OPENSOCIAL_NAMESPACE, TAG_NAME);
}
public void process(Node result, Element tag, TemplateProcessor processor) {
JSONObject person = getValueFromTag(tag, PERSON_ATTR, processor, JSONObject.class);
if (person == null) {
return;
}
JSONObject name = person.optJSONObject("name");
if (name == null) {
return;
}
String formatted = name.optString("formatted");
if (formatted.length() == 0) {
formatted = name.optString("givenName") + " " + name.optString("familyName");
}
Document doc = result.getOwnerDocument();
Element root = doc.createElement("b");
+ result.appendChild(root);
appendTextNode(root, formatted);
}
}
| true | true | public void process(Node result, Element tag, TemplateProcessor processor) {
JSONObject person = getValueFromTag(tag, PERSON_ATTR, processor, JSONObject.class);
if (person == null) {
return;
}
JSONObject name = person.optJSONObject("name");
if (name == null) {
return;
}
String formatted = name.optString("formatted");
if (formatted.length() == 0) {
formatted = name.optString("givenName") + " " + name.optString("familyName");
}
Document doc = result.getOwnerDocument();
Element root = doc.createElement("b");
appendTextNode(root, formatted);
}
| public void process(Node result, Element tag, TemplateProcessor processor) {
JSONObject person = getValueFromTag(tag, PERSON_ATTR, processor, JSONObject.class);
if (person == null) {
return;
}
JSONObject name = person.optJSONObject("name");
if (name == null) {
return;
}
String formatted = name.optString("formatted");
if (formatted.length() == 0) {
formatted = name.optString("givenName") + " " + name.optString("familyName");
}
Document doc = result.getOwnerDocument();
Element root = doc.createElement("b");
result.appendChild(root);
appendTextNode(root, formatted);
}
|
diff --git a/javasrc/src/org/ccnx/ccn/profiles/namespace/NamespaceManager.java b/javasrc/src/org/ccnx/ccn/profiles/namespace/NamespaceManager.java
index 70580b39f..2c6b6148e 100644
--- a/javasrc/src/org/ccnx/ccn/profiles/namespace/NamespaceManager.java
+++ b/javasrc/src/org/ccnx/ccn/profiles/namespace/NamespaceManager.java
@@ -1,114 +1,114 @@
/**
* Part of the CCNx Java Library.
*
* Copyright (C) 2009,2010 Palo Alto Research Center, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details. You should have received
* a copy of the GNU Lesser General Public License along with this library;
* if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA.
*/
package org.ccnx.ccn.profiles.namespace;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.profiles.VersioningProfile;
import org.ccnx.ccn.profiles.search.Pathfinder;
import org.ccnx.ccn.profiles.search.Pathfinder.SearchResults;
import org.ccnx.ccn.protocol.ContentName;
/**
* Maintains a list of existing policy marker prefixes.
**/
public class NamespaceManager {
protected static Set<ContentName> _searchedPathCache = new HashSet<ContentName>();
protected static Set<ContentName> _policyControlledNamespaces = new HashSet<ContentName>();
/**
* Find the closest policy controlled namespace that cover operations on a specific name.
* If none exists in memory than this searches up the name tree.
* @throws IOException
*/
public static ContentName findPolicyControlledNamespace(ContentName controlledName, CCNHandle handle) throws IOException {
// See if we already have a prefix controlling this name.
for (ContentName prefix : _policyControlledNamespaces) {
if (inProtectedNamespace(prefix, controlledName)) {
// Doesn't handle nesting... want to find the longest match that matches this name,
// while marking ones we don't have to search again. Works for now, might need to make
// this more sophisticated if applications warrant.
Log.info("Found policy control prefix {0} protecting {1}", prefix, controlledName);
return prefix;
}
}
// No known prefix exists for this name - now look to see if we can find a prefix up the path to create one...
ContentName searchName = VersioningProfile.cutTerminalVersion(controlledName).first();
Log.info("No cached policy control prefix found, searching for root object for {0}. Removed terminal version, checking path {1}", controlledName, searchName);
// Have a cache of searched paths, so we don't re-search.
if (cacheContainsPath(searchName)) {
Log.info("Cache indicates that we have already checked the path {0} for namespace roots, with none found. Returning null.", searchName);
return null;
}
// Search up a path (towards the root) for an Access Control root marker
Pathfinder pathfinder = new Pathfinder(searchName, null,
NamespaceProfile.policyPostfix(), true, false,
SystemConfiguration.SHORT_TIMEOUT,
_searchedPathCache,
handle);
SearchResults results = pathfinder.waitForResults();
if (null != results.getExcluded()) {
_searchedPathCache.addAll(results.getExcluded());
}
if (null != results.getResult()) {
- ContentName policyPrefix = results.getResult().name().cut(searchName.count() + NamespaceProfile.policyPostfix().count());
+ ContentName policyPrefix = results.getResult().name().cut(results.getInterestName().count() + NamespaceProfile.policyPostfix().count());
_policyControlledNamespaces.add(policyPrefix);
return policyPrefix;
}
return null;
}
public synchronized static void clearSearchedPathCache() { _searchedPathCache.clear(); }
public synchronized static void addToSearchedPathCache(Set<ContentName> newPaths) {
_searchedPathCache.addAll(newPaths);
}
public synchronized static void removeFromSearchedPathCache(ContentName path) {
_searchedPathCache.remove(path);
}
public static boolean cacheContainsPath(ContentName path) {
// Need cache to contain everything on the path to be useful.
while (_searchedPathCache.contains(path)) {
if (path.equals(ContentName.ROOT)) {
break;
}
path = path.parent();
}
if (path.equals(ContentName.ROOT) && _searchedPathCache.contains(path)) {
return true;
}
return false;
}
public static boolean inProtectedNamespace(ContentName namespace, ContentName content) {
return namespace.isPrefixOf(content);
}
}
| true | true | public static ContentName findPolicyControlledNamespace(ContentName controlledName, CCNHandle handle) throws IOException {
// See if we already have a prefix controlling this name.
for (ContentName prefix : _policyControlledNamespaces) {
if (inProtectedNamespace(prefix, controlledName)) {
// Doesn't handle nesting... want to find the longest match that matches this name,
// while marking ones we don't have to search again. Works for now, might need to make
// this more sophisticated if applications warrant.
Log.info("Found policy control prefix {0} protecting {1}", prefix, controlledName);
return prefix;
}
}
// No known prefix exists for this name - now look to see if we can find a prefix up the path to create one...
ContentName searchName = VersioningProfile.cutTerminalVersion(controlledName).first();
Log.info("No cached policy control prefix found, searching for root object for {0}. Removed terminal version, checking path {1}", controlledName, searchName);
// Have a cache of searched paths, so we don't re-search.
if (cacheContainsPath(searchName)) {
Log.info("Cache indicates that we have already checked the path {0} for namespace roots, with none found. Returning null.", searchName);
return null;
}
// Search up a path (towards the root) for an Access Control root marker
Pathfinder pathfinder = new Pathfinder(searchName, null,
NamespaceProfile.policyPostfix(), true, false,
SystemConfiguration.SHORT_TIMEOUT,
_searchedPathCache,
handle);
SearchResults results = pathfinder.waitForResults();
if (null != results.getExcluded()) {
_searchedPathCache.addAll(results.getExcluded());
}
if (null != results.getResult()) {
ContentName policyPrefix = results.getResult().name().cut(searchName.count() + NamespaceProfile.policyPostfix().count());
_policyControlledNamespaces.add(policyPrefix);
return policyPrefix;
}
return null;
}
| public static ContentName findPolicyControlledNamespace(ContentName controlledName, CCNHandle handle) throws IOException {
// See if we already have a prefix controlling this name.
for (ContentName prefix : _policyControlledNamespaces) {
if (inProtectedNamespace(prefix, controlledName)) {
// Doesn't handle nesting... want to find the longest match that matches this name,
// while marking ones we don't have to search again. Works for now, might need to make
// this more sophisticated if applications warrant.
Log.info("Found policy control prefix {0} protecting {1}", prefix, controlledName);
return prefix;
}
}
// No known prefix exists for this name - now look to see if we can find a prefix up the path to create one...
ContentName searchName = VersioningProfile.cutTerminalVersion(controlledName).first();
Log.info("No cached policy control prefix found, searching for root object for {0}. Removed terminal version, checking path {1}", controlledName, searchName);
// Have a cache of searched paths, so we don't re-search.
if (cacheContainsPath(searchName)) {
Log.info("Cache indicates that we have already checked the path {0} for namespace roots, with none found. Returning null.", searchName);
return null;
}
// Search up a path (towards the root) for an Access Control root marker
Pathfinder pathfinder = new Pathfinder(searchName, null,
NamespaceProfile.policyPostfix(), true, false,
SystemConfiguration.SHORT_TIMEOUT,
_searchedPathCache,
handle);
SearchResults results = pathfinder.waitForResults();
if (null != results.getExcluded()) {
_searchedPathCache.addAll(results.getExcluded());
}
if (null != results.getResult()) {
ContentName policyPrefix = results.getResult().name().cut(results.getInterestName().count() + NamespaceProfile.policyPostfix().count());
_policyControlledNamespaces.add(policyPrefix);
return policyPrefix;
}
return null;
}
|
diff --git a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/Template.java b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/Template.java
index 795da63159..c6bcddf55d 100644
--- a/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/Template.java
+++ b/oak-core/src/main/java/org/apache/jackrabbit/oak/plugins/segment/Template.java
@@ -1,488 +1,488 @@
/*
* 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.jackrabbit.oak.plugins.segment;
import static com.google.common.base.Preconditions.checkElementIndex;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.MISSING_NODE;
import static org.apache.jackrabbit.oak.plugins.segment.Segment.RECORD_ID_BYTES;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.plugins.memory.MemoryChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateDiff;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
class Template {
static final String ZERO_CHILD_NODES = null;
static final String MANY_CHILD_NODES = "";
/**
* The {@code jcr:primaryType} property, if present as a single-valued
* {@code NAME} property. Otherwise {@code null}.
*/
@CheckForNull
private final PropertyState primaryType;
/**
* The {@code jcr:mixinTypes} property, if present as a multi-valued
* {@code NAME} property. Otherwise {@code null}.
*/
@CheckForNull
private final PropertyState mixinTypes;
/**
* Templates of all the properties of a node, excluding the
* above-mentioned {@code NAME}-valued type properties, if any.
*/
@Nonnull
private final PropertyTemplate[] properties;
/**
* Name of the single child node, if the node contains just one child.
* Otherwise {@link #ZERO_CHILD_NODES} (i.e. {@code null}) if there are
* no children, or {@link #MANY_CHILD_NODES} if there are more than one.
*/
@CheckForNull
private final String childName;
Template(
PropertyState primaryType, PropertyState mixinTypes,
PropertyTemplate[] properties, String childName) {
this.primaryType = primaryType;
this.mixinTypes = mixinTypes;
this.properties = properties;
this.childName = childName;
}
Template(NodeState state) {
PropertyState primary = null;
PropertyState mixins = null;
List<PropertyTemplate> templates = Lists.newArrayList();
for (PropertyState property : state.getProperties()) {
String name = property.getName();
Type<?> type = property.getType();
if ("jcr:primaryType".equals(name) && type == Type.NAME) {
primary = property;
} else if ("jcr:mixinTypes".equals(name) && type == Type.NAMES) {
mixins = property;
} else {
templates.add(new PropertyTemplate(property));
}
}
this.primaryType = primary;
this.mixinTypes = mixins;
this.properties =
templates.toArray(new PropertyTemplate[templates.size()]);
Arrays.sort(properties);
long count = state.getChildNodeCount();
if (count == 0) {
childName = ZERO_CHILD_NODES;
} else if (count == 1) {
childName = state.getChildNodeNames().iterator().next();
checkState(childName != null && !childName.equals(MANY_CHILD_NODES));
} else {
childName = MANY_CHILD_NODES;
}
}
public boolean hasPrimaryType() {
return primaryType != null;
}
public String getPrimaryType() {
if (primaryType != null) {
return primaryType.getValue(Type.NAME);
} else {
return null;
}
}
public boolean hasMixinTypes() {
return mixinTypes != null;
}
public Iterable<String> getMixinTypes() {
if (mixinTypes != null) {
return mixinTypes.getValue(Type.NAMES);
} else {
return null;
}
}
public PropertyTemplate[] getPropertyTemplates() {
return properties;
}
public boolean hasNoChildNodes() {
return childName == ZERO_CHILD_NODES;
}
public boolean hasOneChildNode() {
return !hasNoChildNodes() && !hasManyChildNodes();
}
public boolean hasManyChildNodes() {
return childName == MANY_CHILD_NODES;
}
public String getChildName() {
if (hasOneChildNode()) {
return childName;
} else {
return null;
}
}
public int getPropertyCount() {
if (primaryType != null && mixinTypes != null) {
return properties.length + 2;
} else if (primaryType != null || mixinTypes != null) {
return properties.length + 1;
} else {
return properties.length;
}
}
public PropertyState getProperty(
String name, SegmentStore store, RecordId recordId) {
if ("jcr:primaryType".equals(name) && primaryType != null) {
return primaryType;
} else if ("jcr:mixinTypes".equals(name) && mixinTypes != null) {
return mixinTypes;
} else {
int hash = name.hashCode();
int index = 0;
while (index < properties.length
&& properties[index].getName().hashCode() < hash) {
index++;
}
while (index < properties.length
&& properties[index].getName().hashCode() == hash) {
if (name.equals(properties[index].getName())) {
return getProperty(store, recordId, index);
}
index++;
}
return null;
}
}
private PropertyState getProperty(
SegmentStore store, RecordId recordId, int index) {
checkNotNull(store);
checkNotNull(recordId);
checkElementIndex(index, properties.length);
int offset = recordId.getOffset() + RECORD_ID_BYTES;
if (!hasNoChildNodes()) {
offset += RECORD_ID_BYTES;
}
offset += index * RECORD_ID_BYTES;
Segment segment = store.readSegment(recordId.getSegmentId());
return new SegmentPropertyState(
properties[index], store, segment.readRecordId(offset));
}
public Iterable<PropertyState> getProperties(
SegmentStore store, RecordId recordId) {
List<PropertyState> list =
Lists.newArrayListWithCapacity(properties.length + 2);
if (primaryType != null) {
list.add(primaryType);
}
if (mixinTypes != null) {
list.add(mixinTypes);
}
int offset = recordId.getOffset() + RECORD_ID_BYTES;
if (!hasNoChildNodes()) {
offset += RECORD_ID_BYTES;
}
Segment segment = store.readSegment(recordId.getSegmentId());
for (int i = 0; i < properties.length; i++) {
RecordId propertyId = segment.readRecordId(offset);
list.add(new SegmentPropertyState(
properties[i], store, propertyId));
offset += RECORD_ID_BYTES;
}
return list;
}
public long getChildNodeCount(SegmentStore store, RecordId recordId) {
if (hasNoChildNodes()) {
return 0;
} else if (hasManyChildNodes()) {
MapRecord map = getChildNodeMap(store, recordId);
return map.size();
} else {
return 1;
}
}
MapRecord getChildNodeMap(SegmentStore store, RecordId recordId) {
checkState(hasManyChildNodes());
int offset = recordId.getOffset() + RECORD_ID_BYTES;
Segment segment = store.readSegment(recordId.getSegmentId());
RecordId childNodesId = segment.readRecordId(offset);
return MapRecord.readMap(store, childNodesId);
}
public boolean hasChildNode(
String name, SegmentStore store, RecordId recordId) {
if (hasNoChildNodes()) {
return false;
} else if (hasManyChildNodes()) {
MapRecord map = getChildNodeMap(store, recordId);
return map.getEntry(name) != null;
} else {
return name.equals(childName);
}
}
public NodeState getChildNode(
String name, SegmentStore store, RecordId recordId) {
if (hasNoChildNodes()) {
return MISSING_NODE;
} else if (hasManyChildNodes()) {
MapRecord map = getChildNodeMap(store, recordId);
RecordId childNodeId = map.getEntry(name);
if (childNodeId != null) {
return new SegmentNodeState(store, childNodeId);
} else {
return MISSING_NODE;
}
} else if (name.equals(childName)) {
int offset = recordId.getOffset() + RECORD_ID_BYTES;
Segment segment = store.readSegment(recordId.getSegmentId());
RecordId childNodeId = segment.readRecordId(offset);
return new SegmentNodeState(store, childNodeId);
} else {
return MISSING_NODE;
}
}
Iterable<String> getChildNodeNames(SegmentStore store, RecordId recordId) {
if (hasNoChildNodes()) {
return Collections.emptyList();
} else if (hasManyChildNodes()) {
MapRecord map = getChildNodeMap(store, recordId);
return map.getKeys();
} else {
return Collections.singletonList(childName);
}
}
Iterable<? extends ChildNodeEntry> getChildNodeEntries(
SegmentStore store, RecordId recordId) {
if (hasNoChildNodes()) {
return Collections.emptyList();
} else if (hasManyChildNodes()) {
MapRecord map = getChildNodeMap(store, recordId);
return map.getEntries();
} else {
int offset = recordId.getOffset() + RECORD_ID_BYTES;
Segment segment = store.readSegment(recordId.getSegmentId());
RecordId childNodeId = segment.readRecordId(offset);
return Collections.singletonList(new MemoryChildNodeEntry(
childName, new SegmentNodeState(store, childNodeId)));
}
}
public void compareAgainstBaseState(
SegmentStore store, RecordId afterId,
Template beforeTemplate, RecordId beforeId,
NodeStateDiff diff) {
checkNotNull(store);
checkNotNull(afterId);
checkNotNull(beforeTemplate);
checkNotNull(beforeId);
checkNotNull(diff);
// Compare type properties
compareProperties(beforeTemplate.primaryType, primaryType, diff);
compareProperties(beforeTemplate.mixinTypes, mixinTypes, diff);
// Compare other properties, leveraging the ordering
int beforeIndex = 0;
int afterIndex = 0;
while (beforeIndex < beforeTemplate.properties.length
&& afterIndex < properties.length) {
int d = Integer.valueOf(properties[afterIndex].hashCode())
.compareTo(Integer.valueOf(beforeTemplate.properties[beforeIndex].hashCode()));
if (d == 0) {
d = properties[afterIndex].getName().compareTo(
beforeTemplate.properties[beforeIndex].getName());
}
PropertyState beforeProperty = null;
PropertyState afterProperty = null;
if (d < 0) {
afterProperty = getProperty(store, afterId, afterIndex++);
} else if (d > 0) {
beforeProperty = beforeTemplate.getProperty(
store, beforeId, beforeIndex++);
} else {
afterProperty = getProperty(store, afterId, afterIndex++);
beforeProperty = beforeTemplate.getProperty(
store, beforeId, beforeIndex++);
}
compareProperties(beforeProperty, afterProperty, diff);
}
while (afterIndex < properties.length) {
diff.propertyAdded(getProperty(store, afterId, afterIndex++));
}
while (beforeIndex < beforeTemplate.properties.length) {
diff.propertyDeleted(beforeTemplate.getProperty(
store, beforeId, beforeIndex++));
}
if (hasNoChildNodes()) {
if (!beforeTemplate.hasNoChildNodes()) {
for (ChildNodeEntry entry :
beforeTemplate.getChildNodeEntries(store, beforeId)) {
diff.childNodeDeleted(
entry.getName(), entry.getNodeState());
}
}
} else if (hasOneChildNode()) {
NodeState afterNode = getChildNode(childName, store, afterId);
NodeState beforeNode = beforeTemplate.getChildNode(
childName, store, beforeId);
- if (beforeNode == null) {
+ if (!beforeNode.exists()) {
diff.childNodeAdded(childName, afterNode);
} else if (!beforeNode.equals(afterNode)) {
diff.childNodeChanged(childName, beforeNode, afterNode);
}
- if ((beforeTemplate.hasOneChildNode() && beforeNode == null)
+ if ((beforeTemplate.hasOneChildNode() && !beforeNode.exists())
|| beforeTemplate.hasManyChildNodes()) {
for (ChildNodeEntry entry :
beforeTemplate.getChildNodeEntries(store, beforeId)) {
if (!childName.equals(entry.getName())) {
diff.childNodeDeleted(
entry.getName(), entry.getNodeState());
}
}
}
} else {
// TODO: Leverage the HAMT data structure for the comparison
Set<String> baseChildNodes = new HashSet<String>();
for (ChildNodeEntry beforeCNE
: beforeTemplate.getChildNodeEntries(store, beforeId)) {
String name = beforeCNE.getName();
NodeState beforeChild = beforeCNE.getNodeState();
NodeState afterChild = getChildNode(name, store, afterId);
- if (afterChild == null) {
+ if (!afterChild.exists()) {
diff.childNodeDeleted(name, beforeChild);
} else {
baseChildNodes.add(name);
if (!beforeChild.equals(afterChild)) {
diff.childNodeChanged(name, beforeChild, afterChild);
}
}
}
for (ChildNodeEntry afterChild
: getChildNodeEntries(store, afterId)) {
String name = afterChild.getName();
if (!baseChildNodes.contains(name)) {
diff.childNodeAdded(name, afterChild.getNodeState());
}
}
}
}
private void compareProperties(
PropertyState before, PropertyState after, NodeStateDiff diff) {
if (before == null) {
if (after != null) {
diff.propertyAdded(after);
}
} else if (after == null) {
diff.propertyDeleted(before);
} else if (!before.equals(after)) {
diff.propertyChanged(before, after);
}
}
//------------------------------------------------------------< Object >--
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
} else if (object instanceof Template) {
Template that = (Template) object;
return Objects.equal(primaryType, that.primaryType)
&& Objects.equal(mixinTypes, that.mixinTypes)
&& Arrays.equals(properties, that.properties)
&& Objects.equal(childName, that.childName);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(
primaryType, mixinTypes, Arrays.asList(properties), childName);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{ ");
if (primaryType != null) {
builder.append(primaryType);
builder.append(", ");
}
if (mixinTypes != null) {
builder.append(mixinTypes);
builder.append(", ");
}
for (int i = 0; i < properties.length; i++) {
builder.append(properties[i]);
builder.append(" = ?, ");
}
if (hasNoChildNodes()) {
builder.append("<no children>");
} else if (hasManyChildNodes()) {
builder.append("<many children>");
} else {
builder.append(childName + " = <node>");
}
builder.append(" }");
return builder.toString();
}
}
| false | true | public void compareAgainstBaseState(
SegmentStore store, RecordId afterId,
Template beforeTemplate, RecordId beforeId,
NodeStateDiff diff) {
checkNotNull(store);
checkNotNull(afterId);
checkNotNull(beforeTemplate);
checkNotNull(beforeId);
checkNotNull(diff);
// Compare type properties
compareProperties(beforeTemplate.primaryType, primaryType, diff);
compareProperties(beforeTemplate.mixinTypes, mixinTypes, diff);
// Compare other properties, leveraging the ordering
int beforeIndex = 0;
int afterIndex = 0;
while (beforeIndex < beforeTemplate.properties.length
&& afterIndex < properties.length) {
int d = Integer.valueOf(properties[afterIndex].hashCode())
.compareTo(Integer.valueOf(beforeTemplate.properties[beforeIndex].hashCode()));
if (d == 0) {
d = properties[afterIndex].getName().compareTo(
beforeTemplate.properties[beforeIndex].getName());
}
PropertyState beforeProperty = null;
PropertyState afterProperty = null;
if (d < 0) {
afterProperty = getProperty(store, afterId, afterIndex++);
} else if (d > 0) {
beforeProperty = beforeTemplate.getProperty(
store, beforeId, beforeIndex++);
} else {
afterProperty = getProperty(store, afterId, afterIndex++);
beforeProperty = beforeTemplate.getProperty(
store, beforeId, beforeIndex++);
}
compareProperties(beforeProperty, afterProperty, diff);
}
while (afterIndex < properties.length) {
diff.propertyAdded(getProperty(store, afterId, afterIndex++));
}
while (beforeIndex < beforeTemplate.properties.length) {
diff.propertyDeleted(beforeTemplate.getProperty(
store, beforeId, beforeIndex++));
}
if (hasNoChildNodes()) {
if (!beforeTemplate.hasNoChildNodes()) {
for (ChildNodeEntry entry :
beforeTemplate.getChildNodeEntries(store, beforeId)) {
diff.childNodeDeleted(
entry.getName(), entry.getNodeState());
}
}
} else if (hasOneChildNode()) {
NodeState afterNode = getChildNode(childName, store, afterId);
NodeState beforeNode = beforeTemplate.getChildNode(
childName, store, beforeId);
if (beforeNode == null) {
diff.childNodeAdded(childName, afterNode);
} else if (!beforeNode.equals(afterNode)) {
diff.childNodeChanged(childName, beforeNode, afterNode);
}
if ((beforeTemplate.hasOneChildNode() && beforeNode == null)
|| beforeTemplate.hasManyChildNodes()) {
for (ChildNodeEntry entry :
beforeTemplate.getChildNodeEntries(store, beforeId)) {
if (!childName.equals(entry.getName())) {
diff.childNodeDeleted(
entry.getName(), entry.getNodeState());
}
}
}
} else {
// TODO: Leverage the HAMT data structure for the comparison
Set<String> baseChildNodes = new HashSet<String>();
for (ChildNodeEntry beforeCNE
: beforeTemplate.getChildNodeEntries(store, beforeId)) {
String name = beforeCNE.getName();
NodeState beforeChild = beforeCNE.getNodeState();
NodeState afterChild = getChildNode(name, store, afterId);
if (afterChild == null) {
diff.childNodeDeleted(name, beforeChild);
} else {
baseChildNodes.add(name);
if (!beforeChild.equals(afterChild)) {
diff.childNodeChanged(name, beforeChild, afterChild);
}
}
}
for (ChildNodeEntry afterChild
: getChildNodeEntries(store, afterId)) {
String name = afterChild.getName();
if (!baseChildNodes.contains(name)) {
diff.childNodeAdded(name, afterChild.getNodeState());
}
}
}
}
| public void compareAgainstBaseState(
SegmentStore store, RecordId afterId,
Template beforeTemplate, RecordId beforeId,
NodeStateDiff diff) {
checkNotNull(store);
checkNotNull(afterId);
checkNotNull(beforeTemplate);
checkNotNull(beforeId);
checkNotNull(diff);
// Compare type properties
compareProperties(beforeTemplate.primaryType, primaryType, diff);
compareProperties(beforeTemplate.mixinTypes, mixinTypes, diff);
// Compare other properties, leveraging the ordering
int beforeIndex = 0;
int afterIndex = 0;
while (beforeIndex < beforeTemplate.properties.length
&& afterIndex < properties.length) {
int d = Integer.valueOf(properties[afterIndex].hashCode())
.compareTo(Integer.valueOf(beforeTemplate.properties[beforeIndex].hashCode()));
if (d == 0) {
d = properties[afterIndex].getName().compareTo(
beforeTemplate.properties[beforeIndex].getName());
}
PropertyState beforeProperty = null;
PropertyState afterProperty = null;
if (d < 0) {
afterProperty = getProperty(store, afterId, afterIndex++);
} else if (d > 0) {
beforeProperty = beforeTemplate.getProperty(
store, beforeId, beforeIndex++);
} else {
afterProperty = getProperty(store, afterId, afterIndex++);
beforeProperty = beforeTemplate.getProperty(
store, beforeId, beforeIndex++);
}
compareProperties(beforeProperty, afterProperty, diff);
}
while (afterIndex < properties.length) {
diff.propertyAdded(getProperty(store, afterId, afterIndex++));
}
while (beforeIndex < beforeTemplate.properties.length) {
diff.propertyDeleted(beforeTemplate.getProperty(
store, beforeId, beforeIndex++));
}
if (hasNoChildNodes()) {
if (!beforeTemplate.hasNoChildNodes()) {
for (ChildNodeEntry entry :
beforeTemplate.getChildNodeEntries(store, beforeId)) {
diff.childNodeDeleted(
entry.getName(), entry.getNodeState());
}
}
} else if (hasOneChildNode()) {
NodeState afterNode = getChildNode(childName, store, afterId);
NodeState beforeNode = beforeTemplate.getChildNode(
childName, store, beforeId);
if (!beforeNode.exists()) {
diff.childNodeAdded(childName, afterNode);
} else if (!beforeNode.equals(afterNode)) {
diff.childNodeChanged(childName, beforeNode, afterNode);
}
if ((beforeTemplate.hasOneChildNode() && !beforeNode.exists())
|| beforeTemplate.hasManyChildNodes()) {
for (ChildNodeEntry entry :
beforeTemplate.getChildNodeEntries(store, beforeId)) {
if (!childName.equals(entry.getName())) {
diff.childNodeDeleted(
entry.getName(), entry.getNodeState());
}
}
}
} else {
// TODO: Leverage the HAMT data structure for the comparison
Set<String> baseChildNodes = new HashSet<String>();
for (ChildNodeEntry beforeCNE
: beforeTemplate.getChildNodeEntries(store, beforeId)) {
String name = beforeCNE.getName();
NodeState beforeChild = beforeCNE.getNodeState();
NodeState afterChild = getChildNode(name, store, afterId);
if (!afterChild.exists()) {
diff.childNodeDeleted(name, beforeChild);
} else {
baseChildNodes.add(name);
if (!beforeChild.equals(afterChild)) {
diff.childNodeChanged(name, beforeChild, afterChild);
}
}
}
for (ChildNodeEntry afterChild
: getChildNodeEntries(store, afterId)) {
String name = afterChild.getName();
if (!baseChildNodes.contains(name)) {
diff.childNodeAdded(name, afterChild.getNodeState());
}
}
}
}
|
diff --git a/src/main/java/ch/iterate/openstack/swift/handler/AuthenticationJson11ResponseHandler.java b/src/main/java/ch/iterate/openstack/swift/handler/AuthenticationJson11ResponseHandler.java
index 8f9d373..52ea251 100644
--- a/src/main/java/ch/iterate/openstack/swift/handler/AuthenticationJson11ResponseHandler.java
+++ b/src/main/java/ch/iterate/openstack/swift/handler/AuthenticationJson11ResponseHandler.java
@@ -1,69 +1,69 @@
package ch.iterate.openstack.swift.handler;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.ContentType;
import org.apache.http.protocol.HTTP;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import ch.iterate.openstack.swift.AuthenticationResponse;
import ch.iterate.openstack.swift.Response;
import ch.iterate.openstack.swift.exception.AuthorizationException;
import ch.iterate.openstack.swift.exception.GenericException;
import ch.iterate.openstack.swift.model.Region;
public class AuthenticationJson11ResponseHandler implements ResponseHandler<AuthenticationResponse> {
public AuthenticationResponse handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
if(response.getStatusLine().getStatusCode() == 200 ||
response.getStatusLine().getStatusCode() == 203) {
Charset charset = HTTP.DEF_CONTENT_CHARSET;
ContentType contentType = ContentType.get(response.getEntity());
if(contentType != null) {
if(contentType.getCharset() != null) {
charset = contentType.getCharset();
}
}
JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(response.getEntity().getContent(), charset));
JSONObject auth = (JSONObject) json.get("auth");
String token = ((JSONObject) auth.get("token")).get("id").toString();
Map<String, String> cdnUrls = new HashMap<String, String>();
JSONObject serviceCatalog = (JSONObject) auth.get("serviceCatalog");
for(Object cloudFilesCDN : (JSONArray) serviceCatalog.get("cloudFilesCDN")) {
String regionId = ((JSONObject) cloudFilesCDN).get("region").toString();
String publicUrl = ((JSONObject) cloudFilesCDN).get("publicURL").toString();
cdnUrls.put(regionId, publicUrl);
}
Set<Region> regions = new HashSet<Region>();
for(Object cloudFiles : (JSONArray) serviceCatalog.get("cloudFiles")) {
String regionId = ((JSONObject) cloudFiles).get("region").toString();
String publicUrl = ((JSONObject) cloudFiles).get("publicURL").toString();
String cdnUrl = cdnUrls.containsKey(regionId) ? cdnUrls.get(regionId) : null;
Boolean v1Default = ((JSONObject) cloudFiles).containsKey("v1Default")
? (Boolean) ((JSONObject) cloudFiles).get("v1Default")
: Boolean.FALSE;
- regions.add(new Region(regionId, URI.create(publicUrl), URI.create(cdnUrl), v1Default));
+ regions.add(new Region(regionId, URI.create(publicUrl), cdnUrl == null ? null : URI.create(cdnUrl), v1Default));
}
return new AuthenticationResponse(response, token, regions);
}
else if(response.getStatusLine().getStatusCode() == 401 || response.getStatusLine().getStatusCode() == 403) {
throw new AuthorizationException(new Response(response));
}
else {
throw new GenericException(new Response(response));
}
}
}
| true | true | public AuthenticationResponse handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
if(response.getStatusLine().getStatusCode() == 200 ||
response.getStatusLine().getStatusCode() == 203) {
Charset charset = HTTP.DEF_CONTENT_CHARSET;
ContentType contentType = ContentType.get(response.getEntity());
if(contentType != null) {
if(contentType.getCharset() != null) {
charset = contentType.getCharset();
}
}
JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(response.getEntity().getContent(), charset));
JSONObject auth = (JSONObject) json.get("auth");
String token = ((JSONObject) auth.get("token")).get("id").toString();
Map<String, String> cdnUrls = new HashMap<String, String>();
JSONObject serviceCatalog = (JSONObject) auth.get("serviceCatalog");
for(Object cloudFilesCDN : (JSONArray) serviceCatalog.get("cloudFilesCDN")) {
String regionId = ((JSONObject) cloudFilesCDN).get("region").toString();
String publicUrl = ((JSONObject) cloudFilesCDN).get("publicURL").toString();
cdnUrls.put(regionId, publicUrl);
}
Set<Region> regions = new HashSet<Region>();
for(Object cloudFiles : (JSONArray) serviceCatalog.get("cloudFiles")) {
String regionId = ((JSONObject) cloudFiles).get("region").toString();
String publicUrl = ((JSONObject) cloudFiles).get("publicURL").toString();
String cdnUrl = cdnUrls.containsKey(regionId) ? cdnUrls.get(regionId) : null;
Boolean v1Default = ((JSONObject) cloudFiles).containsKey("v1Default")
? (Boolean) ((JSONObject) cloudFiles).get("v1Default")
: Boolean.FALSE;
regions.add(new Region(regionId, URI.create(publicUrl), URI.create(cdnUrl), v1Default));
}
return new AuthenticationResponse(response, token, regions);
}
else if(response.getStatusLine().getStatusCode() == 401 || response.getStatusLine().getStatusCode() == 403) {
throw new AuthorizationException(new Response(response));
}
else {
throw new GenericException(new Response(response));
}
}
| public AuthenticationResponse handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
if(response.getStatusLine().getStatusCode() == 200 ||
response.getStatusLine().getStatusCode() == 203) {
Charset charset = HTTP.DEF_CONTENT_CHARSET;
ContentType contentType = ContentType.get(response.getEntity());
if(contentType != null) {
if(contentType.getCharset() != null) {
charset = contentType.getCharset();
}
}
JSONObject json = (JSONObject) JSONValue.parse(new InputStreamReader(response.getEntity().getContent(), charset));
JSONObject auth = (JSONObject) json.get("auth");
String token = ((JSONObject) auth.get("token")).get("id").toString();
Map<String, String> cdnUrls = new HashMap<String, String>();
JSONObject serviceCatalog = (JSONObject) auth.get("serviceCatalog");
for(Object cloudFilesCDN : (JSONArray) serviceCatalog.get("cloudFilesCDN")) {
String regionId = ((JSONObject) cloudFilesCDN).get("region").toString();
String publicUrl = ((JSONObject) cloudFilesCDN).get("publicURL").toString();
cdnUrls.put(regionId, publicUrl);
}
Set<Region> regions = new HashSet<Region>();
for(Object cloudFiles : (JSONArray) serviceCatalog.get("cloudFiles")) {
String regionId = ((JSONObject) cloudFiles).get("region").toString();
String publicUrl = ((JSONObject) cloudFiles).get("publicURL").toString();
String cdnUrl = cdnUrls.containsKey(regionId) ? cdnUrls.get(regionId) : null;
Boolean v1Default = ((JSONObject) cloudFiles).containsKey("v1Default")
? (Boolean) ((JSONObject) cloudFiles).get("v1Default")
: Boolean.FALSE;
regions.add(new Region(regionId, URI.create(publicUrl), cdnUrl == null ? null : URI.create(cdnUrl), v1Default));
}
return new AuthenticationResponse(response, token, regions);
}
else if(response.getStatusLine().getStatusCode() == 401 || response.getStatusLine().getStatusCode() == 403) {
throw new AuthorizationException(new Response(response));
}
else {
throw new GenericException(new Response(response));
}
}
|
diff --git a/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java b/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java
index 86cd0c3be..f0382dcac 100644
--- a/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java
+++ b/servicemix-common/src/main/java/org/apache/servicemix/common/xbean/ClassLoaderXmlPreprocessor.java
@@ -1,118 +1,118 @@
/**
*
* Copyright 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.apache.servicemix.common.xbean;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.apache.xbean.server.classloader.MultiParentClassLoader;
import org.apache.xbean.server.repository.Repository;
import org.apache.xbean.server.spring.loader.SpringLoader;
import org.apache.xbean.spring.context.SpringXmlPreprocessor;
import org.apache.xbean.spring.context.SpringApplicationContext;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* ClassLoaderXmlPreprocessor extracts a ClassLoader definition from the xml document, builds a class loader, assigns
* the class loader to the application context and xml reader, and removes the classpath element from document.
*
* @org.apache.xbean.XBean namespace="http://xbean.org/schemas/server" element="class-loader-xml-preprocessor"
* description="Extracts a ClassLoader definition from the xml document."
*
* @author Dain Sundstrom
* @version $Id$
* @since 2.0
*/
public class ClassLoaderXmlPreprocessor implements SpringXmlPreprocessor {
private final Repository repository;
/**
* Creates a ClassLoaderXmlPreprocessor that uses the specified repository to resolve the class path locations.
* @param repository the repository used to resolve the class path locations
*/
public ClassLoaderXmlPreprocessor(Repository repository) {
this.repository = repository;
}
/**
* Extracts a ClassLoader definition from the xml document, builds a class loader, assigns
* the class loader to the application context and xml reader, and removes the classpath element from document.
*
* @param applicationContext the application context on which the class loader will be set
* @param reader the xml reader on which the class loader will be set
* @param document the xml document to inspect
*/
public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) {
// determine the classLoader
ClassLoader classLoader;
NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath");
if (classpathElements.getLength() < 1) {
- classLoader = getClass().getClassLoader();
+ classLoader = getClassLoader(applicationContext);
} else if (classpathElements.getLength() > 1) {
throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength());
} else {
Element classpathElement = (Element) classpathElements.item(0);
// build the classpath
List classpath = new ArrayList();
NodeList locations = classpathElement.getElementsByTagName("location");
for (int i = 0; i < locations.getLength(); i++) {
Element locationElement = (Element) locations.item(i);
String location = ((Text) locationElement.getFirstChild()).getData().trim();
classpath.add(location);
}
// convert the paths to URLS
URL[] urls = new URL[classpath.size()];
for (ListIterator iterator = classpath.listIterator(); iterator.hasNext();) {
String location = (String) iterator.next();
urls[iterator.previousIndex()] = repository.getResource(location);
}
// create the classloader
ClassLoader parentLoader = getClassLoader(applicationContext);
classLoader = new MultiParentClassLoader(applicationContext.getDisplayName(), urls, parentLoader);
// remove the classpath element so Spring doesn't get confused
document.getDocumentElement().removeChild(classpathElement);
}
// assign the class loader to the xml reader and the application context
reader.setBeanClassLoader(classLoader);
applicationContext.setClassLoader(classLoader);
Thread.currentThread().setContextClassLoader(classLoader);
}
private static ClassLoader getClassLoader(SpringApplicationContext applicationContext) {
ClassLoader classLoader = applicationContext.getClassLoader();
if (classLoader == null) {
classLoader = Thread.currentThread().getContextClassLoader();
}
if (classLoader == null) {
classLoader = SpringLoader.class.getClassLoader();
}
return classLoader;
}
}
| true | true | public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) {
// determine the classLoader
ClassLoader classLoader;
NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath");
if (classpathElements.getLength() < 1) {
classLoader = getClass().getClassLoader();
} else if (classpathElements.getLength() > 1) {
throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength());
} else {
Element classpathElement = (Element) classpathElements.item(0);
// build the classpath
List classpath = new ArrayList();
NodeList locations = classpathElement.getElementsByTagName("location");
for (int i = 0; i < locations.getLength(); i++) {
Element locationElement = (Element) locations.item(i);
String location = ((Text) locationElement.getFirstChild()).getData().trim();
classpath.add(location);
}
// convert the paths to URLS
URL[] urls = new URL[classpath.size()];
for (ListIterator iterator = classpath.listIterator(); iterator.hasNext();) {
String location = (String) iterator.next();
urls[iterator.previousIndex()] = repository.getResource(location);
}
// create the classloader
ClassLoader parentLoader = getClassLoader(applicationContext);
classLoader = new MultiParentClassLoader(applicationContext.getDisplayName(), urls, parentLoader);
// remove the classpath element so Spring doesn't get confused
document.getDocumentElement().removeChild(classpathElement);
}
// assign the class loader to the xml reader and the application context
reader.setBeanClassLoader(classLoader);
applicationContext.setClassLoader(classLoader);
Thread.currentThread().setContextClassLoader(classLoader);
}
| public void preprocess(SpringApplicationContext applicationContext, XmlBeanDefinitionReader reader, Document document) {
// determine the classLoader
ClassLoader classLoader;
NodeList classpathElements = document.getDocumentElement().getElementsByTagName("classpath");
if (classpathElements.getLength() < 1) {
classLoader = getClassLoader(applicationContext);
} else if (classpathElements.getLength() > 1) {
throw new FatalBeanException("Expected only classpath element but found " + classpathElements.getLength());
} else {
Element classpathElement = (Element) classpathElements.item(0);
// build the classpath
List classpath = new ArrayList();
NodeList locations = classpathElement.getElementsByTagName("location");
for (int i = 0; i < locations.getLength(); i++) {
Element locationElement = (Element) locations.item(i);
String location = ((Text) locationElement.getFirstChild()).getData().trim();
classpath.add(location);
}
// convert the paths to URLS
URL[] urls = new URL[classpath.size()];
for (ListIterator iterator = classpath.listIterator(); iterator.hasNext();) {
String location = (String) iterator.next();
urls[iterator.previousIndex()] = repository.getResource(location);
}
// create the classloader
ClassLoader parentLoader = getClassLoader(applicationContext);
classLoader = new MultiParentClassLoader(applicationContext.getDisplayName(), urls, parentLoader);
// remove the classpath element so Spring doesn't get confused
document.getDocumentElement().removeChild(classpathElement);
}
// assign the class loader to the xml reader and the application context
reader.setBeanClassLoader(classLoader);
applicationContext.setClassLoader(classLoader);
Thread.currentThread().setContextClassLoader(classLoader);
}
|
diff --git a/src/main/java/com/whiterabbit/bondi/DataVerticle.java b/src/main/java/com/whiterabbit/bondi/DataVerticle.java
index b6f496d..43e3c2e 100644
--- a/src/main/java/com/whiterabbit/bondi/DataVerticle.java
+++ b/src/main/java/com/whiterabbit/bondi/DataVerticle.java
@@ -1,102 +1,102 @@
package com.whiterabbit.bondi;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Handler;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.Verticle;
import com.whiterabbit.bondi.domain.Position;
public class DataVerticle extends Verticle {
private static final Logger log = LoggerFactory.getLogger(DataVerticle.class);
private Map<String, Map<String, Position>> data = new HashMap<>();
@Override
public void start() {
log.info("Starting DataVerticle");
vertx.eventBus().registerHandler(Messages.PUT_DATA,
new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
JsonObject body = message.body();
String bus = body.getString("bus");
String clientId = body.getString("clientId");
if (!data.containsKey(bus)) {
data.put(bus, new HashMap<String, Position>());
}
Map<String, Position> positions = data.get(bus);
if (positions.containsKey(clientId)) {
updatePosition(positions.get(clientId), body);
} else {
positions.put(clientId, createPosition(body));
}
body.removeField("clientId"); // Remove the clientId to avoid publishing it.
vertx.eventBus().publish("bondis.server.position.update", body);
}
});
vertx.eventBus().registerHandler("bondis.client.list",new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
- final String bus = message.body().getString("bus");
+ final String bus = message.body().getString("busLine");
JsonArray result = new JsonArray();
if (data.containsKey(bus)) {
Map<String, Position> positions = data.get(bus);
log.debug(String.format(
"Found bus data, collecting %s positions",
positions.size()));
for (Position position : positions.values()) {
result.addObject(positionToJson(position));
}
}
message.reply(result);
}
});
log.debug("DataVerticle started");
}
protected Position createPosition(JsonObject body) {
Position position = new Position();
position.setLatitude(body.getNumber("latitude").doubleValue());
position.setLongitude(body.getNumber("longitude").doubleValue());
position.setTimestamp(now());
return position;
}
protected void updatePosition(Position position, JsonObject body) {
position.setLatitude(body.getNumber("latitude").doubleValue());
position.setLongitude(body.getNumber("longitude").doubleValue());
position.setTimestamp(now());
}
protected JsonObject positionToJson(Position position) {
JsonObject jsonObject = new JsonObject();
jsonObject.putNumber("latitude", position.getLatitude());
jsonObject.putNumber("longitude", position.getLongitude());
return jsonObject;
}
protected Date now() {
return new Date();
}
}
| true | true | public void start() {
log.info("Starting DataVerticle");
vertx.eventBus().registerHandler(Messages.PUT_DATA,
new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
JsonObject body = message.body();
String bus = body.getString("bus");
String clientId = body.getString("clientId");
if (!data.containsKey(bus)) {
data.put(bus, new HashMap<String, Position>());
}
Map<String, Position> positions = data.get(bus);
if (positions.containsKey(clientId)) {
updatePosition(positions.get(clientId), body);
} else {
positions.put(clientId, createPosition(body));
}
body.removeField("clientId"); // Remove the clientId to avoid publishing it.
vertx.eventBus().publish("bondis.server.position.update", body);
}
});
vertx.eventBus().registerHandler("bondis.client.list",new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
final String bus = message.body().getString("bus");
JsonArray result = new JsonArray();
if (data.containsKey(bus)) {
Map<String, Position> positions = data.get(bus);
log.debug(String.format(
"Found bus data, collecting %s positions",
positions.size()));
for (Position position : positions.values()) {
result.addObject(positionToJson(position));
}
}
message.reply(result);
}
});
log.debug("DataVerticle started");
}
| public void start() {
log.info("Starting DataVerticle");
vertx.eventBus().registerHandler(Messages.PUT_DATA,
new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
JsonObject body = message.body();
String bus = body.getString("bus");
String clientId = body.getString("clientId");
if (!data.containsKey(bus)) {
data.put(bus, new HashMap<String, Position>());
}
Map<String, Position> positions = data.get(bus);
if (positions.containsKey(clientId)) {
updatePosition(positions.get(clientId), body);
} else {
positions.put(clientId, createPosition(body));
}
body.removeField("clientId"); // Remove the clientId to avoid publishing it.
vertx.eventBus().publish("bondis.server.position.update", body);
}
});
vertx.eventBus().registerHandler("bondis.client.list",new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> message) {
final String bus = message.body().getString("busLine");
JsonArray result = new JsonArray();
if (data.containsKey(bus)) {
Map<String, Position> positions = data.get(bus);
log.debug(String.format(
"Found bus data, collecting %s positions",
positions.size()));
for (Position position : positions.values()) {
result.addObject(positionToJson(position));
}
}
message.reply(result);
}
});
log.debug("DataVerticle started");
}
|
diff --git a/components/Faces/src/main/java/org/dejava/component/faces/message/FacesMessageHandler.java b/components/Faces/src/main/java/org/dejava/component/faces/message/FacesMessageHandler.java
index bd7514128..21ccb5f63 100644
--- a/components/Faces/src/main/java/org/dejava/component/faces/message/FacesMessageHandler.java
+++ b/components/Faces/src/main/java/org/dejava/component/faces/message/FacesMessageHandler.java
@@ -1,127 +1,127 @@
package org.dejava.component.faces.message;
import java.util.Locale;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;
import org.dejava.component.exception.localized.unchecked.InvalidParameterException;
import org.dejava.component.faces.message.annotation.MessageType;
import org.dejava.component.faces.message.constant.ParamKeys;
import org.dejava.component.i18n.message.exception.MessageNotFoundException;
import org.dejava.component.i18n.message.handler.ApplicationMessageHandler;
import org.dejava.component.i18n.message.handler.MessageHandler;
import org.dejava.component.reflection.AnnotationMirror;
import org.dejava.component.reflection.ClassMirror;
import org.dejava.component.validation.method.PreConditions;
/**
* Java server faces message handler.
*/
public class FacesMessageHandler implements ApplicationMessageHandler {
/**
* Generated serial.
*/
private static final long serialVersionUID = 4989446047854032562L;
/**
* Decorated message handler.
*/
private final MessageHandler messageHandler;
/**
* The faces context to be used.
*/
private final FacesContext facesContext;
/**
* @see org.dejava.component.i18n.message.handler.MessageHandler#getMessage(java.lang.Object,
* java.util.Locale, java.lang.String, java.lang.Object[])
*/
@Override
public String getMessage(final Object type, final Locale locale, final String key,
final Object[] parametersValues) throws MessageNotFoundException, InvalidParameterException {
return messageHandler.getMessage(type, locale, key, parametersValues);
}
/**
* Gets the message severity for the given type. If no severity is found, the error severity is used.
*
* @param type
* Type of the message.
* @return The message severity for the given type.
*/
private Severity getMessageSeverity(final Object type) {
// By default, the message severity is error.
Severity severity = FacesMessage.SEVERITY_ERROR;
// Gets the class of the message type.
- final ClassMirror<Object> messageTypeClass = new ClassMirror<>(type.getClass());
- //
+ final ClassMirror<Object> messageTypeClass = new ClassMirror<>((Class<?>)type);
+ // Gets the message type annotation from the message type.
final AnnotationMirror<MessageType> messageTypeInfo = messageTypeClass
.getAnnotation(MessageType.class);
// If the message type annotation is found.
if (messageTypeInfo != null) {
// Depending on the annotation severity.
switch (messageTypeInfo.getReflectedAnnotation().severity()) {
// If the severity is info.
case INFO:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_INFO;
break;
// If the severity is warn.
case WARN:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_WARN;
break;
// If the severity is fatal.
case FATAL:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_FATAL;
break;
// By default, the severity is error.
default:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_ERROR;
break;
}
}
// Returns the message severity.
return severity;
}
/**
* @see org.dejava.component.i18n.message.handler.ApplicationMessageHandler#addMessage(java.lang.Object,
* java.util.Locale, java.lang.String, java.lang.Object[])
*/
@Override
public String addMessage(final Object type, final Locale locale, final String key,
final Object[] parametersValues) throws MessageNotFoundException, InvalidParameterException {
// Gets the message.
final String message = getMessage(type, locale, key, parametersValues);
// Adds the message to the faces context. TODO Think about summary.
facesContext.addMessage(null, new FacesMessage(getMessageSeverity(type), message, message));
// Returns the message.
return message;
}
/**
* Default constructor.
*
* @param messageHandler
* Message handler to be decorated.
* @param facesContext
* The faces context to be used.
*
*/
public FacesMessageHandler(final MessageHandler messageHandler, final FacesContext facesContext) {
// Assert that the given parameters are not null.
PreConditions.assertParamNotNull(ParamKeys.MESSAGE_HANDLER, messageHandler);
PreConditions.assertParamNotNull(ParamKeys.FACES_CONTEXT, facesContext);
// Sets the fields.
this.messageHandler = messageHandler;
this.facesContext = facesContext;
}
}
| true | true | private Severity getMessageSeverity(final Object type) {
// By default, the message severity is error.
Severity severity = FacesMessage.SEVERITY_ERROR;
// Gets the class of the message type.
final ClassMirror<Object> messageTypeClass = new ClassMirror<>(type.getClass());
//
final AnnotationMirror<MessageType> messageTypeInfo = messageTypeClass
.getAnnotation(MessageType.class);
// If the message type annotation is found.
if (messageTypeInfo != null) {
// Depending on the annotation severity.
switch (messageTypeInfo.getReflectedAnnotation().severity()) {
// If the severity is info.
case INFO:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_INFO;
break;
// If the severity is warn.
case WARN:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_WARN;
break;
// If the severity is fatal.
case FATAL:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_FATAL;
break;
// By default, the severity is error.
default:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_ERROR;
break;
}
}
// Returns the message severity.
return severity;
}
| private Severity getMessageSeverity(final Object type) {
// By default, the message severity is error.
Severity severity = FacesMessage.SEVERITY_ERROR;
// Gets the class of the message type.
final ClassMirror<Object> messageTypeClass = new ClassMirror<>((Class<?>)type);
// Gets the message type annotation from the message type.
final AnnotationMirror<MessageType> messageTypeInfo = messageTypeClass
.getAnnotation(MessageType.class);
// If the message type annotation is found.
if (messageTypeInfo != null) {
// Depending on the annotation severity.
switch (messageTypeInfo.getReflectedAnnotation().severity()) {
// If the severity is info.
case INFO:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_INFO;
break;
// If the severity is warn.
case WARN:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_WARN;
break;
// If the severity is fatal.
case FATAL:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_FATAL;
break;
// By default, the severity is error.
default:
// Updates the severity to be returned.
severity = FacesMessage.SEVERITY_ERROR;
break;
}
}
// Returns the message severity.
return severity;
}
|
diff --git a/src/org/subethamail/smtp/server/Session.java b/src/org/subethamail/smtp/server/Session.java
index 5055ad2..2d7818f 100644
--- a/src/org/subethamail/smtp/server/Session.java
+++ b/src/org/subethamail/smtp/server/Session.java
@@ -1,442 +1,442 @@
package org.subethamail.smtp.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.*;
import java.security.cert.Certificate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.AuthenticationHandler;
import org.subethamail.smtp.MessageContext;
import org.subethamail.smtp.MessageHandler;
import org.subethamail.smtp.io.CRLFTerminatedReader;
/**
* The thread that handles a connection. This class
* passes most of it's responsibilities off to the
* CommandHandler.
*
* @author Jon Stevens
* @author Jeff Schnitzer
*/
public class Session extends Thread implements MessageContext
{
private final static Logger log = LoggerFactory.getLogger(Session.class);
/** A link to our parent server */
private SMTPServer server;
/** Set this true when doing an ordered shutdown */
private boolean quitting = false;
/** I/O to the client */
private Socket socket;
private InputStream input;
private CRLFTerminatedReader reader;
private PrintWriter writer;
/** Might exist if the client has successfully authenticated */
private AuthenticationHandler authenticationHandler;
/** Might exist if the client is giving us a message */
private MessageHandler messageHandler;
/** Some state information */
private String helo;
private boolean hasMailFrom;
private int recipientCount;
/**
* If the client told us the size of the message, this is the value.
* If they didn't, the value will be 0.
*/
private int declaredMessageSize = 0;
/** Some more state information */
private boolean tlsStarted;
private Certificate[] tlsPeerCertificates;
/**
* Creates (but does not start) the thread object.
*
* @param server a link to our parent
* @param socket is the socket to the client
* @throws IOException
*/
public Session(SMTPServer server, Socket socket)
throws IOException
{
super(server.getSessionGroup(), Session.class.getName()
+ "-" + socket.getInetAddress() + ":" + socket.getPort());
this.server = server;
this.setSocket(socket);
}
/**
* @return a reference to the master server object
*/
public SMTPServer getServer()
{
return this.server;
}
/**
* The thread for each session runs on this and shuts down when the shutdown member goes true.
*/
@Override
public void run()
{
if (log.isDebugEnabled())
{
InetAddress remoteInetAddress = this.getRemoteAddress().getAddress();
remoteInetAddress.getHostName(); // Causes future toString() to print the name too
log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress, this.server.getNumberOfConnections());
}
try
{
if (this.server.hasTooManyConnections())
{
log.debug("SMTP Too many connections!");
- this.sendResponse("554 Transaction failed. Too many connections.");
+ this.sendResponse("421 Too many connections, try again later");
return;
}
this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getName());
// Start with fresh message state
this.resetMessageState();
while (!this.quitting)
{
try
{
String line = null;
try
{
line = this.reader.readLine();
}
catch (SocketException ex)
{
// Lots of clients just "hang up" rather than issuing QUIT, which would
// fill our logs with the warning in the outer catch.
if (log.isDebugEnabled())
log.debug("Error reading client command: " + ex.getMessage(), ex);
return;
}
if (line == null)
{
log.debug("no more lines from client");
return;
}
if (log.isDebugEnabled())
log.debug("Client: " + line);
this.server.getCommandHandler().handleCommand(this, line);
}
catch (SocketTimeoutException ex)
{
this.sendResponse("421 Timeout waiting for data from client.");
return;
}
catch (CRLFTerminatedReader.TerminationException te)
{
String msg = "501 Syntax error at character position "
+ te.position()
+ ". CR and LF must be CRLF paired. See RFC 2821 #2.7.1.";
log.debug(msg);
this.sendResponse(msg);
// if people are screwing with things, close connection
return;
}
catch (CRLFTerminatedReader.MaxLineLengthException mlle)
{
String msg = "501 " + mlle.getMessage();
log.debug(msg);
this.sendResponse(msg);
// if people are screwing with things, close connection
return;
}
}
}
catch (IOException e1)
{
if (!this.quitting)
{
try
{
// Send a temporary failure back so that the server will try to resend
// the message later.
this.sendResponse("450 Problem attempting to execute commands. Please try again later.");
}
catch (IOException e) {}
if (log.isWarnEnabled())
log.warn("Exception during SMTP transaction", e1);
}
}
finally
{
this.closeConnection();
this.endMessageHandler();
}
}
/**
* Close reader, writer, and socket, logging exceptions but otherwise ignoring them
*/
private void closeConnection()
{
try
{
try
{
this.writer.close();
this.input.close();
}
finally
{
this.closeSocket();
}
}
catch (IOException e)
{
log.info(e.toString());
}
}
/**
* Initializes our reader, writer, and the i/o filter chains based on
* the specified socket. This is called internally when we startup
* and when (if) SSL is started.
*/
public void setSocket(Socket socket) throws IOException
{
this.socket = socket;
this.input = this.socket.getInputStream();
this.reader = new CRLFTerminatedReader(this.input);
this.writer = new PrintWriter(this.socket.getOutputStream());
this.socket.setSoTimeout(this.server.getConnectionTimeout());
}
/**
* This method is only used by the start tls command
* @return the current socket to the client
*/
public Socket getSocket()
{
return this.socket;
}
/** Close the client socket if it is open */
public void closeSocket() throws IOException
{
if ((this.socket != null) && this.socket.isBound() && !this.socket.isClosed())
this.socket.close();
}
/**
* @return the raw input stream from the client
*/
public InputStream getRawInput()
{
return this.input;
}
/**
* @return the cooked CRLF-terminated reader from the client
*/
public CRLFTerminatedReader getReader()
{
return this.reader;
}
/** Sends the response to the client */
public void sendResponse(String response) throws IOException
{
if (log.isDebugEnabled())
log.debug("Server: " + response);
this.writer.print(response + "\r\n");
this.writer.flush();
}
/* (non-Javadoc)
* @see org.subethamail.smtp.MessageContext#getRemoteAddress()
*/
public InetSocketAddress getRemoteAddress()
{
return (InetSocketAddress)this.socket.getRemoteSocketAddress();
}
/* (non-Javadoc)
* @see org.subethamail.smtp.MessageContext#getSMTPServer()
*/
public SMTPServer getSMTPServer()
{
return this.server;
}
/**
* @return the current message handler
*/
public MessageHandler getMessageHandler()
{
return this.messageHandler;
}
/** Simple state */
public String getHelo()
{
return this.helo;
}
/** */
public void setHelo(String value)
{
this.helo = value;
}
/** */
public boolean getHasMailFrom()
{
return this.hasMailFrom;
}
/** */
public void setHasMailFrom(boolean value)
{
this.hasMailFrom = value;
}
/** */
public void addRecipient()
{
this.recipientCount++;
}
/** */
public int getRecipientCount()
{
return this.recipientCount;
}
/** */
public boolean isAuthenticated()
{
return this.authenticationHandler != null;
}
/** */
public AuthenticationHandler getAuthenticationHandler()
{
return this.authenticationHandler;
}
/**
* This is called by the AuthCommand when a session is successfully authenticated. The
* handler will be an object created by the AuthenticationHandlerFactory.
*/
public void setAuthenticationHandler(AuthenticationHandler handler)
{
this.authenticationHandler = handler;
}
/**
* @return the maxMessageSize
*/
public int getDeclaredMessageSize()
{
return this.declaredMessageSize;
}
/**
* @param declaredMessageSize the size that the client says the message will be
*/
public void setDeclaredMessageSize(int declaredMessageSize)
{
this.declaredMessageSize = declaredMessageSize;
}
/**
* Some state is associated with each particular message (senders, recipients, the message handler).
* Some state is not; seeing hello, TLS, authentication.
*/
public void resetMessageState()
{
this.endMessageHandler();
this.messageHandler = this.server.getMessageHandlerFactory().create(this);
this.helo = null;
this.hasMailFrom = false;
this.recipientCount = 0;
this.declaredMessageSize = 0;
}
/** Safely calls done() on a message hander, if one exists */
protected void endMessageHandler()
{
if (this.messageHandler != null)
{
try
{
this.messageHandler.done();
}
catch (Exception ex)
{
log.error("done() threw exception", ex);
}
}
}
/**
* Triggers the shutdown of the thread and the closing of the connection.
*/
public void quit()
{
this.quitting = true;
this.closeConnection();
}
/**
* @return true when the TLS handshake was completed, false otherwise
*/
public boolean isTLSStarted()
{
return tlsStarted;
}
/**
* @param tlsStarted true when the TLS handshake was completed, false otherwise
*/
public void setTlsStarted(boolean tlsStarted)
{
this.tlsStarted = tlsStarted;
}
public void setTlsPeerCertificates(Certificate[] tlsPeerCertificates)
{
this.tlsPeerCertificates = tlsPeerCertificates;
}
/**
* {@inheritDoc}
*/
public Certificate[] getTlsPeerCertificates()
{
return tlsPeerCertificates;
}
}
| true | true | public void run()
{
if (log.isDebugEnabled())
{
InetAddress remoteInetAddress = this.getRemoteAddress().getAddress();
remoteInetAddress.getHostName(); // Causes future toString() to print the name too
log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress, this.server.getNumberOfConnections());
}
try
{
if (this.server.hasTooManyConnections())
{
log.debug("SMTP Too many connections!");
this.sendResponse("554 Transaction failed. Too many connections.");
return;
}
this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getName());
// Start with fresh message state
this.resetMessageState();
while (!this.quitting)
{
try
{
String line = null;
try
{
line = this.reader.readLine();
}
catch (SocketException ex)
{
// Lots of clients just "hang up" rather than issuing QUIT, which would
// fill our logs with the warning in the outer catch.
if (log.isDebugEnabled())
log.debug("Error reading client command: " + ex.getMessage(), ex);
return;
}
if (line == null)
{
log.debug("no more lines from client");
return;
}
if (log.isDebugEnabled())
log.debug("Client: " + line);
this.server.getCommandHandler().handleCommand(this, line);
}
catch (SocketTimeoutException ex)
{
this.sendResponse("421 Timeout waiting for data from client.");
return;
}
catch (CRLFTerminatedReader.TerminationException te)
{
String msg = "501 Syntax error at character position "
+ te.position()
+ ". CR and LF must be CRLF paired. See RFC 2821 #2.7.1.";
log.debug(msg);
this.sendResponse(msg);
// if people are screwing with things, close connection
return;
}
catch (CRLFTerminatedReader.MaxLineLengthException mlle)
{
String msg = "501 " + mlle.getMessage();
log.debug(msg);
this.sendResponse(msg);
// if people are screwing with things, close connection
return;
}
}
}
catch (IOException e1)
{
if (!this.quitting)
{
try
{
// Send a temporary failure back so that the server will try to resend
// the message later.
this.sendResponse("450 Problem attempting to execute commands. Please try again later.");
}
catch (IOException e) {}
if (log.isWarnEnabled())
log.warn("Exception during SMTP transaction", e1);
}
}
finally
{
this.closeConnection();
this.endMessageHandler();
}
}
| public void run()
{
if (log.isDebugEnabled())
{
InetAddress remoteInetAddress = this.getRemoteAddress().getAddress();
remoteInetAddress.getHostName(); // Causes future toString() to print the name too
log.debug("SMTP connection from {}, new connection count: {}", remoteInetAddress, this.server.getNumberOfConnections());
}
try
{
if (this.server.hasTooManyConnections())
{
log.debug("SMTP Too many connections!");
this.sendResponse("421 Too many connections, try again later");
return;
}
this.sendResponse("220 " + this.server.getHostName() + " ESMTP " + this.server.getName());
// Start with fresh message state
this.resetMessageState();
while (!this.quitting)
{
try
{
String line = null;
try
{
line = this.reader.readLine();
}
catch (SocketException ex)
{
// Lots of clients just "hang up" rather than issuing QUIT, which would
// fill our logs with the warning in the outer catch.
if (log.isDebugEnabled())
log.debug("Error reading client command: " + ex.getMessage(), ex);
return;
}
if (line == null)
{
log.debug("no more lines from client");
return;
}
if (log.isDebugEnabled())
log.debug("Client: " + line);
this.server.getCommandHandler().handleCommand(this, line);
}
catch (SocketTimeoutException ex)
{
this.sendResponse("421 Timeout waiting for data from client.");
return;
}
catch (CRLFTerminatedReader.TerminationException te)
{
String msg = "501 Syntax error at character position "
+ te.position()
+ ". CR and LF must be CRLF paired. See RFC 2821 #2.7.1.";
log.debug(msg);
this.sendResponse(msg);
// if people are screwing with things, close connection
return;
}
catch (CRLFTerminatedReader.MaxLineLengthException mlle)
{
String msg = "501 " + mlle.getMessage();
log.debug(msg);
this.sendResponse(msg);
// if people are screwing with things, close connection
return;
}
}
}
catch (IOException e1)
{
if (!this.quitting)
{
try
{
// Send a temporary failure back so that the server will try to resend
// the message later.
this.sendResponse("450 Problem attempting to execute commands. Please try again later.");
}
catch (IOException e) {}
if (log.isWarnEnabled())
log.warn("Exception during SMTP transaction", e1);
}
}
finally
{
this.closeConnection();
this.endMessageHandler();
}
}
|
diff --git a/src/main/java/org/freeeed/main/Version.java b/src/main/java/org/freeeed/main/Version.java
index dbe25d6e..5784c6b0 100644
--- a/src/main/java/org/freeeed/main/Version.java
+++ b/src/main/java/org/freeeed/main/Version.java
@@ -1,16 +1,16 @@
package org.freeeed.main;
/**
*
* @author mark
*/
public class Version {
public static String getVersion() {
- return "FreeEed V2.9.1";
+ return "FreeEed V2.9.2";
}
public static String getSupportEmail() {
return "[email protected]";
}
}
| true | true | public static String getVersion() {
return "FreeEed V2.9.1";
}
| public static String getVersion() {
return "FreeEed V2.9.2";
}
|
diff --git a/src/View/ClassSelectionView.java b/src/View/ClassSelectionView.java
index 0dacb4c..31e2d75 100644
--- a/src/View/ClassSelectionView.java
+++ b/src/View/ClassSelectionView.java
@@ -1,205 +1,205 @@
package View;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.*;
import org.newdawn.slick.state.*;
import Model.MainHub;
import Model.Player;
import Model.Classes.*;
import Model.Obstacles.Obstacle;
import Model.Skills.Skill;
import Model.Skills.Hunter.*;
import Model.Skills.Warrior.*;
import Model.Skills.Wizard.*;
public class ClassSelectionView extends BasicGameState implements ActionListener{
private String mouse = "No input yet";
private boolean isMultiplayer;
Player player = null;
// private String classType = null;
Image backgroundImage;
Image backButton;
Image classImage;
String classDescription = "";
String title = "";
Obstacle[] obstacles = new Obstacle[100];
Image singleplayerButton;
Image multiplayerButton;
public ClassSelectionView (int state){
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException{
singleplayerButton = new Image("res/buttons/singleplayer.png");
multiplayerButton = new Image("res/buttons/multiplayer.png");
backgroundImage = new Image("res/miscImages/classSelectionBg.png");
backButton = new Image("res/buttons/back.png");
classImage = new Image("res/classImages/classes2.png");
title = "Choose your class!";
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException{
g.setColor(Color.black);
g.drawImage(backgroundImage, 0, 0);
g.drawString(mouse, 500, 20);
g.drawImage(classImage, 336, 100);
g.setColor(Color.white);
g.drawString(classDescription, 366, 445);
g.drawString(title, 550, 75);
g.setColor(Color.white);
g.drawImage(singleplayerButton, gc.getWidth()/2 - singleplayerButton.getWidth()/2, 550);
g.drawImage(multiplayerButton, gc.getWidth()/2 - multiplayerButton.getWidth()/2, 600);
g.drawImage(backButton, gc.getWidth()/2 - backButton.getWidth()/2, 650);
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
/*Random obsGenerator = new Random();
for(int i=0; i<obsGenerator.nextInt(50); i++){
obstacles[i] = new ObstaclePillar(obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1);
}*/
Input input = gc.getInput();
// Control = new PlayerController("Player", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
if((580<xPos && xPos<700) && (650<yPos && yPos<695)){
backButton = new Image("res/buttons/back_pressed.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
// If you're in the Multiplayer-view and click back, the connection will close.
if(MainHub.getController().isMulti()) {
MainHub.getController().getSocketClient().getPlayer().setConnected(false);
MainHub.getController().getSocketClient().closeConnection();
}
sbg.enterState(0);
}
}else{
backButton = new Image("res/buttons/back.png");
}
if((340<xPos && xPos<517) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/warriorSelected.png");
classDescription = "The heart of a warrior is filled with courage and strength. \n" +
"Your skills with weapons in close combat makes you a powerful \n" +
"force on the battlefield and a durable opponent for all who \n" +
"dares cross your way.";
- player = new ClassWarrior(MainHub.getController().getActivePlayerName(), "player", 120, 100, 0);
+ player = new ClassWarrior(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("WarriorMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
}
}
if((518<xPos && xPos<719) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/hunterSelected.png");
classDescription = "Hunters are stealthy, wealthy and wise to the ways of \n" +
"their opponents. Able to take down tyrants without blinking \n" +
"an eye or breaking a bowstring, you'll range far and wide \n" +
"with this class.";
// classType = "Hunter";
- player = new ClassHunter(MainHub.getController().getActivePlayerName(), "player", 120, 100, 0);
+ player = new ClassHunter(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("HunterMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Hunter");
}
}
if((720<xPos && xPos<938) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/mageSelected.png");
classDescription = "Mages are the quintessential magic user. They attack from \n" +
"a distance, able to cause great harm or restrict a targets \n" +
"actions using their supreme knowledge of the elements.";
// classType = "Wizard";
player = new ClassWizard(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("WizardMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Wizard");
}
}
if((580<xPos && xPos<700) && (550<yPos && yPos<595)){
singleplayerButton = new Image("res/buttons/singleplayer_pressed.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
MainHub.getController().setSingleOrMulti(false);
Player aiPlayer = new ClassWarrior("Enemy", "ai", 600, 600, 1);
MainHub.getController().addPlayer(aiPlayer, 1);
aiPlayer.setReady(true);
MainHub.getController().addPlayer(player, 0);
sbg.enterState(5);
}
} else if((580<xPos && xPos<700) && (600<yPos && yPos<645)){
multiplayerButton = new Image("res/buttons/multiplayer_pressed.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
MainHub.getController().setSingleOrMulti(true);
MainHub.getController().getSocketClient().changePlayer(player);
// Try to connect to server.
MainHub.getController().getSocketClient().getPlayer().setConnected(true);
MainHub.getController().getSocketClient().findConnection();
long oldTime = System.currentTimeMillis();
long timeDiff = 0;
// Wait ca 3 seconds
while(timeDiff < 3000) {
timeDiff = System.currentTimeMillis() - oldTime;
if(MainHub.getController().getSocketClient().getPlayer().isConnected()) {
break;
}
}
// Enter Multiplayer state if and only if SocketClient successfully connecter to the server.
if(MainHub.getController().getSocketClient().getPlayer().isConnected()) {
//Setting correct playerindex
player.setIndex(MainHub.getController().getActivePlayerIndex());
// MainHub.getController().addPlayer(player, MainHub.getController().getActivePlayerIndex());
//MainHub.getController().getSocketClient().changePlayer(player);
sbg.enterState(4);
} else {
}
}
}else{
singleplayerButton = new Image("res/buttons/singleplayer.png");
multiplayerButton = new Image("res/buttons/multiplayer.png");
}
}
public int getID(){
return 3;
}
@Override
public void actionPerformed(ActionEvent arg0) {
}
}
| false | true | public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
/*Random obsGenerator = new Random();
for(int i=0; i<obsGenerator.nextInt(50); i++){
obstacles[i] = new ObstaclePillar(obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1);
}*/
Input input = gc.getInput();
// Control = new PlayerController("Player", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
if((580<xPos && xPos<700) && (650<yPos && yPos<695)){
backButton = new Image("res/buttons/back_pressed.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
// If you're in the Multiplayer-view and click back, the connection will close.
if(MainHub.getController().isMulti()) {
MainHub.getController().getSocketClient().getPlayer().setConnected(false);
MainHub.getController().getSocketClient().closeConnection();
}
sbg.enterState(0);
}
}else{
backButton = new Image("res/buttons/back.png");
}
if((340<xPos && xPos<517) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/warriorSelected.png");
classDescription = "The heart of a warrior is filled with courage and strength. \n" +
"Your skills with weapons in close combat makes you a powerful \n" +
"force on the battlefield and a durable opponent for all who \n" +
"dares cross your way.";
player = new ClassWarrior(MainHub.getController().getActivePlayerName(), "player", 120, 100, 0);
// Control = new PlayerController("WarriorMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
}
}
if((518<xPos && xPos<719) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/hunterSelected.png");
classDescription = "Hunters are stealthy, wealthy and wise to the ways of \n" +
"their opponents. Able to take down tyrants without blinking \n" +
"an eye or breaking a bowstring, you'll range far and wide \n" +
"with this class.";
// classType = "Hunter";
player = new ClassHunter(MainHub.getController().getActivePlayerName(), "player", 120, 100, 0);
// Control = new PlayerController("HunterMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Hunter");
}
}
if((720<xPos && xPos<938) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/mageSelected.png");
classDescription = "Mages are the quintessential magic user. They attack from \n" +
"a distance, able to cause great harm or restrict a targets \n" +
"actions using their supreme knowledge of the elements.";
// classType = "Wizard";
player = new ClassWizard(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("WizardMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Wizard");
}
}
if((580<xPos && xPos<700) && (550<yPos && yPos<595)){
singleplayerButton = new Image("res/buttons/singleplayer_pressed.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
MainHub.getController().setSingleOrMulti(false);
Player aiPlayer = new ClassWarrior("Enemy", "ai", 600, 600, 1);
MainHub.getController().addPlayer(aiPlayer, 1);
aiPlayer.setReady(true);
MainHub.getController().addPlayer(player, 0);
sbg.enterState(5);
}
} else if((580<xPos && xPos<700) && (600<yPos && yPos<645)){
multiplayerButton = new Image("res/buttons/multiplayer_pressed.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
MainHub.getController().setSingleOrMulti(true);
MainHub.getController().getSocketClient().changePlayer(player);
// Try to connect to server.
MainHub.getController().getSocketClient().getPlayer().setConnected(true);
MainHub.getController().getSocketClient().findConnection();
long oldTime = System.currentTimeMillis();
long timeDiff = 0;
// Wait ca 3 seconds
while(timeDiff < 3000) {
timeDiff = System.currentTimeMillis() - oldTime;
if(MainHub.getController().getSocketClient().getPlayer().isConnected()) {
break;
}
}
// Enter Multiplayer state if and only if SocketClient successfully connecter to the server.
if(MainHub.getController().getSocketClient().getPlayer().isConnected()) {
//Setting correct playerindex
player.setIndex(MainHub.getController().getActivePlayerIndex());
// MainHub.getController().addPlayer(player, MainHub.getController().getActivePlayerIndex());
//MainHub.getController().getSocketClient().changePlayer(player);
sbg.enterState(4);
} else {
}
}
}else{
singleplayerButton = new Image("res/buttons/singleplayer.png");
multiplayerButton = new Image("res/buttons/multiplayer.png");
}
}
| public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
int xPos = Mouse.getX();
int yPos = 720 - Mouse.getY();
mouse = "Mouse position: (" + xPos + "," + yPos + ")";
/*Random obsGenerator = new Random();
for(int i=0; i<obsGenerator.nextInt(50); i++){
obstacles[i] = new ObstaclePillar(obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1);
}*/
Input input = gc.getInput();
// Control = new PlayerController("Player", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
if((580<xPos && xPos<700) && (650<yPos && yPos<695)){
backButton = new Image("res/buttons/back_pressed.png");
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
// If you're in the Multiplayer-view and click back, the connection will close.
if(MainHub.getController().isMulti()) {
MainHub.getController().getSocketClient().getPlayer().setConnected(false);
MainHub.getController().getSocketClient().closeConnection();
}
sbg.enterState(0);
}
}else{
backButton = new Image("res/buttons/back.png");
}
if((340<xPos && xPos<517) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/warriorSelected.png");
classDescription = "The heart of a warrior is filled with courage and strength. \n" +
"Your skills with weapons in close combat makes you a powerful \n" +
"force on the battlefield and a durable opponent for all who \n" +
"dares cross your way.";
player = new ClassWarrior(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("WarriorMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Warrior");
}
}
if((518<xPos && xPos<719) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/hunterSelected.png");
classDescription = "Hunters are stealthy, wealthy and wise to the ways of \n" +
"their opponents. Able to take down tyrants without blinking \n" +
"an eye or breaking a bowstring, you'll range far and wide \n" +
"with this class.";
// classType = "Hunter";
player = new ClassHunter(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("HunterMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Hunter");
}
}
if((720<xPos && xPos<938) && (106<yPos && yPos<425)){
if(input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
classImage = new Image("res/classImages/mageSelected.png");
classDescription = "Mages are the quintessential magic user. They attack from \n" +
"a distance, able to cause great harm or restrict a targets \n" +
"actions using their supreme knowledge of the elements.";
// classType = "Wizard";
player = new ClassWizard(MainHub.getController().getActivePlayerName(), "player", 160, 300, 0);
// Control = new PlayerController("WizardMan", obsGenerator.nextInt(1280), obsGenerator.nextInt(719) + 1, obstacles, "Wizard");
}
}
if((580<xPos && xPos<700) && (550<yPos && yPos<595)){
singleplayerButton = new Image("res/buttons/singleplayer_pressed.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
MainHub.getController().setSingleOrMulti(false);
Player aiPlayer = new ClassWarrior("Enemy", "ai", 600, 600, 1);
MainHub.getController().addPlayer(aiPlayer, 1);
aiPlayer.setReady(true);
MainHub.getController().addPlayer(player, 0);
sbg.enterState(5);
}
} else if((580<xPos && xPos<700) && (600<yPos && yPos<645)){
multiplayerButton = new Image("res/buttons/multiplayer_pressed.png");
if(player != null && input.isMousePressed(0)){ // 0 = leftclick, 1 = rightclick
MainHub.getController().setSingleOrMulti(true);
MainHub.getController().getSocketClient().changePlayer(player);
// Try to connect to server.
MainHub.getController().getSocketClient().getPlayer().setConnected(true);
MainHub.getController().getSocketClient().findConnection();
long oldTime = System.currentTimeMillis();
long timeDiff = 0;
// Wait ca 3 seconds
while(timeDiff < 3000) {
timeDiff = System.currentTimeMillis() - oldTime;
if(MainHub.getController().getSocketClient().getPlayer().isConnected()) {
break;
}
}
// Enter Multiplayer state if and only if SocketClient successfully connecter to the server.
if(MainHub.getController().getSocketClient().getPlayer().isConnected()) {
//Setting correct playerindex
player.setIndex(MainHub.getController().getActivePlayerIndex());
// MainHub.getController().addPlayer(player, MainHub.getController().getActivePlayerIndex());
//MainHub.getController().getSocketClient().changePlayer(player);
sbg.enterState(4);
} else {
}
}
}else{
singleplayerButton = new Image("res/buttons/singleplayer.png");
multiplayerButton = new Image("res/buttons/multiplayer.png");
}
}
|
diff --git a/projects/bundles/oracleerp/src/main/java/org/identityconnectors/oracleerp/OracleERPOperationSchema.java b/projects/bundles/oracleerp/src/main/java/org/identityconnectors/oracleerp/OracleERPOperationSchema.java
index fcfa7ac7..68f7c08b 100644
--- a/projects/bundles/oracleerp/src/main/java/org/identityconnectors/oracleerp/OracleERPOperationSchema.java
+++ b/projects/bundles/oracleerp/src/main/java/org/identityconnectors/oracleerp/OracleERPOperationSchema.java
@@ -1,468 +1,468 @@
/*
* ====================
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2008-2009 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License("CDDL") (the "License"). You may not use this file
* except in compliance with the License.
*
* You can obtain a copy of the License at
* http://IdentityConnectors.dev.java.net/legal/license.txt
* See the License for the specific language governing permissions and limitations
* under the License.
*
* When distributing the Covered Code, include this CDDL Header Notice in each file
* and include the License file at identityconnectors/legal/license.txt.
* If applicable, add the following below this CDDL Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
* ====================
*/
package org.identityconnectors.oracleerp;
import static org.identityconnectors.oracleerp.OracleERPUtil.*;
import java.util.EnumSet;
import java.util.Set;
import org.identityconnectors.common.StringUtil;
import org.identityconnectors.common.logging.Log;
import org.identityconnectors.common.security.GuardedString;
import org.identityconnectors.framework.common.objects.AttributeInfo;
import org.identityconnectors.framework.common.objects.AttributeInfoBuilder;
import org.identityconnectors.framework.common.objects.Name;
import org.identityconnectors.framework.common.objects.ObjectClass;
import org.identityconnectors.framework.common.objects.ObjectClassInfo;
import org.identityconnectors.framework.common.objects.ObjectClassInfoBuilder;
import org.identityconnectors.framework.common.objects.OperationalAttributeInfos;
import org.identityconnectors.framework.common.objects.OperationalAttributes;
import org.identityconnectors.framework.common.objects.Schema;
import org.identityconnectors.framework.common.objects.SchemaBuilder;
import org.identityconnectors.framework.common.objects.AttributeInfo.Flags;
import org.identityconnectors.framework.spi.operations.CreateOp;
import org.identityconnectors.framework.spi.operations.DeleteOp;
import org.identityconnectors.framework.spi.operations.SchemaOp;
import org.identityconnectors.framework.spi.operations.UpdateOp;
/**
* The schema implementation of the SPI
* @author Petr Jung
* @version $Revision 1.0$
* @since 1.0
*/
final class OracleERPOperationSchema extends Operation implements SchemaOp {
private static final Log log = Log.getLog(OracleERPOperationSchema.class);
//Optional aggregated user attributes
static final EnumSet<Flags> NRD = EnumSet.of(Flags.NOT_READABLE, Flags.NOT_RETURNED_BY_DEFAULT);
static final EnumSet<Flags> RNU = EnumSet.of(Flags.REQUIRED, Flags.NOT_UPDATEABLE);
static final EnumSet<Flags> NCU = EnumSet.of(Flags.NOT_CREATABLE, Flags.NOT_UPDATEABLE);
static final EnumSet<Flags> MNCUD = EnumSet.of(Flags.MULTIVALUED, Flags.NOT_CREATABLE, Flags.NOT_UPDATEABLE,
Flags.NOT_RETURNED_BY_DEFAULT);
static final EnumSet<Flags> NCUD = EnumSet.of(Flags.NOT_CREATABLE, Flags.NOT_UPDATEABLE,
Flags.NOT_RETURNED_BY_DEFAULT);
static final EnumSet<Flags> MNCU = EnumSet.of(Flags.MULTIVALUED, Flags.NOT_CREATABLE, Flags.NOT_UPDATEABLE);
static final EnumSet<Flags> M = EnumSet.of(Flags.MULTIVALUED);
OracleERPOperationSchema(OracleERPConnection conn, OracleERPConfiguration cfg) {
super(conn, cfg);
}
public Schema schema() {
log.ok("schema");
// Use SchemaBuilder to build the schema.
SchemaBuilder schemaBld = new SchemaBuilder(OracleERPConnector.class);
final ObjectClassInfo accountOci = getAccountObjectClassInfo();
schemaBld.defineObjectClass(accountOci);
// The ResponsibilityNames
final ObjectClassInfo respNamesOci = getRespNamesObjectClassInfo();
addSearchableOnlyOC(schemaBld, respNamesOci);
// The Responsibilities for listing
final ObjectClassInfo respOci = getResponsibilitiesObjectClassInfo();
addSearchableOnlyOC(schemaBld, respOci);
// The Applications for listing
final ObjectClassInfo appOci = getApplicationsObjectClassInfo();
addSearchableOnlyOC(schemaBld, appOci);
// The Auditor for listing
final ObjectClassInfo auditOci = getAuditorResponsibilitiesObjectClassInfo();
addSearchableOnlyOC(schemaBld, auditOci);
// The DirectResponsibilities for listing
final ObjectClassInfo directOci = getDirectResponsibilitiesObjectClassInfo();
addSearchableOnlyOC(schemaBld, directOci);
// The IndirectResponsibilities for listing
final ObjectClassInfo indirectOci = getIndirectResponsibilitiesObjectClassInfo();
addSearchableOnlyOC(schemaBld, indirectOci);
// The IndirectResponsibilities for listing
final ObjectClassInfo secAttrOci = getSecuringAttrsGroupObjectClassInfo();
addSearchableOnlyOC(schemaBld, secAttrOci);
// The IndirectResponsibilities for listing
final ObjectClassInfo secGrpsOci = getSecurngGroupsObjectClassInfo();
addSearchableOnlyOC(schemaBld, secGrpsOci);
final Schema schema = schemaBld.build();
log.ok("schema done");
return schema;
}
/**
* Add only searchable object class
* @param schemaBld
* @param oci
*/
private void addSearchableOnlyOC(SchemaBuilder schemaBld, final ObjectClassInfo oci) {
schemaBld.defineObjectClass(oci);
schemaBld.removeSupportedObjectClass(DeleteOp.class, oci);
schemaBld.removeSupportedObjectClass(CreateOp.class, oci);
schemaBld.removeSupportedObjectClass(UpdateOp.class, oci);
}
/**
* Get the Account Object Class Info
*
* @return objectClass {@link ObjectClassInfo} info
*/
private ObjectClassInfo getAccountObjectClassInfo() {
ObjectClassInfoBuilder ocib = new ObjectClassInfoBuilder();
ocib.setType(ObjectClass.ACCOUNT_NAME);
// The Name is supported attribute
ocib.addAttributeInfo(AttributeInfoBuilder.build(Name.NAME, String.class, RNU));
// name='owner' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(OWNER, String.class, NRD));
// name='session_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SESS_NUM, String.class, NCU));
// reset is implemented as change password
// name='Password', Password is mapped to operationalAttribute
ocib.addAttributeInfo(OperationalAttributeInfos.PASSWORD);
// name='start_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(START_DATE, String.class));
// name='end_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(END_DATE, String.class));
// name='description' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(DESCR, String.class));
// name='expirePassword' type='string' required='false' is mapped to PASSWORD_EXPIRED
ocib.addAttributeInfo(AttributeInfoBuilder.build(EXP_PWD, Boolean.class, NRD));
// name='password_accesses_left' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_DATE, String.class));
// name='password_accesses_left' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_ACCESSES_LEFT, String.class));
// name='password_lifespan_accesses' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_LIFESPAN_ACCESSES, String.class));
// name='password_lifespan_days' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_LIFESPAN_DAYS, String.class));
// name='employee_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMP_ID, String.class));
// name='employee_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMP_NUM, String.class));
// name='person_fullname' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PERSON_FULLNAME, String.class));
// name='npw_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(NPW_NUM, String.class));
// name='email_address' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMAIL, String.class));
// name='fax' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FAX, String.class));
// name='customer_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(CUST_ID, String.class));
// name='supplier_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SUPP_ID, String.class));
// name='person_party_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PERSON_PARTY_ID, String.class, NCU));
if (getCfg().isNewResponsibilityViews()) {
// name='DIRECT_RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(DIRECT_RESPS, String.class, M));
// name='INDIRECT_RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(INDIRECT_RESPS, String.class, MNCU));
} else {
// name='RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESPS, String.class, M));
}
// name='RESPKEYS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESPKEYS, String.class, MNCU));
// name='SEC_ATTRS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SEC_ATTRS, String.class, M));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESP_NAMES, String.class, MNCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(AUDITOR_RESPS, String.class, MNCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_MENU_NAMES, String.class, MNCUD));
// name='menuIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(MENU_IDS, String.class, MNCUD));
// name='userFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FUNCTION_NAMES, String.class, MNCUD));
// name='functionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_IDS, String.class, MNCUD));
// name='formIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_IDS, String.class, MNCUD));
// name='formNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_NAMES, String.class, MNCUD));
// name='functionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_NAMES, String.class, MNCUD));
// name='userFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_IDS, String.class, MNCUD));
// name='readWriteOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_ONLY_FORM_IDS, String.class, MNCUD));
// name='readOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTION_NAMES, String.class, MNCUD));
// name='readOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_USER_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTIONS_IDS, String.class, MNCUD));
// name='readWriteOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FORM_NAMES, String.class, MNCUD));
// name='readWriteOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_USER_FORM_NAMES, String.class, MNCUD));
// name='readWriteOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_NAMES, String.class, MNCUD));
// name='readWriteOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_IDS, String.class, MNCUD));
//user_id
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_ID, String.class, NCUD));
// name='last_logon_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(LAST_LOGON_DATE, String.class, OracleERPOperationSchema.NCU));
/*ocib.addAttributeInfo(OperationalAttributeInfos.ENABLE_DATE);
ocib.addAttributeInfo(OperationalAttributeInfos.DISABLE_DATE);
ocib.addAttributeInfo(PredefinedAttributeInfos.LAST_LOGIN_DATE);
ocib.addAttributeInfo(PredefinedAttributeInfos.LAST_PASSWORD_CHANGE_DATE);*/
// <Views><String>Enable</String></Views>
ocib.addAttributeInfo(OperationalAttributeInfos.ENABLE);
// The expired password is not returned by default
ocib.addAttributeInfo(AttributeInfoBuilder.build(OperationalAttributes.PASSWORD_EXPIRED_NAME, boolean.class, NRD));
// name='passwordAttribute', there is restriction, the name must be unique, not exists in the attribute info set
if (StringUtil.isNotBlank(getCfg().getPasswordAttribute())) {
Set<AttributeInfo> currentInfos = ocib.build().getAttributeInfo();
for (AttributeInfo attributeInfo : currentInfos) {
if (attributeInfo.is(getCfg().getPasswordAttribute())) {
throw new IllegalArgumentException(getCfg().getMessage(MSG_INVALID_PASSWORD_ATTRIBUTE, getCfg().getPasswordAttribute()));
}
}
// now it is clear we can add the new attribute
- AttributeInfoBuilder.build(getCfg().getPasswordAttribute(), GuardedString.class, EnumSet.of(Flags.NOT_READABLE, Flags.NOT_RETURNED_BY_DEFAULT));
+ ocib.addAttributeInfo(AttributeInfoBuilder.build(getCfg().getPasswordAttribute(), GuardedString.class, EnumSet.of(Flags.NOT_READABLE, Flags.NOT_RETURNED_BY_DEFAULT)));
}
return ocib.build();
}
/**
* The object class info
* @return the info class
*/
private ObjectClassInfo getRespNamesObjectClassInfo() {
ObjectClassInfoBuilder ocib = new ObjectClassInfoBuilder();
ocib.setType(RESP_NAMES_OC.getObjectClassValue());
ocib.addAttributeInfo(Name.INFO);
// The Name is supported attribute
ocib.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_MENU_NAMES, String.class, MNCU));
// name='menuIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(MENU_IDS, String.class, MNCU));
// name='userFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FUNCTION_NAMES, String.class, MNCU));
// name='functionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_IDS, String.class, MNCU));
// name='formIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_IDS, String.class, MNCU));
// name='formNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_NAMES, String.class, MNCU));
// name='functionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_NAMES, String.class, MNCU));
// name='userFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FORM_NAMES, String.class, MNCU));
// name='readOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_IDS, String.class, MNCU));
// name='readWriteOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_ONLY_FORM_IDS, String.class, MNCU));
// name='readOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_NAMES, String.class, MNCU));
// name='readOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTION_NAMES, String.class, MNCU));
// name='readOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_USER_FORM_NAMES, String.class, MNCU));
// name='readOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTIONS_IDS, String.class, MNCU));
// name='readWriteOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FORM_NAMES, String.class, MNCU));
// name='readWriteOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_USER_FORM_NAMES, String.class, MNCU));
// name='readWriteOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_NAMES, String.class, MNCU));
// name='readWriteOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_IDS, String.class, MNCU));
return ocib.build();
}
/**
* The object class info
* @return the info class
*/
private ObjectClassInfo getAuditorResponsibilitiesObjectClassInfo() {
//Auditor responsibilities
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(AUDITOR_RESPS_OC.getObjectClassValue());
oc.addAttributeInfo(Name.INFO);
// The Name is supported attribute
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
// name='userMenuNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(USER_MENU_NAMES, String.class, MNCU));
// name='menuIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(MENU_IDS, String.class, MNCU));
// name='userFunctionNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(USER_FUNCTION_NAMES, String.class, MNCU));
// name='functionIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_IDS, String.class, MNCU));
// name='formIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(FORM_IDS, String.class, MNCU));
// name='formNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(FORM_NAMES, String.class, MNCU));
// name='functionNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_NAMES, String.class, MNCU));
// name='userFormNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(USER_FORM_NAMES, String.class, MNCU));
// name='readOnlyFormIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_IDS, String.class, MNCU));
// name='readWriteOnlyFormIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RW_ONLY_FORM_IDS, String.class, MNCU));
// name='readOnlyFormNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_NAMES, String.class, MNCU));
// name='readOnlyFunctionNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTION_NAMES, String.class, MNCU));
// name='readOnlyUserFormNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RO_USER_FORM_NAMES, String.class, MNCU));
// name='readOnlyFunctionIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTIONS_IDS, String.class, MNCU));
// name='readWriteOnlyFormNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RW_FORM_NAMES, String.class, MNCU));
// name='readWriteOnlyUserFormNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RW_USER_FORM_NAMES, String.class, MNCU));
// name='readWriteOnlyFunctionNames' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_NAMES, String.class, MNCU));
// name='readWriteOnlyFunctionIds' type='string' audit='false'
oc.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_IDS, String.class, MNCU));
return oc.build();
}
/**
* The object class info
* @return the info class
*/
private ObjectClassInfo getResponsibilitiesObjectClassInfo() {
//Resp object class
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(RESP_OC.getObjectClassValue());
// The Name is supported attribute
oc.addAttributeInfo(Name.INFO);
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
return oc.build();
}
/**
* The object class info
*
* @return the info class
*/
private ObjectClassInfo getDirectResponsibilitiesObjectClassInfo() {
//Resp object class
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(DIRECT_RESP_OC.getObjectClassValue());
// The Name is supported attribute
oc.addAttributeInfo(Name.INFO);
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
return oc.build();
}
/**
* The object class info
*
* @return the info class
*/
private ObjectClassInfo getIndirectResponsibilitiesObjectClassInfo() {
//directResponsibilities object class
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(INDIRECT_RESP_OC.getObjectClassValue());
// The Name is supported attribute
oc.addAttributeInfo(Name.INFO);
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
return oc.build();
}
/**
* The object class info
*
* @return the info class
*/
private ObjectClassInfo getApplicationsObjectClassInfo() {
//Applications object class
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(APPS_OC.getObjectClassValue());
// The Name is supported attribute
oc.addAttributeInfo(Name.INFO);
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
return oc.build();
}
//Seems to be hidden object class, no contract tests
/**
* The object class info
*
* @return the info class
*/
private ObjectClassInfo getSecurngGroupsObjectClassInfo() {
//securityGroups object class
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(SEC_GROUPS_OC.getObjectClassValue());
// The Name is supported attribute
oc.addAttributeInfo(Name.INFO);
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
return oc.build();
}
/**
* The object class info
*
* @return the info class
*/
private ObjectClassInfo getSecuringAttrsGroupObjectClassInfo() {
//securingAttrs object class
ObjectClassInfoBuilder oc = new ObjectClassInfoBuilder();
oc.setType(SEC_ATTRS_OC.getObjectClassValue());
// The Name is supported attribute
oc.addAttributeInfo(Name.INFO);
oc.addAttributeInfo(AttributeInfoBuilder.build(NAME, String.class, NCUD));
return oc.build();
}
}
| true | true | private ObjectClassInfo getAccountObjectClassInfo() {
ObjectClassInfoBuilder ocib = new ObjectClassInfoBuilder();
ocib.setType(ObjectClass.ACCOUNT_NAME);
// The Name is supported attribute
ocib.addAttributeInfo(AttributeInfoBuilder.build(Name.NAME, String.class, RNU));
// name='owner' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(OWNER, String.class, NRD));
// name='session_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SESS_NUM, String.class, NCU));
// reset is implemented as change password
// name='Password', Password is mapped to operationalAttribute
ocib.addAttributeInfo(OperationalAttributeInfos.PASSWORD);
// name='start_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(START_DATE, String.class));
// name='end_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(END_DATE, String.class));
// name='description' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(DESCR, String.class));
// name='expirePassword' type='string' required='false' is mapped to PASSWORD_EXPIRED
ocib.addAttributeInfo(AttributeInfoBuilder.build(EXP_PWD, Boolean.class, NRD));
// name='password_accesses_left' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_DATE, String.class));
// name='password_accesses_left' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_ACCESSES_LEFT, String.class));
// name='password_lifespan_accesses' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_LIFESPAN_ACCESSES, String.class));
// name='password_lifespan_days' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_LIFESPAN_DAYS, String.class));
// name='employee_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMP_ID, String.class));
// name='employee_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMP_NUM, String.class));
// name='person_fullname' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PERSON_FULLNAME, String.class));
// name='npw_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(NPW_NUM, String.class));
// name='email_address' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMAIL, String.class));
// name='fax' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FAX, String.class));
// name='customer_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(CUST_ID, String.class));
// name='supplier_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SUPP_ID, String.class));
// name='person_party_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PERSON_PARTY_ID, String.class, NCU));
if (getCfg().isNewResponsibilityViews()) {
// name='DIRECT_RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(DIRECT_RESPS, String.class, M));
// name='INDIRECT_RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(INDIRECT_RESPS, String.class, MNCU));
} else {
// name='RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESPS, String.class, M));
}
// name='RESPKEYS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESPKEYS, String.class, MNCU));
// name='SEC_ATTRS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SEC_ATTRS, String.class, M));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESP_NAMES, String.class, MNCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(AUDITOR_RESPS, String.class, MNCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_MENU_NAMES, String.class, MNCUD));
// name='menuIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(MENU_IDS, String.class, MNCUD));
// name='userFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FUNCTION_NAMES, String.class, MNCUD));
// name='functionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_IDS, String.class, MNCUD));
// name='formIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_IDS, String.class, MNCUD));
// name='formNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_NAMES, String.class, MNCUD));
// name='functionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_NAMES, String.class, MNCUD));
// name='userFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_IDS, String.class, MNCUD));
// name='readWriteOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_ONLY_FORM_IDS, String.class, MNCUD));
// name='readOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTION_NAMES, String.class, MNCUD));
// name='readOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_USER_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTIONS_IDS, String.class, MNCUD));
// name='readWriteOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FORM_NAMES, String.class, MNCUD));
// name='readWriteOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_USER_FORM_NAMES, String.class, MNCUD));
// name='readWriteOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_NAMES, String.class, MNCUD));
// name='readWriteOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_IDS, String.class, MNCUD));
//user_id
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_ID, String.class, NCUD));
// name='last_logon_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(LAST_LOGON_DATE, String.class, OracleERPOperationSchema.NCU));
/*ocib.addAttributeInfo(OperationalAttributeInfos.ENABLE_DATE);
ocib.addAttributeInfo(OperationalAttributeInfos.DISABLE_DATE);
ocib.addAttributeInfo(PredefinedAttributeInfos.LAST_LOGIN_DATE);
ocib.addAttributeInfo(PredefinedAttributeInfos.LAST_PASSWORD_CHANGE_DATE);*/
// <Views><String>Enable</String></Views>
ocib.addAttributeInfo(OperationalAttributeInfos.ENABLE);
// The expired password is not returned by default
ocib.addAttributeInfo(AttributeInfoBuilder.build(OperationalAttributes.PASSWORD_EXPIRED_NAME, boolean.class, NRD));
// name='passwordAttribute', there is restriction, the name must be unique, not exists in the attribute info set
if (StringUtil.isNotBlank(getCfg().getPasswordAttribute())) {
Set<AttributeInfo> currentInfos = ocib.build().getAttributeInfo();
for (AttributeInfo attributeInfo : currentInfos) {
if (attributeInfo.is(getCfg().getPasswordAttribute())) {
throw new IllegalArgumentException(getCfg().getMessage(MSG_INVALID_PASSWORD_ATTRIBUTE, getCfg().getPasswordAttribute()));
}
}
// now it is clear we can add the new attribute
AttributeInfoBuilder.build(getCfg().getPasswordAttribute(), GuardedString.class, EnumSet.of(Flags.NOT_READABLE, Flags.NOT_RETURNED_BY_DEFAULT));
}
return ocib.build();
}
| private ObjectClassInfo getAccountObjectClassInfo() {
ObjectClassInfoBuilder ocib = new ObjectClassInfoBuilder();
ocib.setType(ObjectClass.ACCOUNT_NAME);
// The Name is supported attribute
ocib.addAttributeInfo(AttributeInfoBuilder.build(Name.NAME, String.class, RNU));
// name='owner' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(OWNER, String.class, NRD));
// name='session_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SESS_NUM, String.class, NCU));
// reset is implemented as change password
// name='Password', Password is mapped to operationalAttribute
ocib.addAttributeInfo(OperationalAttributeInfos.PASSWORD);
// name='start_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(START_DATE, String.class));
// name='end_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(END_DATE, String.class));
// name='description' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(DESCR, String.class));
// name='expirePassword' type='string' required='false' is mapped to PASSWORD_EXPIRED
ocib.addAttributeInfo(AttributeInfoBuilder.build(EXP_PWD, Boolean.class, NRD));
// name='password_accesses_left' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_DATE, String.class));
// name='password_accesses_left' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_ACCESSES_LEFT, String.class));
// name='password_lifespan_accesses' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_LIFESPAN_ACCESSES, String.class));
// name='password_lifespan_days' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PWD_LIFESPAN_DAYS, String.class));
// name='employee_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMP_ID, String.class));
// name='employee_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMP_NUM, String.class));
// name='person_fullname' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PERSON_FULLNAME, String.class));
// name='npw_number' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(NPW_NUM, String.class));
// name='email_address' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(EMAIL, String.class));
// name='fax' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FAX, String.class));
// name='customer_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(CUST_ID, String.class));
// name='supplier_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SUPP_ID, String.class));
// name='person_party_id' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(PERSON_PARTY_ID, String.class, NCU));
if (getCfg().isNewResponsibilityViews()) {
// name='DIRECT_RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(DIRECT_RESPS, String.class, M));
// name='INDIRECT_RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(INDIRECT_RESPS, String.class, MNCU));
} else {
// name='RESPS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESPS, String.class, M));
}
// name='RESPKEYS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESPKEYS, String.class, MNCU));
// name='SEC_ATTRS' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(SEC_ATTRS, String.class, M));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RESP_NAMES, String.class, MNCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(AUDITOR_RESPS, String.class, MNCUD));
// name='userMenuNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_MENU_NAMES, String.class, MNCUD));
// name='menuIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(MENU_IDS, String.class, MNCUD));
// name='userFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FUNCTION_NAMES, String.class, MNCUD));
// name='functionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_IDS, String.class, MNCUD));
// name='formIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_IDS, String.class, MNCUD));
// name='formNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FORM_NAMES, String.class, MNCUD));
// name='functionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(FUNCTION_NAMES, String.class, MNCUD));
// name='userFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_IDS, String.class, MNCUD));
// name='readWriteOnlyFormIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_ONLY_FORM_IDS, String.class, MNCUD));
// name='readOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTION_NAMES, String.class, MNCUD));
// name='readOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_USER_FORM_NAMES, String.class, MNCUD));
// name='readOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RO_FUNCTIONS_IDS, String.class, MNCUD));
// name='readWriteOnlyFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FORM_NAMES, String.class, MNCUD));
// name='readWriteOnlyUserFormNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_USER_FORM_NAMES, String.class, MNCUD));
// name='readWriteOnlyFunctionNames' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_NAMES, String.class, MNCUD));
// name='readWriteOnlyFunctionIds' type='string' audit='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(RW_FUNCTION_IDS, String.class, MNCUD));
//user_id
ocib.addAttributeInfo(AttributeInfoBuilder.build(USER_ID, String.class, NCUD));
// name='last_logon_date' type='string' required='false'
ocib.addAttributeInfo(AttributeInfoBuilder.build(LAST_LOGON_DATE, String.class, OracleERPOperationSchema.NCU));
/*ocib.addAttributeInfo(OperationalAttributeInfos.ENABLE_DATE);
ocib.addAttributeInfo(OperationalAttributeInfos.DISABLE_DATE);
ocib.addAttributeInfo(PredefinedAttributeInfos.LAST_LOGIN_DATE);
ocib.addAttributeInfo(PredefinedAttributeInfos.LAST_PASSWORD_CHANGE_DATE);*/
// <Views><String>Enable</String></Views>
ocib.addAttributeInfo(OperationalAttributeInfos.ENABLE);
// The expired password is not returned by default
ocib.addAttributeInfo(AttributeInfoBuilder.build(OperationalAttributes.PASSWORD_EXPIRED_NAME, boolean.class, NRD));
// name='passwordAttribute', there is restriction, the name must be unique, not exists in the attribute info set
if (StringUtil.isNotBlank(getCfg().getPasswordAttribute())) {
Set<AttributeInfo> currentInfos = ocib.build().getAttributeInfo();
for (AttributeInfo attributeInfo : currentInfos) {
if (attributeInfo.is(getCfg().getPasswordAttribute())) {
throw new IllegalArgumentException(getCfg().getMessage(MSG_INVALID_PASSWORD_ATTRIBUTE, getCfg().getPasswordAttribute()));
}
}
// now it is clear we can add the new attribute
ocib.addAttributeInfo(AttributeInfoBuilder.build(getCfg().getPasswordAttribute(), GuardedString.class, EnumSet.of(Flags.NOT_READABLE, Flags.NOT_RETURNED_BY_DEFAULT)));
}
return ocib.build();
}
|
diff --git a/activemq-core/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java b/activemq-core/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java
index 988b16361..30c4243ae 100755
--- a/activemq-core/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java
+++ b/activemq-core/src/test/java/org/apache/activemq/usecases/DurableConsumerCloseAndReconnectTest.java
@@ -1,181 +1,181 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.test.TestSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @version $Revision: 1.1.1.1 $
*/
public class DurableConsumerCloseAndReconnectTest extends TestSupport {
protected static final long RECEIVE_TIMEOUT = 5000L;
private static final Log LOG = LogFactory.getLog(DurableConsumerCloseAndReconnectTest.class);
private Connection connection;
private Session session;
private MessageConsumer consumer;
private MessageProducer producer;
private Destination destination;
private int messageCount;
protected ActiveMQConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://localhost?broker.deleteAllMessagesOnStartup=false");
}
public void testCreateDurableConsumerCloseThenReconnect() throws Exception {
// force the server to stay up across both connection tests
Connection dummyConnection = createConnection();
dummyConnection.start();
consumeMessagesDeliveredWhileConsumerClosed();
dummyConnection.close();
// now lets try again without one connection open
consumeMessagesDeliveredWhileConsumerClosed();
// now delete the db
ActiveMQConnectionFactory fac = new ActiveMQConnectionFactory("vm://localhost?broker.deleteAllMessagesOnStartup=true");
dummyConnection = fac.createConnection();
dummyConnection.start();
dummyConnection.close();
}
protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception {
makeConsumer();
closeConsumer();
publish();
// wait a few moments for the close to really occur
Thread.sleep(1000);
makeConsumer();
Message message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
closeConsumer();
LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again");
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
- LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again");
+ LOG.info("Now lets create the consumer again and because we did ack, we should not get it again");
makeConsumer();
message = consumer.receive(2000);
assertTrue("Should have no more messages left!", message == null);
closeConsumer();
LOG.info("Lets publish one more message now");
publish();
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
}
protected void publish() throws Exception {
connection = createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = createDestination();
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
TextMessage msg = session.createTextMessage("This is a test: " + messageCount++);
producer.send(msg);
producer.close();
producer = null;
closeSession();
}
protected Destination createDestination() throws JMSException {
if (isTopic()) {
return session.createTopic(getSubject());
} else {
return session.createQueue(getSubject());
}
}
protected boolean isTopic() {
return true;
}
protected void closeConsumer() throws JMSException {
consumer.close();
consumer = null;
closeSession();
}
protected void closeSession() throws JMSException {
session.close();
session = null;
connection.close();
connection = null;
}
protected void makeConsumer() throws Exception {
String durableName = getName();
String clientID = getSubject();
LOG.info("Creating a durable subscribe for clientID: " + clientID + " and durable name: " + durableName);
createSession(clientID);
consumer = createConsumer(durableName);
}
private MessageConsumer createConsumer(String durableName) throws JMSException {
if (destination instanceof Topic) {
return session.createDurableSubscriber((Topic)destination, durableName);
} else {
return session.createConsumer(destination);
}
}
protected void createSession(String clientID) throws Exception {
connection = createConnection();
connection.setClientID(clientID);
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = createDestination();
}
}
| true | true | protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception {
makeConsumer();
closeConsumer();
publish();
// wait a few moments for the close to really occur
Thread.sleep(1000);
makeConsumer();
Message message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
closeConsumer();
LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again");
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again");
makeConsumer();
message = consumer.receive(2000);
assertTrue("Should have no more messages left!", message == null);
closeConsumer();
LOG.info("Lets publish one more message now");
publish();
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
}
| protected void consumeMessagesDeliveredWhileConsumerClosed() throws Exception {
makeConsumer();
closeConsumer();
publish();
// wait a few moments for the close to really occur
Thread.sleep(1000);
makeConsumer();
Message message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
closeConsumer();
LOG.info("Now lets create the consumer again and because we didn't ack, we should get it again");
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
LOG.info("Now lets create the consumer again and because we did ack, we should not get it again");
makeConsumer();
message = consumer.receive(2000);
assertTrue("Should have no more messages left!", message == null);
closeConsumer();
LOG.info("Lets publish one more message now");
publish();
makeConsumer();
message = consumer.receive(RECEIVE_TIMEOUT);
assertTrue("Should have received a message!", message != null);
message.acknowledge();
closeConsumer();
}
|
diff --git a/src/org/nosco/ant/ClassGenerator.java b/src/org/nosco/ant/ClassGenerator.java
index cd71c42..6adb12a 100644
--- a/src/org/nosco/ant/ClassGenerator.java
+++ b/src/org/nosco/ant/ClassGenerator.java
@@ -1,1032 +1,1032 @@
package org.nosco.ant;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.nosco.Field;
import org.nosco.Query;
import org.nosco.json.JSONArray;
import org.nosco.json.JSONException;
import org.nosco.json.JSONObject;
import org.nosco.util.Misc;
class ClassGenerator {
private final String pkg;
private final String dir;
private String[] stripPrefixes;
private String[] stripSuffixes;
private Map<String, String> tableToClassName;
private JSONObject classTypeMappings = new JSONObject();
private JSONObject typeMappingFunctions = new JSONObject();
private Map<Pattern, String> schemaTypeMappings;
public ClassGenerator(String dir, String pkg, String[] stripPrefixes, String[] stripSuffixes) {
this.dir = dir;
this.pkg = pkg;
this.stripPrefixes = stripPrefixes.clone();
this.stripSuffixes = stripSuffixes.clone();
}
private static class FK {
String name = null;
String[] reffing = null;
String[] reffed = null;
Map<String,String> columns = new LinkedHashMap<String,String>();
}
public static void go(String dir, String pkg, String[] stripPrefixes,
String[] stripSuffixes, String metadataFile, String fakefksFile,
String typeMappingsFile, String dataSource, String callbackPackage, JSONObject enums)
throws IOException, JSONException {
BufferedReader br = new BufferedReader(new FileReader(metadataFile));
StringBuffer sb = new StringBuffer();
String s = null;
while ((s=br.readLine())!=null) sb.append(s).append('\n');
JSONObject metadata = new JSONObject(sb.toString());
JSONObject fakeFKs = new JSONObject();
File fakeFKsFile = new File(fakefksFile);
if (fakeFKsFile.exists()) {
br = new BufferedReader(new FileReader(fakeFKsFile));
sb = new StringBuffer();
s = null;
while ((s=br.readLine())!=null) sb.append(s).append('\n');
fakeFKs = new JSONObject(sb.toString());
}
JSONObject classTypeMappings = new JSONObject();
JSONObject schemaTypeMappings = new JSONObject();
JSONObject typeMappingFunctions = new JSONObject();
File mappingsFile = typeMappingsFile==null ? null : new File(typeMappingsFile);
if (mappingsFile!=null && mappingsFile.exists()) {
br = new BufferedReader(new FileReader(mappingsFile));
sb = new StringBuffer();
s = null;
while ((s=br.readLine())!=null) sb.append(s).append('\n');
JSONObject allMappings = new JSONObject(sb.toString());
classTypeMappings = allMappings.getJSONObject("class_mappings");
schemaTypeMappings = allMappings.getJSONObject("schema_mappings");
typeMappingFunctions = allMappings.getJSONObject("functions");
}
ClassGenerator generator = new ClassGenerator(dir, pkg, stripPrefixes, stripSuffixes);
generator.classTypeMappings = classTypeMappings;
generator.typeMappingFunctions = typeMappingFunctions;
generator.schemaTypeMappings = new LinkedHashMap<Pattern,String>();
for (String key : schemaTypeMappings.keySet()) {
String value = schemaTypeMappings.optString(key);
generator.schemaTypeMappings.put(Pattern.compile(key), value);
}
JSONObject schemas = metadata.getJSONObject("schemas");
JSONObject foreignKeys = metadata.getJSONObject("foreign_keys");
String dataSourceName = DataSourceGenerator.getDataSourceName(dataSource);
for (String schema : schemas.keySet()) {
JSONObject tables = schemas.getJSONObject(schema);
generator.tableToClassName = new HashMap<String,String>();
for (String table : new TreeSet<String>(tables.keySet())) {
// we process these in order to avoid naming conflicts when you have
// both plural and singular tables of the same root word
generator.genTableClassName(table);
}
for (String table : tables.keySet()) {
// skip these junk mssql tables
if(table.startsWith("syncobj_")) continue;
JSONObject columns = tables.getJSONObject(table);
JSONArray pks = getJSONArray(metadata, "primary_keys", schema, table);
List<FK> fks = new ArrayList<FK>();
List<FK> fksIn = new ArrayList<FK>();
for (String constraint_name : foreignKeys.keySet()) {
JSONObject fkmd = foreignKeys.getJSONObject(constraint_name);
splitFK(schema, table, fks, fksIn, constraint_name, fkmd);
}
for (String constraint_name : fakeFKs.keySet()) {
JSONObject fkmd = fakeFKs.getJSONObject(constraint_name);
splitFK(schema, table, fks, fksIn, constraint_name, fkmd);
}
generator.generate(schema, table, columns, pks, fks, fksIn, dataSourceName,
callbackPackage, enums);
}
}
}
private static void splitFK(String schema, String table, List<FK> fks, List<FK> fksIn,
String constraint_name, JSONObject fkmd) throws JSONException {
FK fk = new FK();
fk.name = constraint_name;
String[] reffing = {fkmd.getJSONArray("reffing").getString(0),
fkmd.getJSONArray("reffing").getString(1)};
fk.reffing = reffing;
String[] reffed = {fkmd.getJSONArray("reffed").getString(0),
fkmd.getJSONArray("reffed").getString(1)};
fk.reffed = reffed;
JSONObject cols = fkmd.getJSONObject("columns");
for (String key : cols.keySet()) {
fk.columns.put(key, cols.getString(key));
}
if (schema.equals(fk.reffing[0]) && table.equals(fk.reffing[1])) {
fks.add(fk);
}
if (schema.equals(fk.reffed[0]) && table.equals(fk.reffed[1])) {
fksIn.add(fk);
}
}
private static JSONObject getJSONObject(JSONObject o, String... path) throws JSONException {
for (String s : path) {
if (o==null) return null;
if (o.has(s)) o = o.optJSONObject(s);
else return null;
}
return o;
}
private static JSONArray getJSONArray(Object o, String... path) throws JSONException {
for (String s : path) {
if (o==null) return null;
if (o instanceof JSONObject && ((JSONObject)o).has(s)) {
o = ((JSONObject)o).opt(s);
} else return null;
}
if (o instanceof JSONArray) return (JSONArray) o;
else return null;
}
private static void recursiveDelete(File file) {
if (file==null) return;
for (File f : file.listFiles()) {
if (f.isDirectory()) recursiveDelete(f);
else f.delete();
}
file.delete();
}
private static String getFieldName(String column) {
return column.replace(' ', '_')
.replace("%", "_PERCENT")
.replace("-", "_DASH_")
.toUpperCase();
}
private static String getFieldName(Collection<String> columns) {
StringBuffer sb = new StringBuffer();
int i = 1;
for (String column : columns) {
sb.append(column.replace(' ', '_').toUpperCase());
if (++i < columns.size()) sb.append("__");
}
return sb.toString();
}
private void generate(String schema, String table, JSONObject columns, JSONArray pks,
List<FK> fks, List<FK> fksIn, String dataSourceName, String callbackPackage,
JSONObject enums)
throws IOException, JSONException {
String className = genTableClassName(table);
Set<String> pkSet = new HashSet<String>();
if (pks == null) pks = new JSONArray();
for (int i=0; i<pks.length(); ++i) {
pkSet.add(pks.getString(i));
}
int fieldCount = columns.keySet().size();
String pkgDir = Misc.join("/", pkg.split("[.]"));
new File(Misc.join("/", dir, pkgDir, schema)).mkdirs();
File file = new File(Misc.join("/", dir, pkgDir, schema, className+".java"));
System.out.println("writing: "+ file.getAbsolutePath());
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("package "+ pkg +"."+ schema +";\n\n");
br.write("import java.lang.reflect.Method;\n");
br.write("import java.lang.reflect.InvocationTargetException;\n");
br.write("import java.sql.SQLException;\n");
br.write("import javax.sql.DataSource;\n");
br.write("import java.util.Map;\n\n");
br.write("import java.util.HashMap;\n\n");
br.write("import org.nosco.Field;\n");
br.write("import org.nosco.Query;\n");
br.write("import org.nosco.QueryFactory;\n");
br.write("import org.nosco.Table;\n");
br.write("\n");
br.write("public class "+ className +" extends Table implements Comparable<"+ className +"> {\n\n");
// write field constants
int index = 0;
for (String column : columns.keySet()) {
br.write("\tpublic static final Field<");
br.write(getFieldType(schema, table, column, columns.getString(column)));
br.write("> "+ getFieldName(column));
br.write(" = new Field<"+ getFieldType(schema, table, column, columns.getString(column)));
br.write(">("+ index +", "+ className +".class, \""+ column);
br.write("\", "+ getFieldType(schema, table, column, columns.getString(column)) +".class");
br.write(");\n");
++index;
}
br.write("\n");
// write primary keys
br.write("\tpublic static Field.PK<"+ className +"> PK = new Field.PK<"+ className +">(");
for (int i=0; i<pks.length(); ++i) {
br.write(pks.getString(i).toUpperCase());
if (i<pks.length()-1) br.write(", ");
}
br.write(");\n");
br.write("\tpublic org.nosco.Field.PK PK() { return PK; }\n\n");
// write foreign keys
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String fkName = genFKName(fk.columns.keySet(), referencedTable);
br.write("\tpublic static final Field.FK<"+ referencedTableClassName +"> FK_"+ fkName);
br.write(" = new Field.FK<"+ referencedTableClassName +">("+ index +", "+ className +".class, ");
br.write(referencedTableClassName +".class");
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ e.getKey().toUpperCase());
}
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ referencedTableClassName +".");
br.write(e.getValue().toUpperCase());
}
br.write(");\n");
++index;
}
br.write("\n");
// write enums
for (String column : columns.keySet()) {
String enumKey = schema +"."+ table +"."+ column;
if (!enums.has(enumKey)) continue;
JSONObject instances = enums.optJSONObject(enumKey);
boolean simple = pkSet.size() == 1;
if (simple) {
String pk = pkSet.iterator().next();
String pkType = getFieldType(schema, table, pk, columns.getString(pk));
br.write("\tpublic enum PKS implements Table.__SimplePrimaryKey<"+ className +", "+ pkType +"> {\n\n");
int count = 0;
for (String name : instances.keySet()) {
++ count;
String value = instances.optJSONArray(name).getString(0);
if ("java.lang.String".equals(pkType)) value = "\""+ value +"\"";
br.write("\t\t"+ name.toUpperCase().replaceAll("\\W", "_"));
br.write("("+ value +")");
if (count < instances.keySet().size()) br.write(",\n");
- else br.write(";\n\n");
}
+ br.write(";\n\n");
br.write("\t\tpublic final "+ pkType +" "+ getFieldName(pk) +";\n");
br.write("\t\tPKS("+ pkType +" v) {\n");
br.write("\t\t\t"+ getFieldName(pk) +" = v;\n");
br.write("\t\t}\n");
br.write("\t\t@SuppressWarnings(\"unchecked\")\n");
br.write("\t\t@Override\n");
br.write("\t\tpublic <R> R get(Field<R> field) {\n");
br.write("\t\t\tif (field=="+ className +"."+ getFieldName(pk)
+") return (R) Integer.valueOf("+ getFieldName(pk) +"); \n");
br.write("\t\t\tif ("+ className +"."+ getFieldName(pk)
+".sameField(field)) return (R) Integer.valueOf("
+ getFieldName(pk) +");\n");
br.write("\t\t\tthrow new RuntimeException(\"field \"+ field +\" is not part of this primary key\");\n");
br.write("\t\t}\n");
br.write("\t\t@Override\n");
br.write("\t\tpublic "+ pkType +" value() {\n");
br.write("\t\t\treturn "+ getFieldName(pk)+ ";\n");
br.write("\t\t}\n\n");
br.write("\t}\n");
}
}
// write field value references
for (String column : columns.keySet()) {
br.write("\tprivate "+ getFieldType(schema, table, column, columns.getString(column)));
br.write(" "+ getInstanceFieldName(column) + " = null;\n");
}
br.write("\n");
// write constructors
br.write("\tpublic "+ className +"() {}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tprotected "+ className +"(Field[] fields, Object[] objects, int start, int end) {\n");
br.write("\t\tif (fields.length != objects.length)\n\t\t\tthrow new IllegalArgumentException(");
br.write("\"fields.length != objects.length => \"+ fields.length +\" != \"+ objects.length");
br.write(" +\"\");\n");
br.write("\t\tfor (int i=start; i<end; ++i) {\n");
for (String column : columns.keySet()) {
br.write("\t\t\tif (fields[i]=="+ getFieldName(column) +") {\n");
br.write("\t\t\t\t"+ getInstanceFieldName(column) +" = ");
String assignment = convertToActualType(schema, table, column,
columns.getString(column),
"("+ getFieldClassType(columns.getString(column)).getName()+ ") objects[i]");
br.write(assignment);
br.write(";\n");
br.write("\t\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t\t\tcontinue;\n");
br.write("\t\t\t}\n");
}
br.write("\t\t}\n\t}\n\n");
// write abstract method impls
br.write("\tpublic String SCHEMA_NAME() {\n\t\treturn \""+ schema +"\";\n\t}\n\n");
br.write("\tpublic String TABLE_NAME() {\n\t\treturn \""+ table +"\";\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field[] FIELDS() {\n\t\tField[] fields = {");
for (String column : columns.keySet()) {
br.write(getFieldName(column)+",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field.FK[] FKS() {\n\t\tField.FK[] fields = {");
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
// if (!schema.equals(fk.reffed[0])) {
// referencedTable = fk.reffed[0] +"_"+ referencedTable;
// }
br.write("FK_" + genFKName(fk.columns.keySet(), referencedTable) + ",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
// write the generic get(field) method
br.write("\t@SuppressWarnings(\"unchecked\")\n");
br.write("\tpublic <S> S get(Field<S> _field) {\n");
for (String column : columns.keySet()) {
br.write("\t\tif (_field=="+ getFieldName(column) +") ");
br.write("return (S) "+ getInstanceFieldName(column) +";\n");
}
br.write("\t\tthrow new IllegalArgumentException(\"unknown field \"+ _field);\n");
br.write("\t}\n\n");
// write the generic set(field, value) method
br.write("\tpublic <S> void set(Field<S> _field, S _value) {\n");
for (String column : columns.keySet()) {
br.write("\t\tif (_field=="+ getFieldName(column) +") ");
br.write(getInstanceFieldName(column) +" = ("+ getFieldType(schema, table, column, columns.getString(column)) +") _value;\n");
}
br.write("\t\tthrow new IllegalArgumentException(\"unknown field \"+ _field);\n");
br.write("\t}\n\n");
//br.write("\tpublic Field[] GET_PRIMARY_KEY_FIELDS() {\n\t\tField[] fields = {");
//for (int i=0; i<pks.length(); ++i) {
// br.write(pks.getString(i).toUpperCase()+",");
//}
//br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\tpublic static final Query<"+ className +"> ALL = QueryFactory.IT.getQuery("
+ className +".class).use("+ pkg +"."+ dataSourceName +"."+ schema.toUpperCase() +");\n\n");
// write toString
br.write("\t public String toString() {\n");
br.write("\t\treturn \"["+ className);
for (int i=0; i<pks.length(); ++i) {
String pk = pks.getString(i);
br.write(" "+ pk+":");
br.write("\"+"+ getInstanceFieldName(pk));
br.write("+\"");
}
for (String column : columns.keySet()) {
if (!"name".equalsIgnoreCase(column)) continue;
// if "name" exists but isn't a PK, we should still use it for toString()
br.write(" "+ column +":");
br.write("\"+"+ getInstanceFieldName(column));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write toString
br.write("\t public String toStringDetailed() {\n");
br.write("\t\treturn \"["+ className);
for (String column : columns.keySet()) {
br.write(" "+ column +":");
br.write("\"+"+ getInstanceFieldName(column));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write getters and setters
for (String column : columns.keySet()) {
String cls = getFieldType(schema, table, column, columns.getString(column));
br.write("\tpublic "+ cls +" get"+ getInstanceMethodName(column) +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\t"+ className +" _tmp = ALL.onlyFields(");
br.write(getFieldName(column)+")");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(".getTheOnly();\n");
br.write("\t\t\t"+ getInstanceFieldName(column) +" = _tmp == null ? null : _tmp.get"
+ getInstanceMethodName(column) +"();");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ getInstanceFieldName(column) +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ cls +" v) {\n");
br.write("\t\t"+ getInstanceFieldName(column) +" = v;\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\t}\n\n");
if (!cls.equals(getFieldClassType(columns.getString(column)).getName())) {
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ getFieldClassType(columns.getString(column)).getName() +" v) {\n");
br.write("\t\treturn set"+ getInstanceMethodName(column) +"("+
this.convertToActualType(schema, table, column,
columns.getString(column), "v") +");\n");
br.write("\t}\n\n");
}
}
// write getters and setters for FKs
for (FK fk : fks) {
String referencedSchema = fk.reffed[0];
String referencedTable = fk.reffed[1];
//String referencedColumn = referenced.getString(2);
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String methodName = genFKMethodName(fk.columns.keySet(), referencedTable);
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
br.write("\tprivate "+ referencedTableClassName +" "+ cachedObjectName +" = null;\n\n");
br.write("\tpublic "+ referencedTableClassName +" get"+ methodName +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX)) {\n");
br.write("\t\t\t"+ cachedObjectName +" = "+ referencedTableClassName +".ALL");
br.write(".where("+ referencedTableClassName +"."+ getFieldName(fk.columns.values()) +".eq("+ underscoreToCamelCase(fk.columns.keySet(), false) +"))");
br.write(".getTheOnly();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ cachedObjectName +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ methodName +"("+ referencedTableClassName +" v) {\n");
//br.write(" v) {\n\t\tPUT_VALUE(");
br.write("\t\t"+ underscoreToCamelCase(fk.columns.keySet(), false) +" = v.get"+ underscoreToCamelCase(fk.columns.values(), true) +"();\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(fk.columns.keySet()) +".INDEX);\n");
br.write("\t\t"+ cachedObjectName +" = v;\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\n\t}\n\n");
}
// write SET_FK
br.write("\tprotected void SET_FK(Field.FK<?> field, Object v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fks) {
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
br.write("\t\telse if (field == FK_"+ genFKName(fk.columns.keySet(), referencedTable) +") {\n");
br.write("\t\t\t"+ cachedObjectName +" = ("+ referencedTableClassName +") v;\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
// write SET_FK_SET
/*
protected void SET_FK_SET(Field.FK field, Query<?> v) {
if (false);
if (Instrument.FK_INSTRUMENT_TYPE.equals(field)) {
__NOSCO_CACHED_FK_SET___instrument___instrument_type_id = (Query<Instrument>) v;
}
else {throw new RuntimeException("unknown FK");}
}
*/
br.write("\t@SuppressWarnings(\"unchecked\")\n");
br.write("\tprotected void SET_FK_SET(Field.FK<?> fk, Query<?> v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
if (!schema.equals(relatedSchema)) {
relatedTableClassName = pkg +"."+ relatedSchema +"."+ relatedTableClassName;
}
String fkName = "FK_"+ genFKName(fk.columns.keySet(), fk.reffed[1]);
String localVar = "__NOSCO_CACHED_FK_SET___"+ relatedTable + "___"
+ Misc.join("__", fk.columns.keySet());
br.write("\t\telse if ("+ relatedTableClassName +"."+ fkName +".equals(fk)) {\n");
br.write("\t\t\t"+ localVar +" = (Query<"+ relatedTableClassName +">) v;\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
// write the getTableFKSet() functions
Map<String, Integer> reffingCounts = new HashMap<String,Integer>();
for (FK fk : fksIn) {
String relatedTable = fk.reffing[1];
Integer c = reffingCounts.get(relatedTable);
if (c == null) c = 0;
reffingCounts.put(relatedTable, c+1);
}
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
//String method = genFKMethodName(fk.columns.keySet(), relatedTableClassName);
if (!schema.equals(relatedSchema)) {
relatedTableClassName = pkg +"."+ relatedSchema +"."+ relatedTableClassName;
}
String method = getInstanceMethodName(relatedTable);
if (reffingCounts.get(relatedTable) > 1) {
String tmp = Misc.join("_", fk.columns.keySet());
method = method + "_" + getInstanceMethodName(tmp);
}
String localVar = "__NOSCO_CACHED_FK_SET___"+ relatedTable + "___"
+ Misc.join("__", fk.columns.keySet());
br.write("\tprivate Query<"+ relatedTableClassName +"> "+ localVar +" = null;\n");
br.write("\tpublic Query<"+ relatedTableClassName +"> get"+ method +"Set() {\n");
br.write("\t\tif ("+ localVar +" != null) return "+ localVar + ";\n");
br.write("\t\telse return "+ relatedTableClassName +".ALL");
for (Entry<String, String> e : fk.columns.entrySet()) {
String relatedColumn = e.getKey();
String column = e.getValue();
br.write(".where("+ relatedTableClassName +"."+ getFieldName(relatedColumn) +".eq(get"+ getInstanceMethodName(column) +"()))");
}
br.write(";\n");
br.write("\t}\n\n");
}
// write save function
br.write("\tpublic boolean save() throws SQLException {\n");
br.write("\t\t return save(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean save(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (pkSet == null || pkSet.isEmpty()) {
br.write("\t\tthrow new RuntimeException(\"save() is ambiguous on objects without PKs - use insert() or update()\");\n");
} else {
br.write("\t\tint size = query.size();\n");
br.write("\t\tif (size == 0) return this.insert(ds);\n");
br.write("\t\telse if (size == 1) return this.update(ds);\n");
br.write("\t\telse throw new RuntimeException(\"more than one result was returned " +
"for a query that specified all the PKs. this is bad.\");\n");
br.write("\t\t\n");
}
br.write("\t}\n");
// write update function
br.write("\tpublic boolean update() throws SQLException {\n");
br.write("\t\t return update(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean update(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
if (pkSet == null || pkSet.size() == 0) {
for (String column : columns.keySet()) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
}
br.write(";\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "
+ convertToOriginalType(schema, table, column, columns.getString(column), getInstanceFieldName(column)) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\tint count = query.update();\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this, ds); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write delete function
br.write("\tpublic boolean delete() throws SQLException {\n");
br.write("\t\t return delete(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean delete(DataSource ds) throws SQLException {\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
if (pkSet == null || pkSet.size() == 0) {
for (String column : columns.keySet()) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
}
br.write(";\n");
br.write("\t\tint count = query.deleteAll();\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write insert function
br.write("\tpublic boolean insert() throws SQLException {\n");
br.write("\t\t return insert(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean insert(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (__NOSCO_CALLBACK_INSERT_PRE!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tupdates.put("+ getFieldName(column) +", "
+ convertToOriginalType(schema, table, column, columns.getString(column), getInstanceFieldName(column)) +");\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\t\tquery.insert();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_INSERT_POST!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_POST.invoke(null, this, ds); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn true;\n");
br.write("\t}\n");
// write exists function
br.write("\tpublic boolean exists() throws SQLException {\n");
br.write("\t\t return exists(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean exists(DataSource ds) throws SQLException {\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
br.write(";\n");
br.write("\t\tint size = query.size();\n");
br.write("\t\treturn size > 0;\n");
br.write("\t}\n");
// write callbacks
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_POST = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_POST = null;\n");
br.write("\tstatic {\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postInsert\", "
+ className +".class, DataSource.class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postUpdate\", "
+ className +".class, DataSource.class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t}\n");
// write the alias function
br.write("\t/**\n");
br.write("\t * Returns a table alias. This is used when specifying manual joins\n");
br.write("\t * to reference later using Field.from(alias) in where() conditions.\n");
br.write("\t */\n");
br.write("\tpublic static Table.__Alias<"+ className +"> as(String alias) {\n");
br.write("\t\treturn new Table.__Alias<"+ className +">("+ className +".class, alias);\n");
br.write("\t}\n\n");
// write the hashcode function
br.write("\t@Override\n");
br.write("\tpublic int hashCode() {\n");
br.write("\t\tfinal int prime = 31;\n");
br.write("\t\tint result = 1;\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\tresult = prime * result + (("+ getInstanceFieldName(column)
+" == null) ? 0 : "+ getInstanceFieldName(column) +".hashCode());\n");
}
br.write("\t\treturn result;\n");
br.write("\t}\n\n");
// write the equals function
br.write("\t@Override\n");
br.write("\tpublic boolean equals(Object other) {\n");
br.write("\t\treturn (other == this) || ((other != null) \n");
br.write("\t\t\t&& (other instanceof "+ className +")\n");
br.write("\t\t\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\t\t&& (("+ getInstanceFieldName(column) +" == null) ? ((("
+ className +")other)."+ getInstanceFieldName(column) +" == null) : ("
+ getInstanceFieldName(column) +".equals((("+ className +")other)."
+ getInstanceFieldName(column) +")))\n");
}
br.write("\t\t);\n");
br.write("\t}\n\n");
// write the compare function
br.write("\t@Override\n");
br.write("\tpublic int compareTo("+ className +" o) {\n");
br.write("\t\tint v = 0;\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\tv = "+ getInstanceFieldName(column) +"==null ? (o."
+ getInstanceFieldName(column) +"==null ? 0 : -1) : "
+ getInstanceFieldName(column) +".compareTo(o."
+ getInstanceFieldName(column) +");\n");
br.write("\t\tif (v != 0) return v;\n");
}
br.write("\t\treturn 0;\n");
br.write("\t}\n\n");
// write the map type function
br.write("\t@Override\n");
br.write("\tpublic java.lang.Object __NOSCO_PRIVATE_mapType(java.lang.Object o) {\n");
Set<String> coveredTypes = new HashSet<String>();
for (String origType : classTypeMappings.keySet()) {
String actualType = classTypeMappings.optString(origType);
br.write("\t\tif (o instanceof "+ actualType +") return ");
br.write(typeMappingFunctions.optString(actualType +" "+ origType)
.replaceAll("[%]s", "(("+ actualType +")o)"));
br.write(";\n");
coveredTypes.add(actualType);
}
for (String actualType : this.schemaTypeMappings.values()) {
if (coveredTypes.contains(actualType)) continue;
String origType = null;
for (String column : columns.keySet()) {
String type = columns.getString(column);
if (actualType.equals(this.getFieldType(schema, table, column, type))) {
origType = this.getFieldClassType(type).getName();
break;
}
}
if (origType == null) continue;
br.write("\t\tif (o instanceof "+ actualType +") return ");
br.write(typeMappingFunctions.optString(actualType +" "+ origType)
.replaceAll("[%]s", "(("+ actualType +")o)"));
br.write(";\n");
coveredTypes.add(actualType);
}
br.write("\t\treturn o;\n");
br.write("\t}\n\n");
// end class
br.write("}\n");
br.close();
}
private static String getInstanceFieldName(String column) {
if ("class".equals(column)) column = "JAVA_KEYWORD_class";
if ("for".equals(column)) column = "JAVA_KEYWORD_for";
column = column.replace("-", "_DASH_");
return underscoreToCamelCase(column, false);
}
private static String getInstanceMethodName(String column) {
if ("class".equals(column)) column = "JAVA_KEYWORD_class";
column = column.replace("-", "_DASH_");
return underscoreToCamelCase(column, true);
}
private String genFKName(Set<String> columns, String referencedTable) {
for(String column : columns) {
column = column.toUpperCase();
referencedTable = referencedTable.toUpperCase();
if (column.endsWith("_ID")) column = column.substring(0,column.length()-3);
if (referencedTable.startsWith(column)) {
return dePlural(referencedTable).toUpperCase();
} else {
return dePlural(column +"_"+ referencedTable).toUpperCase();
}
}
return null;
}
private String genFKMethodName(Set<String> columns, String referencedTable) {
return this.underscoreToCamelCase(columns, true)+"FK";
//return genTableClassName(genFKName(columns, referencedTable));
}
private String genTableClassName(String table) {
if (tableToClassName.containsKey(table)) return tableToClassName.get(table);
String proposed = table;
for (String prefix : stripPrefixes) {
if (proposed.startsWith(prefix)) {
proposed = proposed.substring(prefix.length());
break;
}
}
/*for (String suffix : stripSuffixes) {
if (table.endsWith(suffix)) {
table = table.substring(0,table.length()-suffix.length());
break;
}
} //*/
String proposed2 = underscoreToCamelCase(dePlural(proposed), true);
if (tableToClassName.containsValue(proposed2)) {
proposed2 = underscoreToCamelCase(proposed, true);
}
tableToClassName.put(table, proposed2);
return proposed2;
}
private String dePlural(String s) {
s = s.toLowerCase();
if (s.endsWith("series"));
else if (s.endsWith("us"));
else if (s.endsWith("is"));
else if (s.endsWith("as"));
else if (s.endsWith("ies")) s = s.substring(0,s.length()-3)+"y";
else if (s.endsWith("s")) s = s.substring(0,s.length()-1);
return s;
}
private String convertToActualType(String schema, String table, String column,
String type, String var) {
String origType = getFieldClassType(type).getName();
String actualType = getFieldType(schema, table, column, type);
if (origType.equals(actualType)) {
return var;
}
return convertType(var, origType, actualType);
}
private String convertType(String var, String fromType, String toType) {
String key = fromType +" "+ toType;
if (!typeMappingFunctions.has(key)) {
throw new RuntimeException("a mapping function of '" + key +"' was not " +
"found");
}
try {
String ret = typeMappingFunctions.getString(key);
ret = "("+ var +"== null) ? null : " + ret.replaceAll("[%]s", var);
return ret;
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("the mapping function of '" + key +"' needs " +
"to be a JSON string");
}
}
private String convertToOriginalType(String schema, String table, String column,
String type, String var) {
String origType = getFieldClassType(type).getName();
String actualType = getFieldType(schema, table, column, type);
if (origType.equals(actualType)) {
return var;
}
return convertType(var, actualType, origType);
}
private String getFieldType(String schema, String table, String column, String type) {
String s = getFieldClassType(type).getName();
String v = schema +"."+ table +"."+ column;
for (Entry<Pattern, String> e : schemaTypeMappings.entrySet()) {
if (e.getKey().matcher(v).matches()) {
return e.getValue();
}
}
try {
return classTypeMappings.has(s) ? classTypeMappings.getString(s) : s;
} catch (JSONException e) {
e.printStackTrace();
try {
throw new RuntimeException("a String was expected for the type mapping of "
+ s +" but a "+ classTypeMappings.get(s) +" was found");
} catch (JSONException e1) {
e1.printStackTrace();
throw new RuntimeException("this should never happen");
}
}
}
private Class<? extends Object> getFieldClassType(String type) {
if ("varchar".equals(type)) return String.class;
if ("char".equals(type)) return Character.class;
if ("nvarchar".equals(type)) return String.class;
if ("nchar".equals(type)) return String.class;
if ("longtext".equals(type)) return String.class;
if ("text".equals(type)) return String.class;
if ("tinytext".equals(type)) return String.class;
if ("mediumtext".equals(type)) return String.class;
if ("ntext".equals(type)) return String.class;
if ("xml".equals(type)) return String.class;
if ("int".equals(type)) return Integer.class;
if ("mediumint".equals(type)) return Integer.class;
if ("smallint".equals(type)) return Integer.class;
if ("tinyint".equals(type)) return Integer.class;
if ("bigint".equals(type)) return Long.class;
if ("decimal".equals(type)) return Double.class;
if ("money".equals(type)) return Double.class;
if ("numeric".equals(type)) return Double.class;
if ("float".equals(type)) return Double.class;
if ("real".equals(type)) return Float.class;
if ("blob".equals(type)) return Blob.class;
if ("longblob".equals(type)) return Blob.class;
if ("datetime".equals(type)) return Timestamp.class;
if ("date".equals(type)) return Date.class;
if ("timestamp".equals(type)) return Timestamp.class;
if ("year".equals(type)) return Integer.class;
if ("enum".equals(type)) return Integer.class;
if ("set".equals(type)) return String.class;
if ("bit".equals(type)) return Boolean.class;
if ("binary".equals(type)) return java.sql.Blob.class;
if ("varbinary".equals(type)) return java.sql.Blob.class;
if ("sql_variant".equals(type)) return Object.class;
if ("smalldatetime".equals(type)) return Timestamp.class;
if ("uniqueidentifier".equals(type)) return String.class;
if ("image".equals(type)) return java.sql.Blob.class;
System.err.println("unknown field type: "+ type);
return null;
}
private static String underscoreToCamelCase(String s, boolean capitalizeFirstChar) {
if (s==null) return null;
if (s.length()==0) return s;
s = s.toLowerCase();
s = s.replace(' ', '_').replace("%", "_PERCENT");
char[] c = s.toCharArray();
if (capitalizeFirstChar) {
c[0] = Character.toUpperCase(c[0]);
}
for (int i=1; i<c.length; ++i) {
if (c[i-1]=='_') {
c[i] = Character.toUpperCase(c[i]);
}
}
return new String(c).replaceAll("_", "");
}
private static String underscoreToCamelCase(Collection<String> strings, boolean capitalizeFirstChar) {
StringBuffer sb = new StringBuffer();
for (String s : strings) {
sb.append(underscoreToCamelCase(s, capitalizeFirstChar));
capitalizeFirstChar = true;
}
return sb.toString();
}
}
| false | true | private void generate(String schema, String table, JSONObject columns, JSONArray pks,
List<FK> fks, List<FK> fksIn, String dataSourceName, String callbackPackage,
JSONObject enums)
throws IOException, JSONException {
String className = genTableClassName(table);
Set<String> pkSet = new HashSet<String>();
if (pks == null) pks = new JSONArray();
for (int i=0; i<pks.length(); ++i) {
pkSet.add(pks.getString(i));
}
int fieldCount = columns.keySet().size();
String pkgDir = Misc.join("/", pkg.split("[.]"));
new File(Misc.join("/", dir, pkgDir, schema)).mkdirs();
File file = new File(Misc.join("/", dir, pkgDir, schema, className+".java"));
System.out.println("writing: "+ file.getAbsolutePath());
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("package "+ pkg +"."+ schema +";\n\n");
br.write("import java.lang.reflect.Method;\n");
br.write("import java.lang.reflect.InvocationTargetException;\n");
br.write("import java.sql.SQLException;\n");
br.write("import javax.sql.DataSource;\n");
br.write("import java.util.Map;\n\n");
br.write("import java.util.HashMap;\n\n");
br.write("import org.nosco.Field;\n");
br.write("import org.nosco.Query;\n");
br.write("import org.nosco.QueryFactory;\n");
br.write("import org.nosco.Table;\n");
br.write("\n");
br.write("public class "+ className +" extends Table implements Comparable<"+ className +"> {\n\n");
// write field constants
int index = 0;
for (String column : columns.keySet()) {
br.write("\tpublic static final Field<");
br.write(getFieldType(schema, table, column, columns.getString(column)));
br.write("> "+ getFieldName(column));
br.write(" = new Field<"+ getFieldType(schema, table, column, columns.getString(column)));
br.write(">("+ index +", "+ className +".class, \""+ column);
br.write("\", "+ getFieldType(schema, table, column, columns.getString(column)) +".class");
br.write(");\n");
++index;
}
br.write("\n");
// write primary keys
br.write("\tpublic static Field.PK<"+ className +"> PK = new Field.PK<"+ className +">(");
for (int i=0; i<pks.length(); ++i) {
br.write(pks.getString(i).toUpperCase());
if (i<pks.length()-1) br.write(", ");
}
br.write(");\n");
br.write("\tpublic org.nosco.Field.PK PK() { return PK; }\n\n");
// write foreign keys
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String fkName = genFKName(fk.columns.keySet(), referencedTable);
br.write("\tpublic static final Field.FK<"+ referencedTableClassName +"> FK_"+ fkName);
br.write(" = new Field.FK<"+ referencedTableClassName +">("+ index +", "+ className +".class, ");
br.write(referencedTableClassName +".class");
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ e.getKey().toUpperCase());
}
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ referencedTableClassName +".");
br.write(e.getValue().toUpperCase());
}
br.write(");\n");
++index;
}
br.write("\n");
// write enums
for (String column : columns.keySet()) {
String enumKey = schema +"."+ table +"."+ column;
if (!enums.has(enumKey)) continue;
JSONObject instances = enums.optJSONObject(enumKey);
boolean simple = pkSet.size() == 1;
if (simple) {
String pk = pkSet.iterator().next();
String pkType = getFieldType(schema, table, pk, columns.getString(pk));
br.write("\tpublic enum PKS implements Table.__SimplePrimaryKey<"+ className +", "+ pkType +"> {\n\n");
int count = 0;
for (String name : instances.keySet()) {
++ count;
String value = instances.optJSONArray(name).getString(0);
if ("java.lang.String".equals(pkType)) value = "\""+ value +"\"";
br.write("\t\t"+ name.toUpperCase().replaceAll("\\W", "_"));
br.write("("+ value +")");
if (count < instances.keySet().size()) br.write(",\n");
else br.write(";\n\n");
}
br.write("\t\tpublic final "+ pkType +" "+ getFieldName(pk) +";\n");
br.write("\t\tPKS("+ pkType +" v) {\n");
br.write("\t\t\t"+ getFieldName(pk) +" = v;\n");
br.write("\t\t}\n");
br.write("\t\t@SuppressWarnings(\"unchecked\")\n");
br.write("\t\t@Override\n");
br.write("\t\tpublic <R> R get(Field<R> field) {\n");
br.write("\t\t\tif (field=="+ className +"."+ getFieldName(pk)
+") return (R) Integer.valueOf("+ getFieldName(pk) +"); \n");
br.write("\t\t\tif ("+ className +"."+ getFieldName(pk)
+".sameField(field)) return (R) Integer.valueOf("
+ getFieldName(pk) +");\n");
br.write("\t\t\tthrow new RuntimeException(\"field \"+ field +\" is not part of this primary key\");\n");
br.write("\t\t}\n");
br.write("\t\t@Override\n");
br.write("\t\tpublic "+ pkType +" value() {\n");
br.write("\t\t\treturn "+ getFieldName(pk)+ ";\n");
br.write("\t\t}\n\n");
br.write("\t}\n");
}
}
// write field value references
for (String column : columns.keySet()) {
br.write("\tprivate "+ getFieldType(schema, table, column, columns.getString(column)));
br.write(" "+ getInstanceFieldName(column) + " = null;\n");
}
br.write("\n");
// write constructors
br.write("\tpublic "+ className +"() {}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tprotected "+ className +"(Field[] fields, Object[] objects, int start, int end) {\n");
br.write("\t\tif (fields.length != objects.length)\n\t\t\tthrow new IllegalArgumentException(");
br.write("\"fields.length != objects.length => \"+ fields.length +\" != \"+ objects.length");
br.write(" +\"\");\n");
br.write("\t\tfor (int i=start; i<end; ++i) {\n");
for (String column : columns.keySet()) {
br.write("\t\t\tif (fields[i]=="+ getFieldName(column) +") {\n");
br.write("\t\t\t\t"+ getInstanceFieldName(column) +" = ");
String assignment = convertToActualType(schema, table, column,
columns.getString(column),
"("+ getFieldClassType(columns.getString(column)).getName()+ ") objects[i]");
br.write(assignment);
br.write(";\n");
br.write("\t\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t\t\tcontinue;\n");
br.write("\t\t\t}\n");
}
br.write("\t\t}\n\t}\n\n");
// write abstract method impls
br.write("\tpublic String SCHEMA_NAME() {\n\t\treturn \""+ schema +"\";\n\t}\n\n");
br.write("\tpublic String TABLE_NAME() {\n\t\treturn \""+ table +"\";\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field[] FIELDS() {\n\t\tField[] fields = {");
for (String column : columns.keySet()) {
br.write(getFieldName(column)+",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field.FK[] FKS() {\n\t\tField.FK[] fields = {");
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
// if (!schema.equals(fk.reffed[0])) {
// referencedTable = fk.reffed[0] +"_"+ referencedTable;
// }
br.write("FK_" + genFKName(fk.columns.keySet(), referencedTable) + ",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
// write the generic get(field) method
br.write("\t@SuppressWarnings(\"unchecked\")\n");
br.write("\tpublic <S> S get(Field<S> _field) {\n");
for (String column : columns.keySet()) {
br.write("\t\tif (_field=="+ getFieldName(column) +") ");
br.write("return (S) "+ getInstanceFieldName(column) +";\n");
}
br.write("\t\tthrow new IllegalArgumentException(\"unknown field \"+ _field);\n");
br.write("\t}\n\n");
// write the generic set(field, value) method
br.write("\tpublic <S> void set(Field<S> _field, S _value) {\n");
for (String column : columns.keySet()) {
br.write("\t\tif (_field=="+ getFieldName(column) +") ");
br.write(getInstanceFieldName(column) +" = ("+ getFieldType(schema, table, column, columns.getString(column)) +") _value;\n");
}
br.write("\t\tthrow new IllegalArgumentException(\"unknown field \"+ _field);\n");
br.write("\t}\n\n");
//br.write("\tpublic Field[] GET_PRIMARY_KEY_FIELDS() {\n\t\tField[] fields = {");
//for (int i=0; i<pks.length(); ++i) {
// br.write(pks.getString(i).toUpperCase()+",");
//}
//br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\tpublic static final Query<"+ className +"> ALL = QueryFactory.IT.getQuery("
+ className +".class).use("+ pkg +"."+ dataSourceName +"."+ schema.toUpperCase() +");\n\n");
// write toString
br.write("\t public String toString() {\n");
br.write("\t\treturn \"["+ className);
for (int i=0; i<pks.length(); ++i) {
String pk = pks.getString(i);
br.write(" "+ pk+":");
br.write("\"+"+ getInstanceFieldName(pk));
br.write("+\"");
}
for (String column : columns.keySet()) {
if (!"name".equalsIgnoreCase(column)) continue;
// if "name" exists but isn't a PK, we should still use it for toString()
br.write(" "+ column +":");
br.write("\"+"+ getInstanceFieldName(column));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write toString
br.write("\t public String toStringDetailed() {\n");
br.write("\t\treturn \"["+ className);
for (String column : columns.keySet()) {
br.write(" "+ column +":");
br.write("\"+"+ getInstanceFieldName(column));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write getters and setters
for (String column : columns.keySet()) {
String cls = getFieldType(schema, table, column, columns.getString(column));
br.write("\tpublic "+ cls +" get"+ getInstanceMethodName(column) +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\t"+ className +" _tmp = ALL.onlyFields(");
br.write(getFieldName(column)+")");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(".getTheOnly();\n");
br.write("\t\t\t"+ getInstanceFieldName(column) +" = _tmp == null ? null : _tmp.get"
+ getInstanceMethodName(column) +"();");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ getInstanceFieldName(column) +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ cls +" v) {\n");
br.write("\t\t"+ getInstanceFieldName(column) +" = v;\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\t}\n\n");
if (!cls.equals(getFieldClassType(columns.getString(column)).getName())) {
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ getFieldClassType(columns.getString(column)).getName() +" v) {\n");
br.write("\t\treturn set"+ getInstanceMethodName(column) +"("+
this.convertToActualType(schema, table, column,
columns.getString(column), "v") +");\n");
br.write("\t}\n\n");
}
}
// write getters and setters for FKs
for (FK fk : fks) {
String referencedSchema = fk.reffed[0];
String referencedTable = fk.reffed[1];
//String referencedColumn = referenced.getString(2);
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String methodName = genFKMethodName(fk.columns.keySet(), referencedTable);
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
br.write("\tprivate "+ referencedTableClassName +" "+ cachedObjectName +" = null;\n\n");
br.write("\tpublic "+ referencedTableClassName +" get"+ methodName +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX)) {\n");
br.write("\t\t\t"+ cachedObjectName +" = "+ referencedTableClassName +".ALL");
br.write(".where("+ referencedTableClassName +"."+ getFieldName(fk.columns.values()) +".eq("+ underscoreToCamelCase(fk.columns.keySet(), false) +"))");
br.write(".getTheOnly();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ cachedObjectName +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ methodName +"("+ referencedTableClassName +" v) {\n");
//br.write(" v) {\n\t\tPUT_VALUE(");
br.write("\t\t"+ underscoreToCamelCase(fk.columns.keySet(), false) +" = v.get"+ underscoreToCamelCase(fk.columns.values(), true) +"();\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(fk.columns.keySet()) +".INDEX);\n");
br.write("\t\t"+ cachedObjectName +" = v;\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\n\t}\n\n");
}
// write SET_FK
br.write("\tprotected void SET_FK(Field.FK<?> field, Object v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fks) {
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
br.write("\t\telse if (field == FK_"+ genFKName(fk.columns.keySet(), referencedTable) +") {\n");
br.write("\t\t\t"+ cachedObjectName +" = ("+ referencedTableClassName +") v;\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
// write SET_FK_SET
/*
protected void SET_FK_SET(Field.FK field, Query<?> v) {
if (false);
if (Instrument.FK_INSTRUMENT_TYPE.equals(field)) {
__NOSCO_CACHED_FK_SET___instrument___instrument_type_id = (Query<Instrument>) v;
}
else {throw new RuntimeException("unknown FK");}
}
*/
br.write("\t@SuppressWarnings(\"unchecked\")\n");
br.write("\tprotected void SET_FK_SET(Field.FK<?> fk, Query<?> v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
if (!schema.equals(relatedSchema)) {
relatedTableClassName = pkg +"."+ relatedSchema +"."+ relatedTableClassName;
}
String fkName = "FK_"+ genFKName(fk.columns.keySet(), fk.reffed[1]);
String localVar = "__NOSCO_CACHED_FK_SET___"+ relatedTable + "___"
+ Misc.join("__", fk.columns.keySet());
br.write("\t\telse if ("+ relatedTableClassName +"."+ fkName +".equals(fk)) {\n");
br.write("\t\t\t"+ localVar +" = (Query<"+ relatedTableClassName +">) v;\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
// write the getTableFKSet() functions
Map<String, Integer> reffingCounts = new HashMap<String,Integer>();
for (FK fk : fksIn) {
String relatedTable = fk.reffing[1];
Integer c = reffingCounts.get(relatedTable);
if (c == null) c = 0;
reffingCounts.put(relatedTable, c+1);
}
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
//String method = genFKMethodName(fk.columns.keySet(), relatedTableClassName);
if (!schema.equals(relatedSchema)) {
relatedTableClassName = pkg +"."+ relatedSchema +"."+ relatedTableClassName;
}
String method = getInstanceMethodName(relatedTable);
if (reffingCounts.get(relatedTable) > 1) {
String tmp = Misc.join("_", fk.columns.keySet());
method = method + "_" + getInstanceMethodName(tmp);
}
String localVar = "__NOSCO_CACHED_FK_SET___"+ relatedTable + "___"
+ Misc.join("__", fk.columns.keySet());
br.write("\tprivate Query<"+ relatedTableClassName +"> "+ localVar +" = null;\n");
br.write("\tpublic Query<"+ relatedTableClassName +"> get"+ method +"Set() {\n");
br.write("\t\tif ("+ localVar +" != null) return "+ localVar + ";\n");
br.write("\t\telse return "+ relatedTableClassName +".ALL");
for (Entry<String, String> e : fk.columns.entrySet()) {
String relatedColumn = e.getKey();
String column = e.getValue();
br.write(".where("+ relatedTableClassName +"."+ getFieldName(relatedColumn) +".eq(get"+ getInstanceMethodName(column) +"()))");
}
br.write(";\n");
br.write("\t}\n\n");
}
// write save function
br.write("\tpublic boolean save() throws SQLException {\n");
br.write("\t\t return save(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean save(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (pkSet == null || pkSet.isEmpty()) {
br.write("\t\tthrow new RuntimeException(\"save() is ambiguous on objects without PKs - use insert() or update()\");\n");
} else {
br.write("\t\tint size = query.size();\n");
br.write("\t\tif (size == 0) return this.insert(ds);\n");
br.write("\t\telse if (size == 1) return this.update(ds);\n");
br.write("\t\telse throw new RuntimeException(\"more than one result was returned " +
"for a query that specified all the PKs. this is bad.\");\n");
br.write("\t\t\n");
}
br.write("\t}\n");
// write update function
br.write("\tpublic boolean update() throws SQLException {\n");
br.write("\t\t return update(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean update(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
if (pkSet == null || pkSet.size() == 0) {
for (String column : columns.keySet()) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
}
br.write(";\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "
+ convertToOriginalType(schema, table, column, columns.getString(column), getInstanceFieldName(column)) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\tint count = query.update();\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this, ds); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write delete function
br.write("\tpublic boolean delete() throws SQLException {\n");
br.write("\t\t return delete(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean delete(DataSource ds) throws SQLException {\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
if (pkSet == null || pkSet.size() == 0) {
for (String column : columns.keySet()) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
}
br.write(";\n");
br.write("\t\tint count = query.deleteAll();\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write insert function
br.write("\tpublic boolean insert() throws SQLException {\n");
br.write("\t\t return insert(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean insert(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (__NOSCO_CALLBACK_INSERT_PRE!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tupdates.put("+ getFieldName(column) +", "
+ convertToOriginalType(schema, table, column, columns.getString(column), getInstanceFieldName(column)) +");\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\t\tquery.insert();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_INSERT_POST!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_POST.invoke(null, this, ds); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn true;\n");
br.write("\t}\n");
// write exists function
br.write("\tpublic boolean exists() throws SQLException {\n");
br.write("\t\t return exists(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean exists(DataSource ds) throws SQLException {\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
br.write(";\n");
br.write("\t\tint size = query.size();\n");
br.write("\t\treturn size > 0;\n");
br.write("\t}\n");
// write callbacks
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_POST = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_POST = null;\n");
br.write("\tstatic {\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postInsert\", "
+ className +".class, DataSource.class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postUpdate\", "
+ className +".class, DataSource.class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t}\n");
// write the alias function
br.write("\t/**\n");
br.write("\t * Returns a table alias. This is used when specifying manual joins\n");
br.write("\t * to reference later using Field.from(alias) in where() conditions.\n");
br.write("\t */\n");
br.write("\tpublic static Table.__Alias<"+ className +"> as(String alias) {\n");
br.write("\t\treturn new Table.__Alias<"+ className +">("+ className +".class, alias);\n");
br.write("\t}\n\n");
// write the hashcode function
br.write("\t@Override\n");
br.write("\tpublic int hashCode() {\n");
br.write("\t\tfinal int prime = 31;\n");
br.write("\t\tint result = 1;\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\tresult = prime * result + (("+ getInstanceFieldName(column)
+" == null) ? 0 : "+ getInstanceFieldName(column) +".hashCode());\n");
}
br.write("\t\treturn result;\n");
br.write("\t}\n\n");
// write the equals function
br.write("\t@Override\n");
br.write("\tpublic boolean equals(Object other) {\n");
br.write("\t\treturn (other == this) || ((other != null) \n");
br.write("\t\t\t&& (other instanceof "+ className +")\n");
br.write("\t\t\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\t\t&& (("+ getInstanceFieldName(column) +" == null) ? ((("
+ className +")other)."+ getInstanceFieldName(column) +" == null) : ("
+ getInstanceFieldName(column) +".equals((("+ className +")other)."
+ getInstanceFieldName(column) +")))\n");
}
br.write("\t\t);\n");
br.write("\t}\n\n");
// write the compare function
br.write("\t@Override\n");
br.write("\tpublic int compareTo("+ className +" o) {\n");
br.write("\t\tint v = 0;\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\tv = "+ getInstanceFieldName(column) +"==null ? (o."
+ getInstanceFieldName(column) +"==null ? 0 : -1) : "
+ getInstanceFieldName(column) +".compareTo(o."
+ getInstanceFieldName(column) +");\n");
br.write("\t\tif (v != 0) return v;\n");
}
br.write("\t\treturn 0;\n");
br.write("\t}\n\n");
// write the map type function
br.write("\t@Override\n");
br.write("\tpublic java.lang.Object __NOSCO_PRIVATE_mapType(java.lang.Object o) {\n");
Set<String> coveredTypes = new HashSet<String>();
for (String origType : classTypeMappings.keySet()) {
String actualType = classTypeMappings.optString(origType);
br.write("\t\tif (o instanceof "+ actualType +") return ");
br.write(typeMappingFunctions.optString(actualType +" "+ origType)
.replaceAll("[%]s", "(("+ actualType +")o)"));
br.write(";\n");
coveredTypes.add(actualType);
}
for (String actualType : this.schemaTypeMappings.values()) {
if (coveredTypes.contains(actualType)) continue;
String origType = null;
for (String column : columns.keySet()) {
String type = columns.getString(column);
if (actualType.equals(this.getFieldType(schema, table, column, type))) {
origType = this.getFieldClassType(type).getName();
break;
}
}
if (origType == null) continue;
br.write("\t\tif (o instanceof "+ actualType +") return ");
br.write(typeMappingFunctions.optString(actualType +" "+ origType)
.replaceAll("[%]s", "(("+ actualType +")o)"));
br.write(";\n");
coveredTypes.add(actualType);
}
br.write("\t\treturn o;\n");
br.write("\t}\n\n");
// end class
br.write("}\n");
br.close();
}
| private void generate(String schema, String table, JSONObject columns, JSONArray pks,
List<FK> fks, List<FK> fksIn, String dataSourceName, String callbackPackage,
JSONObject enums)
throws IOException, JSONException {
String className = genTableClassName(table);
Set<String> pkSet = new HashSet<String>();
if (pks == null) pks = new JSONArray();
for (int i=0; i<pks.length(); ++i) {
pkSet.add(pks.getString(i));
}
int fieldCount = columns.keySet().size();
String pkgDir = Misc.join("/", pkg.split("[.]"));
new File(Misc.join("/", dir, pkgDir, schema)).mkdirs();
File file = new File(Misc.join("/", dir, pkgDir, schema, className+".java"));
System.out.println("writing: "+ file.getAbsolutePath());
BufferedWriter br = new BufferedWriter(new FileWriter(file));
br.write("package "+ pkg +"."+ schema +";\n\n");
br.write("import java.lang.reflect.Method;\n");
br.write("import java.lang.reflect.InvocationTargetException;\n");
br.write("import java.sql.SQLException;\n");
br.write("import javax.sql.DataSource;\n");
br.write("import java.util.Map;\n\n");
br.write("import java.util.HashMap;\n\n");
br.write("import org.nosco.Field;\n");
br.write("import org.nosco.Query;\n");
br.write("import org.nosco.QueryFactory;\n");
br.write("import org.nosco.Table;\n");
br.write("\n");
br.write("public class "+ className +" extends Table implements Comparable<"+ className +"> {\n\n");
// write field constants
int index = 0;
for (String column : columns.keySet()) {
br.write("\tpublic static final Field<");
br.write(getFieldType(schema, table, column, columns.getString(column)));
br.write("> "+ getFieldName(column));
br.write(" = new Field<"+ getFieldType(schema, table, column, columns.getString(column)));
br.write(">("+ index +", "+ className +".class, \""+ column);
br.write("\", "+ getFieldType(schema, table, column, columns.getString(column)) +".class");
br.write(");\n");
++index;
}
br.write("\n");
// write primary keys
br.write("\tpublic static Field.PK<"+ className +"> PK = new Field.PK<"+ className +">(");
for (int i=0; i<pks.length(); ++i) {
br.write(pks.getString(i).toUpperCase());
if (i<pks.length()-1) br.write(", ");
}
br.write(");\n");
br.write("\tpublic org.nosco.Field.PK PK() { return PK; }\n\n");
// write foreign keys
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String fkName = genFKName(fk.columns.keySet(), referencedTable);
br.write("\tpublic static final Field.FK<"+ referencedTableClassName +"> FK_"+ fkName);
br.write(" = new Field.FK<"+ referencedTableClassName +">("+ index +", "+ className +".class, ");
br.write(referencedTableClassName +".class");
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ e.getKey().toUpperCase());
}
for (Entry<String, String> e : fk.columns.entrySet()) {
br.write(", "+ referencedTableClassName +".");
br.write(e.getValue().toUpperCase());
}
br.write(");\n");
++index;
}
br.write("\n");
// write enums
for (String column : columns.keySet()) {
String enumKey = schema +"."+ table +"."+ column;
if (!enums.has(enumKey)) continue;
JSONObject instances = enums.optJSONObject(enumKey);
boolean simple = pkSet.size() == 1;
if (simple) {
String pk = pkSet.iterator().next();
String pkType = getFieldType(schema, table, pk, columns.getString(pk));
br.write("\tpublic enum PKS implements Table.__SimplePrimaryKey<"+ className +", "+ pkType +"> {\n\n");
int count = 0;
for (String name : instances.keySet()) {
++ count;
String value = instances.optJSONArray(name).getString(0);
if ("java.lang.String".equals(pkType)) value = "\""+ value +"\"";
br.write("\t\t"+ name.toUpperCase().replaceAll("\\W", "_"));
br.write("("+ value +")");
if (count < instances.keySet().size()) br.write(",\n");
}
br.write(";\n\n");
br.write("\t\tpublic final "+ pkType +" "+ getFieldName(pk) +";\n");
br.write("\t\tPKS("+ pkType +" v) {\n");
br.write("\t\t\t"+ getFieldName(pk) +" = v;\n");
br.write("\t\t}\n");
br.write("\t\t@SuppressWarnings(\"unchecked\")\n");
br.write("\t\t@Override\n");
br.write("\t\tpublic <R> R get(Field<R> field) {\n");
br.write("\t\t\tif (field=="+ className +"."+ getFieldName(pk)
+") return (R) Integer.valueOf("+ getFieldName(pk) +"); \n");
br.write("\t\t\tif ("+ className +"."+ getFieldName(pk)
+".sameField(field)) return (R) Integer.valueOf("
+ getFieldName(pk) +");\n");
br.write("\t\t\tthrow new RuntimeException(\"field \"+ field +\" is not part of this primary key\");\n");
br.write("\t\t}\n");
br.write("\t\t@Override\n");
br.write("\t\tpublic "+ pkType +" value() {\n");
br.write("\t\t\treturn "+ getFieldName(pk)+ ";\n");
br.write("\t\t}\n\n");
br.write("\t}\n");
}
}
// write field value references
for (String column : columns.keySet()) {
br.write("\tprivate "+ getFieldType(schema, table, column, columns.getString(column)));
br.write(" "+ getInstanceFieldName(column) + " = null;\n");
}
br.write("\n");
// write constructors
br.write("\tpublic "+ className +"() {}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tprotected "+ className +"(Field[] fields, Object[] objects, int start, int end) {\n");
br.write("\t\tif (fields.length != objects.length)\n\t\t\tthrow new IllegalArgumentException(");
br.write("\"fields.length != objects.length => \"+ fields.length +\" != \"+ objects.length");
br.write(" +\"\");\n");
br.write("\t\tfor (int i=start; i<end; ++i) {\n");
for (String column : columns.keySet()) {
br.write("\t\t\tif (fields[i]=="+ getFieldName(column) +") {\n");
br.write("\t\t\t\t"+ getInstanceFieldName(column) +" = ");
String assignment = convertToActualType(schema, table, column,
columns.getString(column),
"("+ getFieldClassType(columns.getString(column)).getName()+ ") objects[i]");
br.write(assignment);
br.write(";\n");
br.write("\t\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t\t\tcontinue;\n");
br.write("\t\t\t}\n");
}
br.write("\t\t}\n\t}\n\n");
// write abstract method impls
br.write("\tpublic String SCHEMA_NAME() {\n\t\treturn \""+ schema +"\";\n\t}\n\n");
br.write("\tpublic String TABLE_NAME() {\n\t\treturn \""+ table +"\";\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field[] FIELDS() {\n\t\tField[] fields = {");
for (String column : columns.keySet()) {
br.write(getFieldName(column)+",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic Field.FK[] FKS() {\n\t\tField.FK[] fields = {");
for (FK fk : fks) {
String referencedTable = fk.reffed[1];
// if (!schema.equals(fk.reffed[0])) {
// referencedTable = fk.reffed[0] +"_"+ referencedTable;
// }
br.write("FK_" + genFKName(fk.columns.keySet(), referencedTable) + ",");
}
br.write("};\n\t\treturn fields;\n\t}\n\n");
// write the generic get(field) method
br.write("\t@SuppressWarnings(\"unchecked\")\n");
br.write("\tpublic <S> S get(Field<S> _field) {\n");
for (String column : columns.keySet()) {
br.write("\t\tif (_field=="+ getFieldName(column) +") ");
br.write("return (S) "+ getInstanceFieldName(column) +";\n");
}
br.write("\t\tthrow new IllegalArgumentException(\"unknown field \"+ _field);\n");
br.write("\t}\n\n");
// write the generic set(field, value) method
br.write("\tpublic <S> void set(Field<S> _field, S _value) {\n");
for (String column : columns.keySet()) {
br.write("\t\tif (_field=="+ getFieldName(column) +") ");
br.write(getInstanceFieldName(column) +" = ("+ getFieldType(schema, table, column, columns.getString(column)) +") _value;\n");
}
br.write("\t\tthrow new IllegalArgumentException(\"unknown field \"+ _field);\n");
br.write("\t}\n\n");
//br.write("\tpublic Field[] GET_PRIMARY_KEY_FIELDS() {\n\t\tField[] fields = {");
//for (int i=0; i<pks.length(); ++i) {
// br.write(pks.getString(i).toUpperCase()+",");
//}
//br.write("};\n\t\treturn fields;\n\t}\n\n");
br.write("\tpublic static final Query<"+ className +"> ALL = QueryFactory.IT.getQuery("
+ className +".class).use("+ pkg +"."+ dataSourceName +"."+ schema.toUpperCase() +");\n\n");
// write toString
br.write("\t public String toString() {\n");
br.write("\t\treturn \"["+ className);
for (int i=0; i<pks.length(); ++i) {
String pk = pks.getString(i);
br.write(" "+ pk+":");
br.write("\"+"+ getInstanceFieldName(pk));
br.write("+\"");
}
for (String column : columns.keySet()) {
if (!"name".equalsIgnoreCase(column)) continue;
// if "name" exists but isn't a PK, we should still use it for toString()
br.write(" "+ column +":");
br.write("\"+"+ getInstanceFieldName(column));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write toString
br.write("\t public String toStringDetailed() {\n");
br.write("\t\treturn \"["+ className);
for (String column : columns.keySet()) {
br.write(" "+ column +":");
br.write("\"+"+ getInstanceFieldName(column));
br.write("+\"");
}
br.write("]\";\n");
br.write("\t}\n\n");
// write getters and setters
for (String column : columns.keySet()) {
String cls = getFieldType(schema, table, column, columns.getString(column));
br.write("\tpublic "+ cls +" get"+ getInstanceMethodName(column) +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\t"+ className +" _tmp = ALL.onlyFields(");
br.write(getFieldName(column)+")");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(".getTheOnly();\n");
br.write("\t\t\t"+ getInstanceFieldName(column) +" = _tmp == null ? null : _tmp.get"
+ getInstanceMethodName(column) +"();");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ getInstanceFieldName(column) +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ cls +" v) {\n");
br.write("\t\t"+ getInstanceFieldName(column) +" = v;\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\t__NOSCO_FETCHED_VALUES.set("+ getFieldName(column) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\t}\n\n");
if (!cls.equals(getFieldClassType(columns.getString(column)).getName())) {
br.write("\tpublic "+ className +" set"+ getInstanceMethodName(column));
br.write("("+ getFieldClassType(columns.getString(column)).getName() +" v) {\n");
br.write("\t\treturn set"+ getInstanceMethodName(column) +"("+
this.convertToActualType(schema, table, column,
columns.getString(column), "v") +");\n");
br.write("\t}\n\n");
}
}
// write getters and setters for FKs
for (FK fk : fks) {
String referencedSchema = fk.reffed[0];
String referencedTable = fk.reffed[1];
//String referencedColumn = referenced.getString(2);
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
String methodName = genFKMethodName(fk.columns.keySet(), referencedTable);
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
br.write("\tprivate "+ referencedTableClassName +" "+ cachedObjectName +" = null;\n\n");
br.write("\tpublic "+ referencedTableClassName +" get"+ methodName +"() {\n");
br.write("\t\tif (!__NOSCO_FETCHED_VALUES.get(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX)) {\n");
br.write("\t\t\t"+ cachedObjectName +" = "+ referencedTableClassName +".ALL");
br.write(".where("+ referencedTableClassName +"."+ getFieldName(fk.columns.values()) +".eq("+ underscoreToCamelCase(fk.columns.keySet(), false) +"))");
br.write(".getTheOnly();\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
br.write("\t\treturn "+ cachedObjectName +";\n\t}\n\n");
br.write("\tpublic "+ className +" set"+ methodName +"("+ referencedTableClassName +" v) {\n");
//br.write(" v) {\n\t\tPUT_VALUE(");
br.write("\t\t"+ underscoreToCamelCase(fk.columns.keySet(), false) +" = v.get"+ underscoreToCamelCase(fk.columns.values(), true) +"();\n");
br.write("\t\tif (__NOSCO_UPDATED_VALUES == null) __NOSCO_UPDATED_VALUES = new java.util.BitSet();\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set("+ getFieldName(fk.columns.keySet()) +".INDEX);\n");
br.write("\t\t"+ cachedObjectName +" = v;\n");
br.write("\t\t__NOSCO_UPDATED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\treturn this;\n");
br.write("\n\t}\n\n");
}
// write SET_FK
br.write("\tprotected void SET_FK(Field.FK<?> field, Object v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fks) {
String cachedObjectName = "_NOSCO_FK_"+ underscoreToCamelCase(fk.columns.keySet(), false);
String referencedTable = fk.reffed[1];
String referencedTableClassName = genTableClassName(referencedTable);
if (!schema.equals(fk.reffed[0])) {
referencedTableClassName = pkg +"."+ fk.reffed[0] +"."+ referencedTableClassName;
}
br.write("\t\telse if (field == FK_"+ genFKName(fk.columns.keySet(), referencedTable) +") {\n");
br.write("\t\t\t"+ cachedObjectName +" = ("+ referencedTableClassName +") v;\n");
br.write("\t\t\t__NOSCO_FETCHED_VALUES.set(FK_"+ genFKName(fk.columns.keySet(), referencedTable) +".INDEX);\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
// write SET_FK_SET
/*
protected void SET_FK_SET(Field.FK field, Query<?> v) {
if (false);
if (Instrument.FK_INSTRUMENT_TYPE.equals(field)) {
__NOSCO_CACHED_FK_SET___instrument___instrument_type_id = (Query<Instrument>) v;
}
else {throw new RuntimeException("unknown FK");}
}
*/
br.write("\t@SuppressWarnings(\"unchecked\")\n");
br.write("\tprotected void SET_FK_SET(Field.FK<?> fk, Query<?> v) {\n");
br.write("\t\tif (false);\n");
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
if (!schema.equals(relatedSchema)) {
relatedTableClassName = pkg +"."+ relatedSchema +"."+ relatedTableClassName;
}
String fkName = "FK_"+ genFKName(fk.columns.keySet(), fk.reffed[1]);
String localVar = "__NOSCO_CACHED_FK_SET___"+ relatedTable + "___"
+ Misc.join("__", fk.columns.keySet());
br.write("\t\telse if ("+ relatedTableClassName +"."+ fkName +".equals(fk)) {\n");
br.write("\t\t\t"+ localVar +" = (Query<"+ relatedTableClassName +">) v;\n");
br.write("\t\t}\n");
}
br.write("\t\telse {throw new RuntimeException(\"unknown FK\");}\n");
br.write("\t}\n\n");
// write the getTableFKSet() functions
Map<String, Integer> reffingCounts = new HashMap<String,Integer>();
for (FK fk : fksIn) {
String relatedTable = fk.reffing[1];
Integer c = reffingCounts.get(relatedTable);
if (c == null) c = 0;
reffingCounts.put(relatedTable, c+1);
}
for (FK fk : fksIn) {
String relatedSchema = fk.reffing[0];
String relatedTable = fk.reffing[1];
String relatedTableClassName = this.genTableClassName(relatedTable);
//String method = genFKMethodName(fk.columns.keySet(), relatedTableClassName);
if (!schema.equals(relatedSchema)) {
relatedTableClassName = pkg +"."+ relatedSchema +"."+ relatedTableClassName;
}
String method = getInstanceMethodName(relatedTable);
if (reffingCounts.get(relatedTable) > 1) {
String tmp = Misc.join("_", fk.columns.keySet());
method = method + "_" + getInstanceMethodName(tmp);
}
String localVar = "__NOSCO_CACHED_FK_SET___"+ relatedTable + "___"
+ Misc.join("__", fk.columns.keySet());
br.write("\tprivate Query<"+ relatedTableClassName +"> "+ localVar +" = null;\n");
br.write("\tpublic Query<"+ relatedTableClassName +"> get"+ method +"Set() {\n");
br.write("\t\tif ("+ localVar +" != null) return "+ localVar + ";\n");
br.write("\t\telse return "+ relatedTableClassName +".ALL");
for (Entry<String, String> e : fk.columns.entrySet()) {
String relatedColumn = e.getKey();
String column = e.getValue();
br.write(".where("+ relatedTableClassName +"."+ getFieldName(relatedColumn) +".eq(get"+ getInstanceMethodName(column) +"()))");
}
br.write(";\n");
br.write("\t}\n\n");
}
// write save function
br.write("\tpublic boolean save() throws SQLException {\n");
br.write("\t\t return save(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean save(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (pkSet == null || pkSet.isEmpty()) {
br.write("\t\tthrow new RuntimeException(\"save() is ambiguous on objects without PKs - use insert() or update()\");\n");
} else {
br.write("\t\tint size = query.size();\n");
br.write("\t\tif (size == 0) return this.insert(ds);\n");
br.write("\t\telse if (size == 1) return this.update(ds);\n");
br.write("\t\telse throw new RuntimeException(\"more than one result was returned " +
"for a query that specified all the PKs. this is bad.\");\n");
br.write("\t\t\n");
}
br.write("\t}\n");
// write update function
br.write("\tpublic boolean update() throws SQLException {\n");
br.write("\t\t return update(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean update(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
if (pkSet == null || pkSet.size() == 0) {
for (String column : columns.keySet()) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
}
br.write(";\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_PRE!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tif (__NOSCO_UPDATED_VALUES.get("+ getFieldName(column) +".INDEX)) {\n");
br.write("\t\t\tupdates.put("+ getFieldName(column) +", "
+ convertToOriginalType(schema, table, column, columns.getString(column), getInstanceFieldName(column)) +");\n");
br.write("\t\t}\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\tint count = query.update();\n");
br.write("\t\tif (__NOSCO_CALLBACK_UPDATE_POST!=null) "
+ "try { __NOSCO_CALLBACK_UPDATE_POST.invoke(null, this, ds); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write delete function
br.write("\tpublic boolean delete() throws SQLException {\n");
br.write("\t\t return delete(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean delete(DataSource ds) throws SQLException {\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
if (pkSet == null || pkSet.size() == 0) {
for (String column : columns.keySet()) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
}
br.write(";\n");
br.write("\t\tint count = query.deleteAll();\n");
br.write("\t\treturn count==1;\n");
br.write("\t}\n");
// write insert function
br.write("\tpublic boolean insert() throws SQLException {\n");
br.write("\t\t return insert(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean insert(DataSource ds) throws SQLException {\n");
br.write("\t\tif (!dirty()) return false;\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String pk : pkSet) {
br.write(".where("+ getFieldName(pk) +".eq("+ getInstanceFieldName(pk) +"))");
}
br.write(";\n");
if (!pkSet.isEmpty()) {
br.write("\t\tif (__NOSCO_CALLBACK_INSERT_PRE!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_PRE.invoke(null, this); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
}
br.write("\t\tMap<Field<?>,Object> updates = new HashMap<Field<?>,Object>();\n");
for (String column : columns.keySet()) {
br.write("\t\tupdates.put("+ getFieldName(column) +", "
+ convertToOriginalType(schema, table, column, columns.getString(column), getInstanceFieldName(column)) +");\n");
}
br.write("\t\tquery = query.set(updates);\n");
br.write("\t\t\tquery.insert();\n");
br.write("\t\t\tif (__NOSCO_CALLBACK_INSERT_POST!=null) "
+ "try { __NOSCO_CALLBACK_INSERT_POST.invoke(null, this, ds); }"
+ "catch (IllegalAccessException e) { e.printStackTrace(); } "
+ "catch (InvocationTargetException e) { e.printStackTrace(); }\n");
br.write("\t\t\treturn true;\n");
br.write("\t}\n");
// write exists function
br.write("\tpublic boolean exists() throws SQLException {\n");
br.write("\t\t return exists(ALL.getDataSource());\n");
br.write("\t}\n");
br.write("\t@SuppressWarnings(\"rawtypes\")\n");
br.write("\tpublic boolean exists(DataSource ds) throws SQLException {\n");
br.write("\t\tQuery<"+ className +"> query = ALL.use(ds)");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write(".where("+ getFieldName(column) +".eq("+ getInstanceFieldName(column) +"))");
}
br.write(";\n");
br.write("\t\tint size = query.size();\n");
br.write("\t\treturn size > 0;\n");
br.write("\t}\n");
// write callbacks
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_INSERT_POST = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_PRE = null;\n");
br.write("\tprivate static Method __NOSCO_CALLBACK_UPDATE_POST = null;\n");
br.write("\tstatic {\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preInsert\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_INSERT_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postInsert\", "
+ className +".class, DataSource.class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_PRE = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"preUpdate\", "
+ className +".class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t\ttry {\n\t\t\t __NOSCO_CALLBACK_UPDATE_POST = Class.forName(\""+ callbackPackage
+"."+ schema +"."+ className +"CB\").getMethod(\"postUpdate\", "
+ className +".class, DataSource.class);\n\t\t} catch (Exception e) { /* ignore */ }\n");
br.write("\t}\n");
// write the alias function
br.write("\t/**\n");
br.write("\t * Returns a table alias. This is used when specifying manual joins\n");
br.write("\t * to reference later using Field.from(alias) in where() conditions.\n");
br.write("\t */\n");
br.write("\tpublic static Table.__Alias<"+ className +"> as(String alias) {\n");
br.write("\t\treturn new Table.__Alias<"+ className +">("+ className +".class, alias);\n");
br.write("\t}\n\n");
// write the hashcode function
br.write("\t@Override\n");
br.write("\tpublic int hashCode() {\n");
br.write("\t\tfinal int prime = 31;\n");
br.write("\t\tint result = 1;\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\tresult = prime * result + (("+ getInstanceFieldName(column)
+" == null) ? 0 : "+ getInstanceFieldName(column) +".hashCode());\n");
}
br.write("\t\treturn result;\n");
br.write("\t}\n\n");
// write the equals function
br.write("\t@Override\n");
br.write("\tpublic boolean equals(Object other) {\n");
br.write("\t\treturn (other == this) || ((other != null) \n");
br.write("\t\t\t&& (other instanceof "+ className +")\n");
br.write("\t\t\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\t\t&& (("+ getInstanceFieldName(column) +" == null) ? ((("
+ className +")other)."+ getInstanceFieldName(column) +" == null) : ("
+ getInstanceFieldName(column) +".equals((("+ className +")other)."
+ getInstanceFieldName(column) +")))\n");
}
br.write("\t\t);\n");
br.write("\t}\n\n");
// write the compare function
br.write("\t@Override\n");
br.write("\tpublic int compareTo("+ className +" o) {\n");
br.write("\t\tint v = 0;\n");
for (String column : pkSet == null || pkSet.size() == 0 ? columns.keySet() : pkSet) {
br.write("\t\tv = "+ getInstanceFieldName(column) +"==null ? (o."
+ getInstanceFieldName(column) +"==null ? 0 : -1) : "
+ getInstanceFieldName(column) +".compareTo(o."
+ getInstanceFieldName(column) +");\n");
br.write("\t\tif (v != 0) return v;\n");
}
br.write("\t\treturn 0;\n");
br.write("\t}\n\n");
// write the map type function
br.write("\t@Override\n");
br.write("\tpublic java.lang.Object __NOSCO_PRIVATE_mapType(java.lang.Object o) {\n");
Set<String> coveredTypes = new HashSet<String>();
for (String origType : classTypeMappings.keySet()) {
String actualType = classTypeMappings.optString(origType);
br.write("\t\tif (o instanceof "+ actualType +") return ");
br.write(typeMappingFunctions.optString(actualType +" "+ origType)
.replaceAll("[%]s", "(("+ actualType +")o)"));
br.write(";\n");
coveredTypes.add(actualType);
}
for (String actualType : this.schemaTypeMappings.values()) {
if (coveredTypes.contains(actualType)) continue;
String origType = null;
for (String column : columns.keySet()) {
String type = columns.getString(column);
if (actualType.equals(this.getFieldType(schema, table, column, type))) {
origType = this.getFieldClassType(type).getName();
break;
}
}
if (origType == null) continue;
br.write("\t\tif (o instanceof "+ actualType +") return ");
br.write(typeMappingFunctions.optString(actualType +" "+ origType)
.replaceAll("[%]s", "(("+ actualType +")o)"));
br.write(";\n");
coveredTypes.add(actualType);
}
br.write("\t\treturn o;\n");
br.write("\t}\n\n");
// end class
br.write("}\n");
br.close();
}
|
diff --git a/framework/src/play/test/Fixtures.java b/framework/src/play/test/Fixtures.java
index 04320597..ad4b54af 100644
--- a/framework/src/play/test/Fixtures.java
+++ b/framework/src/play/test/Fixtures.java
@@ -1,266 +1,266 @@
package play.test;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import org.apache.commons.io.FileUtils;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.scanner.ScannerException;
import play.Logger;
import play.Play;
import play.classloading.ApplicationClasses;
import play.db.DB;
import play.db.DBPlugin;
import play.db.jpa.FileAttachment;
import play.db.jpa.JPA;
import play.db.jpa.JPASupport;
import play.exceptions.YAMLException;
import play.vfs.VirtualFile;
public class Fixtures {
static Pattern keyPattern = Pattern.compile("([^(]+)\\(([^)]+)\\)");
public static void delete(Class... types) {
if (getForeignKeyToggleStmt(false) != null) {
DB.execute(getForeignKeyToggleStmt(false));
}
for (Class type : types) {
JPA.em().createQuery("delete from " + type.getName()).executeUpdate();
}
if (getForeignKeyToggleStmt(true) != null) {
DB.execute(getForeignKeyToggleStmt(true));
}
JPA.em().clear();
}
public static void delete(List<Class> classes) {
Class[] types = new Class[classes.size()];
for (int i = 0; i < types.length; i++) {
types[i] = classes.get(i);
}
delete(types);
}
public static void deleteAllEntities() {
List<Class> classes = new ArrayList<Class>();
for (ApplicationClasses.ApplicationClass c :
Play.classes.getAnnotatedClasses(Entity.class)) {
classes.add(c.javaClass);
}
Fixtures.delete(classes);
}
static String getForeignKeyToggleStmt(boolean enable) {
if (DBPlugin.url.startsWith("jdbc:hsqldb:")) {
return "SET REFERENTIAL_INTEGRITY " + (enable ? "TRUE" : "FALSE");
}
if (DBPlugin.url.startsWith("jdbc:mysql:")) {
return "SET foreign_key_checks = " + (enable ? "1" : "0") + ";";
}
return null;
}
static String getDeleteTableStmt(String name) {
if (DBPlugin.url.startsWith("jdbc:mysql:")) {
return "TRUNCATE TABLE " + name;
}
return "DELETE FROM " + name;
}
public static void deleteAll() {
try {
List<String> names = new ArrayList<String>();
ResultSet rs = DB.getConnection().getMetaData().getTables(null, null, null, new String[]{"TABLE"});
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
names.add(name);
}
if (getForeignKeyToggleStmt(false) != null) {
DB.execute(getForeignKeyToggleStmt(false));
}
for (String name : names) {
Logger.trace("Dropping content of table %s", name);
DB.execute(getDeleteTableStmt(name));
}
if (getForeignKeyToggleStmt(true) != null) {
DB.execute(getForeignKeyToggleStmt(true));
}
if (JPA.isEnabled()) {
JPA.em().clear();
}
} catch (Exception e) {
throw new RuntimeException("Cannot delete all table data : " + e.getMessage(), e);
}
}
public static void load(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
InputStream is = Play.classloader.getResourceAsStream(name);
if (is == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
Yaml yaml = new Yaml();
Object o = yaml.load(is);
if (o instanceof LinkedHashMap) {
LinkedHashMap objects = (LinkedHashMap) o;
Map<String, Object> idCache = new HashMap<String, Object>();
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
serialize((Map) objects.get(key), "object", params);
Class cType = Play.classloader.loadClass(type);
resolveDependencies(cType, params, idCache);
- JPASupport model = JPASupport.create(cType, "object", params);
+ JPASupport model = JPASupport.create(cType, "object", params, null);
for(Field f : model.getClass().getFields()) {
if(f.getType().isAssignableFrom(FileAttachment.class)) {
String[] value = params.get("object."+f.getName());
if(value != null && value.length > 0) {
VirtualFile vf = Play.getVirtualFile(value[0]);
if(vf != null && vf.exists()) {
FileAttachment fa = new FileAttachment();
fa.set(vf.getRealFile());
f.set(model, fa);
}
}
}
}
model.save();
JPA.em().persist(model);
while (!cType.equals(JPASupport.class)) {
idCache.put(cType.getName() + "-" + id, JPASupport.findKey(model));
cType = cType.getSuperclass();
}
// Not very good for performance but will avoid outOfMemory
JPA.em().flush();
JPA.em().clear();
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
static void serialize(Map values, String prefix, Map<String, String[]> serialized) {
for (Object key : values.keySet()) {
Object value = values.get(key);
if (value == null) {
continue;
}
if (value instanceof Map) {
serialize((Map) value, prefix + "." + key, serialized);
} else if (value instanceof Date) {
serialized.put(prefix + "." + key.toString(), new String[]{new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss").format(((Date) value))});
} else if (value instanceof List) {
List l = (List) value;
String[] r = new String[l.size()];
int i = 0;
for (Object el : l) {
r[i++] = el.toString();
}
serialized.put(prefix + "." + key.toString(), r);
} else if (value instanceof String && value.toString().matches("<<<\\s*\\{[^}]+}\\s*")) {
Matcher m = Pattern.compile("<<<\\s*\\{([^}]+)}\\s*").matcher(value.toString());
m.find();
String file = m.group(1);
VirtualFile f = Play.getVirtualFile(file);
if(f != null && f.exists()) {
serialized.put(prefix + "." + key.toString(), new String[]{f.contentAsString()});
}
} else {
serialized.put(prefix + "." + key.toString(), new String[]{value.toString()});
}
}
}
static void resolveDependencies(Class type, Map<String, String[]> serialized, Map<String, Object> idCache) {
Set<Field> fields = new HashSet<Field>();
Class clazz = type;
while (!clazz.equals(JPASupport.class)) {
Collections.addAll(fields, clazz.getDeclaredFields());
clazz = clazz.getSuperclass();
}
for (Field field : fields) {
boolean isEntity = false;
String relation = null;
if (field.isAnnotationPresent(OneToOne.class) || field.isAnnotationPresent(ManyToOne.class)) {
isEntity = true;
relation = field.getType().getName();
}
if (field.isAnnotationPresent(OneToMany.class) || field.isAnnotationPresent(ManyToMany.class)) {
Class fieldType = (Class) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
isEntity = true;
relation = fieldType.getName();
}
if (isEntity) {
String[] ids = serialized.get("object." + field.getName());
if (ids != null) {
for (int i = 0; i < ids.length; i++) {
String id = ids[i];
id = relation + "-" + id;
if (!idCache.containsKey(id)) {
throw new RuntimeException("No previous reference found for object of type " + relation + " with id " + ids[i]);
}
ids[i] = idCache.get(id).toString();
}
}
serialized.remove("object." + field.getName());
serialized.put("object." + field.getName() + "@id", ids);
}
}
}
public static void deleteAttachmentsDir() {
File atttachmentsDir = FileAttachment.getStore();
try {
if (atttachmentsDir.exists()) {
FileUtils.deleteDirectory(atttachmentsDir);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| true | true | public static void load(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
InputStream is = Play.classloader.getResourceAsStream(name);
if (is == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
Yaml yaml = new Yaml();
Object o = yaml.load(is);
if (o instanceof LinkedHashMap) {
LinkedHashMap objects = (LinkedHashMap) o;
Map<String, Object> idCache = new HashMap<String, Object>();
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
serialize((Map) objects.get(key), "object", params);
Class cType = Play.classloader.loadClass(type);
resolveDependencies(cType, params, idCache);
JPASupport model = JPASupport.create(cType, "object", params);
for(Field f : model.getClass().getFields()) {
if(f.getType().isAssignableFrom(FileAttachment.class)) {
String[] value = params.get("object."+f.getName());
if(value != null && value.length > 0) {
VirtualFile vf = Play.getVirtualFile(value[0]);
if(vf != null && vf.exists()) {
FileAttachment fa = new FileAttachment();
fa.set(vf.getRealFile());
f.set(model, fa);
}
}
}
}
model.save();
JPA.em().persist(model);
while (!cType.equals(JPASupport.class)) {
idCache.put(cType.getName() + "-" + id, JPASupport.findKey(model));
cType = cType.getSuperclass();
}
// Not very good for performance but will avoid outOfMemory
JPA.em().flush();
JPA.em().clear();
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
| public static void load(String name) {
VirtualFile yamlFile = null;
try {
for (VirtualFile vf : Play.javaPath) {
yamlFile = vf.child(name);
if (yamlFile != null && yamlFile.exists()) {
break;
}
}
InputStream is = Play.classloader.getResourceAsStream(name);
if (is == null) {
throw new RuntimeException("Cannot load fixture " + name + ", the file was not found");
}
Yaml yaml = new Yaml();
Object o = yaml.load(is);
if (o instanceof LinkedHashMap) {
LinkedHashMap objects = (LinkedHashMap) o;
Map<String, Object> idCache = new HashMap<String, Object>();
for (Object key : objects.keySet()) {
Matcher matcher = keyPattern.matcher(key.toString().trim());
if (matcher.matches()) {
String type = matcher.group(1);
String id = matcher.group(2);
if (!type.startsWith("models.")) {
type = "models." + type;
}
if (idCache.containsKey(type + "-" + id)) {
throw new RuntimeException("Cannot load fixture " + name + ", duplicate id '" + id + "' for type " + type);
}
Map<String, String[]> params = new HashMap<String, String[]>();
serialize((Map) objects.get(key), "object", params);
Class cType = Play.classloader.loadClass(type);
resolveDependencies(cType, params, idCache);
JPASupport model = JPASupport.create(cType, "object", params, null);
for(Field f : model.getClass().getFields()) {
if(f.getType().isAssignableFrom(FileAttachment.class)) {
String[] value = params.get("object."+f.getName());
if(value != null && value.length > 0) {
VirtualFile vf = Play.getVirtualFile(value[0]);
if(vf != null && vf.exists()) {
FileAttachment fa = new FileAttachment();
fa.set(vf.getRealFile());
f.set(model, fa);
}
}
}
}
model.save();
JPA.em().persist(model);
while (!cType.equals(JPASupport.class)) {
idCache.put(cType.getName() + "-" + id, JPASupport.findKey(model));
cType = cType.getSuperclass();
}
// Not very good for performance but will avoid outOfMemory
JPA.em().flush();
JPA.em().clear();
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Class " + e.getMessage() + " was not found", e);
} catch (ScannerException e) {
throw new YAMLException(e, yamlFile);
} catch (Throwable e) {
throw new RuntimeException("Cannot load fixture " + name + ": " + e.getMessage(), e);
}
}
|
diff --git a/src/main/java/com/openfeint/memcached/Memcached.java b/src/main/java/com/openfeint/memcached/Memcached.java
index f41fbc6..dbf1aa4 100644
--- a/src/main/java/com/openfeint/memcached/Memcached.java
+++ b/src/main/java/com/openfeint/memcached/Memcached.java
@@ -1,346 +1,346 @@
package com.openfeint.memcached;
import com.openfeint.memcached.error.Error;
import com.openfeint.memcached.transcoder.MarshalTranscoder;
import com.openfeint.memcached.transcoder.MarshalZlibTranscoder;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Locator;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.DefaultHashAlgorithm;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.transcoders.Transcoder;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyBoolean;
import org.jruby.RubyClass;
import org.jruby.RubyHash;
import org.jruby.RubyObject;
import org.jruby.RubyString;
import org.jruby.anno.JRubyClass;
import org.jruby.anno.JRubyMethod;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
@JRubyClass(name = "Memcached")
public class Memcached extends RubyObject {
private MemcachedClient client;
private Transcoder<IRubyObject> transcoder;
private int ttl;
private String prefixKey;
public Memcached(final Ruby ruby, RubyClass rubyClass) {
super(ruby, rubyClass);
ttl = 604800;
prefixKey = "";
}
@JRubyMethod(name = "initialize", optional = 2)
public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
Ruby ruby = context.getRuntime();
RubyHash options;
if (args.length > 1) {
options = args[1].convertToHash();
} else {
options = new RubyHash(ruby);
}
List<String> servers = new ArrayList<String>();
if (args.length > 0) {
if (args[0] instanceof RubyString) {
servers.add(args[0].toString());
} else if (args[0] instanceof RubyArray) {
servers.addAll((List<String>) args[0].convertToArray());
}
}
if (servers.isEmpty()) {
servers.add("127.0.0.1:11211");
}
return init(context, servers, options);
}
@JRubyMethod
public IRubyObject servers(ThreadContext context) {
Ruby ruby = context.getRuntime();
List<IRubyObject> addresses = new ArrayList<IRubyObject>();
for (SocketAddress address : client.getAvailableServers()) {
String addressStr = address.toString();
if (addressStr.indexOf("/") == 0) {
addressStr = addressStr.replace("/", "");
}
addresses.add(ruby.newString(addressStr));
}
return ruby.newArray(addresses);
}
@JRubyMethod(name = "add", required = 2, optional = 3)
public IRubyObject add(ThreadContext context, IRubyObject[] args) {
Ruby ruby = context.getRuntime();
String key = getFullKey(args[0].toString());
IRubyObject value = args[1];
int timeout = getTimeout(args);
try {
boolean result = client.add(key, timeout, value, transcoder).get();
if (result == false) {
throw Error.newNotStored(ruby, "not stored");
}
return context.nil;
} catch (ExecutionException ee) {
throw ruby.newRuntimeError(ee.getLocalizedMessage());
} catch (InterruptedException ie) {
throw ruby.newThreadError(ie.getLocalizedMessage());
}
}
@JRubyMethod(name = "replace", required = 2, optional = 3)
public IRubyObject replace(ThreadContext context, IRubyObject [] args) {
Ruby ruby = context.getRuntime();
String key = getFullKey(args[0].toString());
IRubyObject value = args[1];
int timeout = getTimeout(args);
try {
boolean result = client.replace(key, timeout, value, transcoder).get();
if (result == false) {
throw Error.newNotStored(ruby, "not stored");
}
return context.nil;
} catch (ExecutionException ee) {
throw ruby.newRuntimeError(ee.getLocalizedMessage());
} catch (InterruptedException ie) {
throw ruby.newThreadError(ie.getLocalizedMessage());
}
}
@JRubyMethod(name = "set", required = 2, optional = 3)
public IRubyObject set(ThreadContext context, IRubyObject[] args) {
Ruby ruby = context.getRuntime();
String key = getFullKey(args[0].toString());
IRubyObject value = args[1];
int timeout = getTimeout(args);
try {
boolean result = client.set(key, timeout, value, transcoder).get();
if (result == false) {
throw Error.newNotStored(ruby, "not stored");
}
return context.nil;
} catch (ExecutionException ee) {
throw ruby.newRuntimeError(ee.getLocalizedMessage());
} catch (InterruptedException ie) {
throw ruby.newThreadError(ie.getLocalizedMessage());
}
}
@JRubyMethod(name = "get", required = 1, optional = 1)
public IRubyObject get(ThreadContext context, IRubyObject[] args) {
Ruby ruby = context.getRuntime();
IRubyObject keys = args[0];
if (keys instanceof RubyString) {
IRubyObject value = client.get(getFullKey(keys.toString()), transcoder);
if (value == null) {
throw Error.newNotFound(ruby, "not found");
}
return value;
} else if (keys instanceof RubyArray) {
RubyHash results = RubyHash.newHash(ruby);
Map<String, IRubyObject> bulkResults = client.getBulk(getFullKeys(keys.convertToArray()), transcoder);
for (String key : (List<String>) keys.convertToArray()) {
if (bulkResults.containsKey(getFullKey(key))) {
results.put(key, bulkResults.get(getFullKey(key)));
}
}
return results;
}
return context.nil;
}
@JRubyMethod(name = "incr", required = 1, optional = 2)
public IRubyObject incr(ThreadContext context, IRubyObject[] args) {
Ruby ruby = context.getRuntime();
String key = getFullKey(args[0].toString());
int by = getIncrDecrBy(args);
int timeout = getTimeout(args);
long result = client.incr(key, by, 1, timeout);
return ruby.newFixnum(result);
}
@JRubyMethod(name = "decr", required = 1, optional = 2)
public IRubyObject decr(ThreadContext context, IRubyObject[] args) {
Ruby ruby = context.getRuntime();
String key = getFullKey(args[0].toString());
int by = getIncrDecrBy(args);
int timeout = getTimeout(args);
long result = client.decr(key, by, 0, timeout);
return ruby.newFixnum(result);
}
@JRubyMethod
public IRubyObject delete(ThreadContext context, IRubyObject key) {
Ruby ruby = context.getRuntime();
try {
boolean result = client.delete(getFullKey(key.toString())).get();
if (result == false) {
throw Error.newNotFound(ruby, "not found");
}
return context.nil;
} catch (ExecutionException ee) {
throw ruby.newRuntimeError(ee.getLocalizedMessage());
} catch (InterruptedException ie) {
throw ruby.newThreadError(ie.getLocalizedMessage());
}
}
@JRubyMethod
public IRubyObject flush(ThreadContext context) {
Ruby ruby = context.getRuntime();
try {
client.flush().get();
return context.nil;
} catch (ExecutionException ee) {
throw ruby.newRuntimeError(ee.getLocalizedMessage());
} catch (InterruptedException ie) {
throw ruby.newThreadError(ie.getLocalizedMessage());
}
}
@JRubyMethod
public IRubyObject stats(ThreadContext context) {
Ruby ruby = context.getRuntime();
RubyHash results = RubyHash.newHash(ruby);
for(Map.Entry<SocketAddress, Map<String, String>> entry : client.getStats().entrySet()) {
RubyHash serverHash = RubyHash.newHash(ruby);
for(Map.Entry<String, String> server : entry.getValue().entrySet()) {
serverHash.op_aset(context, ruby.newString(server.getKey()), ruby.newString(server.getValue()));
}
results.op_aset(context, ruby.newString(entry.getKey().toString()), serverHash);
}
return results;
}
@JRubyMethod(name = {"quit", "shutdown"})
public IRubyObject shutdown(ThreadContext context) {
client.shutdown();
return context.nil;
}
protected int getDefaultTTL() {
return ttl;
}
protected IRubyObject init(ThreadContext context, List<String> servers, RubyHash options) {
Ruby ruby = context.getRuntime();
List<InetSocketAddress> addresses = AddrUtil.getAddresses(servers);
try {
ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
String distributionValue = "ketama";
String hashValue = "fnv1_32";
RubyBoolean binaryValue = ruby.getFalse();
String transcoderValue = null;
if (!options.isEmpty()) {
RubyHash opts = options.convertToHash();
if (opts.containsKey(ruby.newSymbol("distribution"))) {
distributionValue = opts.get(ruby.newSymbol("distribution")).toString();
}
if (opts.containsKey(ruby.newSymbol("hash"))) {
hashValue = opts.get(ruby.newSymbol("hash")).toString();
}
if (opts.containsKey(ruby.newSymbol("binary_protocol"))) {
binaryValue = (RubyBoolean) opts.get(ruby.newSymbol("binary_protocol"));
}
if (opts.containsKey(ruby.newSymbol("default_ttl"))) {
ttl = Integer.parseInt(opts.get(ruby.newSymbol("default_ttl")).toString());
}
if (opts.containsKey(ruby.newSymbol("namespace"))) {
prefixKey = opts.get(ruby.newSymbol("namespace")).toString();
}
if (opts.containsKey(ruby.newSymbol("prefix_key"))) {
prefixKey = opts.get(ruby.newSymbol("prefix_key")).toString();
}
if (opts.containsKey(ruby.newSymbol("transcoder"))) {
transcoderValue = opts.get(ruby.newSymbol("transcoder")).toString();
}
}
if ("array_mod".equals(distributionValue)) {
builder.setLocatorType(Locator.ARRAY_MOD);
} else if ("ketama".equals(distributionValue) || "consistent_ketama".equals(distributionValue)) {
builder.setLocatorType(Locator.CONSISTENT);
} else {
throw Error.newNotSupport(ruby, "distribution not support");
}
if ("native".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.NATIVE_HASH);
} else if ("crc".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.CRC_HASH);
} else if ("fnv1_64".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1_64_HASH);
} else if ("fnv1a_64".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1A_64_HASH);
} else if ("fnv1_32".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1_32_HASH);
} else if ("fnv1a_32".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1A_32_HASH);
} else if ("ketama".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.KETAMA_HASH);
} else {
throw Error.newNotSupport(ruby, "hash not support");
}
if (ruby.getTrue() == binaryValue) {
builder.setProtocol(Protocol.BINARY);
}
builder.setDaemon(true);
client = new MemcachedClient(builder.build(), addresses);
if ("marshal_zlib".equals(transcoderValue)) {
- transcoder = new MarshalZlibTranscoder(ruby);
+ transcoder = new MarshalZlibTranscoder(ruby);
} else {
- transcoder = new MarshalTranscoder(ruby);
+ transcoder = new MarshalTranscoder(ruby);
}
} catch (IOException ioe) {
throw ruby.newIOErrorFromException(ioe);
}
return context.nil;
}
private int getTimeout(IRubyObject[] args) {
if (args.length > 2) {
return (int) args[2].convertToInteger().getLongValue();
}
return ttl;
}
private int getIncrDecrBy(IRubyObject[] args) {
if (args.length > 1) {
return (int) args[1].convertToInteger().getLongValue();
}
return 1;
}
private List<String> getFullKeys(List<String> keys) {
List<String> fullKeys = new ArrayList<String>();
for (String key : keys) {
fullKeys.add(getFullKey(key));
}
return fullKeys;
}
private String getFullKey(String key) {
return prefixKey + key;
}
}
| false | true | protected IRubyObject init(ThreadContext context, List<String> servers, RubyHash options) {
Ruby ruby = context.getRuntime();
List<InetSocketAddress> addresses = AddrUtil.getAddresses(servers);
try {
ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
String distributionValue = "ketama";
String hashValue = "fnv1_32";
RubyBoolean binaryValue = ruby.getFalse();
String transcoderValue = null;
if (!options.isEmpty()) {
RubyHash opts = options.convertToHash();
if (opts.containsKey(ruby.newSymbol("distribution"))) {
distributionValue = opts.get(ruby.newSymbol("distribution")).toString();
}
if (opts.containsKey(ruby.newSymbol("hash"))) {
hashValue = opts.get(ruby.newSymbol("hash")).toString();
}
if (opts.containsKey(ruby.newSymbol("binary_protocol"))) {
binaryValue = (RubyBoolean) opts.get(ruby.newSymbol("binary_protocol"));
}
if (opts.containsKey(ruby.newSymbol("default_ttl"))) {
ttl = Integer.parseInt(opts.get(ruby.newSymbol("default_ttl")).toString());
}
if (opts.containsKey(ruby.newSymbol("namespace"))) {
prefixKey = opts.get(ruby.newSymbol("namespace")).toString();
}
if (opts.containsKey(ruby.newSymbol("prefix_key"))) {
prefixKey = opts.get(ruby.newSymbol("prefix_key")).toString();
}
if (opts.containsKey(ruby.newSymbol("transcoder"))) {
transcoderValue = opts.get(ruby.newSymbol("transcoder")).toString();
}
}
if ("array_mod".equals(distributionValue)) {
builder.setLocatorType(Locator.ARRAY_MOD);
} else if ("ketama".equals(distributionValue) || "consistent_ketama".equals(distributionValue)) {
builder.setLocatorType(Locator.CONSISTENT);
} else {
throw Error.newNotSupport(ruby, "distribution not support");
}
if ("native".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.NATIVE_HASH);
} else if ("crc".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.CRC_HASH);
} else if ("fnv1_64".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1_64_HASH);
} else if ("fnv1a_64".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1A_64_HASH);
} else if ("fnv1_32".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1_32_HASH);
} else if ("fnv1a_32".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1A_32_HASH);
} else if ("ketama".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.KETAMA_HASH);
} else {
throw Error.newNotSupport(ruby, "hash not support");
}
if (ruby.getTrue() == binaryValue) {
builder.setProtocol(Protocol.BINARY);
}
builder.setDaemon(true);
client = new MemcachedClient(builder.build(), addresses);
if ("marshal_zlib".equals(transcoderValue)) {
transcoder = new MarshalZlibTranscoder(ruby);
} else {
transcoder = new MarshalTranscoder(ruby);
}
} catch (IOException ioe) {
throw ruby.newIOErrorFromException(ioe);
}
return context.nil;
}
| protected IRubyObject init(ThreadContext context, List<String> servers, RubyHash options) {
Ruby ruby = context.getRuntime();
List<InetSocketAddress> addresses = AddrUtil.getAddresses(servers);
try {
ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder();
String distributionValue = "ketama";
String hashValue = "fnv1_32";
RubyBoolean binaryValue = ruby.getFalse();
String transcoderValue = null;
if (!options.isEmpty()) {
RubyHash opts = options.convertToHash();
if (opts.containsKey(ruby.newSymbol("distribution"))) {
distributionValue = opts.get(ruby.newSymbol("distribution")).toString();
}
if (opts.containsKey(ruby.newSymbol("hash"))) {
hashValue = opts.get(ruby.newSymbol("hash")).toString();
}
if (opts.containsKey(ruby.newSymbol("binary_protocol"))) {
binaryValue = (RubyBoolean) opts.get(ruby.newSymbol("binary_protocol"));
}
if (opts.containsKey(ruby.newSymbol("default_ttl"))) {
ttl = Integer.parseInt(opts.get(ruby.newSymbol("default_ttl")).toString());
}
if (opts.containsKey(ruby.newSymbol("namespace"))) {
prefixKey = opts.get(ruby.newSymbol("namespace")).toString();
}
if (opts.containsKey(ruby.newSymbol("prefix_key"))) {
prefixKey = opts.get(ruby.newSymbol("prefix_key")).toString();
}
if (opts.containsKey(ruby.newSymbol("transcoder"))) {
transcoderValue = opts.get(ruby.newSymbol("transcoder")).toString();
}
}
if ("array_mod".equals(distributionValue)) {
builder.setLocatorType(Locator.ARRAY_MOD);
} else if ("ketama".equals(distributionValue) || "consistent_ketama".equals(distributionValue)) {
builder.setLocatorType(Locator.CONSISTENT);
} else {
throw Error.newNotSupport(ruby, "distribution not support");
}
if ("native".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.NATIVE_HASH);
} else if ("crc".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.CRC_HASH);
} else if ("fnv1_64".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1_64_HASH);
} else if ("fnv1a_64".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1A_64_HASH);
} else if ("fnv1_32".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1_32_HASH);
} else if ("fnv1a_32".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.FNV1A_32_HASH);
} else if ("ketama".equals(hashValue)) {
builder.setHashAlg(DefaultHashAlgorithm.KETAMA_HASH);
} else {
throw Error.newNotSupport(ruby, "hash not support");
}
if (ruby.getTrue() == binaryValue) {
builder.setProtocol(Protocol.BINARY);
}
builder.setDaemon(true);
client = new MemcachedClient(builder.build(), addresses);
if ("marshal_zlib".equals(transcoderValue)) {
transcoder = new MarshalZlibTranscoder(ruby);
} else {
transcoder = new MarshalTranscoder(ruby);
}
} catch (IOException ioe) {
throw ruby.newIOErrorFromException(ioe);
}
return context.nil;
}
|
diff --git a/src/com/android/calendar/event/EditEventFragment.java b/src/com/android/calendar/event/EditEventFragment.java
index 0c9424a9..ff35e5a1 100644
--- a/src/com/android/calendar/event/EditEventFragment.java
+++ b/src/com/android/calendar/event/EditEventFragment.java
@@ -1,953 +1,958 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar.event;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.AsyncQueryHandler;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Colors;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.text.TextUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.android.calendar.AsyncQueryService;
import com.android.calendar.CalendarController;
import com.android.calendar.CalendarController.EventHandler;
import com.android.calendar.CalendarController.EventInfo;
import com.android.calendar.CalendarController.EventType;
import com.android.calendar.CalendarEventModel;
import com.android.calendar.CalendarEventModel.Attendee;
import com.android.calendar.CalendarEventModel.ReminderEntry;
import com.android.calendar.DeleteEventHelper;
import com.android.calendar.R;
import com.android.calendar.Utils;
import com.android.colorpicker.ColorPickerSwatch.OnColorSelectedListener;
import com.android.colorpicker.HsvColorComparator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
public class EditEventFragment extends Fragment implements EventHandler, OnColorSelectedListener {
private static final String TAG = "EditEventActivity";
private static final int REQUEST_CODE_COLOR_PICKER = 0;
private static final String BUNDLE_KEY_MODEL = "key_model";
private static final String BUNDLE_KEY_EDIT_STATE = "key_edit_state";
private static final String BUNDLE_KEY_EVENT = "key_event";
private static final String BUNDLE_KEY_READ_ONLY = "key_read_only";
private static final String BUNDLE_KEY_EDIT_ON_LAUNCH = "key_edit_on_launch";
private static final String BUNDLE_KEY_DATE_BUTTON_CLICKED = "date_button_clicked";
private static final boolean DEBUG = false;
private static final int TOKEN_EVENT = 1;
private static final int TOKEN_ATTENDEES = 1 << 1;
private static final int TOKEN_REMINDERS = 1 << 2;
private static final int TOKEN_CALENDARS = 1 << 3;
private static final int TOKEN_COLORS = 1 << 4;
private static final int TOKEN_ALL = TOKEN_EVENT | TOKEN_ATTENDEES | TOKEN_REMINDERS
| TOKEN_CALENDARS | TOKEN_COLORS;
private static final int TOKEN_UNITIALIZED = 1 << 31;
/**
* A bitfield of TOKEN_* to keep track which query hasn't been completed
* yet. Once all queries have returned, the model can be applied to the
* view.
*/
private int mOutstandingQueries = TOKEN_UNITIALIZED;
EditEventHelper mHelper;
CalendarEventModel mModel;
CalendarEventModel mOriginalModel;
CalendarEventModel mRestoreModel;
EditEventView mView;
QueryHandler mHandler;
private AlertDialog mModifyDialog;
int mModification = Utils.MODIFY_UNINITIALIZED;
private final EventInfo mEvent;
private EventBundle mEventBundle;
private ArrayList<ReminderEntry> mReminders;
private int mEventColor;
private boolean mEventColorInitialized = false;
private Uri mUri;
private long mBegin;
private long mEnd;
private long mCalendarId = -1;
private EventColorPickerDialog mDialog;
private Activity mContext;
private final Done mOnDone = new Done();
private boolean mSaveOnDetach = true;
private boolean mIsReadOnly = false;
public boolean mShowModifyDialogOnLaunch = false;
private boolean mTimeSelectedWasStartTime;
private boolean mDateSelectedWasStartDate;
private InputMethodManager mInputMethodManager;
private final Intent mIntent;
private boolean mUseCustomActionBar;
private final View.OnClickListener mActionBarListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
onActionBarItemSelected(v.getId());
}
};
// TODO turn this into a helper function in EditEventHelper for building the
// model
private class QueryHandler extends AsyncQueryHandler {
public QueryHandler(ContentResolver cr) {
super(cr);
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// If the query didn't return a cursor for some reason return
if (cursor == null) {
return;
}
// If the Activity is finishing, then close the cursor.
// Otherwise, use the new cursor in the adapter.
final Activity activity = EditEventFragment.this.getActivity();
if (activity == null || activity.isFinishing()) {
cursor.close();
return;
}
long eventId;
switch (token) {
case TOKEN_EVENT:
if (cursor.getCount() == 0) {
// The cursor is empty. This can happen if the event
// was deleted.
cursor.close();
mOnDone.setDoneCode(Utils.DONE_EXIT);
mSaveOnDetach = false;
mOnDone.run();
return;
}
mOriginalModel = new CalendarEventModel();
EditEventHelper.setModelFromCursor(mOriginalModel, cursor);
EditEventHelper.setModelFromCursor(mModel, cursor);
cursor.close();
mOriginalModel.mUri = mUri.toString();
mModel.mUri = mUri.toString();
mModel.mOriginalStart = mBegin;
mModel.mOriginalEnd = mEnd;
mModel.mIsFirstEventInSeries = mBegin == mOriginalModel.mStart;
mModel.mStart = mBegin;
mModel.mEnd = mEnd;
if (mEventColorInitialized) {
mModel.setEventColor(mEventColor);
}
eventId = mModel.mId;
// TOKEN_ATTENDEES
if (mModel.mHasAttendeeData && eventId != -1) {
Uri attUri = Attendees.CONTENT_URI;
String[] whereArgs = {
Long.toString(eventId)
};
mHandler.startQuery(TOKEN_ATTENDEES, null, attUri,
EditEventHelper.ATTENDEES_PROJECTION,
EditEventHelper.ATTENDEES_WHERE /* selection */,
whereArgs /* selection args */, null /* sort order */);
} else {
setModelIfDone(TOKEN_ATTENDEES);
}
// TOKEN_REMINDERS
if (mModel.mHasAlarm && mReminders == null) {
Uri rUri = Reminders.CONTENT_URI;
String[] remArgs = {
Long.toString(eventId)
};
mHandler.startQuery(TOKEN_REMINDERS, null, rUri,
EditEventHelper.REMINDERS_PROJECTION,
EditEventHelper.REMINDERS_WHERE /* selection */,
remArgs /* selection args */, null /* sort order */);
} else {
- Collections.sort(mReminders);
+ if (mReminders == null) {
+ // mReminders should not be null.
+ mReminders = new ArrayList<ReminderEntry>();
+ } else {
+ Collections.sort(mReminders);
+ }
mOriginalModel.mReminders = mReminders;
mModel.mReminders =
(ArrayList<ReminderEntry>) mReminders.clone();
setModelIfDone(TOKEN_REMINDERS);
}
// TOKEN_CALENDARS
String[] selArgs = {
Long.toString(mModel.mCalendarId)
};
mHandler.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI,
EditEventHelper.CALENDARS_PROJECTION, EditEventHelper.CALENDARS_WHERE,
selArgs /* selection args */, null /* sort order */);
setModelIfDone(TOKEN_EVENT);
break;
case TOKEN_ATTENDEES:
try {
while (cursor.moveToNext()) {
String name = cursor.getString(EditEventHelper.ATTENDEES_INDEX_NAME);
String email = cursor.getString(EditEventHelper.ATTENDEES_INDEX_EMAIL);
int status = cursor.getInt(EditEventHelper.ATTENDEES_INDEX_STATUS);
int relationship = cursor
.getInt(EditEventHelper.ATTENDEES_INDEX_RELATIONSHIP);
if (relationship == Attendees.RELATIONSHIP_ORGANIZER) {
if (email != null) {
mModel.mOrganizer = email;
mModel.mIsOrganizer = mModel.mOwnerAccount
.equalsIgnoreCase(email);
mOriginalModel.mOrganizer = email;
mOriginalModel.mIsOrganizer = mOriginalModel.mOwnerAccount
.equalsIgnoreCase(email);
}
if (TextUtils.isEmpty(name)) {
mModel.mOrganizerDisplayName = mModel.mOrganizer;
mOriginalModel.mOrganizerDisplayName =
mOriginalModel.mOrganizer;
} else {
mModel.mOrganizerDisplayName = name;
mOriginalModel.mOrganizerDisplayName = name;
}
}
if (email != null) {
if (mModel.mOwnerAccount != null &&
mModel.mOwnerAccount.equalsIgnoreCase(email)) {
int attendeeId =
cursor.getInt(EditEventHelper.ATTENDEES_INDEX_ID);
mModel.mOwnerAttendeeId = attendeeId;
mModel.mSelfAttendeeStatus = status;
mOriginalModel.mOwnerAttendeeId = attendeeId;
mOriginalModel.mSelfAttendeeStatus = status;
continue;
}
}
Attendee attendee = new Attendee(name, email);
attendee.mStatus = status;
mModel.addAttendee(attendee);
mOriginalModel.addAttendee(attendee);
}
} finally {
cursor.close();
}
setModelIfDone(TOKEN_ATTENDEES);
break;
case TOKEN_REMINDERS:
try {
// Add all reminders to the models
while (cursor.moveToNext()) {
int minutes = cursor.getInt(EditEventHelper.REMINDERS_INDEX_MINUTES);
int method = cursor.getInt(EditEventHelper.REMINDERS_INDEX_METHOD);
ReminderEntry re = ReminderEntry.valueOf(minutes, method);
mModel.mReminders.add(re);
mOriginalModel.mReminders.add(re);
}
// Sort appropriately for display
Collections.sort(mModel.mReminders);
Collections.sort(mOriginalModel.mReminders);
} finally {
cursor.close();
}
setModelIfDone(TOKEN_REMINDERS);
break;
case TOKEN_CALENDARS:
try {
if (mModel.mId == -1) {
// Populate Calendar spinner only if no event id is set.
MatrixCursor matrixCursor = Utils.matrixCursorFromCursor(cursor);
if (DEBUG) {
Log.d(TAG, "onQueryComplete: setting cursor with "
+ matrixCursor.getCount() + " calendars");
}
mView.setCalendarsCursor(matrixCursor, isAdded() && isResumed(),
mCalendarId);
} else {
// Populate model for an existing event
EditEventHelper.setModelFromCalendarCursor(mModel, cursor);
EditEventHelper.setModelFromCalendarCursor(mOriginalModel, cursor);
}
startQuery(TOKEN_COLORS, null, Colors.CONTENT_URI,
EditEventHelper.COLORS_PROJECTION,
Colors.COLOR_TYPE + "=" + Colors.TYPE_EVENT, null, null);
} finally {
cursor.close();
}
setModelIfDone(TOKEN_CALENDARS);
break;
case TOKEN_COLORS:
if (cursor.moveToFirst()) {
EventColorCache cache = new EventColorCache();
do
{
int colorKey = cursor.getInt(EditEventHelper.COLORS_INDEX_COLOR_KEY);
int rawColor = cursor.getInt(EditEventHelper.COLORS_INDEX_COLOR);
int displayColor = Utils.getDisplayColorFromColor(rawColor);
String accountName = cursor
.getString(EditEventHelper.COLORS_INDEX_ACCOUNT_NAME);
String accountType = cursor
.getString(EditEventHelper.COLORS_INDEX_ACCOUNT_TYPE);
cache.insertColor(accountName, accountType,
displayColor, colorKey);
} while (cursor.moveToNext());
cache.sortPalettes(new HsvColorComparator());
mModel.mEventColorCache = cache;
mView.mColorPickerNewEvent.setOnClickListener(mOnColorPickerClicked);
mView.mColorPickerExistingEvent.setOnClickListener(mOnColorPickerClicked);
}
if (cursor != null) {
cursor.close();
}
mView.setColorPickerButtonStates(mModel.getCalendarEventColors());
setModelIfDone(TOKEN_COLORS);
break;
default:
cursor.close();
break;
}
}
}
private View.OnClickListener mOnColorPickerClicked = new View.OnClickListener() {
@Override
public void onClick(View v) {
int[] colors = mModel.getCalendarEventColors();
if (mDialog == null) {
mDialog = EventColorPickerDialog.newInstance(colors, mModel.getEventColor(),
mModel.getCalendarColor(), mView.mIsMultipane);
mDialog.setTargetFragment(EditEventFragment.this, REQUEST_CODE_COLOR_PICKER);
} else {
mDialog.setCalendarColor(mModel.getCalendarColor());
mDialog.setColors(colors, mModel.getEventColor());
}
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.executePendingTransactions();
if (!mDialog.isAdded()) {
mDialog.show(fragmentManager, TAG);
}
}
};
private void setModelIfDone(int queryType) {
synchronized (this) {
mOutstandingQueries &= ~queryType;
if (mOutstandingQueries == 0) {
if (mRestoreModel != null) {
mModel = mRestoreModel;
}
if (mShowModifyDialogOnLaunch && mModification == Utils.MODIFY_UNINITIALIZED) {
if (!TextUtils.isEmpty(mModel.mRrule)) {
displayEditWhichDialog();
} else {
mModification = Utils.MODIFY_ALL;
}
}
mView.setModel(mModel);
mView.setModification(mModification);
}
}
}
public EditEventFragment() {
this(null, null, false, -1, false, null);
}
public EditEventFragment(EventInfo event, ArrayList<ReminderEntry> reminders,
boolean eventColorInitialized, int eventColor, boolean readOnly, Intent intent) {
mEvent = event;
mIsReadOnly = readOnly;
mIntent = intent;
mReminders = reminders;
mEventColorInitialized = eventColorInitialized;
if (eventColorInitialized) {
mEventColor = eventColor;
}
setHasOptionsMenu(true);
}
private void startQuery() {
mUri = null;
mBegin = -1;
mEnd = -1;
if (mEvent != null) {
if (mEvent.id != -1) {
mModel.mId = mEvent.id;
mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEvent.id);
} else {
// New event. All day?
mModel.mAllDay = mEvent.extraLong == CalendarController.EXTRA_CREATE_ALL_DAY;
}
if (mEvent.startTime != null) {
mBegin = mEvent.startTime.toMillis(true);
}
if (mEvent.endTime != null) {
mEnd = mEvent.endTime.toMillis(true);
}
if (mEvent.calendarId != -1) {
mCalendarId = mEvent.calendarId;
}
} else if (mEventBundle != null) {
if (mEventBundle.id != -1) {
mModel.mId = mEventBundle.id;
mUri = ContentUris.withAppendedId(Events.CONTENT_URI, mEventBundle.id);
}
mBegin = mEventBundle.start;
mEnd = mEventBundle.end;
}
if (mReminders != null) {
mModel.mReminders = mReminders;
}
if (mEventColorInitialized) {
mModel.setEventColor(mEventColor);
}
if (mBegin <= 0) {
// use a default value instead
mBegin = mHelper.constructDefaultStartTime(System.currentTimeMillis());
}
if (mEnd < mBegin) {
// use a default value instead
mEnd = mHelper.constructDefaultEndTime(mBegin);
}
// Kick off the query for the event
boolean newEvent = mUri == null;
if (!newEvent) {
mModel.mCalendarAccessLevel = Calendars.CAL_ACCESS_NONE;
mOutstandingQueries = TOKEN_ALL;
if (DEBUG) {
Log.d(TAG, "startQuery: uri for event is " + mUri.toString());
}
mHandler.startQuery(TOKEN_EVENT, null, mUri, EditEventHelper.EVENT_PROJECTION,
null /* selection */, null /* selection args */, null /* sort order */);
} else {
mOutstandingQueries = TOKEN_CALENDARS;
if (DEBUG) {
Log.d(TAG, "startQuery: Editing a new event.");
}
mModel.mOriginalStart = mBegin;
mModel.mOriginalEnd = mEnd;
mModel.mStart = mBegin;
mModel.mEnd = mEnd;
mModel.mCalendarId = mCalendarId;
mModel.mSelfAttendeeStatus = Attendees.ATTENDEE_STATUS_ACCEPTED;
// Start a query in the background to read the list of calendars
mHandler.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI,
EditEventHelper.CALENDARS_PROJECTION,
EditEventHelper.CALENDARS_WHERE_WRITEABLE_VISIBLE, null /* selection args */,
null /* sort order */);
mModification = Utils.MODIFY_ALL;
mView.setModification(mModification);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
mHelper = new EditEventHelper(activity, null);
mHandler = new QueryHandler(activity.getContentResolver());
mModel = new CalendarEventModel(activity, mIntent);
mInputMethodManager = (InputMethodManager)
activity.getSystemService(Context.INPUT_METHOD_SERVICE);
mUseCustomActionBar = !Utils.getConfigBool(mContext, R.bool.multiple_pane_config);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// mContext.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
View view;
if (mIsReadOnly) {
view = inflater.inflate(R.layout.edit_event_single_column, null);
} else {
view = inflater.inflate(R.layout.edit_event, null);
}
mView = new EditEventView(mContext, view, mOnDone, mTimeSelectedWasStartTime,
mDateSelectedWasStartDate);
startQuery();
if (mUseCustomActionBar) {
View actionBarButtons = inflater.inflate(R.layout.edit_event_custom_actionbar,
new LinearLayout(mContext), false);
View cancelActionView = actionBarButtons.findViewById(R.id.action_cancel);
cancelActionView.setOnClickListener(mActionBarListener);
View doneActionView = actionBarButtons.findViewById(R.id.action_done);
doneActionView.setOnClickListener(mActionBarListener);
mContext.getActionBar().setCustomView(actionBarButtons);
}
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mUseCustomActionBar) {
mContext.getActionBar().setCustomView(null);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(BUNDLE_KEY_MODEL)) {
mRestoreModel = (CalendarEventModel) savedInstanceState.getSerializable(
BUNDLE_KEY_MODEL);
}
if (savedInstanceState.containsKey(BUNDLE_KEY_EDIT_STATE)) {
mModification = savedInstanceState.getInt(BUNDLE_KEY_EDIT_STATE);
}
if (savedInstanceState.containsKey(BUNDLE_KEY_EDIT_ON_LAUNCH)) {
mShowModifyDialogOnLaunch = savedInstanceState
.getBoolean(BUNDLE_KEY_EDIT_ON_LAUNCH);
}
if (savedInstanceState.containsKey(BUNDLE_KEY_EVENT)) {
mEventBundle = (EventBundle) savedInstanceState.getSerializable(BUNDLE_KEY_EVENT);
}
if (savedInstanceState.containsKey(BUNDLE_KEY_READ_ONLY)) {
mIsReadOnly = savedInstanceState.getBoolean(BUNDLE_KEY_READ_ONLY);
}
if (savedInstanceState.containsKey("EditEventView_timebuttonclicked")) {
mTimeSelectedWasStartTime = savedInstanceState.getBoolean(
"EditEventView_timebuttonclicked");
}
if (savedInstanceState.containsKey(BUNDLE_KEY_DATE_BUTTON_CLICKED)) {
mDateSelectedWasStartDate = savedInstanceState.getBoolean(
BUNDLE_KEY_DATE_BUTTON_CLICKED);
}
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (!mUseCustomActionBar) {
inflater.inflate(R.menu.edit_event_title_bar, menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return onActionBarItemSelected(item.getItemId());
}
/**
* Handles menu item selections, whether they come from our custom action bar buttons or from
* the standard menu items. Depends on the menu item ids matching the custom action bar button
* ids.
*
* @param itemId the button or menu item id
* @return whether the event was handled here
*/
private boolean onActionBarItemSelected(int itemId) {
if (itemId == R.id.action_done) {
if (EditEventHelper.canModifyEvent(mModel) || EditEventHelper.canRespond(mModel)) {
if (mView != null && mView.prepareForSave()) {
if (mModification == Utils.MODIFY_UNINITIALIZED) {
mModification = Utils.MODIFY_ALL;
}
mOnDone.setDoneCode(Utils.DONE_SAVE | Utils.DONE_EXIT);
mOnDone.run();
} else {
mOnDone.setDoneCode(Utils.DONE_REVERT);
mOnDone.run();
}
} else if (EditEventHelper.canAddReminders(mModel) && mModel.mId != -1
&& mOriginalModel != null && mView.prepareForSave()) {
saveReminders();
mOnDone.setDoneCode(Utils.DONE_EXIT);
mOnDone.run();
} else {
mOnDone.setDoneCode(Utils.DONE_REVERT);
mOnDone.run();
}
} else if (itemId == R.id.action_cancel) {
mOnDone.setDoneCode(Utils.DONE_REVERT);
mOnDone.run();
}
return true;
}
private void saveReminders() {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3);
boolean changed = EditEventHelper.saveReminders(ops, mModel.mId, mModel.mReminders,
mOriginalModel.mReminders, false /* no force save */);
if (!changed) {
return;
}
AsyncQueryService service = new AsyncQueryService(getActivity());
service.startBatch(0, null, Calendars.CONTENT_URI.getAuthority(), ops, 0);
// Update the "hasAlarm" field for the event
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mModel.mId);
int len = mModel.mReminders.size();
boolean hasAlarm = len > 0;
if (hasAlarm != mOriginalModel.mHasAlarm) {
ContentValues values = new ContentValues();
values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0);
service.startUpdate(0, null, uri, values, null, null, 0);
}
Toast.makeText(mContext, R.string.saving_event, Toast.LENGTH_SHORT).show();
}
protected void displayEditWhichDialog() {
if (mModification == Utils.MODIFY_UNINITIALIZED) {
final boolean notSynced = TextUtils.isEmpty(mModel.mSyncId);
boolean isFirstEventInSeries = mModel.mIsFirstEventInSeries;
int itemIndex = 0;
CharSequence[] items;
if (notSynced) {
// If this event has not been synced, then don't allow deleting
// or changing a single instance.
if (isFirstEventInSeries) {
// Still display the option so the user knows all events are
// changing
items = new CharSequence[1];
} else {
items = new CharSequence[2];
}
} else {
if (isFirstEventInSeries) {
items = new CharSequence[2];
} else {
items = new CharSequence[3];
}
items[itemIndex++] = mContext.getText(R.string.modify_event);
}
items[itemIndex++] = mContext.getText(R.string.modify_all);
// Do one more check to make sure this remains at the end of the list
if (!isFirstEventInSeries) {
items[itemIndex++] = mContext.getText(R.string.modify_all_following);
}
// Display the modification dialog.
if (mModifyDialog != null) {
mModifyDialog.dismiss();
mModifyDialog = null;
}
mModifyDialog = new AlertDialog.Builder(mContext).setTitle(R.string.edit_event_label)
.setItems(items, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
// Update this if we start allowing exceptions
// to unsynced events in the app
mModification = notSynced ? Utils.MODIFY_ALL
: Utils.MODIFY_SELECTED;
if (mModification == Utils.MODIFY_SELECTED) {
mModel.mOriginalSyncId = notSynced ? null : mModel.mSyncId;
mModel.mOriginalId = mModel.mId;
}
} else if (which == 1) {
mModification = notSynced ? Utils.MODIFY_ALL_FOLLOWING
: Utils.MODIFY_ALL;
} else if (which == 2) {
mModification = Utils.MODIFY_ALL_FOLLOWING;
}
mView.setModification(mModification);
}
}).show();
mModifyDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Activity a = EditEventFragment.this.getActivity();
if (a != null) {
a.finish();
}
}
});
}
}
class Done implements EditEventHelper.EditDoneRunnable {
private int mCode = -1;
@Override
public void setDoneCode(int code) {
mCode = code;
}
@Override
public void run() {
// We only want this to get called once, either because the user
// pressed back/home or one of the buttons on screen
mSaveOnDetach = false;
if (mModification == Utils.MODIFY_UNINITIALIZED) {
// If this is uninitialized the user hit back, the only
// changeable item is response to default to all events.
mModification = Utils.MODIFY_ALL;
}
if ((mCode & Utils.DONE_SAVE) != 0 && mModel != null
&& (EditEventHelper.canRespond(mModel)
|| EditEventHelper.canModifyEvent(mModel))
&& mView.prepareForSave()
&& !isEmptyNewEvent()
&& mModel.normalizeReminders()
&& mHelper.saveEvent(mModel, mOriginalModel, mModification)) {
int stringResource;
if (!mModel.mAttendeesList.isEmpty()) {
if (mModel.mUri != null) {
stringResource = R.string.saving_event_with_guest;
} else {
stringResource = R.string.creating_event_with_guest;
}
} else {
if (mModel.mUri != null) {
stringResource = R.string.saving_event;
} else {
stringResource = R.string.creating_event;
}
}
Toast.makeText(mContext, stringResource, Toast.LENGTH_SHORT).show();
} else if ((mCode & Utils.DONE_SAVE) != 0 && mModel != null && isEmptyNewEvent()) {
Toast.makeText(mContext, R.string.empty_event, Toast.LENGTH_SHORT).show();
}
if ((mCode & Utils.DONE_DELETE) != 0 && mOriginalModel != null
&& EditEventHelper.canModifyCalendar(mOriginalModel)) {
long begin = mModel.mStart;
long end = mModel.mEnd;
int which = -1;
switch (mModification) {
case Utils.MODIFY_SELECTED:
which = DeleteEventHelper.DELETE_SELECTED;
break;
case Utils.MODIFY_ALL_FOLLOWING:
which = DeleteEventHelper.DELETE_ALL_FOLLOWING;
break;
case Utils.MODIFY_ALL:
which = DeleteEventHelper.DELETE_ALL;
break;
}
DeleteEventHelper deleteHelper = new DeleteEventHelper(
mContext, mContext, !mIsReadOnly /* exitWhenDone */);
deleteHelper.delete(begin, end, mOriginalModel, which);
}
if ((mCode & Utils.DONE_EXIT) != 0) {
// This will exit the edit event screen, should be called
// when we want to return to the main calendar views
if ((mCode & Utils.DONE_SAVE) != 0) {
if (mContext != null) {
long start = mModel.mStart;
long end = mModel.mEnd;
if (mModel.mAllDay) {
// For allday events we want to go to the day in the
// user's current tz
String tz = Utils.getTimeZone(mContext, null);
Time t = new Time(Time.TIMEZONE_UTC);
t.set(start);
t.timezone = tz;
start = t.toMillis(true);
t.timezone = Time.TIMEZONE_UTC;
t.set(end);
t.timezone = tz;
end = t.toMillis(true);
}
CalendarController.getInstance(mContext).launchViewEvent(-1, start, end,
Attendees.ATTENDEE_STATUS_NONE);
}
}
Activity a = EditEventFragment.this.getActivity();
if (a != null) {
a.finish();
}
}
// Hide a software keyboard so that user won't see it even after this Fragment's
// disappearing.
final View focusedView = mContext.getCurrentFocus();
if (focusedView != null) {
mInputMethodManager.hideSoftInputFromWindow(focusedView.getWindowToken(), 0);
focusedView.clearFocus();
}
}
}
boolean isEmptyNewEvent() {
if (mOriginalModel != null) {
// Not new
return false;
}
if (mModel.mOriginalStart != mModel.mStart || mModel.mOriginalEnd != mModel.mEnd) {
return false;
}
if (!mModel.mAttendeesList.isEmpty()) {
return false;
}
return mModel.isEmpty();
}
@Override
public void onPause() {
Activity act = getActivity();
if (mSaveOnDetach && act != null && !mIsReadOnly && !act.isChangingConfigurations()
&& mView.prepareForSave()) {
mOnDone.setDoneCode(Utils.DONE_SAVE);
mOnDone.run();
}
super.onPause();
}
@Override
public void onDestroy() {
if (mView != null) {
mView.setModel(null);
}
if (mModifyDialog != null) {
mModifyDialog.dismiss();
mModifyDialog = null;
}
super.onDestroy();
}
@Override
public void eventsChanged() {
// TODO Requery to see if event has changed
}
@Override
public void onSaveInstanceState(Bundle outState) {
mView.prepareForSave();
outState.putSerializable(BUNDLE_KEY_MODEL, mModel);
outState.putInt(BUNDLE_KEY_EDIT_STATE, mModification);
if (mEventBundle == null && mEvent != null) {
mEventBundle = new EventBundle();
mEventBundle.id = mEvent.id;
if (mEvent.startTime != null) {
mEventBundle.start = mEvent.startTime.toMillis(true);
}
if (mEvent.endTime != null) {
mEventBundle.end = mEvent.startTime.toMillis(true);
}
}
outState.putBoolean(BUNDLE_KEY_EDIT_ON_LAUNCH, mShowModifyDialogOnLaunch);
outState.putSerializable(BUNDLE_KEY_EVENT, mEventBundle);
outState.putBoolean(BUNDLE_KEY_READ_ONLY, mIsReadOnly);
outState.putBoolean("EditEventView_timebuttonclicked", mView.mTimeSelectedWasStartTime);
outState.putBoolean(BUNDLE_KEY_DATE_BUTTON_CLICKED, mView.mDateSelectedWasStartDate);
}
@Override
public long getSupportedEventTypes() {
return EventType.USER_HOME;
}
@Override
public void handleEvent(EventInfo event) {
// It's currently unclear if we want to save the event or not when home
// is pressed. When creating a new event we shouldn't save since we
// can't get the id of the new event easily.
if ((false && event.eventType == EventType.USER_HOME) || (event.eventType == EventType.GO_TO
&& mSaveOnDetach)) {
if (mView != null && mView.prepareForSave()) {
mOnDone.setDoneCode(Utils.DONE_SAVE);
mOnDone.run();
}
}
}
private static class EventBundle implements Serializable {
private static final long serialVersionUID = 1L;
long id = -1;
long start = -1;
long end = -1;
}
@Override
public void onColorSelected(int color) {
if (!mModel.isEventColorInitialized() || mModel.getEventColor() != color) {
mModel.setEventColor(color);
mView.updateHeadlineColor(mModel, color);
}
}
}
| true | true | protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// If the query didn't return a cursor for some reason return
if (cursor == null) {
return;
}
// If the Activity is finishing, then close the cursor.
// Otherwise, use the new cursor in the adapter.
final Activity activity = EditEventFragment.this.getActivity();
if (activity == null || activity.isFinishing()) {
cursor.close();
return;
}
long eventId;
switch (token) {
case TOKEN_EVENT:
if (cursor.getCount() == 0) {
// The cursor is empty. This can happen if the event
// was deleted.
cursor.close();
mOnDone.setDoneCode(Utils.DONE_EXIT);
mSaveOnDetach = false;
mOnDone.run();
return;
}
mOriginalModel = new CalendarEventModel();
EditEventHelper.setModelFromCursor(mOriginalModel, cursor);
EditEventHelper.setModelFromCursor(mModel, cursor);
cursor.close();
mOriginalModel.mUri = mUri.toString();
mModel.mUri = mUri.toString();
mModel.mOriginalStart = mBegin;
mModel.mOriginalEnd = mEnd;
mModel.mIsFirstEventInSeries = mBegin == mOriginalModel.mStart;
mModel.mStart = mBegin;
mModel.mEnd = mEnd;
if (mEventColorInitialized) {
mModel.setEventColor(mEventColor);
}
eventId = mModel.mId;
// TOKEN_ATTENDEES
if (mModel.mHasAttendeeData && eventId != -1) {
Uri attUri = Attendees.CONTENT_URI;
String[] whereArgs = {
Long.toString(eventId)
};
mHandler.startQuery(TOKEN_ATTENDEES, null, attUri,
EditEventHelper.ATTENDEES_PROJECTION,
EditEventHelper.ATTENDEES_WHERE /* selection */,
whereArgs /* selection args */, null /* sort order */);
} else {
setModelIfDone(TOKEN_ATTENDEES);
}
// TOKEN_REMINDERS
if (mModel.mHasAlarm && mReminders == null) {
Uri rUri = Reminders.CONTENT_URI;
String[] remArgs = {
Long.toString(eventId)
};
mHandler.startQuery(TOKEN_REMINDERS, null, rUri,
EditEventHelper.REMINDERS_PROJECTION,
EditEventHelper.REMINDERS_WHERE /* selection */,
remArgs /* selection args */, null /* sort order */);
} else {
Collections.sort(mReminders);
mOriginalModel.mReminders = mReminders;
mModel.mReminders =
(ArrayList<ReminderEntry>) mReminders.clone();
setModelIfDone(TOKEN_REMINDERS);
}
// TOKEN_CALENDARS
String[] selArgs = {
Long.toString(mModel.mCalendarId)
};
mHandler.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI,
EditEventHelper.CALENDARS_PROJECTION, EditEventHelper.CALENDARS_WHERE,
selArgs /* selection args */, null /* sort order */);
setModelIfDone(TOKEN_EVENT);
break;
case TOKEN_ATTENDEES:
try {
while (cursor.moveToNext()) {
String name = cursor.getString(EditEventHelper.ATTENDEES_INDEX_NAME);
String email = cursor.getString(EditEventHelper.ATTENDEES_INDEX_EMAIL);
int status = cursor.getInt(EditEventHelper.ATTENDEES_INDEX_STATUS);
int relationship = cursor
.getInt(EditEventHelper.ATTENDEES_INDEX_RELATIONSHIP);
if (relationship == Attendees.RELATIONSHIP_ORGANIZER) {
if (email != null) {
mModel.mOrganizer = email;
mModel.mIsOrganizer = mModel.mOwnerAccount
.equalsIgnoreCase(email);
mOriginalModel.mOrganizer = email;
mOriginalModel.mIsOrganizer = mOriginalModel.mOwnerAccount
.equalsIgnoreCase(email);
}
if (TextUtils.isEmpty(name)) {
mModel.mOrganizerDisplayName = mModel.mOrganizer;
mOriginalModel.mOrganizerDisplayName =
mOriginalModel.mOrganizer;
} else {
mModel.mOrganizerDisplayName = name;
mOriginalModel.mOrganizerDisplayName = name;
}
}
if (email != null) {
if (mModel.mOwnerAccount != null &&
mModel.mOwnerAccount.equalsIgnoreCase(email)) {
int attendeeId =
cursor.getInt(EditEventHelper.ATTENDEES_INDEX_ID);
mModel.mOwnerAttendeeId = attendeeId;
mModel.mSelfAttendeeStatus = status;
mOriginalModel.mOwnerAttendeeId = attendeeId;
mOriginalModel.mSelfAttendeeStatus = status;
continue;
}
}
Attendee attendee = new Attendee(name, email);
attendee.mStatus = status;
mModel.addAttendee(attendee);
mOriginalModel.addAttendee(attendee);
}
} finally {
cursor.close();
}
setModelIfDone(TOKEN_ATTENDEES);
break;
case TOKEN_REMINDERS:
try {
// Add all reminders to the models
while (cursor.moveToNext()) {
int minutes = cursor.getInt(EditEventHelper.REMINDERS_INDEX_MINUTES);
int method = cursor.getInt(EditEventHelper.REMINDERS_INDEX_METHOD);
ReminderEntry re = ReminderEntry.valueOf(minutes, method);
mModel.mReminders.add(re);
mOriginalModel.mReminders.add(re);
}
// Sort appropriately for display
Collections.sort(mModel.mReminders);
Collections.sort(mOriginalModel.mReminders);
} finally {
cursor.close();
}
setModelIfDone(TOKEN_REMINDERS);
break;
case TOKEN_CALENDARS:
try {
if (mModel.mId == -1) {
// Populate Calendar spinner only if no event id is set.
MatrixCursor matrixCursor = Utils.matrixCursorFromCursor(cursor);
if (DEBUG) {
Log.d(TAG, "onQueryComplete: setting cursor with "
+ matrixCursor.getCount() + " calendars");
}
mView.setCalendarsCursor(matrixCursor, isAdded() && isResumed(),
mCalendarId);
} else {
// Populate model for an existing event
EditEventHelper.setModelFromCalendarCursor(mModel, cursor);
EditEventHelper.setModelFromCalendarCursor(mOriginalModel, cursor);
}
startQuery(TOKEN_COLORS, null, Colors.CONTENT_URI,
EditEventHelper.COLORS_PROJECTION,
Colors.COLOR_TYPE + "=" + Colors.TYPE_EVENT, null, null);
} finally {
cursor.close();
}
setModelIfDone(TOKEN_CALENDARS);
break;
case TOKEN_COLORS:
if (cursor.moveToFirst()) {
EventColorCache cache = new EventColorCache();
do
{
int colorKey = cursor.getInt(EditEventHelper.COLORS_INDEX_COLOR_KEY);
int rawColor = cursor.getInt(EditEventHelper.COLORS_INDEX_COLOR);
int displayColor = Utils.getDisplayColorFromColor(rawColor);
String accountName = cursor
.getString(EditEventHelper.COLORS_INDEX_ACCOUNT_NAME);
String accountType = cursor
.getString(EditEventHelper.COLORS_INDEX_ACCOUNT_TYPE);
cache.insertColor(accountName, accountType,
displayColor, colorKey);
} while (cursor.moveToNext());
cache.sortPalettes(new HsvColorComparator());
mModel.mEventColorCache = cache;
mView.mColorPickerNewEvent.setOnClickListener(mOnColorPickerClicked);
mView.mColorPickerExistingEvent.setOnClickListener(mOnColorPickerClicked);
}
if (cursor != null) {
cursor.close();
}
mView.setColorPickerButtonStates(mModel.getCalendarEventColors());
setModelIfDone(TOKEN_COLORS);
break;
default:
cursor.close();
break;
}
}
| protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
// If the query didn't return a cursor for some reason return
if (cursor == null) {
return;
}
// If the Activity is finishing, then close the cursor.
// Otherwise, use the new cursor in the adapter.
final Activity activity = EditEventFragment.this.getActivity();
if (activity == null || activity.isFinishing()) {
cursor.close();
return;
}
long eventId;
switch (token) {
case TOKEN_EVENT:
if (cursor.getCount() == 0) {
// The cursor is empty. This can happen if the event
// was deleted.
cursor.close();
mOnDone.setDoneCode(Utils.DONE_EXIT);
mSaveOnDetach = false;
mOnDone.run();
return;
}
mOriginalModel = new CalendarEventModel();
EditEventHelper.setModelFromCursor(mOriginalModel, cursor);
EditEventHelper.setModelFromCursor(mModel, cursor);
cursor.close();
mOriginalModel.mUri = mUri.toString();
mModel.mUri = mUri.toString();
mModel.mOriginalStart = mBegin;
mModel.mOriginalEnd = mEnd;
mModel.mIsFirstEventInSeries = mBegin == mOriginalModel.mStart;
mModel.mStart = mBegin;
mModel.mEnd = mEnd;
if (mEventColorInitialized) {
mModel.setEventColor(mEventColor);
}
eventId = mModel.mId;
// TOKEN_ATTENDEES
if (mModel.mHasAttendeeData && eventId != -1) {
Uri attUri = Attendees.CONTENT_URI;
String[] whereArgs = {
Long.toString(eventId)
};
mHandler.startQuery(TOKEN_ATTENDEES, null, attUri,
EditEventHelper.ATTENDEES_PROJECTION,
EditEventHelper.ATTENDEES_WHERE /* selection */,
whereArgs /* selection args */, null /* sort order */);
} else {
setModelIfDone(TOKEN_ATTENDEES);
}
// TOKEN_REMINDERS
if (mModel.mHasAlarm && mReminders == null) {
Uri rUri = Reminders.CONTENT_URI;
String[] remArgs = {
Long.toString(eventId)
};
mHandler.startQuery(TOKEN_REMINDERS, null, rUri,
EditEventHelper.REMINDERS_PROJECTION,
EditEventHelper.REMINDERS_WHERE /* selection */,
remArgs /* selection args */, null /* sort order */);
} else {
if (mReminders == null) {
// mReminders should not be null.
mReminders = new ArrayList<ReminderEntry>();
} else {
Collections.sort(mReminders);
}
mOriginalModel.mReminders = mReminders;
mModel.mReminders =
(ArrayList<ReminderEntry>) mReminders.clone();
setModelIfDone(TOKEN_REMINDERS);
}
// TOKEN_CALENDARS
String[] selArgs = {
Long.toString(mModel.mCalendarId)
};
mHandler.startQuery(TOKEN_CALENDARS, null, Calendars.CONTENT_URI,
EditEventHelper.CALENDARS_PROJECTION, EditEventHelper.CALENDARS_WHERE,
selArgs /* selection args */, null /* sort order */);
setModelIfDone(TOKEN_EVENT);
break;
case TOKEN_ATTENDEES:
try {
while (cursor.moveToNext()) {
String name = cursor.getString(EditEventHelper.ATTENDEES_INDEX_NAME);
String email = cursor.getString(EditEventHelper.ATTENDEES_INDEX_EMAIL);
int status = cursor.getInt(EditEventHelper.ATTENDEES_INDEX_STATUS);
int relationship = cursor
.getInt(EditEventHelper.ATTENDEES_INDEX_RELATIONSHIP);
if (relationship == Attendees.RELATIONSHIP_ORGANIZER) {
if (email != null) {
mModel.mOrganizer = email;
mModel.mIsOrganizer = mModel.mOwnerAccount
.equalsIgnoreCase(email);
mOriginalModel.mOrganizer = email;
mOriginalModel.mIsOrganizer = mOriginalModel.mOwnerAccount
.equalsIgnoreCase(email);
}
if (TextUtils.isEmpty(name)) {
mModel.mOrganizerDisplayName = mModel.mOrganizer;
mOriginalModel.mOrganizerDisplayName =
mOriginalModel.mOrganizer;
} else {
mModel.mOrganizerDisplayName = name;
mOriginalModel.mOrganizerDisplayName = name;
}
}
if (email != null) {
if (mModel.mOwnerAccount != null &&
mModel.mOwnerAccount.equalsIgnoreCase(email)) {
int attendeeId =
cursor.getInt(EditEventHelper.ATTENDEES_INDEX_ID);
mModel.mOwnerAttendeeId = attendeeId;
mModel.mSelfAttendeeStatus = status;
mOriginalModel.mOwnerAttendeeId = attendeeId;
mOriginalModel.mSelfAttendeeStatus = status;
continue;
}
}
Attendee attendee = new Attendee(name, email);
attendee.mStatus = status;
mModel.addAttendee(attendee);
mOriginalModel.addAttendee(attendee);
}
} finally {
cursor.close();
}
setModelIfDone(TOKEN_ATTENDEES);
break;
case TOKEN_REMINDERS:
try {
// Add all reminders to the models
while (cursor.moveToNext()) {
int minutes = cursor.getInt(EditEventHelper.REMINDERS_INDEX_MINUTES);
int method = cursor.getInt(EditEventHelper.REMINDERS_INDEX_METHOD);
ReminderEntry re = ReminderEntry.valueOf(minutes, method);
mModel.mReminders.add(re);
mOriginalModel.mReminders.add(re);
}
// Sort appropriately for display
Collections.sort(mModel.mReminders);
Collections.sort(mOriginalModel.mReminders);
} finally {
cursor.close();
}
setModelIfDone(TOKEN_REMINDERS);
break;
case TOKEN_CALENDARS:
try {
if (mModel.mId == -1) {
// Populate Calendar spinner only if no event id is set.
MatrixCursor matrixCursor = Utils.matrixCursorFromCursor(cursor);
if (DEBUG) {
Log.d(TAG, "onQueryComplete: setting cursor with "
+ matrixCursor.getCount() + " calendars");
}
mView.setCalendarsCursor(matrixCursor, isAdded() && isResumed(),
mCalendarId);
} else {
// Populate model for an existing event
EditEventHelper.setModelFromCalendarCursor(mModel, cursor);
EditEventHelper.setModelFromCalendarCursor(mOriginalModel, cursor);
}
startQuery(TOKEN_COLORS, null, Colors.CONTENT_URI,
EditEventHelper.COLORS_PROJECTION,
Colors.COLOR_TYPE + "=" + Colors.TYPE_EVENT, null, null);
} finally {
cursor.close();
}
setModelIfDone(TOKEN_CALENDARS);
break;
case TOKEN_COLORS:
if (cursor.moveToFirst()) {
EventColorCache cache = new EventColorCache();
do
{
int colorKey = cursor.getInt(EditEventHelper.COLORS_INDEX_COLOR_KEY);
int rawColor = cursor.getInt(EditEventHelper.COLORS_INDEX_COLOR);
int displayColor = Utils.getDisplayColorFromColor(rawColor);
String accountName = cursor
.getString(EditEventHelper.COLORS_INDEX_ACCOUNT_NAME);
String accountType = cursor
.getString(EditEventHelper.COLORS_INDEX_ACCOUNT_TYPE);
cache.insertColor(accountName, accountType,
displayColor, colorKey);
} while (cursor.moveToNext());
cache.sortPalettes(new HsvColorComparator());
mModel.mEventColorCache = cache;
mView.mColorPickerNewEvent.setOnClickListener(mOnColorPickerClicked);
mView.mColorPickerExistingEvent.setOnClickListener(mOnColorPickerClicked);
}
if (cursor != null) {
cursor.close();
}
mView.setColorPickerButtonStates(mModel.getCalendarEventColors());
setModelIfDone(TOKEN_COLORS);
break;
default:
cursor.close();
break;
}
}
|
diff --git a/src/org/protege/editor/core/ui/error/ErrorLogPanel.java b/src/org/protege/editor/core/ui/error/ErrorLogPanel.java
index 4678407..bfefba9 100644
--- a/src/org/protege/editor/core/ui/error/ErrorLogPanel.java
+++ b/src/org/protege/editor/core/ui/error/ErrorLogPanel.java
@@ -1,94 +1,96 @@
package org.protege.editor.core.ui.error;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
/**
* Author: Matthew Horridge<br>
* The University Of Manchester<br>
* Bio-Health Informatics Group<br>
* Date: 28-Feb-2007<br><br>
*/
public class ErrorLogPanel extends JPanel {
private ErrorLog errorLog;
private JTextArea textArea;
private SendErrorReportHandler errorReportHandler;
public ErrorLogPanel(ErrorLog errorLog, SendErrorReportHandler handler) {
this.errorLog = errorLog;
this.errorReportHandler = handler;
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
JPanel contentPane = new JPanel(new BorderLayout(7, 7));
contentPane.add(new JScrollPane(textArea));
if (handler != null) {
JPanel buttonPanel = new JPanel(new BorderLayout());
- buttonPanel.add(new JButton(new AbstractAction("Send bug report") {
+ buttonPanel.add(new JButton(new AbstractAction("Clear Errors") {
public void actionPerformed(ActionEvent e) {
if (handleSendErrorReport()) {
ErrorLogPanel.this.errorLog.clear();
+ fillLog();
+ repaint();
}
}
}), BorderLayout.WEST);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
}
add(contentPane, BorderLayout.CENTER);
fillLog();
}
private boolean handleSendErrorReport() {
return errorReportHandler != null && errorReportHandler.sendErrorReport(errorLog);
}
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
public void setVisible(boolean b) {
fillLog();
Component parent = getParent();
if (parent != null) {
int w = (parent.getWidth() - getWidth()) / 2;
int h = (parent.getHeight() - getHeight()) / 2;
setLocation(w, h);
}
super.setVisible(b);
}
public void fillLog() {
textArea.setText("");
for (ErrorLog.ErrorLogEntry entry : errorLog.getEntries()) {
textArea.append(entry.toString());
textArea.append(
"---------------------------------------------------------------------------------------------------\n\n");
}
}
protected ErrorLog getErrorLog(){
return errorLog;
}
/**
* Shows a local error dialog for displaying one exception
* @param throwable The exception to be displayed
*/
public static void showErrorDialog(Throwable throwable) {
ErrorLog errorLog = new ErrorLog();
errorLog.logError(throwable);
ErrorLogPanel panel = new ErrorLogPanel(errorLog, null);
JOptionPane.showMessageDialog(null, panel, "Error", JOptionPane.ERROR_MESSAGE);
}
}
| false | true | public ErrorLogPanel(ErrorLog errorLog, SendErrorReportHandler handler) {
this.errorLog = errorLog;
this.errorReportHandler = handler;
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
JPanel contentPane = new JPanel(new BorderLayout(7, 7));
contentPane.add(new JScrollPane(textArea));
if (handler != null) {
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.add(new JButton(new AbstractAction("Send bug report") {
public void actionPerformed(ActionEvent e) {
if (handleSendErrorReport()) {
ErrorLogPanel.this.errorLog.clear();
}
}
}), BorderLayout.WEST);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
}
add(contentPane, BorderLayout.CENTER);
fillLog();
}
| public ErrorLogPanel(ErrorLog errorLog, SendErrorReportHandler handler) {
this.errorLog = errorLog;
this.errorReportHandler = handler;
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
JPanel contentPane = new JPanel(new BorderLayout(7, 7));
contentPane.add(new JScrollPane(textArea));
if (handler != null) {
JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.add(new JButton(new AbstractAction("Clear Errors") {
public void actionPerformed(ActionEvent e) {
if (handleSendErrorReport()) {
ErrorLogPanel.this.errorLog.clear();
fillLog();
repaint();
}
}
}), BorderLayout.WEST);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
}
add(contentPane, BorderLayout.CENTER);
fillLog();
}
|
diff --git a/graylog2-server/src/main/java/org/graylog2/dashboards/widgets/FieldChartWidget.java b/graylog2-server/src/main/java/org/graylog2/dashboards/widgets/FieldChartWidget.java
index 91da2c461..c2d9da821 100644
--- a/graylog2-server/src/main/java/org/graylog2/dashboards/widgets/FieldChartWidget.java
+++ b/graylog2-server/src/main/java/org/graylog2/dashboards/widgets/FieldChartWidget.java
@@ -1,122 +1,122 @@
/**
* Copyright 2013 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.dashboards.widgets;
import org.graylog2.Core;
import org.graylog2.indexer.IndexHelper;
import org.graylog2.indexer.Indexer;
import org.graylog2.indexer.results.HistogramResult;
import org.graylog2.indexer.searches.Searches;
import org.graylog2.indexer.searches.timeranges.TimeRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @author Lennart Koopmann <[email protected]>
*/
public class FieldChartWidget extends DashboardWidget {
private static final Logger LOG = LoggerFactory.getLogger(FieldChartWidget.class);
private final Core core;
private final String query;
private final TimeRange timeRange;
private final String streamId;
private final Map<String, Object> config;
public FieldChartWidget(Core core, String id, String description, int cacheTime, Map<String, Object> config, String query, TimeRange timeRange, String creatorUserId) throws InvalidWidgetConfigurationException {
super(core, Type.FIELD_CHART, id, description, cacheTime, config, creatorUserId);
if (!checkConfig(config)) {
throw new InvalidWidgetConfigurationException("Missing or invalid widget configuration. Provided config was: " + config.toString());
}
if (query == null || query.trim().isEmpty()) {
this.query = "*";
} else {
this.query = query;
}
this.timeRange = timeRange;
this.core = core;
this.config = config;
if (config.containsKey("stream_id")) {
this.streamId = (String) config.get("stream_id");
} else {
this.streamId = null;
}
}
@Override
public Map<String, Object> getPersistedConfig() {
return new HashMap<String, Object>() {{
put("query", query);
put("timerange", timeRange.getPersistedConfig());
put("stream_id", streamId);
put("field", config.get("field"));
put("valuetype", config.get("valuetype"));
put("renderer", config.get("renderer"));
put("interpolation", config.get("interpolation"));
put("interval", config.get("interval"));
}};
}
@Override
protected ComputationResult compute() {
String filter = null;
if (streamId != null && !streamId.isEmpty()) {
- filter = "streams:" + filter;
+ filter = "streams:" + streamId;
}
try {
HistogramResult histogramResult = core.getIndexer().searches().fieldHistogram(
query,
(String) config.get("field"),
Indexer.DateHistogramInterval.valueOf(((String) config.get("interval")).toUpperCase()),
filter,
timeRange
);
return new ComputationResult(histogramResult.getResults(), histogramResult.took().millis());
} catch (Searches.FieldTypeException e) {
String msg = "Could not calculate [" + this.getClass().getCanonicalName() + "] widget <" + getId() + ">. Not a numeric field? The field was [" + config.get("field") + "]";
LOG.error(msg, e);
throw new RuntimeException(msg);
} catch (IndexHelper.InvalidRangeFormatException e) {
String msg = "Could not calculate [" + this.getClass().getCanonicalName() + "] widget <" + getId() + ">. Invalid time range.";
LOG.error(msg, e);
throw new RuntimeException(msg);
}
}
private boolean checkConfig(Map<String, Object> config) {
return config.containsKey("field") && config.containsKey("valuetype")
&& config.containsKey("renderer")
&& config.containsKey("interpolation")
&& config.containsKey("interval");
}
}
| true | true | protected ComputationResult compute() {
String filter = null;
if (streamId != null && !streamId.isEmpty()) {
filter = "streams:" + filter;
}
try {
HistogramResult histogramResult = core.getIndexer().searches().fieldHistogram(
query,
(String) config.get("field"),
Indexer.DateHistogramInterval.valueOf(((String) config.get("interval")).toUpperCase()),
filter,
timeRange
);
return new ComputationResult(histogramResult.getResults(), histogramResult.took().millis());
} catch (Searches.FieldTypeException e) {
String msg = "Could not calculate [" + this.getClass().getCanonicalName() + "] widget <" + getId() + ">. Not a numeric field? The field was [" + config.get("field") + "]";
LOG.error(msg, e);
throw new RuntimeException(msg);
} catch (IndexHelper.InvalidRangeFormatException e) {
String msg = "Could not calculate [" + this.getClass().getCanonicalName() + "] widget <" + getId() + ">. Invalid time range.";
LOG.error(msg, e);
throw new RuntimeException(msg);
}
}
| protected ComputationResult compute() {
String filter = null;
if (streamId != null && !streamId.isEmpty()) {
filter = "streams:" + streamId;
}
try {
HistogramResult histogramResult = core.getIndexer().searches().fieldHistogram(
query,
(String) config.get("field"),
Indexer.DateHistogramInterval.valueOf(((String) config.get("interval")).toUpperCase()),
filter,
timeRange
);
return new ComputationResult(histogramResult.getResults(), histogramResult.took().millis());
} catch (Searches.FieldTypeException e) {
String msg = "Could not calculate [" + this.getClass().getCanonicalName() + "] widget <" + getId() + ">. Not a numeric field? The field was [" + config.get("field") + "]";
LOG.error(msg, e);
throw new RuntimeException(msg);
} catch (IndexHelper.InvalidRangeFormatException e) {
String msg = "Could not calculate [" + this.getClass().getCanonicalName() + "] widget <" + getId() + ">. Invalid time range.";
LOG.error(msg, e);
throw new RuntimeException(msg);
}
}
|
diff --git a/src/main/java/de/weltraumschaf/neuron/shell/Parser.java b/src/main/java/de/weltraumschaf/neuron/shell/Parser.java
index 03b6d85..6c5452d 100644
--- a/src/main/java/de/weltraumschaf/neuron/shell/Parser.java
+++ b/src/main/java/de/weltraumschaf/neuron/shell/Parser.java
@@ -1,160 +1,160 @@
/*
* LICENSE
*
* "THE BEER-WARE LICENSE" (Revision 43):
* "Sven Strittmatter" <[email protected]> wrote this file.
* As long as you retain this notice you can do whatever you want with
* this stuff. If we meet some day, and you think this stuff is worth it,
* you can buy me a non alcohol-free beer in return.
*
* Copyright (C) 2012 "Sven Strittmatter" <[email protected]>
*/
package de.weltraumschaf.neuron.shell;
import com.google.common.collect.Lists;
import de.weltraumschaf.neuron.shell.ShellCommand.MainType;
import de.weltraumschaf.neuron.shell.ShellCommand.SubType;
import java.util.List;
/**
* Parses input line from interactive shell.
*
* @author Sven Strittmatter <[email protected]>
*/
class Parser {
/**
* Tokenize the input line.
*/
private final Scanner scanner;
/**
* Dedicated constructor.
*
* @param scanner to scann input line
*/
public Parser(final Scanner scanner) {
super();
this.scanner = scanner;
}
/**
* Parses given input line.
*
* @param input line to parse
* @return recognized shell command
* @throws SyntaxException if, the parsed line has syntax errors
*/
ShellCommand parse(final String input) throws SyntaxException {
final List<Token> tokens = scanner.scan(input);
final Token commandtoken = tokens.get(0);
if (TokenType.LITERAL != commandtoken.getType()) {
throw new SyntaxException("Command expected as first word!");
}
if (! ShellCommand.isCommand(commandtoken)) {
- throw new SyntaxException("Command expected as first word!");
+ throw new SyntaxException(String.format("Unrecognized token '%s'!", commandtoken.getValue()));
}
final MainType command = ShellCommand.determineCommand(commandtoken);
SubType subCommand = SubType.NONE;
int argumentBegin = 1;
if (tokens.size() > 1) {
final Token secondToken = tokens.get(1);
if (secondToken.getType() == TokenType.LITERAL && ShellCommand.isSubCommand(secondToken)) {
++argumentBegin;
subCommand = ShellCommand.determineSubCommand(secondToken);
}
}
List<Token> arguments;
if (tokens.size() > argumentBegin) {
arguments = tokens.subList(argumentBegin, tokens.size());
} else {
arguments = Lists.newArrayList();
}
final ShellCommand cmd = new ShellCommand(command, subCommand, arguments);
verifyCommand(cmd);
return cmd;
}
/**
* Verifies parsed command of consistency.
*
* Consistency checks are:
* - correct sub command type
* - correct number of arguments
*
* @param cmd command to verify
* @throws SyntaxException if, verification has failed
*/
private void verifyCommand(final ShellCommand cmd) throws SyntaxException {
switch (cmd.getCommand()) {
case EXIT:
case HELP:
case RESET:
if (cmd.getSubCommand() != SubType.NONE) {
throw new SyntaxException(String.format("Command %s does not support subcommands!",
cmd.getCommand()));
}
if (! cmd.getArguments().isEmpty()) {
throw new SyntaxException(String.format("Command %s does not support arguments!",
cmd.getCommand()));
}
break;
case NODE:
verifyNodeCommand(cmd);
break;
default:
// Nothing to do here.
}
}
/**
* Verify commands of main command type {@link MainType#NODE}.
*
* Consistency checks are:
* - correct number of arguments for sub command type
*
* @param cmd command to verify
* @throws SyntaxException if, wrong number of arguments or unsupported subcommand was parsed
*/
private void verifyNodeCommand(final ShellCommand cmd) throws SyntaxException {
final int argumentCount = cmd.getArguments().size();
switch (cmd.getSubCommand()) {
case LIST:
if (argumentCount != 0) {
throw new SyntaxException(String.format("Command %s does support no arguments!", cmd.getCommand()));
}
break;
case ADD:
if (argumentCount != 0 && argumentCount != 1) {
throw new SyntaxException(String.format("Command %s one or zero arguments!", cmd.getCommand()));
}
break;
case DEL:
case INFO:
if (argumentCount != 1) {
throw new SyntaxException(String.format("Command %s require one argument!", cmd.getCommand()));
}
break;
case CONNECT:
if (argumentCount != 2) {
throw new SyntaxException(String.format("Command %s require two argument!", cmd.getCommand()));
}
break;
default:
throw new SyntaxException(String.format("Command %s does not support subcommand %s!",
cmd.getCommand(),
cmd.getSubCommand()));
}
}
}
| true | true | ShellCommand parse(final String input) throws SyntaxException {
final List<Token> tokens = scanner.scan(input);
final Token commandtoken = tokens.get(0);
if (TokenType.LITERAL != commandtoken.getType()) {
throw new SyntaxException("Command expected as first word!");
}
if (! ShellCommand.isCommand(commandtoken)) {
throw new SyntaxException("Command expected as first word!");
}
final MainType command = ShellCommand.determineCommand(commandtoken);
SubType subCommand = SubType.NONE;
int argumentBegin = 1;
if (tokens.size() > 1) {
final Token secondToken = tokens.get(1);
if (secondToken.getType() == TokenType.LITERAL && ShellCommand.isSubCommand(secondToken)) {
++argumentBegin;
subCommand = ShellCommand.determineSubCommand(secondToken);
}
}
List<Token> arguments;
if (tokens.size() > argumentBegin) {
arguments = tokens.subList(argumentBegin, tokens.size());
} else {
arguments = Lists.newArrayList();
}
final ShellCommand cmd = new ShellCommand(command, subCommand, arguments);
verifyCommand(cmd);
return cmd;
}
| ShellCommand parse(final String input) throws SyntaxException {
final List<Token> tokens = scanner.scan(input);
final Token commandtoken = tokens.get(0);
if (TokenType.LITERAL != commandtoken.getType()) {
throw new SyntaxException("Command expected as first word!");
}
if (! ShellCommand.isCommand(commandtoken)) {
throw new SyntaxException(String.format("Unrecognized token '%s'!", commandtoken.getValue()));
}
final MainType command = ShellCommand.determineCommand(commandtoken);
SubType subCommand = SubType.NONE;
int argumentBegin = 1;
if (tokens.size() > 1) {
final Token secondToken = tokens.get(1);
if (secondToken.getType() == TokenType.LITERAL && ShellCommand.isSubCommand(secondToken)) {
++argumentBegin;
subCommand = ShellCommand.determineSubCommand(secondToken);
}
}
List<Token> arguments;
if (tokens.size() > argumentBegin) {
arguments = tokens.subList(argumentBegin, tokens.size());
} else {
arguments = Lists.newArrayList();
}
final ShellCommand cmd = new ShellCommand(command, subCommand, arguments);
verifyCommand(cmd);
return cmd;
}
|
diff --git a/src/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java b/src/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java
index 678b3b714..9ca8a6262 100644
--- a/src/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java
+++ b/src/Examples/org/objectweb/proactive/examples/userguide/distributedprimes/PrimeManager.java
@@ -1,96 +1,96 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or any later version.
*
* This 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.examples.userguide.distributedprimes;
import java.io.Serializable;
import java.util.Vector;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
public class PrimeManager implements Serializable {
private Vector<PrimeWorker> workers = new Vector<PrimeWorker>();
public PrimeManager() {
} ////empty no-arg constructor needed by ProActive
//1. send number to all workers and if all of them say the
//number is prime then it is
//2. send the number randomly to one worker if prime
//3. try the next number
public void startComputation(long maxNumber) {
boolean prime;//true after checking if a number is prime
int futureIndex;//updated future index;
long primeCheck = 2; //start number
long primeCounter = 1;
int k = 0;
Vector<BooleanWrapper> answers = new Vector<BooleanWrapper>();
while (primeCounter < maxNumber) {
//1. send request to all workers
for (PrimeWorker worker : workers)
// Non blocking (asynchronous method call)
// adds the futures to the vector
answers.add(worker.isPrime(primeCheck));
//2. wait for all the answers, or an answer that says NO
prime = true;
while (!answers.isEmpty() && prime) {//repeat until a worker says no or all the workers responded (i.e. vector is emptied)
// Will block until a new response is available
futureIndex = PAFuture.waitForAny(answers); //blocks until a future is actualized
prime = answers.get(futureIndex).booleanValue(); //check the answer
answers.remove(futureIndex); //remove the actualized future
}// end while check for primes
if (prime) { //print if prime
sendPrime(primeCheck);
System.out.print(primeCheck + ", ");
primeCounter++;//prime number found
//flush print buffer every 20 numbers
if (k % 20 == 0)
System.out.println("\n");
k++;
}
//flush the answers vector
answers.clear();
- primeCheck++;
+ primeCheck++;
}//end while number loop
}// end StartComputation
//add a workers to the worker Vector
public void addWorker(PrimeWorker worker) {
workers.add(worker);
}
//sends the prime numbers found to one worker randomly
public void sendPrime(long number) {
int destination = (int) Math.round(Math.random() * (workers.size() - 1));
workers.get(destination).addPrime(new Long(number));
}
}
| true | true | public void startComputation(long maxNumber) {
boolean prime;//true after checking if a number is prime
int futureIndex;//updated future index;
long primeCheck = 2; //start number
long primeCounter = 1;
int k = 0;
Vector<BooleanWrapper> answers = new Vector<BooleanWrapper>();
while (primeCounter < maxNumber) {
//1. send request to all workers
for (PrimeWorker worker : workers)
// Non blocking (asynchronous method call)
// adds the futures to the vector
answers.add(worker.isPrime(primeCheck));
//2. wait for all the answers, or an answer that says NO
prime = true;
while (!answers.isEmpty() && prime) {//repeat until a worker says no or all the workers responded (i.e. vector is emptied)
// Will block until a new response is available
futureIndex = PAFuture.waitForAny(answers); //blocks until a future is actualized
prime = answers.get(futureIndex).booleanValue(); //check the answer
answers.remove(futureIndex); //remove the actualized future
}// end while check for primes
if (prime) { //print if prime
sendPrime(primeCheck);
System.out.print(primeCheck + ", ");
primeCounter++;//prime number found
//flush print buffer every 20 numbers
if (k % 20 == 0)
System.out.println("\n");
k++;
}
//flush the answers vector
answers.clear();
primeCheck++;
}//end while number loop
}// end StartComputation
| public void startComputation(long maxNumber) {
boolean prime;//true after checking if a number is prime
int futureIndex;//updated future index;
long primeCheck = 2; //start number
long primeCounter = 1;
int k = 0;
Vector<BooleanWrapper> answers = new Vector<BooleanWrapper>();
while (primeCounter < maxNumber) {
//1. send request to all workers
for (PrimeWorker worker : workers)
// Non blocking (asynchronous method call)
// adds the futures to the vector
answers.add(worker.isPrime(primeCheck));
//2. wait for all the answers, or an answer that says NO
prime = true;
while (!answers.isEmpty() && prime) {//repeat until a worker says no or all the workers responded (i.e. vector is emptied)
// Will block until a new response is available
futureIndex = PAFuture.waitForAny(answers); //blocks until a future is actualized
prime = answers.get(futureIndex).booleanValue(); //check the answer
answers.remove(futureIndex); //remove the actualized future
}// end while check for primes
if (prime) { //print if prime
sendPrime(primeCheck);
System.out.print(primeCheck + ", ");
primeCounter++;//prime number found
//flush print buffer every 20 numbers
if (k % 20 == 0)
System.out.println("\n");
k++;
}
//flush the answers vector
answers.clear();
primeCheck++;
}//end while number loop
}// end StartComputation
|
diff --git a/src/java/org/apache/ftpserver/ftplet/FtpletEnum.java b/src/java/org/apache/ftpserver/ftplet/FtpletEnum.java
index e3b495fb..dbd0498e 100644
--- a/src/java/org/apache/ftpserver/ftplet/FtpletEnum.java
+++ b/src/java/org/apache/ftpserver/ftplet/FtpletEnum.java
@@ -1,88 +1,88 @@
// $Id$
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ftpserver.ftplet;
/**
* This class encapsulates the return values of the ftplet methods.
*
* RET_DEFAULT < RET_NO_FTPLET < RET_SKIP < RET_DISCONNECT
*
* @author <a href="mailto:[email protected]">Rana Bhattacharyya</a>
*/
public
final class FtpletEnum {
/**
* This return value indicates that the next ftplet method will
* be called. If no other ftplet is available, the ftpserver will
* process the request.
*/
public static final FtpletEnum RET_DEFAULT = new FtpletEnum(0);
/**
* This return value indicates that the other ftplet methods will
* not be called but the ftpserver will continue processing this
* request.
*/
public static final FtpletEnum RET_NO_FTPLET = new FtpletEnum(1);
/**
* It indicates that the ftpserver will skip everything. No further
* processing (both ftplet and server) will be done for this request.
*/
public static final FtpletEnum RET_SKIP = new FtpletEnum(2);
/**
* It indicates that the server will skip and disconnect the client.
* No other request from the same client will be served.
*/
public static final FtpletEnum RET_DISCONNECT = new FtpletEnum(3);
private int m_type;
/**
* Private constructor - set the type
*/
private FtpletEnum(int type) {
m_type = type;
}
/**
* Equality check
*/
public boolean equals(Object obj) {
- if(obj instanceof Ftplet) {
+ if(obj instanceof FtpletEnum) {
return m_type == ((FtpletEnum)obj).m_type;
}
return false;
}
/**
* String representation
*/
public String toString() {
return String.valueOf(m_type);
}
}
| true | true | public boolean equals(Object obj) {
if(obj instanceof Ftplet) {
return m_type == ((FtpletEnum)obj).m_type;
}
return false;
}
| public boolean equals(Object obj) {
if(obj instanceof FtpletEnum) {
return m_type == ((FtpletEnum)obj).m_type;
}
return false;
}
|
diff --git a/EdSensor/src/uk/ac/dotrural/quality/edsensor/parser/LineParser.java b/EdSensor/src/uk/ac/dotrural/quality/edsensor/parser/LineParser.java
index 673c649..29bb254 100755
--- a/EdSensor/src/uk/ac/dotrural/quality/edsensor/parser/LineParser.java
+++ b/EdSensor/src/uk/ac/dotrural/quality/edsensor/parser/LineParser.java
@@ -1,76 +1,80 @@
package uk.ac.dotrural.quality.edsensor.parser;
import java.util.ArrayList;
import uk.ac.dotrural.quality.edsensor.observation.*;
public class LineParser {
private int count = 0;
public ArrayList<Observation> parse(String line)
{
ArrayList<Observation> observations = new ArrayList<Observation>();
String[] obs = line.split(",");
try
{
//String date = obs[18];
String date = obs[0];
String time = obs[1];
//String timeM = obs[2];
//String avgX = (obs[3].equals("") ? "0" : obs[3]);
String avgX = (obs[5].equals("") ? "0" : obs[5]);
//String avgY = (obs[8].equals("") ? "0" : obs[6]);
String avgY = (obs[8].equals("") ? "0" : obs[8]);
//String avgZ = (obs[9].equals("") ? "0" : obs[9]);
String avgZ = (obs[11].equals("") ? "0" : obs[11]);
//String hum = (obs[10].equals("") ? "0" : obs[10]);
String hum = (obs[12].equals("") ? "0" : obs[12]);
//String temp = (obs[11].equals("") ? "0" : obs[11]);
String temp = (obs[13].equals("") ? "0" : obs[13]);
//String lat = (obs[12].equals("") ? "0" : obs[12]);
String lat = (obs[14].equals("") ? "0" : obs[14]);
//String lon = (obs[13].equals("") ? "0" : obs[13]);
String lon = (obs[15].equals("") ? "0" : obs[15]);
//String alt = (obs[14].equals("") ? "0" : obs[14]);
String alt = (obs[16].equals("") ? "0" : obs[16]);
//String speed = (obs[15].equals("") ? "0" : obs[15]);
String speed = (obs[17].equals("") ? "0" : obs[17]);
//String sat = (obs[16].equals("") ? "0" : obs[16]);
String sat = (obs[18].equals("") ? "0" : obs[18]);
//String prec = (obs[17].equals("") ? "0" : obs[17]);
String prec = (obs[19].equals("") ? "0" : obs[19]);
String event = (obs[20].equals("") ? "0" : obs[20]);
//String event = "Coastal walk";
time = date.trim() + " " + time.trim();
//String time = date.trim();
- if(!time.equals(" ") && (count == 2) && !time.contains("VALUE"))
+ if(count == 4)
{
- observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "X", time, avgX, event));
- observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Y", time, avgY, event));
- observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Z", time, avgZ, event));
- observations.add(new Observation(ObservationType.HUMIDITY, time, hum, event));
- observations.add(new Observation(ObservationType.TEMPERATURE, time, temp, event));
- observations.add(new GPSObservation(ObservationType.GPS, time, lat, lon, sat, prec, event));
- observations.add(new AltitudeObservation(ObservationType.ALTITUDE, time, alt, sat, event));
- observations.add(new SpeedObservation(ObservationType.SPEED, time, speed, event));
+ if(!time.equals(" ") && !time.contains("#VALUE"))
+ {
+ observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "X", time, avgX, event));
+ observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Y", time, avgY, event));
+ observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Z", time, avgZ, event));
+ observations.add(new Observation(ObservationType.HUMIDITY, time, hum, event));
+ observations.add(new Observation(ObservationType.TEMPERATURE, time, temp, event));
+ observations.add(new GPSObservation(ObservationType.GPS, time, lat, lon, sat, prec, event));
+ observations.add(new AltitudeObservation(ObservationType.ALTITUDE, time, alt, sat, event));
+ observations.add(new SpeedObservation(ObservationType.SPEED, time, speed, event));
+ }
count = 0;
- } else
+ }
+ else
count++;
}
catch(ArrayIndexOutOfBoundsException aex)
{
}
catch(Exception ex)
{
//System.out.println("LineParser Exception: " + ex.toString());
ex.printStackTrace();
}
return observations;
}
}
| false | true | public ArrayList<Observation> parse(String line)
{
ArrayList<Observation> observations = new ArrayList<Observation>();
String[] obs = line.split(",");
try
{
//String date = obs[18];
String date = obs[0];
String time = obs[1];
//String timeM = obs[2];
//String avgX = (obs[3].equals("") ? "0" : obs[3]);
String avgX = (obs[5].equals("") ? "0" : obs[5]);
//String avgY = (obs[8].equals("") ? "0" : obs[6]);
String avgY = (obs[8].equals("") ? "0" : obs[8]);
//String avgZ = (obs[9].equals("") ? "0" : obs[9]);
String avgZ = (obs[11].equals("") ? "0" : obs[11]);
//String hum = (obs[10].equals("") ? "0" : obs[10]);
String hum = (obs[12].equals("") ? "0" : obs[12]);
//String temp = (obs[11].equals("") ? "0" : obs[11]);
String temp = (obs[13].equals("") ? "0" : obs[13]);
//String lat = (obs[12].equals("") ? "0" : obs[12]);
String lat = (obs[14].equals("") ? "0" : obs[14]);
//String lon = (obs[13].equals("") ? "0" : obs[13]);
String lon = (obs[15].equals("") ? "0" : obs[15]);
//String alt = (obs[14].equals("") ? "0" : obs[14]);
String alt = (obs[16].equals("") ? "0" : obs[16]);
//String speed = (obs[15].equals("") ? "0" : obs[15]);
String speed = (obs[17].equals("") ? "0" : obs[17]);
//String sat = (obs[16].equals("") ? "0" : obs[16]);
String sat = (obs[18].equals("") ? "0" : obs[18]);
//String prec = (obs[17].equals("") ? "0" : obs[17]);
String prec = (obs[19].equals("") ? "0" : obs[19]);
String event = (obs[20].equals("") ? "0" : obs[20]);
//String event = "Coastal walk";
time = date.trim() + " " + time.trim();
//String time = date.trim();
if(!time.equals(" ") && (count == 2) && !time.contains("VALUE"))
{
observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "X", time, avgX, event));
observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Y", time, avgY, event));
observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Z", time, avgZ, event));
observations.add(new Observation(ObservationType.HUMIDITY, time, hum, event));
observations.add(new Observation(ObservationType.TEMPERATURE, time, temp, event));
observations.add(new GPSObservation(ObservationType.GPS, time, lat, lon, sat, prec, event));
observations.add(new AltitudeObservation(ObservationType.ALTITUDE, time, alt, sat, event));
observations.add(new SpeedObservation(ObservationType.SPEED, time, speed, event));
count = 0;
} else
count++;
}
catch(ArrayIndexOutOfBoundsException aex)
{
}
catch(Exception ex)
{
//System.out.println("LineParser Exception: " + ex.toString());
ex.printStackTrace();
}
return observations;
}
| public ArrayList<Observation> parse(String line)
{
ArrayList<Observation> observations = new ArrayList<Observation>();
String[] obs = line.split(",");
try
{
//String date = obs[18];
String date = obs[0];
String time = obs[1];
//String timeM = obs[2];
//String avgX = (obs[3].equals("") ? "0" : obs[3]);
String avgX = (obs[5].equals("") ? "0" : obs[5]);
//String avgY = (obs[8].equals("") ? "0" : obs[6]);
String avgY = (obs[8].equals("") ? "0" : obs[8]);
//String avgZ = (obs[9].equals("") ? "0" : obs[9]);
String avgZ = (obs[11].equals("") ? "0" : obs[11]);
//String hum = (obs[10].equals("") ? "0" : obs[10]);
String hum = (obs[12].equals("") ? "0" : obs[12]);
//String temp = (obs[11].equals("") ? "0" : obs[11]);
String temp = (obs[13].equals("") ? "0" : obs[13]);
//String lat = (obs[12].equals("") ? "0" : obs[12]);
String lat = (obs[14].equals("") ? "0" : obs[14]);
//String lon = (obs[13].equals("") ? "0" : obs[13]);
String lon = (obs[15].equals("") ? "0" : obs[15]);
//String alt = (obs[14].equals("") ? "0" : obs[14]);
String alt = (obs[16].equals("") ? "0" : obs[16]);
//String speed = (obs[15].equals("") ? "0" : obs[15]);
String speed = (obs[17].equals("") ? "0" : obs[17]);
//String sat = (obs[16].equals("") ? "0" : obs[16]);
String sat = (obs[18].equals("") ? "0" : obs[18]);
//String prec = (obs[17].equals("") ? "0" : obs[17]);
String prec = (obs[19].equals("") ? "0" : obs[19]);
String event = (obs[20].equals("") ? "0" : obs[20]);
//String event = "Coastal walk";
time = date.trim() + " " + time.trim();
//String time = date.trim();
if(count == 4)
{
if(!time.equals(" ") && !time.contains("#VALUE"))
{
observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "X", time, avgX, event));
observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Y", time, avgY, event));
observations.add(new AccelerometerObservation(ObservationType.ACCELERATION, "Z", time, avgZ, event));
observations.add(new Observation(ObservationType.HUMIDITY, time, hum, event));
observations.add(new Observation(ObservationType.TEMPERATURE, time, temp, event));
observations.add(new GPSObservation(ObservationType.GPS, time, lat, lon, sat, prec, event));
observations.add(new AltitudeObservation(ObservationType.ALTITUDE, time, alt, sat, event));
observations.add(new SpeedObservation(ObservationType.SPEED, time, speed, event));
}
count = 0;
}
else
count++;
}
catch(ArrayIndexOutOfBoundsException aex)
{
}
catch(Exception ex)
{
//System.out.println("LineParser Exception: " + ex.toString());
ex.printStackTrace();
}
return observations;
}
|
diff --git a/src/org/geworkbench/util/AlgorithmSelectionPanel.java b/src/org/geworkbench/util/AlgorithmSelectionPanel.java
index aea455ee..22a2db97 100755
--- a/src/org/geworkbench/util/AlgorithmSelectionPanel.java
+++ b/src/org/geworkbench/util/AlgorithmSelectionPanel.java
@@ -1,83 +1,83 @@
package org.geworkbench.util;
import javax.swing.*;
import java.awt.*;
/**
* Algorithm selection panel
* <p>Title: Bioworks</p>
* <p>Description: Modular Application Framework for Gene Expession, Sequence and Genotype Analysis</p>
* <p>Copyright: Copyright (c) 2003 -2004</p>
* <p>Company: Columbia University</p>
*
*/
public class AlgorithmSelectionPanel extends JPanel {
//algorithm names
public static final String DISCOVER = "discovery";
public static final String EXHAUSTIVE = "exhaustive";
public static final String HIERARCHICAL = "hierarchical";
ButtonGroup algorithmGroup = new ButtonGroup();
JRadioButton discovery = new JRadioButton();
JRadioButton hierarc = new JRadioButton();
JRadioButton exhaustive = new JRadioButton();
FlowLayout flowLayout1 = new FlowLayout();
public AlgorithmSelectionPanel() throws Exception {
try {
jbInit();
} catch (Exception ex) {
}
}
public void jbInit() {
initAlgorithmType();
this.setBorder(null);
setMaximumSize(new Dimension(270, 20));
setMinimumSize(new Dimension(270, 20));
setPreferredSize(new Dimension(270, 20));
this.setLayout(flowLayout1);
exhaustive.setBorder(null);
hierarc.setBorder(null);
discovery.setBorder(null);
this.add(discovery, null);
// remove the hierarchical clustering option for geWorkbencg 1.6 release
//this.add(hierarc, null);
this.add(exhaustive, null);
}
/**
* Initialize algorithm Radio button
*/
private void initAlgorithmType() {
discovery.setText("Norm.");
discovery.setActionCommand(DISCOVER);
hierarc.setText("Hierarch.");
hierarc.setActionCommand(HIERARCHICAL);
- exhaustive.setText("Exhhaust.");
+ exhaustive.setText("Exhaust.");
exhaustive.setActionCommand(EXHAUSTIVE);
discovery.setSelected(true);
algorithmGroup.add(discovery);
algorithmGroup.add(exhaustive);
algorithmGroup.add(hierarc);
add(discovery);
// remove the hierarchical clustering option for geWorkbencg 1.6 release
//add(hierarc);
add(exhaustive);
}
public String getSelectedAlgorithmName() {
return algorithmGroup.getSelection().getActionCommand();
}
public void setSelectedAlgorithm(String algorithmDescription) {
if (algorithmDescription.equalsIgnoreCase(DISCOVER)) {
discovery.setSelected(true);
} else if (algorithmDescription.equalsIgnoreCase(EXHAUSTIVE)) {
exhaustive.setSelected(true);
} else if (algorithmDescription.equalsIgnoreCase(HIERARCHICAL)) {
hierarc.setSelected(true);
}
}
}
| true | true | private void initAlgorithmType() {
discovery.setText("Norm.");
discovery.setActionCommand(DISCOVER);
hierarc.setText("Hierarch.");
hierarc.setActionCommand(HIERARCHICAL);
exhaustive.setText("Exhhaust.");
exhaustive.setActionCommand(EXHAUSTIVE);
discovery.setSelected(true);
algorithmGroup.add(discovery);
algorithmGroup.add(exhaustive);
algorithmGroup.add(hierarc);
add(discovery);
// remove the hierarchical clustering option for geWorkbencg 1.6 release
//add(hierarc);
add(exhaustive);
}
| private void initAlgorithmType() {
discovery.setText("Norm.");
discovery.setActionCommand(DISCOVER);
hierarc.setText("Hierarch.");
hierarc.setActionCommand(HIERARCHICAL);
exhaustive.setText("Exhaust.");
exhaustive.setActionCommand(EXHAUSTIVE);
discovery.setSelected(true);
algorithmGroup.add(discovery);
algorithmGroup.add(exhaustive);
algorithmGroup.add(hierarc);
add(discovery);
// remove the hierarchical clustering option for geWorkbencg 1.6 release
//add(hierarc);
add(exhaustive);
}
|
diff --git a/src/com/android/contacts/dialpad/DialpadFragment.java b/src/com/android/contacts/dialpad/DialpadFragment.java
index 5f5a85574..9a3f3e700 100644
--- a/src/com/android/contacts/dialpad/DialpadFragment.java
+++ b/src/com/android/contacts/dialpad/DialpadFragment.java
@@ -1,1549 +1,1549 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.dialpad;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.SystemProperties;
import android.provider.Contacts.Intents.Insert;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.provider.Contacts.PhonesColumns;
import android.provider.Settings;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DialerKeyListener;
import android.text.style.RelativeSizeSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import com.android.contacts.ContactsUtils;
import com.android.contacts.R;
import com.android.contacts.SpecialCharSequenceMgr;
import com.android.contacts.activities.DialtactsActivity;
import com.android.contacts.util.Constants;
import com.android.contacts.util.PhoneNumberFormatter;
import com.android.internal.telephony.ITelephony;
import com.android.phone.CallLogAsync;
import com.android.phone.HapticFeedback;
/**
* Fragment that displays a twelve-key phone dialpad.
*/
public class DialpadFragment extends Fragment
implements View.OnClickListener,
View.OnLongClickListener, View.OnKeyListener,
AdapterView.OnItemClickListener, TextWatcher,
PopupMenu.OnMenuItemClickListener,
DialpadImageButton.OnPressedListener {
private static final String TAG = DialpadFragment.class.getSimpleName();
private static final boolean DEBUG = DialtactsActivity.DEBUG;
private static final String EMPTY_NUMBER = "";
/** The length of DTMF tones in milliseconds */
private static final int TONE_LENGTH_MS = 150;
private static final int TONE_LENGTH_INFINITE = -1;
/** The DTMF tone volume relative to other sounds in the stream */
private static final int TONE_RELATIVE_VOLUME = 80;
/** Stream type used to play the DTMF tones off call, and mapped to the volume control keys */
private static final int DIAL_TONE_STREAM_TYPE = AudioManager.STREAM_DTMF;
/**
* View (usually FrameLayout) containing mDigits field. This can be null, in which mDigits
* isn't enclosed by the container.
*/
private View mDigitsContainer;
private EditText mDigits;
/** Remembers if we need to clear digits field when the screen is completely gone. */
private boolean mClearDigitsOnStop;
private View mDelete;
private ToneGenerator mToneGenerator;
private final Object mToneGeneratorLock = new Object();
private View mDialpad;
/**
* Remembers the number of dialpad buttons which are pressed at this moment.
* If it becomes 0, meaning no buttons are pressed, we'll call
* {@link ToneGenerator#stopTone()}; the method shouldn't be called unless the last key is
* released.
*/
private int mDialpadPressCount;
private View mDialButtonContainer;
private View mDialButton;
private ListView mDialpadChooser;
private DialpadChooserAdapter mDialpadChooserAdapter;
/**
* Regular expression prohibiting manual phone call. Can be empty, which means "no rule".
*/
private String mProhibitedPhoneNumberRegexp;
// Last number dialed, retrieved asynchronously from the call DB
// in onCreate. This number is displayed when the user hits the
// send key and cleared in onPause.
private final CallLogAsync mCallLog = new CallLogAsync();
private String mLastNumberDialed = EMPTY_NUMBER;
// determines if we want to playback local DTMF tones.
private boolean mDTMFToneEnabled;
// Vibration (haptic feedback) for dialer key presses.
private final HapticFeedback mHaptic = new HapticFeedback();
/** Identifier for the "Add Call" intent extra. */
private static final String ADD_CALL_MODE_KEY = "add_call_mode";
/**
* Identifier for intent extra for sending an empty Flash message for
* CDMA networks. This message is used by the network to simulate a
* press/depress of the "hookswitch" of a landline phone. Aka "empty flash".
*
* TODO: Using an intent extra to tell the phone to send this flash is a
* temporary measure. To be replaced with an ITelephony call in the future.
* TODO: Keep in sync with the string defined in OutgoingCallBroadcaster.java
* in Phone app until this is replaced with the ITelephony API.
*/
private static final String EXTRA_SEND_EMPTY_FLASH
= "com.android.phone.extra.SEND_EMPTY_FLASH";
private String mCurrentCountryIso;
private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
/**
* Listen for phone state changes so that we can take down the
* "dialpad chooser" if the phone becomes idle while the
* chooser UI is visible.
*/
@Override
public void onCallStateChanged(int state, String incomingNumber) {
// Log.i(TAG, "PhoneStateListener.onCallStateChanged: "
// + state + ", '" + incomingNumber + "'");
if ((state == TelephonyManager.CALL_STATE_IDLE) && dialpadChooserVisible()) {
// Log.i(TAG, "Call ended with dialpad chooser visible! Taking it down...");
// Note there's a race condition in the UI here: the
// dialpad chooser could conceivably disappear (on its
// own) at the exact moment the user was trying to select
// one of the choices, which would be confusing. (But at
// least that's better than leaving the dialpad chooser
// onscreen, but useless...)
showDialpadChooser(false);
}
}
};
private boolean mWasEmptyBeforeTextChange;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
mWasEmptyBeforeTextChange = TextUtils.isEmpty(s);
}
@Override
public void onTextChanged(CharSequence input, int start, int before, int changeCount) {
if (mWasEmptyBeforeTextChange != TextUtils.isEmpty(input)) {
final Activity activity = getActivity();
if (activity != null) {
activity.invalidateOptionsMenu();
}
}
// DTMF Tones do not need to be played here any longer -
// the DTMF dialer handles that functionality now.
}
@Override
public void afterTextChanged(Editable input) {
// When DTMF dialpad buttons are being pressed, we delay SpecialCharSequencMgr sequence,
// since some of SpecialCharSequenceMgr's behavior is too abrupt for the "touch-down"
// behavior.
if (SpecialCharSequenceMgr.handleChars(getActivity(), input.toString(), mDigits)) {
// A special sequence was entered, clear the digits
mDigits.getText().clear();
}
if (isDigitsEmpty()) {
mDigits.setCursorVisible(false);
}
updateDialAndDeleteButtonEnabledState();
}
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
mCurrentCountryIso = ContactsUtils.getCurrentCountryIso(getActivity());
try {
mHaptic.init(getActivity(),
getResources().getBoolean(R.bool.config_enable_dialer_key_vibration));
} catch (Resources.NotFoundException nfe) {
Log.e(TAG, "Vibrate control bool missing.", nfe);
}
setHasOptionsMenu(true);
mProhibitedPhoneNumberRegexp = getResources().getString(
R.string.config_prohibited_phone_number_regexp);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedState) {
View fragmentView = inflater.inflate(R.layout.dialpad_fragment, container, false);
// Load up the resources for the text field.
Resources r = getResources();
mDigitsContainer = fragmentView.findViewById(R.id.digits_container);
mDigits = (EditText) fragmentView.findViewById(R.id.digits);
mDigits.setKeyListener(DialerKeyListener.getInstance());
mDigits.setOnClickListener(this);
mDigits.setOnKeyListener(this);
mDigits.setOnLongClickListener(this);
mDigits.addTextChangedListener(this);
PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(getActivity(), mDigits);
// Check for the presence of the keypad
View oneButton = fragmentView.findViewById(R.id.one);
if (oneButton != null) {
setupKeypad(fragmentView);
}
DisplayMetrics dm = getResources().getDisplayMetrics();
int minCellSize = (int) (56 * dm.density); // 56dip == minimum size of menu buttons
int cellCount = dm.widthPixels / minCellSize;
int fakeMenuItemWidth = dm.widthPixels / cellCount;
mDialButtonContainer = fragmentView.findViewById(R.id.dialButtonContainer);
if (mDialButtonContainer != null) {
mDialButtonContainer.setPadding(
fakeMenuItemWidth, mDialButtonContainer.getPaddingTop(),
fakeMenuItemWidth, mDialButtonContainer.getPaddingBottom());
}
mDialButton = fragmentView.findViewById(R.id.dialButton);
if (r.getBoolean(R.bool.config_show_onscreen_dial_button)) {
mDialButton.setOnClickListener(this);
} else {
mDialButton.setVisibility(View.GONE); // It's VISIBLE by default
mDialButton = null;
}
mDelete = fragmentView.findViewById(R.id.deleteButton);
if (mDelete != null) {
mDelete.setOnClickListener(this);
mDelete.setOnLongClickListener(this);
}
mDialpad = fragmentView.findViewById(R.id.dialpad); // This is null in landscape mode.
// In landscape we put the keyboard in phone mode.
if (null == mDialpad) {
mDigits.setInputType(android.text.InputType.TYPE_CLASS_PHONE);
} else {
mDigits.setCursorVisible(false);
}
// Set up the "dialpad chooser" UI; see showDialpadChooser().
mDialpadChooser = (ListView) fragmentView.findViewById(R.id.dialpadChooser);
mDialpadChooser.setOnItemClickListener(this);
configureScreenFromIntent(getActivity().getIntent());
return fragmentView;
}
private boolean isLayoutReady() {
return mDigits != null;
}
public EditText getDigitsWidget() {
return mDigits;
}
/**
* @return true when {@link #mDigits} is actually filled by the Intent.
*/
private boolean fillDigitsIfNecessary(Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_DIAL.equals(action) || Intent.ACTION_VIEW.equals(action)) {
Uri uri = intent.getData();
if (uri != null) {
if (Constants.SCHEME_TEL.equals(uri.getScheme())) {
// Put the requested number into the input area
String data = uri.getSchemeSpecificPart();
setFormattedDigits(data, null);
return true;
} else {
String type = intent.getType();
if (People.CONTENT_ITEM_TYPE.equals(type)
|| Phones.CONTENT_ITEM_TYPE.equals(type)) {
// Query the phone number
Cursor c = getActivity().getContentResolver().query(intent.getData(),
new String[] {PhonesColumns.NUMBER, PhonesColumns.NUMBER_KEY},
null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
// Put the number into the input area
setFormattedDigits(c.getString(0), c.getString(1));
return true;
}
} finally {
c.close();
}
}
}
}
}
}
return false;
}
/**
* @see #showDialpadChooser(boolean)
*/
private static boolean needToShowDialpadChooser(Intent intent, boolean isAddCallMode) {
final String action = intent.getAction();
boolean needToShowDialpadChooser = false;
if (Intent.ACTION_DIAL.equals(action) || Intent.ACTION_VIEW.equals(action)) {
Uri uri = intent.getData();
if (uri == null) {
// ACTION_DIAL or ACTION_VIEW with no data.
// This behaves basically like ACTION_MAIN: If there's
// already an active call, bring up an intermediate UI to
// make the user confirm what they really want to do.
// Be sure *not* to show the dialpad chooser if this is an
// explicit "Add call" action, though.
if (!isAddCallMode && phoneIsInUse()) {
needToShowDialpadChooser = true;
}
}
} else if (Intent.ACTION_MAIN.equals(action)) {
// The MAIN action means we're bringing up a blank dialer
// (e.g. by selecting the Home shortcut, or tabbing over from
// Contacts or Call log.)
//
// At this point, IF there's already an active call, there's a
// good chance that the user got here accidentally (but really
// wanted the in-call dialpad instead). So we bring up an
// intermediate UI to make the user confirm what they really
// want to do.
if (phoneIsInUse()) {
// Log.i(TAG, "resolveIntent(): phone is in use; showing dialpad chooser!");
needToShowDialpadChooser = true;
}
}
return needToShowDialpadChooser;
}
private static boolean isAddCallMode(Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_DIAL.equals(action) || Intent.ACTION_VIEW.equals(action)) {
// see if we are "adding a call" from the InCallScreen; false by default.
return intent.getBooleanExtra(ADD_CALL_MODE_KEY, false);
} else {
return false;
}
}
/**
* Checks the given Intent and changes dialpad's UI state. For example, if the Intent requires
* the screen to enter "Add Call" mode, this method will show correct UI for the mode.
*/
public void configureScreenFromIntent(Intent intent) {
if (!isLayoutReady()) {
// This happens typically when parent's Activity#onNewIntent() is called while
// Fragment#onCreateView() isn't called yet, and thus we cannot configure Views at
// this point. onViewCreate() should call this method after preparing layouts, so
// just ignore this call now.
Log.i(TAG,
"Screen configuration is requested before onCreateView() is called. Ignored");
return;
}
boolean needToShowDialpadChooser = false;
final boolean isAddCallMode = isAddCallMode(intent);
if (!isAddCallMode) {
final boolean digitsFilled = fillDigitsIfNecessary(intent);
if (!digitsFilled) {
needToShowDialpadChooser = needToShowDialpadChooser(intent, isAddCallMode);
}
}
showDialpadChooser(needToShowDialpadChooser);
}
private void setFormattedDigits(String data, String normalizedNumber) {
// strip the non-dialable numbers out of the data string.
String dialString = PhoneNumberUtils.extractNetworkPortion(data);
dialString =
PhoneNumberUtils.formatNumber(dialString, normalizedNumber, mCurrentCountryIso);
if (!TextUtils.isEmpty(dialString)) {
Editable digits = mDigits.getText();
digits.replace(0, digits.length(), dialString);
// for some reason this isn't getting called in the digits.replace call above..
// but in any case, this will make sure the background drawable looks right
afterTextChanged(digits);
}
}
private void setupKeypad(View fragmentView) {
int[] buttonIds = new int[] { R.id.one, R.id.two, R.id.three, R.id.four, R.id.five,
R.id.six, R.id.seven, R.id.eight, R.id.nine, R.id.zero, R.id.star, R.id.pound};
for (int id : buttonIds) {
((DialpadImageButton) fragmentView.findViewById(id)).setOnPressedListener(this);
}
// Long-pressing one button will initiate Voicemail.
fragmentView.findViewById(R.id.one).setOnLongClickListener(this);
// Long-pressing zero button will enter '+' instead.
fragmentView.findViewById(R.id.zero).setOnLongClickListener(this);
}
@Override
public void onResume() {
super.onResume();
// Query the last dialed number. Do it first because hitting
// the DB is 'slow'. This call is asynchronous.
queryLastOutgoingCall();
// retrieve the DTMF tone play back setting.
mDTMFToneEnabled = Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1;
// Retrieve the haptic feedback setting.
mHaptic.checkSystemSetting();
// if the mToneGenerator creation fails, just continue without it. It is
// a local audio signal, and is not as important as the dtmf tone itself.
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
try {
mToneGenerator = new ToneGenerator(DIAL_TONE_STREAM_TYPE, TONE_RELATIVE_VOLUME);
} catch (RuntimeException e) {
Log.w(TAG, "Exception caught while creating local tone generator: " + e);
mToneGenerator = null;
}
}
}
// Prevent unnecessary confusion. Reset the press count anyway.
mDialpadPressCount = 0;
Activity parent = getActivity();
if (parent instanceof DialtactsActivity) {
// See if we were invoked with a DIAL intent. If we were, fill in the appropriate
// digits in the dialer field.
fillDigitsIfNecessary(parent.getIntent());
}
// While we're in the foreground, listen for phone state changes,
// purely so that we can take down the "dialpad chooser" if the
// phone becomes idle while the chooser UI is visible.
TelephonyManager telephonyManager =
(TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
// Potentially show hint text in the mDigits field when the user
// hasn't typed any digits yet. (If there's already an active call,
// this hint text will remind the user that he's about to add a new
// call.)
//
// TODO: consider adding better UI for the case where *both* lines
// are currently in use. (Right now we let the user try to add
// another call, but that call is guaranteed to fail. Perhaps the
// entire dialer UI should be disabled instead.)
if (phoneIsInUse()) {
final SpannableString hint = new SpannableString(
getActivity().getString(R.string.dialerDialpadHintText));
hint.setSpan(new RelativeSizeSpan(0.8f), 0, hint.length(), 0);
mDigits.setHint(hint);
} else {
// Common case; no hint necessary.
mDigits.setHint(null);
// Also, a sanity-check: the "dialpad chooser" UI should NEVER
// be visible if the phone is idle!
showDialpadChooser(false);
}
updateDialAndDeleteButtonEnabledState();
}
@Override
public void onPause() {
super.onPause();
// Stop listening for phone state changes.
TelephonyManager telephonyManager =
(TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
// Make sure we don't leave this activity with a tone still playing.
stopTone();
// Just in case reset the counter too.
mDialpadPressCount = 0;
synchronized (mToneGeneratorLock) {
if (mToneGenerator != null) {
mToneGenerator.release();
mToneGenerator = null;
}
}
// TODO: I wonder if we should not check if the AsyncTask that
// lookup the last dialed number has completed.
mLastNumberDialed = EMPTY_NUMBER; // Since we are going to query again, free stale number.
SpecialCharSequenceMgr.cleanup();
}
@Override
public void onStop() {
super.onStop();
if (mClearDigitsOnStop) {
mClearDigitsOnStop = false;
mDigits.getText().clear();
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
if (ViewConfiguration.get(getActivity()).hasPermanentMenuKey() &&
isLayoutReady() && mDialpadChooser != null) {
inflater.inflate(R.menu.dialpad_options, menu);
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
// Hardware menu key should be available and Views should already be ready.
if (ViewConfiguration.get(getActivity()).hasPermanentMenuKey() &&
isLayoutReady() && mDialpadChooser != null) {
setupMenuItems(menu);
}
}
private void setupMenuItems(Menu menu) {
final MenuItem callSettingsMenuItem = menu.findItem(R.id.menu_call_settings_dialpad);
final MenuItem addToContactMenuItem = menu.findItem(R.id.menu_add_contacts);
final MenuItem twoSecPauseMenuItem = menu.findItem(R.id.menu_2s_pause);
final MenuItem waitMenuItem = menu.findItem(R.id.menu_add_wait);
// Check if all the menu items are inflated correctly. As a shortcut, we assume all menu
// items are ready if the first item is non-null.
if (callSettingsMenuItem == null) {
return;
}
final Activity activity = getActivity();
if (activity != null && ViewConfiguration.get(activity).hasPermanentMenuKey()) {
// Call settings should be available via its parent Activity.
callSettingsMenuItem.setVisible(false);
} else {
callSettingsMenuItem.setVisible(true);
callSettingsMenuItem.setIntent(DialtactsActivity.getCallSettingsIntent());
}
// We show "add to contacts", "2sec pause", and "add wait" menus only when the user is
// seeing usual dialpads and has typed at least one digit.
// We never show a menu if the "choose dialpad" UI is up.
if (dialpadChooserVisible() || isDigitsEmpty()) {
addToContactMenuItem.setVisible(false);
twoSecPauseMenuItem.setVisible(false);
waitMenuItem.setVisible(false);
} else {
final CharSequence digits = mDigits.getText();
// Put the current digits string into an intent
addToContactMenuItem.setIntent(getAddToContactIntent(digits));
addToContactMenuItem.setVisible(true);
// Check out whether to show Pause & Wait option menu items
int selectionStart;
int selectionEnd;
String strDigits = digits.toString();
selectionStart = mDigits.getSelectionStart();
selectionEnd = mDigits.getSelectionEnd();
if (selectionStart != -1) {
if (selectionStart > selectionEnd) {
// swap it as we want start to be less then end
int tmp = selectionStart;
selectionStart = selectionEnd;
selectionEnd = tmp;
}
if (selectionStart != 0) {
// Pause can be visible if cursor is not in the begining
twoSecPauseMenuItem.setVisible(true);
// For Wait to be visible set of condition to meet
waitMenuItem.setVisible(showWait(selectionStart, selectionEnd, strDigits));
} else {
// cursor in the beginning both pause and wait to be invisible
twoSecPauseMenuItem.setVisible(false);
waitMenuItem.setVisible(false);
}
} else {
twoSecPauseMenuItem.setVisible(true);
// cursor is not selected so assume new digit is added to the end
int strLength = strDigits.length();
waitMenuItem.setVisible(showWait(strLength, strLength, strDigits));
}
}
}
private static Intent getAddToContactIntent(CharSequence digits) {
final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.putExtra(Insert.PHONE, digits);
intent.setType(People.CONTENT_ITEM_TYPE);
return intent;
}
private void keyPressed(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_1:
playTone(ToneGenerator.TONE_DTMF_1, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_2:
playTone(ToneGenerator.TONE_DTMF_2, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_3:
playTone(ToneGenerator.TONE_DTMF_3, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_4:
playTone(ToneGenerator.TONE_DTMF_4, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_5:
playTone(ToneGenerator.TONE_DTMF_5, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_6:
playTone(ToneGenerator.TONE_DTMF_6, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_7:
playTone(ToneGenerator.TONE_DTMF_7, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_8:
playTone(ToneGenerator.TONE_DTMF_8, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_9:
playTone(ToneGenerator.TONE_DTMF_9, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_0:
playTone(ToneGenerator.TONE_DTMF_0, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_POUND:
playTone(ToneGenerator.TONE_DTMF_P, TONE_LENGTH_INFINITE);
break;
case KeyEvent.KEYCODE_STAR:
playTone(ToneGenerator.TONE_DTMF_S, TONE_LENGTH_INFINITE);
break;
default:
break;
}
mHaptic.vibrate();
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
mDigits.onKeyDown(keyCode, event);
// If the cursor is at the end of the text we hide it.
final int length = mDigits.length();
if (length == mDigits.getSelectionStart() && length == mDigits.getSelectionEnd()) {
mDigits.setCursorVisible(false);
}
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
switch (view.getId()) {
case R.id.digits:
if (keyCode == KeyEvent.KEYCODE_ENTER) {
dialButtonPressed();
return true;
}
break;
}
return false;
}
/**
* When a key is pressed, we start playing DTMF tone, do vibration, and enter the digit
* immediately. When a key is released, we stop the tone. Note that the "key press" event will
* be delivered by the system with certain amount of delay, it won't be synced with user's
* actual "touch-down" behavior.
*/
@Override
public void onPressed(View view, boolean pressed) {
if (DEBUG) Log.d(TAG, "onPressed(). view: " + view + ", pressed: " + pressed);
if (pressed) {
switch (view.getId()) {
case R.id.one: {
keyPressed(KeyEvent.KEYCODE_1);
break;
}
case R.id.two: {
keyPressed(KeyEvent.KEYCODE_2);
break;
}
case R.id.three: {
keyPressed(KeyEvent.KEYCODE_3);
break;
}
case R.id.four: {
keyPressed(KeyEvent.KEYCODE_4);
break;
}
case R.id.five: {
keyPressed(KeyEvent.KEYCODE_5);
break;
}
case R.id.six: {
keyPressed(KeyEvent.KEYCODE_6);
break;
}
case R.id.seven: {
keyPressed(KeyEvent.KEYCODE_7);
break;
}
case R.id.eight: {
keyPressed(KeyEvent.KEYCODE_8);
break;
}
case R.id.nine: {
keyPressed(KeyEvent.KEYCODE_9);
break;
}
case R.id.zero: {
keyPressed(KeyEvent.KEYCODE_0);
break;
}
case R.id.pound: {
keyPressed(KeyEvent.KEYCODE_POUND);
break;
}
case R.id.star: {
keyPressed(KeyEvent.KEYCODE_STAR);
break;
}
default: {
Log.wtf(TAG, "Unexpected onTouch(ACTION_DOWN) event from: " + view);
break;
}
}
mDialpadPressCount++;
} else {
view.jumpDrawablesToCurrentState();
mDialpadPressCount--;
if (mDialpadPressCount < 0) {
- // This must be a very buggy situation in which the number of touch-down events
- // don't match that of touch-up. We should tolerate the situation anyway.
- Log.e(TAG, "mKeyPressCount become negative.");
+ // May happen when the user action is detected as horizontal swipe, at which only
+ // "up" event is thrown.
+ if (DEBUG) Log.d(TAG, "mKeyPressCount become negative.");
stopTone();
mDialpadPressCount = 0;
} else if (mDialpadPressCount == 0) {
stopTone();
}
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.deleteButton: {
keyPressed(KeyEvent.KEYCODE_DEL);
return;
}
case R.id.dialButton: {
mHaptic.vibrate(); // Vibrate here too, just like we do for the regular keys
dialButtonPressed();
return;
}
case R.id.digits: {
if (!isDigitsEmpty()) {
mDigits.setCursorVisible(true);
}
return;
}
default: {
Log.wtf(TAG, "Unexpected onClick() event from: " + view);
return;
}
}
}
public PopupMenu constructPopupMenu(View anchorView) {
final Context context = getActivity();
if (context == null) {
return null;
}
final PopupMenu popupMenu = new PopupMenu(context, anchorView);
final Menu menu = popupMenu.getMenu();
popupMenu.inflate(R.menu.dialpad_options);
popupMenu.setOnMenuItemClickListener(this);
setupMenuItems(menu);
return popupMenu;
}
@Override
public boolean onLongClick(View view) {
final Editable digits = mDigits.getText();
final int id = view.getId();
switch (id) {
case R.id.deleteButton: {
digits.clear();
// TODO: The framework forgets to clear the pressed
// status of disabled button. Until this is fixed,
// clear manually the pressed status. b/2133127
mDelete.setPressed(false);
return true;
}
case R.id.one: {
// '1' may be already entered since we rely on onTouch() event for numeric buttons.
// Just for safety we also check if the digits field is empty or not.
if (isDigitsEmpty() || TextUtils.equals(mDigits.getText(), "1")) {
// We'll try to initiate voicemail and thus we want to remove irrelevant string.
removePreviousDigitIfPossible();
if (isVoicemailAvailable()) {
callVoicemail();
} else if (getActivity() != null) {
// Voicemail is unavailable maybe because Airplane mode is turned on.
// Check the current status and show the most appropriate error message.
final boolean isAirplaneModeOn =
Settings.System.getInt(getActivity().getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
if (isAirplaneModeOn) {
DialogFragment dialogFragment = ErrorDialogFragment.newInstance(
R.string.dialog_voicemail_airplane_mode_message);
dialogFragment.show(getFragmentManager(),
"voicemail_request_during_airplane_mode");
} else {
DialogFragment dialogFragment = ErrorDialogFragment.newInstance(
R.string.dialog_voicemail_not_ready_message);
dialogFragment.show(getFragmentManager(), "voicemail_not_ready");
}
}
return true;
}
return false;
}
case R.id.zero: {
// Remove tentative input ('0') done by onTouch().
removePreviousDigitIfPossible();
keyPressed(KeyEvent.KEYCODE_PLUS);
return true;
}
case R.id.digits: {
// Right now EditText does not show the "paste" option when cursor is not visible.
// To show that, make the cursor visible, and return false, letting the EditText
// show the option by itself.
mDigits.setCursorVisible(true);
return false;
}
}
return false;
}
/**
* Remove the digit just before the current position. This can be used if we want to replace
* the previous digit or cancel previously entered character.
*/
private void removePreviousDigitIfPossible() {
final Editable editable = mDigits.getText();
final int currentPosition = mDigits.getSelectionStart();
if (currentPosition > 0) {
mDigits.setSelection(currentPosition);
mDigits.getText().delete(currentPosition - 1, currentPosition);
}
}
public void callVoicemail() {
startActivity(ContactsUtils.getVoicemailIntent());
mClearDigitsOnStop = true;
getActivity().finish();
}
public static class ErrorDialogFragment extends DialogFragment {
private int mTitleResId;
private int mMessageResId;
private static final String ARG_TITLE_RES_ID = "argTitleResId";
private static final String ARG_MESSAGE_RES_ID = "argMessageResId";
public static ErrorDialogFragment newInstance(int messageResId) {
return newInstance(0, messageResId);
}
public static ErrorDialogFragment newInstance(int titleResId, int messageResId) {
final ErrorDialogFragment fragment = new ErrorDialogFragment();
final Bundle args = new Bundle();
args.putInt(ARG_TITLE_RES_ID, titleResId);
args.putInt(ARG_MESSAGE_RES_ID, messageResId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTitleResId = getArguments().getInt(ARG_TITLE_RES_ID);
mMessageResId = getArguments().getInt(ARG_MESSAGE_RES_ID);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
if (mTitleResId != 0) {
builder.setTitle(mTitleResId);
}
if (mMessageResId != 0) {
builder.setMessage(mMessageResId);
}
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
});
return builder.create();
}
}
/**
* In most cases, when the dial button is pressed, there is a
* number in digits area. Pack it in the intent, start the
* outgoing call broadcast as a separate task and finish this
* activity.
*
* When there is no digit and the phone is CDMA and off hook,
* we're sending a blank flash for CDMA. CDMA networks use Flash
* messages when special processing needs to be done, mainly for
* 3-way or call waiting scenarios. Presumably, here we're in a
* special 3-way scenario where the network needs a blank flash
* before being able to add the new participant. (This is not the
* case with all 3-way calls, just certain CDMA infrastructures.)
*
* Otherwise, there is no digit, display the last dialed
* number. Don't finish since the user may want to edit it. The
* user needs to press the dial button again, to dial it (general
* case described above).
*/
public void dialButtonPressed() {
if (isDigitsEmpty()) { // No number entered.
if (phoneIsCdma() && phoneIsOffhook()) {
// This is really CDMA specific. On GSM is it possible
// to be off hook and wanted to add a 3rd party using
// the redial feature.
startActivity(newFlashIntent());
} else {
if (!TextUtils.isEmpty(mLastNumberDialed)) {
// Recall the last number dialed.
mDigits.setText(mLastNumberDialed);
// ...and move the cursor to the end of the digits string,
// so you'll be able to delete digits using the Delete
// button (just as if you had typed the number manually.)
//
// Note we use mDigits.getText().length() here, not
// mLastNumberDialed.length(), since the EditText widget now
// contains a *formatted* version of mLastNumberDialed (due to
// mTextWatcher) and its length may have changed.
mDigits.setSelection(mDigits.getText().length());
} else {
// There's no "last number dialed" or the
// background query is still running. There's
// nothing useful for the Dial button to do in
// this case. Note: with a soft dial button, this
// can never happens since the dial button is
// disabled under these conditons.
playTone(ToneGenerator.TONE_PROP_NACK);
}
}
} else {
final String number = mDigits.getText().toString();
// "persist.radio.otaspdial" is a temporary hack needed for one carrier's automated
// test equipment.
// TODO: clean it up.
if (number != null
&& !TextUtils.isEmpty(mProhibitedPhoneNumberRegexp)
&& number.matches(mProhibitedPhoneNumberRegexp)
&& (SystemProperties.getInt("persist.radio.otaspdial", 0) != 1)) {
Log.i(TAG, "The phone number is prohibited explicitly by a rule.");
if (getActivity() != null) {
DialogFragment dialogFragment = ErrorDialogFragment.newInstance(
R.string.dialog_phone_call_prohibited_message);
dialogFragment.show(getFragmentManager(), "phone_prohibited_dialog");
}
// Clear the digits just in case.
mDigits.getText().clear();
} else {
final Intent intent = ContactsUtils.getCallIntent(number,
(getActivity() instanceof DialtactsActivity ?
((DialtactsActivity)getActivity()).getCallOrigin() : null));
startActivity(intent);
mClearDigitsOnStop = true;
getActivity().finish();
}
}
}
/**
* Plays the specified tone for TONE_LENGTH_MS milliseconds.
*/
private void playTone(int tone) {
playTone(tone, TONE_LENGTH_MS);
}
/**
* Play the specified tone for the specified milliseconds
*
* The tone is played locally, using the audio stream for phone calls.
* Tones are played only if the "Audible touch tones" user preference
* is checked, and are NOT played if the device is in silent mode.
*
* The tone length can be -1, meaning "keep playing the tone." If the caller does so, it should
* call stopTone() afterward.
*
* @param tone a tone code from {@link ToneGenerator}
* @param durationMs tone length.
*/
private void playTone(int tone, int durationMs) {
// if local tone playback is disabled, just return.
if (!mDTMFToneEnabled) {
return;
}
// Also do nothing if the phone is in silent mode.
// We need to re-check the ringer mode for *every* playTone()
// call, rather than keeping a local flag that's updated in
// onResume(), since it's possible to toggle silent mode without
// leaving the current activity (via the ENDCALL-longpress menu.)
AudioManager audioManager =
(AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
int ringerMode = audioManager.getRingerMode();
if ((ringerMode == AudioManager.RINGER_MODE_SILENT)
|| (ringerMode == AudioManager.RINGER_MODE_VIBRATE)) {
return;
}
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
Log.w(TAG, "playTone: mToneGenerator == null, tone: " + tone);
return;
}
// Start the new tone (will stop any playing tone)
mToneGenerator.startTone(tone, durationMs);
}
}
/**
* Stop the tone if it is played.
*/
private void stopTone() {
// if local tone playback is disabled, just return.
if (!mDTMFToneEnabled) {
return;
}
synchronized (mToneGeneratorLock) {
if (mToneGenerator == null) {
Log.w(TAG, "stopTone: mToneGenerator == null");
return;
}
mToneGenerator.stopTone();
}
}
/**
* Brings up the "dialpad chooser" UI in place of the usual Dialer
* elements (the textfield/button and the dialpad underneath).
*
* We show this UI if the user brings up the Dialer while a call is
* already in progress, since there's a good chance we got here
* accidentally (and the user really wanted the in-call dialpad instead).
* So in this situation we display an intermediate UI that lets the user
* explicitly choose between the in-call dialpad ("Use touch tone
* keypad") and the regular Dialer ("Add call"). (Or, the option "Return
* to call in progress" just goes back to the in-call UI with no dialpad
* at all.)
*
* @param enabled If true, show the "dialpad chooser" instead
* of the regular Dialer UI
*/
private void showDialpadChooser(boolean enabled) {
// Check if onCreateView() is already called by checking one of View objects.
if (!isLayoutReady()) {
return;
}
if (enabled) {
// Log.i(TAG, "Showing dialpad chooser!");
if (mDigitsContainer != null) {
mDigitsContainer.setVisibility(View.GONE);
} else {
// mDigits is not enclosed by the container. Make the digits field itself gone.
mDigits.setVisibility(View.GONE);
}
if (mDialpad != null) mDialpad.setVisibility(View.GONE);
if (mDialButtonContainer != null) mDialButtonContainer.setVisibility(View.GONE);
mDialpadChooser.setVisibility(View.VISIBLE);
// Instantiate the DialpadChooserAdapter and hook it up to the
// ListView. We do this only once.
if (mDialpadChooserAdapter == null) {
mDialpadChooserAdapter = new DialpadChooserAdapter(getActivity());
}
mDialpadChooser.setAdapter(mDialpadChooserAdapter);
} else {
// Log.i(TAG, "Displaying normal Dialer UI.");
if (mDigitsContainer != null) {
mDigitsContainer.setVisibility(View.VISIBLE);
} else {
mDigits.setVisibility(View.VISIBLE);
}
if (mDialpad != null) mDialpad.setVisibility(View.VISIBLE);
if (mDialButtonContainer != null) mDialButtonContainer.setVisibility(View.VISIBLE);
mDialpadChooser.setVisibility(View.GONE);
}
}
/**
* @return true if we're currently showing the "dialpad chooser" UI.
*/
private boolean dialpadChooserVisible() {
return mDialpadChooser.getVisibility() == View.VISIBLE;
}
/**
* Simple list adapter, binding to an icon + text label
* for each item in the "dialpad chooser" list.
*/
private static class DialpadChooserAdapter extends BaseAdapter {
private LayoutInflater mInflater;
// Simple struct for a single "choice" item.
static class ChoiceItem {
String text;
Bitmap icon;
int id;
public ChoiceItem(String s, Bitmap b, int i) {
text = s;
icon = b;
id = i;
}
}
// IDs for the possible "choices":
static final int DIALPAD_CHOICE_USE_DTMF_DIALPAD = 101;
static final int DIALPAD_CHOICE_RETURN_TO_CALL = 102;
static final int DIALPAD_CHOICE_ADD_NEW_CALL = 103;
private static final int NUM_ITEMS = 3;
private ChoiceItem mChoiceItems[] = new ChoiceItem[NUM_ITEMS];
public DialpadChooserAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
// Initialize the possible choices.
// TODO: could this be specified entirely in XML?
// - "Use touch tone keypad"
mChoiceItems[0] = new ChoiceItem(
context.getString(R.string.dialer_useDtmfDialpad),
BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_dialer_fork_tt_keypad),
DIALPAD_CHOICE_USE_DTMF_DIALPAD);
// - "Return to call in progress"
mChoiceItems[1] = new ChoiceItem(
context.getString(R.string.dialer_returnToInCallScreen),
BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_dialer_fork_current_call),
DIALPAD_CHOICE_RETURN_TO_CALL);
// - "Add call"
mChoiceItems[2] = new ChoiceItem(
context.getString(R.string.dialer_addAnotherCall),
BitmapFactory.decodeResource(context.getResources(),
R.drawable.ic_dialer_fork_add_call),
DIALPAD_CHOICE_ADD_NEW_CALL);
}
@Override
public int getCount() {
return NUM_ITEMS;
}
/**
* Return the ChoiceItem for a given position.
*/
@Override
public Object getItem(int position) {
return mChoiceItems[position];
}
/**
* Return a unique ID for each possible choice.
*/
@Override
public long getItemId(int position) {
return position;
}
/**
* Make a view for each row.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// When convertView is non-null, we can reuse it (there's no need
// to reinflate it.)
if (convertView == null) {
convertView = mInflater.inflate(R.layout.dialpad_chooser_list_item, null);
}
TextView text = (TextView) convertView.findViewById(R.id.text);
text.setText(mChoiceItems[position].text);
ImageView icon = (ImageView) convertView.findViewById(R.id.icon);
icon.setImageBitmap(mChoiceItems[position].icon);
return convertView;
}
}
/**
* Handle clicks from the dialpad chooser.
*/
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
DialpadChooserAdapter.ChoiceItem item =
(DialpadChooserAdapter.ChoiceItem) parent.getItemAtPosition(position);
int itemId = item.id;
switch (itemId) {
case DialpadChooserAdapter.DIALPAD_CHOICE_USE_DTMF_DIALPAD:
// Log.i(TAG, "DIALPAD_CHOICE_USE_DTMF_DIALPAD");
// Fire off an intent to go back to the in-call UI
// with the dialpad visible.
returnToInCallScreen(true);
break;
case DialpadChooserAdapter.DIALPAD_CHOICE_RETURN_TO_CALL:
// Log.i(TAG, "DIALPAD_CHOICE_RETURN_TO_CALL");
// Fire off an intent to go back to the in-call UI
// (with the dialpad hidden).
returnToInCallScreen(false);
break;
case DialpadChooserAdapter.DIALPAD_CHOICE_ADD_NEW_CALL:
// Log.i(TAG, "DIALPAD_CHOICE_ADD_NEW_CALL");
// Ok, guess the user really did want to be here (in the
// regular Dialer) after all. Bring back the normal Dialer UI.
showDialpadChooser(false);
break;
default:
Log.w(TAG, "onItemClick: unexpected itemId: " + itemId);
break;
}
}
/**
* Returns to the in-call UI (where there's presumably a call in
* progress) in response to the user selecting "use touch tone keypad"
* or "return to call" from the dialpad chooser.
*/
private void returnToInCallScreen(boolean showDialpad) {
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) phone.showCallScreenWithDialpad(showDialpad);
} catch (RemoteException e) {
Log.w(TAG, "phone.showCallScreenWithDialpad() failed", e);
}
// Finally, finish() ourselves so that we don't stay on the
// activity stack.
// Note that we do this whether or not the showCallScreenWithDialpad()
// call above had any effect or not! (That call is a no-op if the
// phone is idle, which can happen if the current call ends while
// the dialpad chooser is up. In this case we can't show the
// InCallScreen, and there's no point staying here in the Dialer,
// so we just take the user back where he came from...)
getActivity().finish();
}
/**
* @return true if the phone is "in use", meaning that at least one line
* is active (ie. off hook or ringing or dialing).
*/
public static boolean phoneIsInUse() {
boolean phoneInUse = false;
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) phoneInUse = !phone.isIdle();
} catch (RemoteException e) {
Log.w(TAG, "phone.isIdle() failed", e);
}
return phoneInUse;
}
/**
* @return true if the phone is a CDMA phone type
*/
private boolean phoneIsCdma() {
boolean isCdma = false;
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) {
isCdma = (phone.getActivePhoneType() == TelephonyManager.PHONE_TYPE_CDMA);
}
} catch (RemoteException e) {
Log.w(TAG, "phone.getActivePhoneType() failed", e);
}
return isCdma;
}
/**
* @return true if the phone state is OFFHOOK
*/
private boolean phoneIsOffhook() {
boolean phoneOffhook = false;
try {
ITelephony phone = ITelephony.Stub.asInterface(ServiceManager.checkService("phone"));
if (phone != null) phoneOffhook = phone.isOffhook();
} catch (RemoteException e) {
Log.w(TAG, "phone.isOffhook() failed", e);
}
return phoneOffhook;
}
/**
* Returns true whenever any one of the options from the menu is selected.
* Code changes to support dialpad options
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_2s_pause:
updateDialString(",");
return true;
case R.id.menu_add_wait:
updateDialString(";");
return true;
default:
return false;
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
return onOptionsItemSelected(item);
}
/**
* Updates the dial string (mDigits) after inserting a Pause character (,)
* or Wait character (;).
*/
private void updateDialString(String newDigits) {
int selectionStart;
int selectionEnd;
// SpannableStringBuilder editable_text = new SpannableStringBuilder(mDigits.getText());
int anchor = mDigits.getSelectionStart();
int point = mDigits.getSelectionEnd();
selectionStart = Math.min(anchor, point);
selectionEnd = Math.max(anchor, point);
Editable digits = mDigits.getText();
if (selectionStart != -1) {
if (selectionStart == selectionEnd) {
// then there is no selection. So insert the pause at this
// position and update the mDigits.
digits.replace(selectionStart, selectionStart, newDigits);
} else {
digits.replace(selectionStart, selectionEnd, newDigits);
// Unselect: back to a regular cursor, just pass the character inserted.
mDigits.setSelection(selectionStart + 1);
}
} else {
int len = mDigits.length();
digits.replace(len, len, newDigits);
}
}
/**
* Update the enabledness of the "Dial" and "Backspace" buttons if applicable.
*/
private void updateDialAndDeleteButtonEnabledState() {
final boolean digitsNotEmpty = !isDigitsEmpty();
if (mDialButton != null) {
// On CDMA phones, if we're already on a call, we *always*
// enable the Dial button (since you can press it without
// entering any digits to send an empty flash.)
if (phoneIsCdma() && phoneIsOffhook()) {
mDialButton.setEnabled(true);
} else {
// Common case: GSM, or CDMA but not on a call.
// Enable the Dial button if some digits have
// been entered, or if there is a last dialed number
// that could be redialed.
mDialButton.setEnabled(digitsNotEmpty ||
!TextUtils.isEmpty(mLastNumberDialed));
}
}
mDelete.setEnabled(digitsNotEmpty);
}
/**
* Check if voicemail is enabled/accessible.
*
* @return true if voicemail is enabled and accessibly. Note that this can be false
* "temporarily" after the app boot.
* @see TelephonyManager#getVoiceMailNumber()
*/
private boolean isVoicemailAvailable() {
try {
return (TelephonyManager.getDefault().getVoiceMailNumber() != null);
} catch (SecurityException se) {
// Possibly no READ_PHONE_STATE privilege.
Log.w(TAG, "SecurityException is thrown. Maybe privilege isn't sufficient.");
}
return false;
}
/**
* This function return true if Wait menu item can be shown
* otherwise returns false. Assumes the passed string is non-empty
* and the 0th index check is not required.
*/
private static boolean showWait(int start, int end, String digits) {
if (start == end) {
// visible false in this case
if (start > digits.length()) return false;
// preceding char is ';', so visible should be false
if (digits.charAt(start - 1) == ';') return false;
// next char is ';', so visible should be false
if ((digits.length() > start) && (digits.charAt(start) == ';')) return false;
} else {
// visible false in this case
if (start > digits.length() || end > digits.length()) return false;
// In this case we need to just check for ';' preceding to start
// or next to end
if (digits.charAt(start - 1) == ';') return false;
}
return true;
}
/**
* @return true if the widget with the phone number digits is empty.
*/
private boolean isDigitsEmpty() {
return mDigits.length() == 0;
}
/**
* Starts the asyn query to get the last dialed/outgoing
* number. When the background query finishes, mLastNumberDialed
* is set to the last dialed number or an empty string if none
* exists yet.
*/
private void queryLastOutgoingCall() {
mLastNumberDialed = EMPTY_NUMBER;
CallLogAsync.GetLastOutgoingCallArgs lastCallArgs =
new CallLogAsync.GetLastOutgoingCallArgs(
getActivity(),
new CallLogAsync.OnLastOutgoingCallComplete() {
@Override
public void lastOutgoingCall(String number) {
// TODO: Filter out emergency numbers if
// the carrier does not want redial for
// these.
mLastNumberDialed = number;
updateDialAndDeleteButtonEnabledState();
}
});
mCallLog.getLastOutgoingCall(lastCallArgs);
}
private Intent newFlashIntent() {
final Intent intent = ContactsUtils.getCallIntent(EMPTY_NUMBER);
intent.putExtra(EXTRA_SEND_EMPTY_FLASH, true);
return intent;
}
}
| true | true | public void onPressed(View view, boolean pressed) {
if (DEBUG) Log.d(TAG, "onPressed(). view: " + view + ", pressed: " + pressed);
if (pressed) {
switch (view.getId()) {
case R.id.one: {
keyPressed(KeyEvent.KEYCODE_1);
break;
}
case R.id.two: {
keyPressed(KeyEvent.KEYCODE_2);
break;
}
case R.id.three: {
keyPressed(KeyEvent.KEYCODE_3);
break;
}
case R.id.four: {
keyPressed(KeyEvent.KEYCODE_4);
break;
}
case R.id.five: {
keyPressed(KeyEvent.KEYCODE_5);
break;
}
case R.id.six: {
keyPressed(KeyEvent.KEYCODE_6);
break;
}
case R.id.seven: {
keyPressed(KeyEvent.KEYCODE_7);
break;
}
case R.id.eight: {
keyPressed(KeyEvent.KEYCODE_8);
break;
}
case R.id.nine: {
keyPressed(KeyEvent.KEYCODE_9);
break;
}
case R.id.zero: {
keyPressed(KeyEvent.KEYCODE_0);
break;
}
case R.id.pound: {
keyPressed(KeyEvent.KEYCODE_POUND);
break;
}
case R.id.star: {
keyPressed(KeyEvent.KEYCODE_STAR);
break;
}
default: {
Log.wtf(TAG, "Unexpected onTouch(ACTION_DOWN) event from: " + view);
break;
}
}
mDialpadPressCount++;
} else {
view.jumpDrawablesToCurrentState();
mDialpadPressCount--;
if (mDialpadPressCount < 0) {
// This must be a very buggy situation in which the number of touch-down events
// don't match that of touch-up. We should tolerate the situation anyway.
Log.e(TAG, "mKeyPressCount become negative.");
stopTone();
mDialpadPressCount = 0;
} else if (mDialpadPressCount == 0) {
stopTone();
}
}
}
| public void onPressed(View view, boolean pressed) {
if (DEBUG) Log.d(TAG, "onPressed(). view: " + view + ", pressed: " + pressed);
if (pressed) {
switch (view.getId()) {
case R.id.one: {
keyPressed(KeyEvent.KEYCODE_1);
break;
}
case R.id.two: {
keyPressed(KeyEvent.KEYCODE_2);
break;
}
case R.id.three: {
keyPressed(KeyEvent.KEYCODE_3);
break;
}
case R.id.four: {
keyPressed(KeyEvent.KEYCODE_4);
break;
}
case R.id.five: {
keyPressed(KeyEvent.KEYCODE_5);
break;
}
case R.id.six: {
keyPressed(KeyEvent.KEYCODE_6);
break;
}
case R.id.seven: {
keyPressed(KeyEvent.KEYCODE_7);
break;
}
case R.id.eight: {
keyPressed(KeyEvent.KEYCODE_8);
break;
}
case R.id.nine: {
keyPressed(KeyEvent.KEYCODE_9);
break;
}
case R.id.zero: {
keyPressed(KeyEvent.KEYCODE_0);
break;
}
case R.id.pound: {
keyPressed(KeyEvent.KEYCODE_POUND);
break;
}
case R.id.star: {
keyPressed(KeyEvent.KEYCODE_STAR);
break;
}
default: {
Log.wtf(TAG, "Unexpected onTouch(ACTION_DOWN) event from: " + view);
break;
}
}
mDialpadPressCount++;
} else {
view.jumpDrawablesToCurrentState();
mDialpadPressCount--;
if (mDialpadPressCount < 0) {
// May happen when the user action is detected as horizontal swipe, at which only
// "up" event is thrown.
if (DEBUG) Log.d(TAG, "mKeyPressCount become negative.");
stopTone();
mDialpadPressCount = 0;
} else if (mDialpadPressCount == 0) {
stopTone();
}
}
}
|
diff --git a/assorted/src/main/java/com/id/misc/assorted/ConvertFile2URLDemo.java b/assorted/src/main/java/com/id/misc/assorted/ConvertFile2URLDemo.java
index 037b8d5..732aef2 100644
--- a/assorted/src/main/java/com/id/misc/assorted/ConvertFile2URLDemo.java
+++ b/assorted/src/main/java/com/id/misc/assorted/ConvertFile2URLDemo.java
@@ -1,24 +1,24 @@
package com.id.misc.assorted;
import java.io.File;
/**
* Be careful when converting File to URL.
* See Sun's bugs :
* <br>
* 4273532,
* <br>
* 6179468 - File.toURL() should be deprecated
* @author idanilov
*
*/
public class ConvertFile2URLDemo {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Documents and Settings");
// works improperly.
System.out.println("file.toURL() ----> " + file.toURL());
- // works normally escaping all special charaters.
+ // works normally. escaping all special characters.
System.out.println("file.toURI().toURL() ----> " + file.toURI().toURL());
}
}
| true | true | public static void main(String[] args) throws Exception {
File file = new File("C:\\Documents and Settings");
// works improperly.
System.out.println("file.toURL() ----> " + file.toURL());
// works normally escaping all special charaters.
System.out.println("file.toURI().toURL() ----> " + file.toURI().toURL());
}
| public static void main(String[] args) throws Exception {
File file = new File("C:\\Documents and Settings");
// works improperly.
System.out.println("file.toURL() ----> " + file.toURL());
// works normally. escaping all special characters.
System.out.println("file.toURI().toURL() ----> " + file.toURI().toURL());
}
|
diff --git a/source/de/anomic/http/httpdFileHandler.java b/source/de/anomic/http/httpdFileHandler.java
index e84bd3f90..0174b237f 100644
--- a/source/de/anomic/http/httpdFileHandler.java
+++ b/source/de/anomic/http/httpdFileHandler.java
@@ -1,810 +1,810 @@
// httpdFileHandler.java
// -----------------------
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004, 2005
// last major change: 05.10.2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
/*
Class documentation:
this class provides a file servlet and CGI interface
for the httpd server.
Whenever this server is addressed to load a local file,
this class searches for the file in the local path as
configured in the setting property 'rootPath'
The servlet loads the file and returns it to the client.
Every file can also act as an template for the built-in
CGI interface. There is no specific path for CGI functions.
CGI functionality is triggered, if for the file to-be-served
'template.html' also a file 'template.class' exists. Then,
the class file is called with the GET/POST properties that
are attached to the http call.
Possible variable hand-over are:
- form method GET
- form method POST, enctype text/plain
- form method POST, enctype multipart/form-data
The class that creates the CGI respond must have at least one
static method of the form
public static java.util.Hashtable respond(java.util.HashMap, serverSwitch)
In the HashMap, the GET/POST variables are handed over.
The return value is a Property object that contains replacement
key/value pairs for the patterns in the template file.
The templates must have the form
either '#['<name>']#' for single attributes, or
'#{'<enumname>'}#' and '#{/'<enumname>'}#' for enumerations of
values '#['<value>']#'.
A single value in repetitions/enumerations in the template has
the property key '_'<enumname><count>'_'<value>
Please see also the example files 'test.html' and 'test.java'
*/
package de.anomic.http;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.lang.ref.SoftReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaParser;
import de.anomic.server.serverByteBuffer;
import de.anomic.server.serverClassLoader;
import de.anomic.server.serverCodings;
import de.anomic.server.serverCore;
import de.anomic.server.serverFileUtils;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.server.logging.serverLog;
public final class httpdFileHandler extends httpdAbstractHandler implements httpdHandler {
// class variables
private static final Properties mimeTable = new Properties();
private static final serverClassLoader provider;
private static final HashMap templates = new HashMap();
private static serverSwitch switchboard;
private static File htRootPath = null;
private static File htDocsPath = null;
private static File htTemplatePath = null;
private static String[] defaultFiles = null;
private static File htDefaultPath = null;
private static File htLocalePath = null;
private MessageDigest md5Digest = null;
/**
* Template Cache
* @param switchboard
*/
private static final HashMap templateCache;
private static final HashMap templateMethodCache;
public static boolean useTemplateCache = false;
static {
useTemplateCache = plasmaSwitchboard.getSwitchboard().getConfig("enableTemplateCache","true").equalsIgnoreCase("true");
templateCache = (useTemplateCache)? new HashMap() : new HashMap(0);
templateMethodCache = (useTemplateCache) ? new HashMap() : new HashMap(0);
// create a class loader
provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);
}
public httpdFileHandler(serverSwitch switchboard) {
// creating a logger
this.theLogger = new serverLog("FILEHANDLER");
if (httpdFileHandler.switchboard == null) {
httpdFileHandler.switchboard = switchboard;
if (mimeTable.size() == 0) {
// load the mime table
String mimeTablePath = switchboard.getConfig("mimeConfig","");
BufferedInputStream mimeTableInputStream = null;
try {
serverLog.logConfig("HTTPDFiles", "Loading mime mapping file " + mimeTablePath);
mimeTableInputStream = new BufferedInputStream(new FileInputStream(new File(switchboard.getRootPath(), mimeTablePath)));
mimeTable.load(mimeTableInputStream);
} catch (Exception e) {
serverLog.logSevere("HTTPDFiles", "ERROR: path to configuration file or configuration invalid\n" + e);
System.exit(1);
} finally {
if (mimeTableInputStream != null) try { mimeTableInputStream.close(); } catch (Exception e1) {}
}
}
// create default files array
defaultFiles = switchboard.getConfig("defaultFiles","index.html").split(",");
if (defaultFiles.length == 0) defaultFiles = new String[] {"index.html"};
// create a htRootPath: system pages
if (htRootPath == null) {
htRootPath = new File(switchboard.getRootPath(), switchboard.getConfig("htRootPath","htroot"));
if (!(htRootPath.exists())) htRootPath.mkdir();
}
// create a htDocsPath: user defined pages
if (htDocsPath == null) {
htDocsPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDocsPath", "htdocs"));
if (!(htDocsPath.exists())) htDocsPath.mkdir();
}
// create a htTemplatePath
if (htTemplatePath == null) {
htTemplatePath = new File(switchboard.getRootPath(), switchboard.getConfig("htTemplatePath","htroot/env/templates"));
if (!(htTemplatePath.exists())) htTemplatePath.mkdir();
}
if (templates.size() == 0) templates.putAll(loadTemplates(htTemplatePath));
// create htLocaleDefault, htLocalePath
if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot"));
if (htLocalePath == null) htLocalePath = new File(switchboard.getRootPath(), switchboard.getConfig("htLocalePath","htroot/locale"));
//htLocaleSelection = switchboard.getConfig("htLocaleSelection","default");
}
// initialise an message digest for Content-MD5 support ...
try {
this.md5Digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
serverLog.logWarning("HTTPDFileHandler", "Content-MD5 support not availabel ...");
}
}
/*
* Returns the path of a (existing) localized File, or the english one, if not availible.
* @param path is relative from htroot
* @return the function returns a Filehandle to the translated file, or if not availitble to the english one.
*/
public static File getLocalizedFile(String path){
plasmaSwitchboard switchboard=plasmaSwitchboard.getSwitchboard();
// create htLocaleDefault, htLocalePath
if (htDefaultPath == null) htDefaultPath = new File(switchboard.getRootPath(), switchboard.getConfig("htDefaultPath","htroot"));
if (htLocalePath == null) htLocalePath = new File(switchboard.getRootPath(), switchboard.getConfig("htLocalePath","htroot/locale"));
//htLocaleSelection = switchboard.getConfig("htLocaleSelection","default");
// find locales or alternatives in htDocsPath
String htLocaleSelection = switchboard.getConfig("htLocaleSelection","default");
// look if we have a localization of that file
if (!(htLocaleSelection.equals("default"))) {
File localePath = new File(htLocalePath, htLocaleSelection + "/" + path);
if (localePath.exists())
return localePath;
}
return new File(htDefaultPath, path);
}
// private void textMessage(OutputStream out, int retcode, String body) throws IOException {
// httpd.sendRespondHeader(
// this.connectionProperties, // the connection properties
// out, // the output stream
// "HTTP/1.1", // the http version that should be used
// retcode, // the http status code
// null, // the http status message
// "text/plain", // the mimetype
// body.length(), // the content length
// httpc.nowDate(), // the modification date
// null, // the expires date
// null, // cookies
// null, // content encoding
// null); // transfer encoding
// out.write(body.getBytes());
// out.flush();
// }
private httpHeader getDefaultHeaders(String path) {
httpHeader headers = new httpHeader();
String ext;
int pos;
if ((pos = path.lastIndexOf('.')) < 0) {
ext = "";
} else {
ext = path.substring(pos + 1).toLowerCase();
}
headers.put(httpHeader.SERVER, "AnomicHTTPD (www.anomic.de)");
headers.put(httpHeader.DATE, httpc.dateString(httpc.nowDate()));
if(!(plasmaParser.mediaExtContains(ext))){
headers.put(httpHeader.PRAGMA, "no-cache");
}
return headers;
}
public void doGet(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException {
doResponse(conProp, requestHeader, response, null);
}
public void doHead(Properties conProp, httpHeader requestHeader, OutputStream response) throws IOException {
doResponse(conProp, requestHeader, response, null);
}
public void doPost(Properties conProp, httpHeader requestHeader, OutputStream response, PushbackInputStream body) throws IOException {
doResponse(conProp, requestHeader, response, body);
}
public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) throws IOException {
this.connectionProperties = conProp;
// getting some connection properties
String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
String url = "http://" + requestHeader.get(httpHeader.HOST,"localhost") + path;
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION);
String adminAccountBase64MD5 = switchboard.getConfig("adminAccountBase64MD5", "");
if ((path.endsWith("_p.html")) && (adminAccountBase64MD5.length() != 0)) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization.trim().substring(6)))) {
// Authentication successfull. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty("CLIENTIP"));
} else {
// a wrong authentication was given. Ask again
String clientIP = conProp.getProperty("CLIENTIP", "unknown-host");
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
Integer attempts = (Integer) serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// handle bfHost in case we have authentified correctly
if ((authorization != null) &&
(adminAccountBase64MD5.length() != 0) &&
(adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization.trim().substring(6))))) {
// remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
}
// parse arguments
serverObjects args = new serverObjects();
int argc;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length;
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
GZIPInputStream gzipBody = null;
if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) {
length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH));
} else if (requestHeader.gzip()) {
length = -1;
gzipBody = new GZIPInputStream(body);
} else {
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) {
// parse multipart
HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length);
// integrate these files into the args
if (files != null) {
Iterator fit = files.entrySet().iterator();
Map.Entry entry;
while (fit.hasNext()) {
entry = (Map.Entry) fit.next();
args.put(((String) entry.getKey()) + "$file", entry.getValue());
}
}
argc = Integer.parseInt((String) requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (argc > 0) {
// check all values for occurrences of script values
Enumeration e = args.elements(); // enumeration of values
Object val;
while (e.hasMoreElements()) {
val = e.nextElement();
if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
try {
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
File targetFile = getLocalizedFile(path);
String targetExt = conProp.getProperty("EXT","");
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getLocalizedFile(testpath);
targetClass = rewriteClassFile(new File(htDefaultPath, testpath));
if (!(targetFile.exists())){
targetFile = new File(htDocsPath, testpath);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
if (targetFile.exists()) {
path = testpath;
break;
}
}
}else{
- if (!(targetFile.exists())){
+ if (!(targetFile.exists()) && (!(path.endsWith("png")||path.endsWith("gif")))){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}else{
targetClass = rewriteClassFile(new File(htDefaultPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
Date targetDate;
if ((targetClass != null) && ((path.endsWith("png") || (path.endsWith("gif"))))) {
// call an image-servlet to produce an on-the-fly - generated image
BufferedImage bi = null;
try {
requestHeader.put("CLIENTIP", conProp.getProperty("CLIENTIP"));
requestHeader.put("PATH", path);
// in case that there are no args given, args = null or empty hashmap
bi = (BufferedImage) rewriteMethod(targetClass).invoke(null, new Object[] {requestHeader, args, switchboard});
} catch (InvocationTargetException e) {
this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (bi == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null);
} else {
// send an image to client
targetDate = new Date(System.currentTimeMillis());
String mimeType = mimeTable.getProperty(targetExt,"text/html");
// generate an byte array from the generated image
serverByteBuffer baos = new serverByteBuffer();
ImageIO.write(bi, targetExt, baos);
byte[] result = baos.toByteArray();
baos.close(); baos = null;
// write the array to the client
httpd.sendRespondHeader(this.connectionProperties, out, "HTTP/1.1", 200, null, mimeType, result.length, targetDate, null, null, null, null);
Thread.currentThread().sleep(200); // see below
serverFileUtils.write(result, out);
}
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
String mimeType = mimeTable.getProperty(targetExt,"text/html");
byte[] result;
boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
String md5String = null;
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac")) {
targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}
// call rewrite-class
serverObjects tp = new serverObjects();
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put("CLIENTIP", conProp.getProperty("CLIENTIP"));
requestHeader.put("PATH", path);
// in case that there are no args given, args = null or empty hashmap
tp = (serverObjects) rewriteMethod(targetClass).invoke(null, new Object[] {requestHeader, args, switchboard});
// if no args given , then tp will be an empty Hashtable object (not null)
if (tp == null) tp = new serverObjects();
// check if the servlets requests authentification
if (tp.containsKey("AUTHENTICATE")) {
// handle brute-force protection
if (authorization != null) {
String clientIP = conProp.getProperty("CLIENTIP", "unknown-host");
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
Integer attempts = (Integer) serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
}
// send authentication request to browser
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get("AUTHENTICATE", "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey("LOCATION")) {
String location = tp.get("LOCATION","");
if (location.length() == 0) location = path;
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put("version", switchboard.getConfig("version", ""));
tp.put("uptime", ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes
tp.put("clientname", switchboard.getConfig("peerName", "anomic"));
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
}
targetDate = new Date(System.currentTimeMillis());
}
// read templates
tp.putAll(templates);
// rewrite the file
serverByteBuffer o = null;
InputStream fis = null;
GZIPOutputStream zippedOut = null;
try {
// do fileCaching here
byte[] templateContent = null;
if (useTemplateCache) {
long fileSize = targetFile.length();
if (fileSize <= 512*1024) {
SoftReference ref = (SoftReference) templateCache.get(targetFile);
if (ref != null) {
templateContent = (byte[]) ref.get();
if (templateContent == null)
templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference(templateContent);
templateCache.put(targetFile,ref);
if (this.theLogger.isLoggable(Level.FINEST))
this.theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (this.theLogger.isLoggable(Level.FINEST))
this.theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
o = new serverByteBuffer();
if (zipContent) zippedOut = new GZIPOutputStream(o);
httpTemplate.writeTemplate(fis, (zipContent) ? (OutputStream)zippedOut: (OutputStream)o, tp, "-UNRESOLVED_PATTERN-".getBytes());
if (zipContent) {
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
}
result = o.toByteArray();
if (this.md5Digest != null) {
this.md5Digest.reset();
this.md5Digest.update(result);
byte[] digest = this.md5Digest.digest();
StringBuffer digestString = new StringBuffer();
for ( int i = 0; i < digest.length; i++ )
digestString.append(Integer.toHexString( digest[i]&0xff));
md5String = digestString.toString();
}
} finally {
if (zippedOut != null) try {zippedOut.close();} catch(Exception e) {}
if (o != null) try {o.close(); o = null;} catch(Exception e) {}
if (fis != null) try {fis.close(); fis=null;} catch(Exception e) {}
}
} else { // no html
// write the file to the client
targetDate = new Date(targetFile.lastModified());
result = (zipContent) ? serverFileUtils.readAndZip(targetFile) : serverFileUtils.read(targetFile);
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
// write the array to the client
httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, (zipContent)?"gzip":null, null);
Thread.currentThread().sleep(200); // this solved the message problem (!!)
serverFileUtils.write(result, out);
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
String httpStatusText = null;
StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, errorMessage.toString(),errorExc);
} else {
// otherwise we close the connection
this.forceConnectionClose();
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
this.theLogger.logWarning(errorMessage.toString(),e);
}
} catch (Exception ee) {
this.forceConnectionClose();
}
} finally {
try {out.flush();}catch (Exception e) {}
if (!(requestHeader.get(httpHeader.CONNECTION, "close").equals("keep-alive"))) {
// wait a little time until everything closes so that clients can read from the streams/sockets
try {Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
}
private void forceConnectionClose() {
if (this.connectionProperties != null) {
this.connectionProperties.setProperty(httpHeader.CONNECTION_PROP_PERSISTENT,"close");
}
}
private static HashMap loadTemplates(File path) {
// reads all templates from a path
// we use only the folder from the given file path
HashMap result = new HashMap();
if (path == null) return result;
if (!(path.isDirectory())) path = path.getParentFile();
if ((path == null) || (!(path.isDirectory()))) return result;
String[] templates = path.list();
int c;
for (int i = 0; i < templates.length; i++) {
if (templates[i].endsWith(".template"))
try {
//System.out.println("TEMPLATE " + templates[i].substring(0, templates[i].length() - 9) + ": " + new String(buf, 0, c));
result.put(templates[i].substring(0, templates[i].length() - 9),
new String(serverFileUtils.read(new File(path, templates[i]))));
} catch (Exception e) {}
}
return result;
}
private File rewriteClassFile(File template) {
try {
String f = template.getCanonicalPath();
int p = f.lastIndexOf(".");
if (p < 0) return null;
f = f.substring(0, p) + ".class";
//System.out.println("constructed class path " + f);
File cf = new File(f);
if (cf.exists()) return cf;
return null;
} catch (IOException e) {
return null;
}
}
private final Method rewriteMethod(File classFile) {
Method m = null;
long start = System.currentTimeMillis();
// now make a class out of the stream
try {
if (useTemplateCache) {
SoftReference ref = (SoftReference) templateMethodCache.get(classFile);
if (ref != null) {
m = (Method) ref.get();
if (m == null) {
templateMethodCache.remove(classFile);
} else {
this.theLogger.logFine("Cache HIT for file " + classFile);
return m;
}
}
}
//System.out.println("**DEBUG** loading class file " + classFile);
Class c = provider.loadClass(classFile);
Class[] params = new Class[] {
Class.forName("de.anomic.http.httpHeader"),
Class.forName("de.anomic.server.serverObjects"),
Class.forName("de.anomic.server.serverSwitch")};
m = c.getMethod("respond", params);
if (useTemplateCache) {
// storing the method into the cache
SoftReference ref = new SoftReference(m);
templateMethodCache.put(classFile,ref);
this.theLogger.logFine("Cache MISS for file " + classFile);
}
} catch (ClassNotFoundException e) {
System.out.println("INTERNAL ERROR: class " + classFile + " is missing:" + e.getMessage());
} catch (NoSuchMethodException e) {
System.out.println("INTERNAL ERROR: method respond not found in class " + classFile + ": " + e.getMessage());
}
//System.out.println("found method: " + m.toString());
return m;
}
public void doConnect(Properties conProp, httpHeader requestHeader, InputStream clientIn, OutputStream clientOut) {
throw new UnsupportedOperationException();
}
}
| true | true | public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) throws IOException {
this.connectionProperties = conProp;
// getting some connection properties
String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
String url = "http://" + requestHeader.get(httpHeader.HOST,"localhost") + path;
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION);
String adminAccountBase64MD5 = switchboard.getConfig("adminAccountBase64MD5", "");
if ((path.endsWith("_p.html")) && (adminAccountBase64MD5.length() != 0)) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization.trim().substring(6)))) {
// Authentication successfull. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty("CLIENTIP"));
} else {
// a wrong authentication was given. Ask again
String clientIP = conProp.getProperty("CLIENTIP", "unknown-host");
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
Integer attempts = (Integer) serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// handle bfHost in case we have authentified correctly
if ((authorization != null) &&
(adminAccountBase64MD5.length() != 0) &&
(adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization.trim().substring(6))))) {
// remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
}
// parse arguments
serverObjects args = new serverObjects();
int argc;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length;
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
GZIPInputStream gzipBody = null;
if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) {
length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH));
} else if (requestHeader.gzip()) {
length = -1;
gzipBody = new GZIPInputStream(body);
} else {
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) {
// parse multipart
HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length);
// integrate these files into the args
if (files != null) {
Iterator fit = files.entrySet().iterator();
Map.Entry entry;
while (fit.hasNext()) {
entry = (Map.Entry) fit.next();
args.put(((String) entry.getKey()) + "$file", entry.getValue());
}
}
argc = Integer.parseInt((String) requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (argc > 0) {
// check all values for occurrences of script values
Enumeration e = args.elements(); // enumeration of values
Object val;
while (e.hasMoreElements()) {
val = e.nextElement();
if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
try {
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
File targetFile = getLocalizedFile(path);
String targetExt = conProp.getProperty("EXT","");
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getLocalizedFile(testpath);
targetClass = rewriteClassFile(new File(htDefaultPath, testpath));
if (!(targetFile.exists())){
targetFile = new File(htDocsPath, testpath);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
if (targetFile.exists()) {
path = testpath;
break;
}
}
}else{
if (!(targetFile.exists())){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}else{
targetClass = rewriteClassFile(new File(htDefaultPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
Date targetDate;
if ((targetClass != null) && ((path.endsWith("png") || (path.endsWith("gif"))))) {
// call an image-servlet to produce an on-the-fly - generated image
BufferedImage bi = null;
try {
requestHeader.put("CLIENTIP", conProp.getProperty("CLIENTIP"));
requestHeader.put("PATH", path);
// in case that there are no args given, args = null or empty hashmap
bi = (BufferedImage) rewriteMethod(targetClass).invoke(null, new Object[] {requestHeader, args, switchboard});
} catch (InvocationTargetException e) {
this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (bi == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null);
} else {
// send an image to client
targetDate = new Date(System.currentTimeMillis());
String mimeType = mimeTable.getProperty(targetExt,"text/html");
// generate an byte array from the generated image
serverByteBuffer baos = new serverByteBuffer();
ImageIO.write(bi, targetExt, baos);
byte[] result = baos.toByteArray();
baos.close(); baos = null;
// write the array to the client
httpd.sendRespondHeader(this.connectionProperties, out, "HTTP/1.1", 200, null, mimeType, result.length, targetDate, null, null, null, null);
Thread.currentThread().sleep(200); // see below
serverFileUtils.write(result, out);
}
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
String mimeType = mimeTable.getProperty(targetExt,"text/html");
byte[] result;
boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
String md5String = null;
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac")) {
targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}
// call rewrite-class
serverObjects tp = new serverObjects();
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put("CLIENTIP", conProp.getProperty("CLIENTIP"));
requestHeader.put("PATH", path);
// in case that there are no args given, args = null or empty hashmap
tp = (serverObjects) rewriteMethod(targetClass).invoke(null, new Object[] {requestHeader, args, switchboard});
// if no args given , then tp will be an empty Hashtable object (not null)
if (tp == null) tp = new serverObjects();
// check if the servlets requests authentification
if (tp.containsKey("AUTHENTICATE")) {
// handle brute-force protection
if (authorization != null) {
String clientIP = conProp.getProperty("CLIENTIP", "unknown-host");
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
Integer attempts = (Integer) serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
}
// send authentication request to browser
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get("AUTHENTICATE", "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey("LOCATION")) {
String location = tp.get("LOCATION","");
if (location.length() == 0) location = path;
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put("version", switchboard.getConfig("version", ""));
tp.put("uptime", ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes
tp.put("clientname", switchboard.getConfig("peerName", "anomic"));
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
}
targetDate = new Date(System.currentTimeMillis());
}
// read templates
tp.putAll(templates);
// rewrite the file
serverByteBuffer o = null;
InputStream fis = null;
GZIPOutputStream zippedOut = null;
try {
// do fileCaching here
byte[] templateContent = null;
if (useTemplateCache) {
long fileSize = targetFile.length();
if (fileSize <= 512*1024) {
SoftReference ref = (SoftReference) templateCache.get(targetFile);
if (ref != null) {
templateContent = (byte[]) ref.get();
if (templateContent == null)
templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference(templateContent);
templateCache.put(targetFile,ref);
if (this.theLogger.isLoggable(Level.FINEST))
this.theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (this.theLogger.isLoggable(Level.FINEST))
this.theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
o = new serverByteBuffer();
if (zipContent) zippedOut = new GZIPOutputStream(o);
httpTemplate.writeTemplate(fis, (zipContent) ? (OutputStream)zippedOut: (OutputStream)o, tp, "-UNRESOLVED_PATTERN-".getBytes());
if (zipContent) {
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
}
result = o.toByteArray();
if (this.md5Digest != null) {
this.md5Digest.reset();
this.md5Digest.update(result);
byte[] digest = this.md5Digest.digest();
StringBuffer digestString = new StringBuffer();
for ( int i = 0; i < digest.length; i++ )
digestString.append(Integer.toHexString( digest[i]&0xff));
md5String = digestString.toString();
}
} finally {
if (zippedOut != null) try {zippedOut.close();} catch(Exception e) {}
if (o != null) try {o.close(); o = null;} catch(Exception e) {}
if (fis != null) try {fis.close(); fis=null;} catch(Exception e) {}
}
} else { // no html
// write the file to the client
targetDate = new Date(targetFile.lastModified());
result = (zipContent) ? serverFileUtils.readAndZip(targetFile) : serverFileUtils.read(targetFile);
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
// write the array to the client
httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, (zipContent)?"gzip":null, null);
Thread.currentThread().sleep(200); // this solved the message problem (!!)
serverFileUtils.write(result, out);
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
String httpStatusText = null;
StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, errorMessage.toString(),errorExc);
} else {
// otherwise we close the connection
this.forceConnectionClose();
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
this.theLogger.logWarning(errorMessage.toString(),e);
}
} catch (Exception ee) {
this.forceConnectionClose();
}
} finally {
try {out.flush();}catch (Exception e) {}
if (!(requestHeader.get(httpHeader.CONNECTION, "close").equals("keep-alive"))) {
// wait a little time until everything closes so that clients can read from the streams/sockets
try {Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
}
| public void doResponse(Properties conProp, httpHeader requestHeader, OutputStream out, InputStream body) throws IOException {
this.connectionProperties = conProp;
// getting some connection properties
String method = conProp.getProperty(httpHeader.CONNECTION_PROP_METHOD);
String path = conProp.getProperty(httpHeader.CONNECTION_PROP_PATH);
String argsString = conProp.getProperty(httpHeader.CONNECTION_PROP_ARGS); // is null if no args were given
String httpVersion= conProp.getProperty(httpHeader.CONNECTION_PROP_HTTP_VER);
String url = "http://" + requestHeader.get(httpHeader.HOST,"localhost") + path;
// check hack attacks in path
if (path.indexOf("..") >= 0) {
httpd.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
return;
}
// check permission/granted access
String authorization = (String) requestHeader.get(httpHeader.AUTHORIZATION);
String adminAccountBase64MD5 = switchboard.getConfig("adminAccountBase64MD5", "");
if ((path.endsWith("_p.html")) && (adminAccountBase64MD5.length() != 0)) {
// authentication required
if (authorization == null) {
// no authorization given in response. Ask for that
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization.trim().substring(6)))) {
// Authentication successfull. remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty("CLIENTIP"));
} else {
// a wrong authentication was given. Ask again
String clientIP = conProp.getProperty("CLIENTIP", "unknown-host");
serverLog.logInfo("HTTPD", "Wrong log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
Integer attempts = (Integer) serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"admin log-in\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
}
}
// handle bfHost in case we have authentified correctly
if ((authorization != null) &&
(adminAccountBase64MD5.length() != 0) &&
(adminAccountBase64MD5.equals(serverCodings.standardCoder.encodeMD5Hex(authorization.trim().substring(6))))) {
// remove brute-force flag
serverCore.bfHost.remove(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP));
}
// parse arguments
serverObjects args = new serverObjects();
int argc;
if (argsString == null) {
// no args here, maybe a POST with multipart extension
int length;
//System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
if (method.equals(httpHeader.METHOD_POST)) {
GZIPInputStream gzipBody = null;
if (requestHeader.containsKey(httpHeader.CONTENT_LENGTH)) {
length = Integer.parseInt((String) requestHeader.get(httpHeader.CONTENT_LENGTH));
} else if (requestHeader.gzip()) {
length = -1;
gzipBody = new GZIPInputStream(body);
} else {
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
// if its a POST, it can be either multipart or as args in the body
if ((requestHeader.containsKey(httpHeader.CONTENT_TYPE)) &&
(((String) requestHeader.get(httpHeader.CONTENT_TYPE)).toLowerCase().startsWith("multipart"))) {
// parse multipart
HashMap files = httpd.parseMultipart(requestHeader, args, (gzipBody!=null)?gzipBody:body, length);
// integrate these files into the args
if (files != null) {
Iterator fit = files.entrySet().iterator();
Map.Entry entry;
while (fit.hasNext()) {
entry = (Map.Entry) fit.next();
args.put(((String) entry.getKey()) + "$file", entry.getValue());
}
}
argc = Integer.parseInt((String) requestHeader.get("ARGC"));
} else {
// parse args in body
argc = httpd.parseArgs(args, (gzipBody!=null)?gzipBody:body, length);
}
} else {
// no args
argsString = null;
args = null;
argc = 0;
}
} else {
// simple args in URL (stuff after the "?")
argc = httpd.parseArgs(args, argsString);
}
// check for cross site scripting - attacks in request arguments
if (argc > 0) {
// check all values for occurrences of script values
Enumeration e = args.elements(); // enumeration of values
Object val;
while (e.hasMoreElements()) {
val = e.nextElement();
if ((val != null) && (val instanceof String) && (((String) val).indexOf("<script") >= 0)) {
// deny request
httpd.sendRespondError(conProp,out,4,403,null,"bad post values",null);
return;
}
}
}
// we are finished with parsing
// the result of value hand-over is in args and argc
if (path.length() == 0) {
httpd.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
out.flush();
return;
}
File targetClass=null;
try {
// locate the file
if (!(path.startsWith("/"))) path = "/" + path; // attach leading slash
File targetFile = getLocalizedFile(path);
String targetExt = conProp.getProperty("EXT","");
if (path.endsWith("/")) {
String testpath;
// attach default file name
for (int i = 0; i < defaultFiles.length; i++) {
testpath = path + defaultFiles[i];
targetFile = getLocalizedFile(testpath);
targetClass = rewriteClassFile(new File(htDefaultPath, testpath));
if (!(targetFile.exists())){
targetFile = new File(htDocsPath, testpath);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}
if (targetFile.exists()) {
path = testpath;
break;
}
}
}else{
if (!(targetFile.exists()) && (!(path.endsWith("png")||path.endsWith("gif")))){
targetFile = new File(htDocsPath, path);
targetClass = rewriteClassFile(new File(htDocsPath, path));
}else{
targetClass = rewriteClassFile(new File(htDefaultPath, path));
}
}
//File targetClass = rewriteClassFile(targetFile);
Date targetDate;
if ((targetClass != null) && ((path.endsWith("png") || (path.endsWith("gif"))))) {
// call an image-servlet to produce an on-the-fly - generated image
BufferedImage bi = null;
try {
requestHeader.put("CLIENTIP", conProp.getProperty("CLIENTIP"));
requestHeader.put("PATH", path);
// in case that there are no args given, args = null or empty hashmap
bi = (BufferedImage) rewriteMethod(targetClass).invoke(null, new Object[] {requestHeader, args, switchboard});
} catch (InvocationTargetException e) {
this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage() +
"; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'",e);
targetClass = null;
}
if (bi == null) {
// error with image generation; send file-not-found
httpd.sendRespondError(this.connectionProperties,out,3,404,"File not Found",null,null);
} else {
// send an image to client
targetDate = new Date(System.currentTimeMillis());
String mimeType = mimeTable.getProperty(targetExt,"text/html");
// generate an byte array from the generated image
serverByteBuffer baos = new serverByteBuffer();
ImageIO.write(bi, targetExt, baos);
byte[] result = baos.toByteArray();
baos.close(); baos = null;
// write the array to the client
httpd.sendRespondHeader(this.connectionProperties, out, "HTTP/1.1", 200, null, mimeType, result.length, targetDate, null, null, null, null);
Thread.currentThread().sleep(200); // see below
serverFileUtils.write(result, out);
}
} else if ((targetFile.exists()) && (targetFile.canRead())) {
// we have found a file that can be written to the client
// if this file uses templates, then we use the template
// re-write - method to create an result
String mimeType = mimeTable.getProperty(targetExt,"text/html");
byte[] result;
boolean zipContent = requestHeader.acceptGzip() && httpd.shallTransportZipped("." + conProp.getProperty("EXT",""));
String md5String = null;
if (path.endsWith("html") ||
path.endsWith("xml") ||
path.endsWith("rss") ||
path.endsWith("csv") ||
path.endsWith("pac")) {
targetFile = getLocalizedFile(path);
if (!(targetFile.exists())) {
// try to find that file in the htDocsPath
File trialFile = new File(htDocsPath, path);
if (trialFile.exists()) targetFile = trialFile;
}
// call rewrite-class
serverObjects tp = new serverObjects();
if (targetClass == null) {
targetDate = new Date(targetFile.lastModified());
} else {
// CGI-class: call the class to create a property for rewriting
try {
requestHeader.put("CLIENTIP", conProp.getProperty("CLIENTIP"));
requestHeader.put("PATH", path);
// in case that there are no args given, args = null or empty hashmap
tp = (serverObjects) rewriteMethod(targetClass).invoke(null, new Object[] {requestHeader, args, switchboard});
// if no args given , then tp will be an empty Hashtable object (not null)
if (tp == null) tp = new serverObjects();
// check if the servlets requests authentification
if (tp.containsKey("AUTHENTICATE")) {
// handle brute-force protection
if (authorization != null) {
String clientIP = conProp.getProperty("CLIENTIP", "unknown-host");
serverLog.logInfo("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
Integer attempts = (Integer) serverCore.bfHost.get(clientIP);
if (attempts == null)
serverCore.bfHost.put(clientIP, new Integer(1));
else
serverCore.bfHost.put(clientIP, new Integer(attempts.intValue() + 1));
}
// send authentication request to browser
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.WWW_AUTHENTICATE,"Basic realm=\"" + tp.get("AUTHENTICATE", "") + "\"");
httpd.sendRespondHeader(conProp,out,httpVersion,401,headers);
return;
} else if (tp.containsKey("LOCATION")) {
String location = tp.get("LOCATION","");
if (location.length() == 0) location = path;
httpHeader headers = getDefaultHeaders(path);
headers.put(httpHeader.LOCATION,location);
httpd.sendRespondHeader(conProp,out,httpVersion,302,headers);
return;
}
// add the application version, the uptime and the client name to every rewrite table
tp.put("version", switchboard.getConfig("version", ""));
tp.put("uptime", ((System.currentTimeMillis() - Long.parseLong(switchboard.getConfig("startupTime","0"))) / 1000) / 60); // uptime in minutes
tp.put("clientname", switchboard.getConfig("peerName", "anomic"));
//System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
} catch (InvocationTargetException e) {
if (e.getCause() instanceof InterruptedException) {
throw new InterruptedException(e.getCause().getMessage());
}
this.theLogger.logSevere("INTERNAL ERROR: " + e.toString() + ":" +
e.getMessage() +
" target exception at " + targetClass + ": " +
e.getTargetException().toString() + ":" +
e.getTargetException().getMessage(),e);
targetClass = null;
}
targetDate = new Date(System.currentTimeMillis());
}
// read templates
tp.putAll(templates);
// rewrite the file
serverByteBuffer o = null;
InputStream fis = null;
GZIPOutputStream zippedOut = null;
try {
// do fileCaching here
byte[] templateContent = null;
if (useTemplateCache) {
long fileSize = targetFile.length();
if (fileSize <= 512*1024) {
SoftReference ref = (SoftReference) templateCache.get(targetFile);
if (ref != null) {
templateContent = (byte[]) ref.get();
if (templateContent == null)
templateCache.remove(targetFile);
}
if (templateContent == null) {
// loading the content of the template file into a byte array
templateContent = serverFileUtils.read(targetFile);
// storing the content into the cache
ref = new SoftReference(templateContent);
templateCache.put(targetFile,ref);
if (this.theLogger.isLoggable(Level.FINEST))
this.theLogger.logFinest("Cache MISS for file " + targetFile);
} else {
if (this.theLogger.isLoggable(Level.FINEST))
this.theLogger.logFinest("Cache HIT for file " + targetFile);
}
// creating an inputstream needed by the template rewrite function
fis = new ByteArrayInputStream(templateContent);
templateContent = null;
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
} else {
fis = new BufferedInputStream(new FileInputStream(targetFile));
}
o = new serverByteBuffer();
if (zipContent) zippedOut = new GZIPOutputStream(o);
httpTemplate.writeTemplate(fis, (zipContent) ? (OutputStream)zippedOut: (OutputStream)o, tp, "-UNRESOLVED_PATTERN-".getBytes());
if (zipContent) {
zippedOut.finish();
zippedOut.flush();
zippedOut.close();
zippedOut = null;
}
result = o.toByteArray();
if (this.md5Digest != null) {
this.md5Digest.reset();
this.md5Digest.update(result);
byte[] digest = this.md5Digest.digest();
StringBuffer digestString = new StringBuffer();
for ( int i = 0; i < digest.length; i++ )
digestString.append(Integer.toHexString( digest[i]&0xff));
md5String = digestString.toString();
}
} finally {
if (zippedOut != null) try {zippedOut.close();} catch(Exception e) {}
if (o != null) try {o.close(); o = null;} catch(Exception e) {}
if (fis != null) try {fis.close(); fis=null;} catch(Exception e) {}
}
} else { // no html
// write the file to the client
targetDate = new Date(targetFile.lastModified());
result = (zipContent) ? serverFileUtils.readAndZip(targetFile) : serverFileUtils.read(targetFile);
// check mime type again using the result array: these are 'magics'
// if (serverByteBuffer.equals(result, 1, "PNG".getBytes())) mimeType = mimeTable.getProperty("png","text/html");
// else if (serverByteBuffer.equals(result, 0, "GIF89".getBytes())) mimeType = mimeTable.getProperty("gif","text/html");
// else if (serverByteBuffer.equals(result, 6, "JFIF".getBytes())) mimeType = mimeTable.getProperty("jpg","text/html");
//System.out.print("MAGIC:"); for (int i = 0; i < 10; i++) System.out.print(Integer.toHexString((int) result[i]) + ","); System.out.println();
}
// write the array to the client
httpd.sendRespondHeader(this.connectionProperties, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, (zipContent)?"gzip":null, null);
Thread.currentThread().sleep(200); // this solved the message problem (!!)
serverFileUtils.write(result, out);
} else {
httpd.sendRespondError(conProp,out,3,404,"File not Found",null,null);
return;
}
} catch (Exception e) {
try {
// doing some errorhandling ...
int httpStatusCode = 400;
String httpStatusText = null;
StringBuffer errorMessage = new StringBuffer();
Exception errorExc = null;
String errorMsg = e.getMessage();
if (
(e instanceof InterruptedException) ||
((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
) {
errorMessage.append("Interruption detected while processing query.");
httpStatusCode = 503;
} else {
if ((errorMsg != null) &&
(
errorMsg.startsWith("Broken pipe") ||
errorMsg.startsWith("Connection reset") ||
errorMsg.startsWith("Software caused connection abort")
)) {
// client closed the connection, so we just end silently
errorMessage.append("Client unexpectedly closed connection while processing query.");
} else if ((errorMsg != null) && (errorMsg.startsWith("Connection timed out"))) {
errorMessage.append("Connection timed out.");
} else {
errorMessage.append("Unexpected error while processing query.");
httpStatusCode = 500;
errorExc = e;
}
}
errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
.append("\nQuery: ").append(path)
.append("\nClient: ").append(conProp.getProperty(httpHeader.CONNECTION_PROP_CLIENTIP,"unknown"))
.append("\nReason: ").append(e.toString());
if (!conProp.containsKey(httpHeader.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
// sending back an error message to the client
// if we have not already send an http header
httpd.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, errorMessage.toString(),errorExc);
} else {
// otherwise we close the connection
this.forceConnectionClose();
}
// if it is an unexpected error we log it
if (httpStatusCode == 500) {
this.theLogger.logWarning(errorMessage.toString(),e);
}
} catch (Exception ee) {
this.forceConnectionClose();
}
} finally {
try {out.flush();}catch (Exception e) {}
if (!(requestHeader.get(httpHeader.CONNECTION, "close").equals("keep-alive"))) {
// wait a little time until everything closes so that clients can read from the streams/sockets
try {Thread.sleep(1000);} catch (InterruptedException e) {}
}
}
}
|
diff --git a/src/main/java/ch/iterate/openstack/swift/Client.java b/src/main/java/ch/iterate/openstack/swift/Client.java
index 1ecf117..7212532 100644
--- a/src/main/java/ch/iterate/openstack/swift/Client.java
+++ b/src/main/java/ch/iterate/openstack/swift/Client.java
@@ -1,1402 +1,1402 @@
/*
* See COPYING for license information.
*/
package ch.iterate.openstack.swift;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.*;
import ch.iterate.openstack.swift.exception.AuthorizationException;
import ch.iterate.openstack.swift.exception.ContainerExistsException;
import ch.iterate.openstack.swift.exception.ContainerNotEmptyException;
import ch.iterate.openstack.swift.exception.ContainerNotFoundException;
import ch.iterate.openstack.swift.exception.GenericException;
import ch.iterate.openstack.swift.exception.NotFoundException;
import ch.iterate.openstack.swift.handler.*;
import ch.iterate.openstack.swift.method.Authentication10UsernameKeyRequest;
import ch.iterate.openstack.swift.method.Authentication11UsernameKeyRequest;
import ch.iterate.openstack.swift.method.Authentication20UsernamePasswordRequest;
import ch.iterate.openstack.swift.method.AuthenticationRequest;
import ch.iterate.openstack.swift.model.AccountInfo;
import ch.iterate.openstack.swift.model.CDNContainer;
import ch.iterate.openstack.swift.model.Container;
import ch.iterate.openstack.swift.model.ContainerInfo;
import ch.iterate.openstack.swift.model.ContainerMetadata;
import ch.iterate.openstack.swift.model.ObjectMetadata;
import ch.iterate.openstack.swift.model.Region;
import ch.iterate.openstack.swift.model.StorageObject;
import org.json.simple.parser.JSONParser;
/**
* An OpenStack Swift client interface. Here follows a basic example of logging in, creating a container and an
* object, retrieving the object, and then deleting both the object and container. For more examples,
* see the code in com.iterate.openstack.cloudfiles.sample, which contains a series of examples.
* <p/>
* <pre>
*
* // Create the openstack object for username "jdoe", password "johnsdogsname".
* FilesClient myClient = FilesClient("jdoe", "johnsdogsname");
*
* // Log in (<code>login()</code> will return false if the login was unsuccessful.
* assert(myClient.login());
*
* // Make sure there are no containers in the account
* assert(myClient.listContainers.length() == 0);
*
* // Create the container
* assert(myClient.createContainer("myContainer"));
*
* // Now we should have one
* assert(myClient.listContainers.length() == 1);
*
* // Upload the file "alpaca.jpg"
* assert(myClient.storeObject("myContainer", new File("alapca.jpg"), "image/jpeg"));
*
* // Download "alpaca.jpg"
* FilesObject obj = myClient.getObject("myContainer", "alpaca.jpg");
* byte data[] = obj.getObject();
*
* // Clean up after ourselves.
* // Note: Order here is important, you can't delete non-empty containers.
* assert(myClient.deleteObject("myContainer", "alpaca.jpg"));
* assert(myClient.deleteContainer("myContainer");
* </pre>
*
* @author lvaughn
*/
public class Client {
private String username;
private String password;
private String tenantId;
private AuthVersion authVersion = AuthVersion.v10;
private URI authenticationURL;
private AuthenticationResponse authenticationResponse;
private HttpClient client;
/**
* @param connectionTimeOut The connection timeout, in ms.
*/
public Client(final int connectionTimeOut) {
this(new DefaultHttpClient() {
@Override
protected HttpParams createHttpParams() {
BasicHttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, connectionTimeOut);
return params;
}
@Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
schemeRegistry.register(
new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
return new PoolingClientConnectionManager(schemeRegistry);
}
});
}
/**
* @param client The HttpClient to talk to Swift
*/
public Client(HttpClient client) {
this.client = client;
}
/**
* Release all connections
*/
public void disconnect() {
this.client.getConnectionManager().shutdown();
}
public enum AuthVersion {
/**
* Legacy authentication. ReSTful calls no longer use HTTP headers for request or response parameters.
* Parameters are now sent via the XML or JSON message body.
*/
v10,
/**
* Legacy authentication. Service endpoint URLs are now capable of specifying a region.
*/
v11,
v20
}
/**
* @param authVersion Version
* @param authUrl Authentication endpoint of identity service
* @param username User or access key
* @param password Password or secret key
* @param tenantId Tenant or null
* @return Authentication response with supported regions and authentication token for subsequent requests
*/
public AuthenticationResponse authenticate(AuthVersion authVersion, URI authUrl, String username, String password, String tenantId) throws IOException {
this.authenticationURL = authUrl;
this.authVersion = authVersion;
this.username = username;
this.password = password;
this.tenantId = tenantId;
return this.authenticate();
}
protected AuthenticationResponse authenticate() throws IOException {
switch(authVersion) {
case v10:
default:
return this.authenticate(new Authentication10UsernameKeyRequest(authenticationURL, username, password));
case v11:
return this.authenticate(new Authentication11UsernameKeyRequest(authenticationURL, username, password));
case v20:
return this.authenticate(new Authentication20UsernamePasswordRequest(authenticationURL, username, password, tenantId));
}
}
public AuthenticationResponse authenticate(AuthenticationRequest request) throws IOException {
switch(request.getVersion()) {
case v10:
default:
return this.authenticate(request, new Authentication10ResponseHandler());
case v11:
return this.authenticate(request, new AuthenticationJson11ResponseHandler());
case v20:
return this.authenticate(request, new AuthenticationJson20ResponseHandler());
}
}
public AuthenticationResponse authenticate(AuthenticationRequest request,
ResponseHandler<AuthenticationResponse> handler) throws IOException {
return authenticationResponse = client.execute(request, handler);
}
public AuthenticationResponse getAuthentication() {
return authenticationResponse;
}
public Set<Region> getRegions() {
return authenticationResponse.getRegions();
}
public void setUserAgent(String userAgent) {
client.getParams().setParameter(HTTP.USER_AGENT, userAgent);
}
public String getUserAgent() {
return client.getParams().getParameter(HTTP.USER_AGENT).toString();
}
/**
* List all of the containers available in an account, ordered by container name.
*
* @return null if the user is not logged in or the Account is not found. A List of FSContainers with all of the containers in the account.
* if there are no containers in the account, the list will be zero length.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws ch.iterate.openstack.swift.exception.AuthorizationException
* The openstack's login was invalid.
*/
public List<ContainerInfo> listContainersInfo(Region region) throws IOException {
return listContainersInfo(region, -1, null);
}
/**
* List the containers available in an account, ordered by container name.
*
* @param limit The maximum number of containers to return. -1 returns an unlimited number.
* @return null if the user is not logged in or the Account is not found. A List of FSContainers with all of the containers in the account.
* if there are no containers in the account, the list will be zero length.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws ch.iterate.openstack.swift.exception.AuthorizationException
* The openstack's login was invalid.
*/
public List<ContainerInfo> listContainersInfo(Region region, int limit) throws IOException {
return listContainersInfo(region, limit, null);
}
/**
* List the containers available in an account, ordered by container name.
*
* @param limit The maximum number of containers to return. -1 returns an unlimited number.
* @param marker Return containers that occur after this lexicographically.
* @return null if the user is not logged in or the Account is not found. A List of FSContainers with all of the containers in the account.
* if there are no containers in the account, the list will be zero length.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws ch.iterate.openstack.swift.exception.AuthorizationException
* The openstack's login was invalid.
*/
public List<ContainerInfo> listContainersInfo(Region region, int limit, String marker) throws IOException {
LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
if(limit > 0) {
parameters.add(new BasicNameValuePair("limit", String.valueOf(limit)));
}
if(marker != null) {
parameters.add(new BasicNameValuePair("marker", marker));
}
parameters.add(new BasicNameValuePair("format", "xml"));
HttpGet method = new HttpGet(region.getStorageUrl(parameters));
return this.execute(method, new ContainerInfoResponseHandler(region));
}
/**
* List the containers available in an account.
*
* @return null if the user is not logged in or the Account is not found. A List of FilesContainer with all of the containers in the account.
* if there are no containers in the account, the list will be zero length.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws ch.iterate.openstack.swift.exception.AuthorizationException
* The openstack's login was invalid.
*/
public List<Container> listContainers(Region region) throws IOException {
return listContainers(region, -1, null);
}
/**
* List the containers available in an account.
*
* @param limit The maximum number of containers to return. -1 denotes no limit.
* @return null if the user is not logged in or the Account is not found. A List of FilesContainer with all of the containers in the account.
* if there are no containers in the account, the list will be zero length.
* @throws IOException There was an IO error doing network communication
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws ch.iterate.openstack.swift.exception.AuthorizationException
* The openstack's login was invalid.
*/
public List<Container> listContainers(Region region, int limit) throws IOException {
return listContainers(region, limit, null);
}
/**
* List the containers available in an account.
*
* @param limit The maximum number of containers to return. -1 denotes no limit.
* @param marker Only return containers after this container. Null denotes starting at the beginning (lexicographically).
* @return A List of FilesContainer with all of the containers in the account.
* if there are no containers in the account, the list will be zero length.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws ch.iterate.openstack.swift.exception.AuthorizationException
* The openstack's login was invalid.
*/
public List<Container> listContainers(Region region, int limit, String marker) throws IOException {
LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
if(limit > 0) {
parameters.add(new BasicNameValuePair("limit", String.valueOf(limit)));
}
if(marker != null) {
parameters.add(new BasicNameValuePair("marker", marker));
}
HttpGet method = new HttpGet(region.getStorageUrl(parameters));
return this.execute(method, new ContainerResponseHandler(region));
}
private Response execute(final HttpRequestBase method) throws IOException {
try {
method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
try {
return new DefaultResponseHandler().handleResponse(client.execute(method));
}
catch(AuthorizationException e) {
method.abort();
authenticationResponse = this.authenticate();
method.reset();
// Add new auth token retrieved
method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
// Retry
return new DefaultResponseHandler().handleResponse(client.execute(method));
}
}
catch(IOException e) {
// In case of an IOException the connection will be released back to the connection manager automatically
method.abort();
throw e;
}
}
private <T> T execute(final HttpRequestBase method, ResponseHandler<T> handler) throws IOException {
try {
method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
try {
return client.execute(method, handler);
}
catch(AuthorizationException e) {
method.abort();
authenticationResponse = this.authenticate();
method.reset();
// Add new auth token retrieved
method.setHeader(Constants.X_AUTH_TOKEN, authenticationResponse.getAuthToken());
// Retry
return client.execute(method, handler);
}
}
catch(IOException e) {
// In case of an IOException the connection will be released back to the connection manager automatically
method.abort();
throw e;
}
finally {
method.reset();
}
}
/**
* List all of the objects in a container with the given starting string.
*
* @param container The container name
* @param startsWith The string to start with
* @param path Only look for objects in this path
* @param limit Return at most <code>limit</code> objects
* @param marker Returns objects lexicographically greater than <code>marker</code>. Used in conjunction with <code>limit</code> to paginate the list.
* @return A list of FilesObjects starting with the given string
* @throws IOException There was an IO error doing network communication
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjectsStartingWith(Region region, String container,
String startsWith, String path, int limit, String marker) throws IOException {
return listObjectsStartingWith(region, container, startsWith, path, limit, marker, null);
}
/**
* List all of the objects in a container with the given starting string.
*
* @param container The container name
* @param startsWith The string to start with
* @param path Only look for objects in this path
* @param limit Return at most <code>limit</code> objects
* @param marker Returns objects lexicographically greater than <code>marker</code>. Used in conjunction with <code>limit</code> to paginate the list.
* @param delimiter Use this argument as the delimiter that separates "directories"
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjectsStartingWith(Region region, String container, String startsWith, String path, int limit, String marker, Character delimiter) throws IOException {
LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair("format", "xml"));
if(startsWith != null) {
parameters.add(new BasicNameValuePair("prefix", startsWith));
}
if(path != null) {
parameters.add(new BasicNameValuePair("path", path));
}
if(limit > 0) {
parameters.add(new BasicNameValuePair("limit", String.valueOf(limit)));
}
if(marker != null) {
parameters.add(new BasicNameValuePair("marker", marker));
}
if(delimiter != null) {
parameters.add(new BasicNameValuePair("delimiter", delimiter.toString()));
}
HttpGet method = new HttpGet(region.getStorageUrl(container, parameters));
return this.execute(method, new ObjectResponseHandler());
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjects(Region region, String container) throws IOException {
return listObjectsStartingWith(region, container, null, null, -1, null, null);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param delimiter Use this argument as the delimiter that separates "directories"
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjects(Region region, String container, Character delimiter) throws IOException {
return listObjectsStartingWith(region, container, null, null, -1, null, delimiter);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param limit Return at most <code>limit</code> objects
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjects(Region region, String container, int limit) throws IOException {
return listObjectsStartingWith(region, container, null, null, limit, null, null);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param path Only look for objects in this path
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException
*/
public List<StorageObject> listObjects(Region region, String container, String path) throws IOException {
return listObjectsStartingWith(region, container, null, path, -1, null, null);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param path Only look for objects in this path
* @param delimiter Use this argument as the delimiter that separates "directories"
* @return A list of FilesObjects starting with the given string
* @throws IOException There was an IO error doing network communication
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException
*/
public List<StorageObject> listObjects(Region region, String container, String path, Character delimiter) throws IOException {
return listObjectsStartingWith(region, container, null, path, -1, null, delimiter);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param path Only look for objects in this path
* @param limit Return at most <code>limit</code> objects
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjects(Region region, String container, String path, int limit) throws IOException {
return listObjectsStartingWith(region, container, null, path, limit, null);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param path Only look for objects in this path
* @param limit Return at most <code>limit</code> objects
* @param marker Returns objects lexicographically greater than <code>marker</code>. Used in conjunction with <code>limit</code> to paginate the list.
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException
*/
public List<StorageObject> listObjects(Region region, String container, String path, int limit, String marker) throws IOException {
return listObjectsStartingWith(region, container, null, path, limit, marker);
}
/**
* List the objects in a container in lexicographic order.
*
* @param container The container name
* @param limit Return at most <code>limit</code> objects
* @param marker Returns objects lexicographically greater than <code>marker</code>. Used in conjunction with <code>limit</code> to paginate the list.
* @return A list of FilesObjects starting with the given string
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public List<StorageObject> listObjects(Region region, String container, int limit, String marker) throws IOException {
return listObjectsStartingWith(region, container, null, null, limit, marker);
}
/**
* Convenience method to test for the existence of a container in Cloud Files.
*
* @param container Container name
* @return true if the container exists. false otherwise.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
*/
public boolean containerExists(Region region, String container) throws IOException {
try {
this.getContainerInfo(region, container);
return true;
}
catch(ContainerNotFoundException notfound) {
return false;
}
}
/**
* Gets information for the given account.
*
* @return The FilesAccountInfo with information about the number of containers and number of bytes used
* by the given account.
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack's login was invalid.
*/
public AccountInfo getAccountInfo(Region region) throws IOException {
HttpHead method = new HttpHead(region.getStorageUrl());
return this.execute(method, new AccountInfoHandler());
}
/**
* Get basic information on a container (number of items and the total size).
*
* @param container The container to get information for
* @return ContainerInfo object of the container is present or null if its not present
* @throws ch.iterate.openstack.swift.exception.GenericException
* There was an protocol level exception while talking to Cloudfiles
* @throws ch.iterate.openstack.swift.exception.NotFoundException
* The container was not found
* @throws AuthorizationException The openstack was not logged in or the log in expired.
*/
public ContainerInfo getContainerInfo(Region region, String container) throws IOException {
HttpHead method = new HttpHead(region.getStorageUrl(container));
return this.execute(method, new ContainerInfoHandler(region, container));
}
/**
* Creates a container
*
* @param name The name of the container to be created
* @throws ch.iterate.openstack.swift.exception.GenericException
* Unexpected response
* @throws AuthorizationException The openstack was not property logged in
*/
public void createContainer(Region region, String name) throws IOException {
HttpPut method = new HttpPut(region.getStorageUrl(name));
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
return;
}
else if(response.getStatusCode() == HttpStatus.SC_ACCEPTED) {
throw new ContainerExistsException(response);
}
else {
throw new GenericException(response);
}
}
/**
* Deletes a container
*
* @param name The name of the container
* @throws GenericException Unexpected response
* @throws AuthorizationException The user is not Logged in
* @throws ch.iterate.openstack.swift.exception.NotFoundException
* The container doesn't exist
* @throws ch.iterate.openstack.swift.exception.ContainerNotEmptyException
* The container was not empty
*/
public void deleteContainer(Region region, String name) throws IOException {
HttpDelete method = new HttpDelete(region.getStorageUrl(name));
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CONFLICT) {
throw new ContainerNotEmptyException(response);
}
}
/**
* Enables access of files in this container via the Content Delivery Network.
*
* @param name The name of the container to enable
* @return The CDN Url of the container
* @throws IOException There was an IO error doing network communication
* @throws GenericException Unexpected response
*/
public String cdnEnableContainer(Region region, String name) throws IOException {
HttpPut method = new HttpPut(region.getCDNManagementUrl(name));
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED || response.getStatusCode() == HttpStatus.SC_ACCEPTED) {
return response.getResponseHeader(Constants.X_CDN_URI).getValue();
}
else {
throw new GenericException(response);
}
}
public String cdnUpdateContainer(Region region, String name, int ttl, boolean enabled, boolean retainLogs)
throws IOException {
return cdnUpdateContainer(region, name, ttl, enabled, null, null, retainLogs);
}
/**
* Enables access of files in this container via the Content Delivery Network.
*
* @param name The name of the container to enable
* @param ttl How long the CDN can use the content before checking for an update. A negative value will result in this not being changed.
* @param enabled True if this container should be accessible, false otherwise
* @param referrerAcl ACL
* @param userAgentACL ACL
* @param retainLogs True if cdn access logs should be kept for this container, false otherwise
* @return The CDN Url of the container
* @throws GenericException Unexpected response
*/
/*
* @param referrerAcl Unused for now
* @param userAgentACL Unused for now
*/
private String cdnUpdateContainer(Region region, String name, int ttl, boolean enabled, String referrerAcl, String userAgentACL, boolean retainLogs)
throws IOException {
HttpPost method = new HttpPost(region.getCDNManagementUrl(name));
if(ttl > 0) {
method.setHeader(Constants.X_CDN_TTL, Integer.toString(ttl));
}
method.setHeader(Constants.X_CDN_ENABLED, Boolean.toString(enabled));
method.setHeader(Constants.X_CDN_RETAIN_LOGS, Boolean.toString(retainLogs));
if(referrerAcl != null) {
method.setHeader(Constants.X_CDN_REFERRER_ACL, referrerAcl);
}
if(userAgentACL != null) {
method.setHeader(Constants.X_CDN_USER_AGENT_ACL, userAgentACL);
}
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_ACCEPTED) {
return response.getResponseHeader(Constants.X_CDN_URI).getValue();
}
else {
throw new GenericException(response);
}
}
/**
* Gets current CDN sharing status of the container
*
* @param container Container
* @return Information on the container
* @throws GenericException Unexpected response
* @throws ch.iterate.openstack.swift.exception.NotFoundException
* The Container has never been CDN enabled
*/
public CDNContainer getCDNContainerInfo(Region region, String container) throws IOException {
HttpHead method = new HttpHead(region.getCDNManagementUrl(container));
return this.execute(method, new CdnContainerInfoHandler(region, container));
}
/**
* Gets current CDN sharing status of the container
*
* @param container Container name
* @return Information on the container
* @throws GenericException Unexpected response
* @throws ch.iterate.openstack.swift.exception.NotFoundException
* The Container has never been CDN enabled
*/
public boolean isCDNEnabled(Region region, String container) throws IOException {
final CDNContainer info = this.getCDNContainerInfo(region, container);
return info.isEnabled();
}
/**
* Creates a path (but not any of the sub portions of the path)
*
* @param container The name of the container.
* @param path The name of the Path
* @throws GenericException Unexpected response
*/
public void createPath(Region region, String container, String path) throws IOException {
this.storeObject(region, container, new ByteArrayInputStream(new byte[]{}), "application/directory", path,
new HashMap<String, String>());
}
/**
* Purges all items from a given container from the CDN
*
* @param container The name of the container
* @param emailAddresses An optional comma separated list of email addresses to be notified when the purge is complete.
* <code>null</code> if desired.
* @throws AuthorizationException Log in was not successful, or account is suspended
* @throws GenericException Unexpected response
*/
public void purgeCDNContainer(Region region, String container, String emailAddresses) throws IOException {
HttpDelete method = new HttpDelete(region.getCDNManagementUrl(container));
if(emailAddresses != null) {
method.setHeader(Constants.X_PURGE_EMAIL, emailAddresses);
}
this.execute(method, new DefaultResponseHandler());
}
/**
* Purges all items from a given container from the CDN
*
* @param container The name of the container
* @param object The name of the object
* @param emailAddresses An optional comma separated list of email addresses to be notified when the purge is complete.
* <code>null</code> if desired.
* @throws GenericException Unexpected response
* @throws AuthorizationException Log in was not successful, or account is suspended
*/
public void purgeCDNObject(Region region, String container, String object, String emailAddresses) throws IOException {
HttpDelete method = new HttpDelete(region.getCDNManagementUrl(container, object));
if(emailAddresses != null) {
method.setHeader(Constants.X_PURGE_EMAIL, emailAddresses);
}
this.execute(method, new DefaultResponseHandler());
}
/**
* Gets list of all of the containers associated with this account.
*
* @return A list of containers
* @throws GenericException Unexpected response
*/
public List<CDNContainer> listCdnContainerInfo(Region region) throws IOException {
return listCdnContainerInfo(region, -1, null);
}
/**
* Gets list of all of the containers associated with this account.
*
* @param limit The maximum number of container names to return
* @return A list of containers
* @throws GenericException Unexpected response
*/
public List<CDNContainer> listCdnContainerInfo(Region region, int limit) throws IOException {
return listCdnContainerInfo(region, limit, null);
}
/**
* Gets list of all of the containers associated with this account.
*
* @param limit The maximum number of container names to return
* @param marker All of the names will come after <code>marker</code> lexicographically.
* @return A list of containers
* @throws GenericException Unexpected response
*/
public List<CDNContainer> listCdnContainerInfo(Region region, int limit, String marker) throws IOException {
LinkedList<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("format", "xml"));
if(limit > 0) {
params.add(new BasicNameValuePair("limit", String.valueOf(limit)));
}
if(marker != null) {
params.add(new BasicNameValuePair("marker", marker));
}
HttpGet method = new HttpGet(region.getCDNManagementUrl(params));
return this.execute(method, new CdnContainerInfoListHandler(region));
}
/**
* Create a manifest on the server, including metadata
*
* @param container The name of the container
* @param contentType The MIME type of the file
* @param name The name of the file on the server
* @param manifest Set manifest content here
* @return True if response code is 201
* @throws GenericException Unexpected response
*/
public boolean createManifestObject(Region region, String container, String contentType, String name, String manifest) throws IOException {
return createManifestObject(region, container, contentType, name, manifest, new HashMap<String, String>());
}
/**
* Create a manifest on the server, including metadata
*
* @param container The name of the container
* @param contentType The MIME type of the file
* @param name The name of the file on the server
* @param manifest Set manifest content here
* @param metadata A map with the metadata as key names and values as the metadata values
* @return True if response code is 201
* @throws GenericException Unexpected response
*/
public boolean createManifestObject(Region region, String container, String contentType, String name, String manifest, Map<String, String> metadata) throws IOException {
byte[] arr = new byte[0];
HttpPut method = new HttpPut(region.getStorageUrl(container, name));
method.setHeader(Constants.MANIFEST_HEADER, manifest);
ByteArrayEntity entity = new ByteArrayEntity(arr);
entity.setContentType(contentType);
method.setEntity(entity);
for(Map.Entry<String, String> key : this.renameObjectMetadata(metadata).entrySet()) {
method.setHeader(key.getKey(), key.getValue());
}
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
return true;
}
else {
throw new GenericException(response);
}
}
/**
* Store a file on the server, including metadata, with the contents coming from an input stream. This allows you to
* not know the entire length of your content when you start to write it. Nor do you have to hold it entirely in memory
* at the same time.
*
* @param container The name of the container
* @param data Any object that implements InputStream
* @param contentType The MIME type of the file
* @param name The name of the file on the server
* @param metadata A map with the metadata as key names and values as the metadata values
* @return True if response code is 201
* @throws GenericException Unexpected response
*/
public String storeObject(Region region, String container, InputStream data, String contentType, String name, Map<String, String> metadata) throws IOException {
HttpPut method = new HttpPut(region.getStorageUrl(container, name));
InputStreamEntity entity = new InputStreamEntity(data, -1);
entity.setChunked(true);
entity.setContentType(contentType);
method.setEntity(entity);
for(Map.Entry<String, String> key : this.renameObjectMetadata(metadata).entrySet()) {
method.setHeader(key.getKey(), key.getValue());
}
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
return response.getResponseHeader(HttpHeaders.ETAG).getValue();
}
else {
throw new GenericException(response);
}
}
/**
* @param container The name of the container
* @param name The name of the object
* @param entity The name of the request entity (make sure to set the Content-Type
* @param metadata The metadata for the object
* @param md5sum The 32 character hex encoded MD5 sum of the data
* @return The ETAG if the save was successful, null otherwise
* @throws GenericException There was a protocol level error talking to CloudFiles
*/
public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum) throws IOException {
HttpPut method = new HttpPut(region.getStorageUrl(container, name));
method.setEntity(entity);
if(md5sum != null) {
method.setHeader(HttpHeaders.ETAG, md5sum);
}
method.setHeader(entity.getContentType());
for(Map.Entry<String, String> key : this.renameObjectMetadata(metadata).entrySet()) {
method.setHeader(key.getKey(), key.getValue());
}
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
return response.getResponseHeader(HttpHeaders.ETAG).getValue();
}
else {
throw new GenericException(response);
}
}
/**
* @param container The name of the container
* @param name The name of the object
* @param entity The name of the request entity (make sure to set the Content-Type
* @param metadata The metadata for the object
* @param md5sum The 32 character hex encoded MD5 sum of the data
* @param objectSize The total size in bytes of the object to be stored
* @param segmentSize Optional size in bytes of the object segments to be stored (forces large object support) default 4G
* @param dynamicLargeObject Optional setting to use dynamic large objects, False/null will use static large objects if required
* @param segmentContainer Optional name of container to store file segments, defaults to storing chunks in the same container as the file sill appear
* @param segmentFolder Optional name of folder for storing file segments, defaults to ".chunks/"
* @param leaveSegments Optional setting to leave segments of large objects in place when the manifest is overwrtten/changed
* @return The ETAG if the save was successful, null otherwise
* @throws GenericException There was a protocol level error talking to CloudFiles
*/
public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum, Long objectSize,
Long segmentSize, Boolean dynamicLargeObject, String segmentContainer, String segmentFolder, Boolean leaveSegments) throws IOException, InterruptedException {
/*
* Default values for large object support. We also use
* the defaults combined with the inputs to determine whether
* to store as a large object.
*/
System.out.println("Region: " + region);
System.out.println("Container: " + container);
System.out.println("Name: " + name);
// The maximum size of a single object
long singleObjectSizeLimit = (long)(5 * Math.pow(1024, 3));
// The default minimum segment size
long minSegmentSize = 1024L*1024L;
// Set the segment size if specified,
long actualSegmentSize = (segmentSize == null) ? (long)(4 * Math.pow(1024, 3)) : Math.max(segmentSize, minSegmentSize);
// Use large objects if a segmentSize has been specified and the object size exceeds it
// or if the objectSize is larger than the single object size limit of ~5GiB
boolean useLargeObject = ((segmentSize != null) && (objectSize > actualSegmentSize)) // segmentSize specified, and objectSize large enough
|| (objectSize > singleObjectSizeLimit) // objectSize is larger than the maximum single object size limit
|| ((segmentSize != null) && (objectSize == null)); // segmentSize is specified, but objectSize is not.
// Trust the user that their data is large enough!
// They may get a "large object" with a single segment or a failure
// because their data is smaller than the minimum segment size
if (!useLargeObject) {
return storeObject(region, container, name, entity, metadata, md5sum);
} else {
/*
* We need to upload a large object as defined by the method
* parameters. For now this is done sequentially, but a parallel
* version using appropriate random access to the underlying data
* may be desirable.
*
* We make the assumption that the given file size will not be
* greater than int.MAX_VALUE * segmentSize
*
*/
leaveSegments = (leaveSegments == null) ? Boolean.FALSE : leaveSegments;
dynamicLargeObject = (dynamicLargeObject == null) ? Boolean.FALSE : dynamicLargeObject;
segmentFolder = (segmentFolder == null) ? ".file-segments" : segmentFolder;
segmentContainer = (segmentContainer == null) ? container : segmentContainer;
Map<String, List<StorageObject>> oldSegmentsToRemove = null;
// Deal with existing objects if necessary
if (!leaveSegments){
ObjectMetadata existingMetadata;
String manifestDLO = null;
Boolean manifestSLO = Boolean.FALSE;
try {
existingMetadata = getObjectMetaData(region, container, name);
if (existingMetadata.getMetaData().containsKey(Constants.MANIFEST_HEADER)) {
manifestDLO = existingMetadata.getMetaData().get(Constants.MANIFEST_HEADER);
} else if (existingMetadata.getMetaData().containsKey(Constants.X_STATIC_LARGE_OBJECT)) {
JSONParser parser = new JSONParser();
String manifestSLOValue = existingMetadata.getMetaData().get(Constants.X_STATIC_LARGE_OBJECT);
manifestSLO = (Boolean) parser.parse(manifestSLOValue);
}
} catch (NotFoundException e) {
// Just means no object exists already, so carry on
} catch (ParseException e) {
// X_STATIC_LARGE_OBJECT header existed but failed to parse
// for an SLO this must be set to "true", therefore fail upload
return null;
}
if (manifestDLO != null) {
// We have found an existing dynamic large object, so use the prefix to get a list of existing objects
// if we're putting up a new dlo, make sure the segment prefixes are different
// then we can delete anything that's not in the new list
String oldContainer = manifestDLO.substring(0,manifestDLO.indexOf('/', 1));
String oldPath = manifestDLO.substring(manifestDLO.indexOf('/', 1),manifestDLO.length());
oldSegmentsToRemove = new HashMap<String, List<StorageObject>>();
oldSegmentsToRemove.put(oldContainer, listObjects(region, oldContainer, oldPath));
} else if (manifestSLO) {
// We have found an existing static large object, so grab the manifest data that
// details the existing segments - delete any later that we don't need any more
}
}
int segmentNumber = 1;
long timeStamp = System.currentTimeMillis() / 1000L;
String segmentBase = String.format("%s/%d/%d" , segmentFolder, timeStamp, objectSize);
// Create substream from the entity inputstream
// loop creating objects using the substreams
boolean finished = false;
//InputStream contentStream = entity.getContent();
final PipedInputStream contentInStream = new PipedInputStream(64*1024);
final PipedOutputStream contentOutStream = new PipedOutputStream(contentInStream);
- SubInputStream segmentStream = new SubInputStream(contentInStream, actualSegmentSize+2, false);
+ SubInputStream segmentStream = new SubInputStream(contentInStream, actualSegmentSize, false);
//CheckedInputStream segmentStream2 = new CheckedInputStream(contentInStream);// SubInputStream(contentInStream, actualSegmentSize+2, false);
// Fork the call to entity.writeTo() that allows us to grab any exceptions raised
final HttpEntity e = entity;
final Callable<Boolean> writer = new Callable<Boolean>() {
public Boolean call() throws Exception {
e.writeTo(contentOutStream);
return Boolean.TRUE;
}
};
ExecutorService writeExecutor = Executors.newSingleThreadExecutor();
final Future<Boolean> future = writeExecutor.submit(writer);
// Check the future for exceptions after we've finished upoading segments
Map<String, List<StorageObject>> newSegmentsAdded = new HashMap<String, List<StorageObject>>();
List<StorageObject> newSegments = new LinkedList<StorageObject>();
JSONArray manifestSLO = new JSONArray();
while (!finished) {
String segmentName = String.format("%s/%08d", segmentBase, segmentNumber);
// Upload the segment and record the following information
// * ETAG returned by the simple upload
// * total size of segment uploaded
// * path of segment
String etag = "";
boolean error = false;
try {
etag = storeObject(region, segmentContainer, segmentStream, "application/octet-stream", segmentName, new HashMap<String,String>());
} catch (IOException ex) {
// Finished storing the object
System.out.println("Caught IO Exception: " + ex.getMessage());
ex.printStackTrace();
throw ex;
}
String segmentPath = segmentContainer + "/" + segmentName;
long bytesUploaded = segmentStream.getBytesProduced();
// Create the appropriate manifest structure if we're making an SLO
if (!dynamicLargeObject) {
JSONObject segmentJSON = new JSONObject();
segmentJSON.put("path", segmentPath);
segmentJSON.put("etag", etag);
segmentJSON.put("size_bytes", bytesUploaded);
// append the segment to the segment list maintaining the order
manifestSLO.add(segmentJSON);
newSegments.add(new StorageObject(segmentName));
}
segmentNumber++;
if (!finished) {
finished = segmentStream.endSourceReached();
}
newSegmentsAdded.put(segmentContainer, newSegments);
System.out.println("JSON: " + manifestSLO.toString());
if (error) return "";
segmentStream.readMoreBytes(actualSegmentSize);
}
// Did the writing to the stream work?
try {
future.get();
} catch (InterruptedException ex) {
// The write was interrupted... delete the segments?
} catch (ExecutionException ex) {
// This must be an IOException because we only call entity.writeTo()
throw (IOException) ex.getCause();
}
// create manifest
String manifestEtag = null;
if (dynamicLargeObject) {
// empty manifest with header detailing prefix
metadata.put("X-Object-Manifest", segmentBase);
metadata.put("x-object-meta-mtime", String.format("%s", timeStamp));
manifestEtag = storeObject(region, container, new ByteArrayInputStream(new byte[0]), entity.getContentType().getValue(), name, metadata);
} else {
// specified manifest containing json list specifying details of the files.
URIBuilder urlBuild = new URIBuilder(region.getStorageUrl(container, name));
urlBuild.setParameter("multipart-manifest", "put");
URI url;
try {
url = urlBuild.build();
String manifestContent = manifestSLO.toString();
InputStreamEntity manifestEntity = new InputStreamEntity(new ByteArrayInputStream(manifestContent.getBytes()), -1);
manifestEntity.setChunked(true);
manifestEntity.setContentType(entity.getContentType());
HttpPut method = new HttpPut(url);
method.setEntity(manifestEntity);
method.setHeader("x-static-large-object", "true");
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
manifestEtag = response.getResponseHeader(HttpHeaders.ETAG).getValue();
}
else {
throw new GenericException(response);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
// Delete segments of overwritten file if necessary
if (!leaveSegments) {
// Clear out any objects we overwrote
if (!(oldSegmentsToRemove == null)) {
for (String c: oldSegmentsToRemove.keySet()) {
List<StorageObject> rmv = oldSegmentsToRemove.get(c);
if (newSegmentsAdded.containsKey(c)){
rmv.removeAll(newSegmentsAdded.get(c));
}
List<String> rmvNames = new LinkedList<String>();
for (StorageObject s: rmv) {
rmvNames.add(s.getName());
}
deleteObjects(region, c, rmvNames);
}
}
}
return manifestEtag;
}
}
/**
* @param container The name of the container
* @param name The name of the object
* @param entity The name of the request entity (make sure to set the Content-Type
* @param metadata The metadata for the object
* @param md5sum The 32 character hex encoded MD5 sum of the data
* @param objectSize The total size in bytes of the object to be stored
* @return The ETAG if the save was successful, null otherwise
* @throws GenericException There was a protocol level error talking to CloudFiles
*/
public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum, Long objectSize) throws IOException, InterruptedException {
return storeObject(region, container, name, entity, metadata, md5sum, objectSize, null, null, null, null, null);
}
private Map<String, String> renameContainerMetadata(Map<String, String> metadata) {
return this.renameMetadata(metadata, Constants.X_CONTAINER_META);
}
private Map<String, String> renameObjectMetadata(Map<String, String> metadata) {
return this.renameMetadata(metadata, Constants.X_OBJECT_META);
}
private Map<String, String> renameMetadata(Map<String, String> metadata, String prefix) {
final Map<String, String> converted = new HashMap<String, String>(metadata.size());
for(Map.Entry<String, String> entry : metadata.entrySet()) {
if(entry.getKey().startsWith(prefix)) {
converted.put(entry.getKey(), entry.getValue());
}
else {
if(!Constants.HTTP_HEADER_EDITABLE_NAMES.contains(entry.getKey().toLowerCase(Locale.ENGLISH))) {
converted.put(prefix + entry.getKey(), encode(entry.getValue()));
}
else {
converted.put(entry.getKey(), entry.getValue());
}
}
}
return converted;
}
private static String encode(String object) {
URLCodec codec = new URLCodec();
try {
return codec.encode(object).replaceAll("\\+", "%20");
}
catch(EncoderException ee) {
return object;
}
}
/**
* This method copies the object found in the source container with the
* source object name to the destination container with the destination
* object name.
*
* @param sourceContainer of object to copy
* @param sourceObjName of object to copy
* @param destContainer where object copy will be copied
* @param destObjName of object copy
* @return ETag if successful, else null
* @throws GenericException Unexpected response
*/
public String copyObject(Region region, String sourceContainer,
String sourceObjName, String destContainer, String destObjName)
throws IOException {
HttpPut method = new HttpPut(region.getStorageUrl(destContainer, destObjName));
method.setHeader(Constants.X_COPY_FROM, encode(sourceContainer) + "/" + encode(sourceObjName));
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
return response.getResponseHeader(HttpHeaders.ETAG).getValue();
}
else {
throw new GenericException(response);
}
}
/**
* Delete the given object from it's container.
*
* @param container The container name
* @param object The object name
* @throws IOException There was an IO error doing network communication
* @throws GenericException Unexpected response
* @throws ch.iterate.openstack.swift.exception.NotFoundException
* The file was not found
*/
public void deleteObject(Region region, String container, String object) throws IOException {
HttpDelete method = new HttpDelete(region.getStorageUrl(container, object));
this.execute(method, new DefaultResponseHandler());
}
public void deleteObjects(Region region, String container, List<String> objects) throws IOException {
HttpEntityEnclosingRequestBase method = new HttpEntityEnclosingRequestBase() {
@Override
public String getMethod() {
return "DELETE";
}
};
// Will delete multiple objects or containers from their account with a
// single request. Responds to DELETE requests with query parameter
// ?bulk-delete set.
LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
parameters.add(new BasicNameValuePair("bulk-delete", "1"));
method.setURI(region.getStorageUrl(container, parameters));
method.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
// Newline separated list of url encoded objects to delete
StringBuilder body = new StringBuilder();
for(String object : objects) {
final String path = region.getStorageUrl(container, object).getRawPath();
body.append(path.substring(region.getStorageUrl().getRawPath().length()));
}
method.setEntity(new StringEntity(body.toString(), "UTF-8"));
this.execute(method, new DefaultResponseHandler());
}
/**
* Get an object's metadata
*
* @param container The name of the container
* @param object The name of the object
* @return The object's metadata
* @throws GenericException Unexpected response
* @throws AuthorizationException The Client's Login was invalid.
* @throws ch.iterate.openstack.swift.exception.NotFoundException
* The file was not found
*/
public ObjectMetadata getObjectMetaData(Region region, String container, String object) throws IOException {
HttpHead method = new HttpHead(region.getStorageUrl(container, object));
return this.execute(method, new ObjectMetadataResponseHandler());
}
/**
* Get an container's metadata
*
* @param container The name of the container
* @return The container's metadata
* @throws GenericException Unexpected response
* @throws AuthorizationException The Client's Login was invalid.
*/
public ContainerMetadata getContainerMetaData(Region region, String container) throws IOException {
HttpHead method = new HttpHead(region.getStorageUrl(container));
return this.execute(method, new ContainerMetadataResponseHandler());
}
/**
* Get's the given object's content as a stream
*
* @param container The name of the container
* @param object The name of the object
* @return An input stream that will give the objects content when read from.
* @throws GenericException Unexpected response
*/
public InputStream getObject(Region region, String container, String object) throws IOException {
HttpGet method = new HttpGet(region.getStorageUrl(container, object));
Response response = this.execute(method);
if(response.getStatusCode() == HttpStatus.SC_OK) {
return response.getResponseBodyAsStream();
}
else if(response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
method.abort();
throw new NotFoundException(response);
}
else {
method.abort();
throw new GenericException(response);
}
}
public InputStream getObject(Region region, String container, String object, long offset, long length) throws IOException {
HttpGet method = new HttpGet(region.getStorageUrl(container, object));
method.setHeader("Range", "bytes=" + offset + "-" + length);
Response response = this.execute(method);
if(response.getStatusCode() == HttpStatus.SC_PARTIAL_CONTENT) {
return response.getResponseBodyAsStream();
}
else if(response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
method.abort();
throw new NotFoundException(response);
}
else {
method.abort();
throw new GenericException(response);
}
}
public void updateObjectManifest(Region region, String container, String object, String manifest) throws IOException {
this.updateObjectMetadataAndManifest(region, container, object, new HashMap<String, String>(), manifest);
}
public void updateObjectMetadata(Region region, String container, String object,
Map<String, String> metadata) throws IOException {
this.updateObjectMetadataAndManifest(region, container, object, metadata, null);
}
public void updateObjectMetadataAndManifest(Region region, String container, String object,
Map<String, String> metadata, String manifest) throws IOException {
HttpPost method = new HttpPost(region.getStorageUrl(container, object));
if(manifest != null) {
method.setHeader(Constants.MANIFEST_HEADER, manifest);
}
for(Map.Entry<String, String> key : this.renameObjectMetadata(metadata).entrySet()) {
method.setHeader(key.getKey(), key.getValue());
}
this.execute(method, new DefaultResponseHandler());
}
public void updateContainerMetadata(Region region, String container,
Map<String, String> metadata) throws IOException {
HttpPost method = new HttpPost(region.getStorageUrl(container));
for(Map.Entry<String, String> key : this.renameContainerMetadata(metadata).entrySet()) {
method.setHeader(key.getKey(), key.getValue());
}
this.execute(method, new DefaultResponseHandler());
}
public void updateAccountMetadata(Region region, Map<String, String> metadata) throws IOException {
HttpPost method = new HttpPost(region.getStorageUrl());
for(Map.Entry<String, String> key : metadata.entrySet()) {
method.setHeader(key.getKey(), key.getValue());
}
this.execute(method, new DefaultResponseHandler());
}
}
| true | true | public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum, Long objectSize,
Long segmentSize, Boolean dynamicLargeObject, String segmentContainer, String segmentFolder, Boolean leaveSegments) throws IOException, InterruptedException {
/*
* Default values for large object support. We also use
* the defaults combined with the inputs to determine whether
* to store as a large object.
*/
System.out.println("Region: " + region);
System.out.println("Container: " + container);
System.out.println("Name: " + name);
// The maximum size of a single object
long singleObjectSizeLimit = (long)(5 * Math.pow(1024, 3));
// The default minimum segment size
long minSegmentSize = 1024L*1024L;
// Set the segment size if specified,
long actualSegmentSize = (segmentSize == null) ? (long)(4 * Math.pow(1024, 3)) : Math.max(segmentSize, minSegmentSize);
// Use large objects if a segmentSize has been specified and the object size exceeds it
// or if the objectSize is larger than the single object size limit of ~5GiB
boolean useLargeObject = ((segmentSize != null) && (objectSize > actualSegmentSize)) // segmentSize specified, and objectSize large enough
|| (objectSize > singleObjectSizeLimit) // objectSize is larger than the maximum single object size limit
|| ((segmentSize != null) && (objectSize == null)); // segmentSize is specified, but objectSize is not.
// Trust the user that their data is large enough!
// They may get a "large object" with a single segment or a failure
// because their data is smaller than the minimum segment size
if (!useLargeObject) {
return storeObject(region, container, name, entity, metadata, md5sum);
} else {
/*
* We need to upload a large object as defined by the method
* parameters. For now this is done sequentially, but a parallel
* version using appropriate random access to the underlying data
* may be desirable.
*
* We make the assumption that the given file size will not be
* greater than int.MAX_VALUE * segmentSize
*
*/
leaveSegments = (leaveSegments == null) ? Boolean.FALSE : leaveSegments;
dynamicLargeObject = (dynamicLargeObject == null) ? Boolean.FALSE : dynamicLargeObject;
segmentFolder = (segmentFolder == null) ? ".file-segments" : segmentFolder;
segmentContainer = (segmentContainer == null) ? container : segmentContainer;
Map<String, List<StorageObject>> oldSegmentsToRemove = null;
// Deal with existing objects if necessary
if (!leaveSegments){
ObjectMetadata existingMetadata;
String manifestDLO = null;
Boolean manifestSLO = Boolean.FALSE;
try {
existingMetadata = getObjectMetaData(region, container, name);
if (existingMetadata.getMetaData().containsKey(Constants.MANIFEST_HEADER)) {
manifestDLO = existingMetadata.getMetaData().get(Constants.MANIFEST_HEADER);
} else if (existingMetadata.getMetaData().containsKey(Constants.X_STATIC_LARGE_OBJECT)) {
JSONParser parser = new JSONParser();
String manifestSLOValue = existingMetadata.getMetaData().get(Constants.X_STATIC_LARGE_OBJECT);
manifestSLO = (Boolean) parser.parse(manifestSLOValue);
}
} catch (NotFoundException e) {
// Just means no object exists already, so carry on
} catch (ParseException e) {
// X_STATIC_LARGE_OBJECT header existed but failed to parse
// for an SLO this must be set to "true", therefore fail upload
return null;
}
if (manifestDLO != null) {
// We have found an existing dynamic large object, so use the prefix to get a list of existing objects
// if we're putting up a new dlo, make sure the segment prefixes are different
// then we can delete anything that's not in the new list
String oldContainer = manifestDLO.substring(0,manifestDLO.indexOf('/', 1));
String oldPath = manifestDLO.substring(manifestDLO.indexOf('/', 1),manifestDLO.length());
oldSegmentsToRemove = new HashMap<String, List<StorageObject>>();
oldSegmentsToRemove.put(oldContainer, listObjects(region, oldContainer, oldPath));
} else if (manifestSLO) {
// We have found an existing static large object, so grab the manifest data that
// details the existing segments - delete any later that we don't need any more
}
}
int segmentNumber = 1;
long timeStamp = System.currentTimeMillis() / 1000L;
String segmentBase = String.format("%s/%d/%d" , segmentFolder, timeStamp, objectSize);
// Create substream from the entity inputstream
// loop creating objects using the substreams
boolean finished = false;
//InputStream contentStream = entity.getContent();
final PipedInputStream contentInStream = new PipedInputStream(64*1024);
final PipedOutputStream contentOutStream = new PipedOutputStream(contentInStream);
SubInputStream segmentStream = new SubInputStream(contentInStream, actualSegmentSize+2, false);
//CheckedInputStream segmentStream2 = new CheckedInputStream(contentInStream);// SubInputStream(contentInStream, actualSegmentSize+2, false);
// Fork the call to entity.writeTo() that allows us to grab any exceptions raised
final HttpEntity e = entity;
final Callable<Boolean> writer = new Callable<Boolean>() {
public Boolean call() throws Exception {
e.writeTo(contentOutStream);
return Boolean.TRUE;
}
};
ExecutorService writeExecutor = Executors.newSingleThreadExecutor();
final Future<Boolean> future = writeExecutor.submit(writer);
// Check the future for exceptions after we've finished upoading segments
Map<String, List<StorageObject>> newSegmentsAdded = new HashMap<String, List<StorageObject>>();
List<StorageObject> newSegments = new LinkedList<StorageObject>();
JSONArray manifestSLO = new JSONArray();
while (!finished) {
String segmentName = String.format("%s/%08d", segmentBase, segmentNumber);
// Upload the segment and record the following information
// * ETAG returned by the simple upload
// * total size of segment uploaded
// * path of segment
String etag = "";
boolean error = false;
try {
etag = storeObject(region, segmentContainer, segmentStream, "application/octet-stream", segmentName, new HashMap<String,String>());
} catch (IOException ex) {
// Finished storing the object
System.out.println("Caught IO Exception: " + ex.getMessage());
ex.printStackTrace();
throw ex;
}
String segmentPath = segmentContainer + "/" + segmentName;
long bytesUploaded = segmentStream.getBytesProduced();
// Create the appropriate manifest structure if we're making an SLO
if (!dynamicLargeObject) {
JSONObject segmentJSON = new JSONObject();
segmentJSON.put("path", segmentPath);
segmentJSON.put("etag", etag);
segmentJSON.put("size_bytes", bytesUploaded);
// append the segment to the segment list maintaining the order
manifestSLO.add(segmentJSON);
newSegments.add(new StorageObject(segmentName));
}
segmentNumber++;
if (!finished) {
finished = segmentStream.endSourceReached();
}
newSegmentsAdded.put(segmentContainer, newSegments);
System.out.println("JSON: " + manifestSLO.toString());
if (error) return "";
segmentStream.readMoreBytes(actualSegmentSize);
}
// Did the writing to the stream work?
try {
future.get();
} catch (InterruptedException ex) {
// The write was interrupted... delete the segments?
} catch (ExecutionException ex) {
// This must be an IOException because we only call entity.writeTo()
throw (IOException) ex.getCause();
}
// create manifest
String manifestEtag = null;
if (dynamicLargeObject) {
// empty manifest with header detailing prefix
metadata.put("X-Object-Manifest", segmentBase);
metadata.put("x-object-meta-mtime", String.format("%s", timeStamp));
manifestEtag = storeObject(region, container, new ByteArrayInputStream(new byte[0]), entity.getContentType().getValue(), name, metadata);
} else {
// specified manifest containing json list specifying details of the files.
URIBuilder urlBuild = new URIBuilder(region.getStorageUrl(container, name));
urlBuild.setParameter("multipart-manifest", "put");
URI url;
try {
url = urlBuild.build();
String manifestContent = manifestSLO.toString();
InputStreamEntity manifestEntity = new InputStreamEntity(new ByteArrayInputStream(manifestContent.getBytes()), -1);
manifestEntity.setChunked(true);
manifestEntity.setContentType(entity.getContentType());
HttpPut method = new HttpPut(url);
method.setEntity(manifestEntity);
method.setHeader("x-static-large-object", "true");
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
manifestEtag = response.getResponseHeader(HttpHeaders.ETAG).getValue();
}
else {
throw new GenericException(response);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
// Delete segments of overwritten file if necessary
if (!leaveSegments) {
// Clear out any objects we overwrote
if (!(oldSegmentsToRemove == null)) {
for (String c: oldSegmentsToRemove.keySet()) {
List<StorageObject> rmv = oldSegmentsToRemove.get(c);
if (newSegmentsAdded.containsKey(c)){
rmv.removeAll(newSegmentsAdded.get(c));
}
List<String> rmvNames = new LinkedList<String>();
for (StorageObject s: rmv) {
rmvNames.add(s.getName());
}
deleteObjects(region, c, rmvNames);
}
}
}
return manifestEtag;
}
}
| public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum, Long objectSize,
Long segmentSize, Boolean dynamicLargeObject, String segmentContainer, String segmentFolder, Boolean leaveSegments) throws IOException, InterruptedException {
/*
* Default values for large object support. We also use
* the defaults combined with the inputs to determine whether
* to store as a large object.
*/
System.out.println("Region: " + region);
System.out.println("Container: " + container);
System.out.println("Name: " + name);
// The maximum size of a single object
long singleObjectSizeLimit = (long)(5 * Math.pow(1024, 3));
// The default minimum segment size
long minSegmentSize = 1024L*1024L;
// Set the segment size if specified,
long actualSegmentSize = (segmentSize == null) ? (long)(4 * Math.pow(1024, 3)) : Math.max(segmentSize, minSegmentSize);
// Use large objects if a segmentSize has been specified and the object size exceeds it
// or if the objectSize is larger than the single object size limit of ~5GiB
boolean useLargeObject = ((segmentSize != null) && (objectSize > actualSegmentSize)) // segmentSize specified, and objectSize large enough
|| (objectSize > singleObjectSizeLimit) // objectSize is larger than the maximum single object size limit
|| ((segmentSize != null) && (objectSize == null)); // segmentSize is specified, but objectSize is not.
// Trust the user that their data is large enough!
// They may get a "large object" with a single segment or a failure
// because their data is smaller than the minimum segment size
if (!useLargeObject) {
return storeObject(region, container, name, entity, metadata, md5sum);
} else {
/*
* We need to upload a large object as defined by the method
* parameters. For now this is done sequentially, but a parallel
* version using appropriate random access to the underlying data
* may be desirable.
*
* We make the assumption that the given file size will not be
* greater than int.MAX_VALUE * segmentSize
*
*/
leaveSegments = (leaveSegments == null) ? Boolean.FALSE : leaveSegments;
dynamicLargeObject = (dynamicLargeObject == null) ? Boolean.FALSE : dynamicLargeObject;
segmentFolder = (segmentFolder == null) ? ".file-segments" : segmentFolder;
segmentContainer = (segmentContainer == null) ? container : segmentContainer;
Map<String, List<StorageObject>> oldSegmentsToRemove = null;
// Deal with existing objects if necessary
if (!leaveSegments){
ObjectMetadata existingMetadata;
String manifestDLO = null;
Boolean manifestSLO = Boolean.FALSE;
try {
existingMetadata = getObjectMetaData(region, container, name);
if (existingMetadata.getMetaData().containsKey(Constants.MANIFEST_HEADER)) {
manifestDLO = existingMetadata.getMetaData().get(Constants.MANIFEST_HEADER);
} else if (existingMetadata.getMetaData().containsKey(Constants.X_STATIC_LARGE_OBJECT)) {
JSONParser parser = new JSONParser();
String manifestSLOValue = existingMetadata.getMetaData().get(Constants.X_STATIC_LARGE_OBJECT);
manifestSLO = (Boolean) parser.parse(manifestSLOValue);
}
} catch (NotFoundException e) {
// Just means no object exists already, so carry on
} catch (ParseException e) {
// X_STATIC_LARGE_OBJECT header existed but failed to parse
// for an SLO this must be set to "true", therefore fail upload
return null;
}
if (manifestDLO != null) {
// We have found an existing dynamic large object, so use the prefix to get a list of existing objects
// if we're putting up a new dlo, make sure the segment prefixes are different
// then we can delete anything that's not in the new list
String oldContainer = manifestDLO.substring(0,manifestDLO.indexOf('/', 1));
String oldPath = manifestDLO.substring(manifestDLO.indexOf('/', 1),manifestDLO.length());
oldSegmentsToRemove = new HashMap<String, List<StorageObject>>();
oldSegmentsToRemove.put(oldContainer, listObjects(region, oldContainer, oldPath));
} else if (manifestSLO) {
// We have found an existing static large object, so grab the manifest data that
// details the existing segments - delete any later that we don't need any more
}
}
int segmentNumber = 1;
long timeStamp = System.currentTimeMillis() / 1000L;
String segmentBase = String.format("%s/%d/%d" , segmentFolder, timeStamp, objectSize);
// Create substream from the entity inputstream
// loop creating objects using the substreams
boolean finished = false;
//InputStream contentStream = entity.getContent();
final PipedInputStream contentInStream = new PipedInputStream(64*1024);
final PipedOutputStream contentOutStream = new PipedOutputStream(contentInStream);
SubInputStream segmentStream = new SubInputStream(contentInStream, actualSegmentSize, false);
//CheckedInputStream segmentStream2 = new CheckedInputStream(contentInStream);// SubInputStream(contentInStream, actualSegmentSize+2, false);
// Fork the call to entity.writeTo() that allows us to grab any exceptions raised
final HttpEntity e = entity;
final Callable<Boolean> writer = new Callable<Boolean>() {
public Boolean call() throws Exception {
e.writeTo(contentOutStream);
return Boolean.TRUE;
}
};
ExecutorService writeExecutor = Executors.newSingleThreadExecutor();
final Future<Boolean> future = writeExecutor.submit(writer);
// Check the future for exceptions after we've finished upoading segments
Map<String, List<StorageObject>> newSegmentsAdded = new HashMap<String, List<StorageObject>>();
List<StorageObject> newSegments = new LinkedList<StorageObject>();
JSONArray manifestSLO = new JSONArray();
while (!finished) {
String segmentName = String.format("%s/%08d", segmentBase, segmentNumber);
// Upload the segment and record the following information
// * ETAG returned by the simple upload
// * total size of segment uploaded
// * path of segment
String etag = "";
boolean error = false;
try {
etag = storeObject(region, segmentContainer, segmentStream, "application/octet-stream", segmentName, new HashMap<String,String>());
} catch (IOException ex) {
// Finished storing the object
System.out.println("Caught IO Exception: " + ex.getMessage());
ex.printStackTrace();
throw ex;
}
String segmentPath = segmentContainer + "/" + segmentName;
long bytesUploaded = segmentStream.getBytesProduced();
// Create the appropriate manifest structure if we're making an SLO
if (!dynamicLargeObject) {
JSONObject segmentJSON = new JSONObject();
segmentJSON.put("path", segmentPath);
segmentJSON.put("etag", etag);
segmentJSON.put("size_bytes", bytesUploaded);
// append the segment to the segment list maintaining the order
manifestSLO.add(segmentJSON);
newSegments.add(new StorageObject(segmentName));
}
segmentNumber++;
if (!finished) {
finished = segmentStream.endSourceReached();
}
newSegmentsAdded.put(segmentContainer, newSegments);
System.out.println("JSON: " + manifestSLO.toString());
if (error) return "";
segmentStream.readMoreBytes(actualSegmentSize);
}
// Did the writing to the stream work?
try {
future.get();
} catch (InterruptedException ex) {
// The write was interrupted... delete the segments?
} catch (ExecutionException ex) {
// This must be an IOException because we only call entity.writeTo()
throw (IOException) ex.getCause();
}
// create manifest
String manifestEtag = null;
if (dynamicLargeObject) {
// empty manifest with header detailing prefix
metadata.put("X-Object-Manifest", segmentBase);
metadata.put("x-object-meta-mtime", String.format("%s", timeStamp));
manifestEtag = storeObject(region, container, new ByteArrayInputStream(new byte[0]), entity.getContentType().getValue(), name, metadata);
} else {
// specified manifest containing json list specifying details of the files.
URIBuilder urlBuild = new URIBuilder(region.getStorageUrl(container, name));
urlBuild.setParameter("multipart-manifest", "put");
URI url;
try {
url = urlBuild.build();
String manifestContent = manifestSLO.toString();
InputStreamEntity manifestEntity = new InputStreamEntity(new ByteArrayInputStream(manifestContent.getBytes()), -1);
manifestEntity.setChunked(true);
manifestEntity.setContentType(entity.getContentType());
HttpPut method = new HttpPut(url);
method.setEntity(manifestEntity);
method.setHeader("x-static-large-object", "true");
Response response = this.execute(method, new DefaultResponseHandler());
if(response.getStatusCode() == HttpStatus.SC_CREATED) {
manifestEtag = response.getResponseHeader(HttpHeaders.ETAG).getValue();
}
else {
throw new GenericException(response);
}
} catch (URISyntaxException ex) {
ex.printStackTrace();
}
}
// Delete segments of overwritten file if necessary
if (!leaveSegments) {
// Clear out any objects we overwrote
if (!(oldSegmentsToRemove == null)) {
for (String c: oldSegmentsToRemove.keySet()) {
List<StorageObject> rmv = oldSegmentsToRemove.get(c);
if (newSegmentsAdded.containsKey(c)){
rmv.removeAll(newSegmentsAdded.get(c));
}
List<String> rmvNames = new LinkedList<String>();
for (StorageObject s: rmv) {
rmvNames.add(s.getName());
}
deleteObjects(region, c, rmvNames);
}
}
}
return manifestEtag;
}
}
|
diff --git a/engine/src/tools/jme3tools/savegame/SaveGame.java b/engine/src/tools/jme3tools/savegame/SaveGame.java
index f80d27cfb..1d068cabe 100644
--- a/engine/src/tools/jme3tools/savegame/SaveGame.java
+++ b/engine/src/tools/jme3tools/savegame/SaveGame.java
@@ -1,92 +1,94 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package jme3tools.savegame;
import com.jme3.asset.AssetManager;
import com.jme3.export.Savable;
import com.jme3.export.xml.XMLExporter;
import com.jme3.export.xml.XMLImporter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
/**
* Tool for saving Savables as SaveGame entries in a system-dependent way.
* @author normenhansen
*/
public class SaveGame {
/**
* Saves a savable in a system-dependent way.
* @param gamePath A unique path for this game, e.g. com/mycompany/mygame
* @param dataName A unique name for this savegame, e.g. "save_001"
* @param data The Savable to save
*/
public static void saveGame(String gamePath, String dataName, Savable data) {
Preferences prefs = Preferences.userRoot().node(gamePath);
XMLExporter ex = XMLExporter.getInstance();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ex.save(data, out);
} catch (IOException ex1) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error saving data: {0}", ex1);
ex1.printStackTrace();
}
try {
prefs.put(dataName, out.toString("UTF-8"));
} catch (UnsupportedEncodingException ex1) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error saving data: {0}", ex1);
ex1.printStackTrace();
}
}
/**
* Loads a savable that has been saved on this system with saveGame() before.
* @param gamePath A unique path for this game, e.g. com/mycompany/mygame
* @param dataName A unique name for this savegame, e.g. "save_001"
* @return The savable that was saved
*/
public static Savable loadGame(String gamePath, String dataName) {
return loadGame(gamePath, dataName, null);
}
/**
* Loads a savable that has been saved on this system with saveGame() before.
* @param gamePath A unique path for this game, e.g. com/mycompany/mygame
* @param dataName A unique name for this savegame, e.g. "save_001"
* @param assetManager Link to an AssetManager if required for loading the data (e.g. models with textures)
* @return The savable that was saved
*/
public static Savable loadGame(String gamePath, String dataName, AssetManager manager) {
Preferences prefs = Preferences.userRoot().node(gamePath);
String data = prefs.get(gamePath, dataName);
InputStream is = null;
Savable sav = null;
try {
is = new ByteArrayInputStream(data.getBytes("UTF-8"));
XMLImporter imp = XMLImporter.getInstance();
if (manager != null) {
imp.setAssetManager(manager);
}
sav = imp.load(is);
} catch (IOException ex) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
+ ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
+ ex.printStackTrace();
}
}
}
return sav;
}
}
| false | true | public static Savable loadGame(String gamePath, String dataName, AssetManager manager) {
Preferences prefs = Preferences.userRoot().node(gamePath);
String data = prefs.get(gamePath, dataName);
InputStream is = null;
Savable sav = null;
try {
is = new ByteArrayInputStream(data.getBytes("UTF-8"));
XMLImporter imp = XMLImporter.getInstance();
if (manager != null) {
imp.setAssetManager(manager);
}
sav = imp.load(is);
} catch (IOException ex) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
}
}
}
return sav;
}
| public static Savable loadGame(String gamePath, String dataName, AssetManager manager) {
Preferences prefs = Preferences.userRoot().node(gamePath);
String data = prefs.get(gamePath, dataName);
InputStream is = null;
Savable sav = null;
try {
is = new ByteArrayInputStream(data.getBytes("UTF-8"));
XMLImporter imp = XMLImporter.getInstance();
if (manager != null) {
imp.setAssetManager(manager);
}
sav = imp.load(is);
} catch (IOException ex) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
Logger.getLogger(SaveGame.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
ex.printStackTrace();
}
}
}
return sav;
}
|
diff --git a/overthere/src/main/java/com/xebialabs/overthere/ssh/SshScpFile.java b/overthere/src/main/java/com/xebialabs/overthere/ssh/SshScpFile.java
index 211ac93..a332a64 100644
--- a/overthere/src/main/java/com/xebialabs/overthere/ssh/SshScpFile.java
+++ b/overthere/src/main/java/com/xebialabs/overthere/ssh/SshScpFile.java
@@ -1,426 +1,426 @@
/*
* This file is part of Overthere.
*
* Overthere 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.
*
* Overthere 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 Overthere. If not, see <http://www.gnu.org/licenses/>.
*/
package com.xebialabs.overthere.ssh;
import static com.google.common.collect.Lists.newArrayList;
import static com.xebialabs.overthere.CmdLine.build;
import static com.xebialabs.overthere.util.CapturingOverthereProcessOutputHandler.capturingHandler;
import static com.xebialabs.overthere.util.LoggingOverthereProcessOutputHandler.loggingHandler;
import static com.xebialabs.overthere.util.MultipleOverthereProcessOutputHandler.multiHandler;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.StringTokenizer;
import net.schmizz.sshj.xfer.LocalFileFilter;
import net.schmizz.sshj.xfer.LocalSourceFile;
import net.schmizz.sshj.xfer.scp.SCPUploadClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.xebialabs.overthere.CmdLine;
import com.xebialabs.overthere.OverthereFile;
import com.xebialabs.overthere.RuntimeIOException;
import com.xebialabs.overthere.util.CapturingOverthereProcessOutputHandler;
/**
* A file on a host connected through SSH w/ SCP.
*/
class SshScpFile extends SshFile<SshScpConnection> {
/**
* Constructs an SshScpOverthereFile
*
* @param connection
* the connection to the host
* @param remotePath
* the path of the file on the host
*/
public SshScpFile(SshScpConnection connection, String remotePath) {
super(connection, remotePath);
}
@Override
public boolean exists() {
return getFileInfo().exists;
}
@Override
public boolean canRead() {
return getFileInfo().canRead;
}
@Override
public boolean canWrite() {
return getFileInfo().canWrite;
}
@Override
public boolean canExecute() {
return getFileInfo().canExecute;
}
@Override
public boolean isFile() {
return getFileInfo().isFile;
}
@Override
public boolean isDirectory() {
return getFileInfo().isDirectory;
}
@Override
public long lastModified() {
// FIXME: Implement by parsing the date output of `ls -l`
throw new UnsupportedOperationException();
}
@Override
public long length() {
return getFileInfo().length;
}
/**
* Gets information about the file by executing "ls -ld" on it.
*
* @param file
* the file
* @return the information about the file, never <code>null</code>.
* @throws RuntimeIOException
* if an I/O exception occurs
*/
public LsResults getFileInfo() throws RuntimeIOException {
LsResults results = new LsResults();
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(capturedOutput, CmdLine.build("ls", "-ld", getPath()));
if (errno == 0) {
results.exists = true;
if (capturedOutput.getOutputLines().size() > 0) {
// parse ls results
- String outputLine = capturedOutput.getOutputLines().get(0);
+ String outputLine = capturedOutput.getOutputLines().get(capturedOutput.getOutputLines().size() - 1);
if (logger.isDebugEnabled())
logger.debug("ls output = " + outputLine);
StringTokenizer outputTokens = new StringTokenizer(outputLine);
if (outputTokens.countTokens() < 5) {
throw new RuntimeIOException("ls -ld " + getPath() + " returned output that contains less than the expected 5 tokens: " + outputLine);
}
String permissions = outputTokens.nextToken();
@SuppressWarnings("unused")
String inodelinkes = outputTokens.nextToken();
@SuppressWarnings("unused")
String owner = outputTokens.nextToken();
@SuppressWarnings("unused")
String group = outputTokens.nextToken();
String size = outputTokens.nextToken();
results.isFile = permissions.length() >= 1 && permissions.charAt(0) == '-';
results.isDirectory = permissions.length() >= 1 && permissions.charAt(0) == 'd';
results.canRead = permissions.length() >= 2 && permissions.charAt(1) == 'r';
results.canWrite = permissions.length() >= 3 && permissions.charAt(2) == 'w';
results.canExecute = permissions.length() >= 4 && permissions.charAt(3) == 'x';
try {
results.length = Integer.parseInt(size);
} catch (NumberFormatException exc) {
logger.warn("Cannot parse length of " + this.getPath() + " from ls output: " + outputLine + ". Length will be reported as -1.", exc);
}
}
} else {
results.exists = false;
}
if (logger.isDebugEnabled())
logger.debug("Listed file " + this + ": exists=" + results.exists + ", isDirectory=" + results.isDirectory + ", length=" + results.length
+ ", canRead=" + results.canRead + ", canWrite=" + results.canWrite + ", canExecute=" + results.canExecute);
return results;
}
/**
* Holds results of an ls call
*/
public static class LsResults {
public boolean exists;
public boolean isFile;
public boolean isDirectory;
public long length = -1;
public boolean canRead;
public boolean canWrite;
public boolean canExecute;
}
@Override
public InputStream getInputStream() throws RuntimeIOException {
logger.debug("Opening SCP input stream to read from file {}", this);
try {
final File tempFile = File.createTempFile("scp_download", ".tmp");
tempFile.deleteOnExit();
connection.getSshClient().newSCPFileTransfer().download(getPath(), tempFile.getPath());
return new FileInputStream(tempFile) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
tempFile.delete();
}
}
};
} catch (IOException e) {
throw new RuntimeIOException("Could not open " + this + " for reading", e);
}
}
@Override
public OutputStream getOutputStream() throws RuntimeIOException {
logger.debug("Opening SCP output stream to write to file {}", this);
try {
final File tempFile = File.createTempFile("scp_upload", ".tmp");
tempFile.deleteOnExit();
return new FileOutputStream(tempFile) {
@Override
public void close() throws IOException {
try {
super.close();
} finally {
uploadAndDelete(tempFile);
}
}
private void uploadAndDelete(File tempFile) throws IOException {
try {
connection.getSshClient().newSCPFileTransfer().upload(tempFile.getPath(), getPath());
} finally {
tempFile.delete();
}
}
};
} catch (IOException e) {
throw new RuntimeIOException("Could not open " + this + " for reading", e);
}
}
@Override
public List<OverthereFile> listFiles() {
logger.debug("Listing directory {}", this);
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
// Yes, this *is* meant to be 'el es minus one'! Each file should go one a separate line, even if we create a pseudo-tty. Long format is NOT what we
// want here.
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), build("ls", "-1", getPath()));
if (errno != 0) {
throw new RuntimeIOException("Cannot list directory " + this + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
List<OverthereFile> files = newArrayList();
for (String lsLine : capturedOutput.getOutputLines()) {
files.add(connection.getFile(this, lsLine));
}
return files;
}
public void mkdir() {
logger.debug("Creating directory {}", this);
mkdir(new String[0]);
}
public void mkdirs() {
logger.debug("Creating directories {}", this);
mkdir("-p");
}
protected void mkdir(String... mkdirOptions) throws RuntimeIOException {
CmdLine commandLine = CmdLine.build("mkdir");
for (String opt : mkdirOptions) {
commandLine.addArgument(opt);
}
commandLine.addArgument(getPath());
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), commandLine);
if (errno != 0) {
throw new RuntimeIOException("Cannot create directory or -ies " + this + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
if (logger.isDebugEnabled()) {
logger.debug("Created directory " + this + " (with options:" + Joiner.on(' ').join(mkdirOptions));
}
}
@Override
public void renameTo(OverthereFile dest) {
logger.debug("Renaming {} to {}", this, dest);
if (dest instanceof SshScpFile) {
SshScpFile sshScpDestFile = (SshScpFile) dest;
if (sshScpDestFile.getConnection() == getConnection()) {
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), CmdLine.build("mv", getPath(), sshScpDestFile.getPath()));
if (errno != 0) {
throw new RuntimeIOException("Cannot rename file/directory " + this + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
} else {
throw new RuntimeIOException("Cannot rename ssh_scp file/directory " + this + " to ssh_scp file/directory " + dest + " because it is in a different connection");
}
} else {
throw new RuntimeIOException("Cannot rename ssh_scp file/directory " + this + " to non-ssh_scp file/directory " + dest);
}
}
@Override
public void setExecutable(boolean executable) {
logger.debug("Setting execute permission on {} to {}", this, executable);
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), CmdLine.build("chmod", executable ? "+x" : "-x", getPath()));
if (errno != 0) {
throw new RuntimeIOException("Cannot set execute permission on file " + this + " to " + executable + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
}
@Override
protected void deleteDirectory() {
logger.debug("Deleting directory {}", this);
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), CmdLine.build("rmdir", getPath()));
if (errno != 0) {
throw new RuntimeIOException("Cannot delete directory " + this + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
}
@Override
protected void deleteFile() {
logger.debug("Deleting file {}", this);
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), CmdLine.build("rm", "-f", getPath()));
if (errno != 0) {
throw new RuntimeIOException("Cannot delete file " + this + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
}
@Override
public void deleteRecursively() throws RuntimeIOException {
logger.debug("Recursively deleting file or directory {}", this);
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(multiHandler(loggingHandler(logger), capturedOutput), CmdLine.build("rm", "-rf", getPath()));
if (errno != 0) {
throw new RuntimeIOException("Cannot recursively delete file or directory " + this + ": " + capturedOutput.getError() + " (errno=" + errno + ")");
}
}
@Override
protected void copyFrom(OverthereFile source) {
logger.debug("Copying file or directory {} to {}", source, this);
SCPUploadClient uploadClient = connection.getSshClient().newSCPFileTransfer().newSCPUploadClient();
try {
if (source.isDirectory() && this.exists()) {
for(OverthereFile sourceFile : source.listFiles()) {
uploadClient.copy(new OverthereFileLocalSourceFile(sourceFile), getPath());
}
} else {
uploadClient.copy(new OverthereFileLocalSourceFile(source), getPath());
}
} catch (IOException e) {
throw new RuntimeIOException("Cannot copy " + source + " to " + this, e);
}
}
protected static class OverthereFileLocalSourceFile implements LocalSourceFile {
private OverthereFile f;
public OverthereFileLocalSourceFile(OverthereFile f) {
this.f = f;
}
@Override
public String getName() {
return f.getName();
}
@Override
public long getLength() {
return f.length();
}
@Override
public InputStream getInputStream() throws IOException {
return f.getInputStream();
}
@Override
public int getPermissions() throws IOException {
return f.isDirectory() ? 0755 : 0644;
}
@Override
public boolean isFile() {
return f.isFile();
}
@Override
public boolean isDirectory() {
return f.isDirectory();
}
@Override
public Iterable<? extends LocalSourceFile> getChildren(LocalFileFilter filter) throws IOException {
List<LocalSourceFile> files = newArrayList();
for(OverthereFile each: f.listFiles()) {
files.add(new OverthereFileLocalSourceFile(each));
}
return files;
}
@Override
public boolean providesAtimeMtime() {
return false;
}
@Override
public long getLastAccessTime() throws IOException {
return 0;
}
@Override
public long getLastModifiedTime() throws IOException {
return 0;
}
}
private Logger logger = LoggerFactory.getLogger(SshScpFile.class);
}
| true | true | public LsResults getFileInfo() throws RuntimeIOException {
LsResults results = new LsResults();
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(capturedOutput, CmdLine.build("ls", "-ld", getPath()));
if (errno == 0) {
results.exists = true;
if (capturedOutput.getOutputLines().size() > 0) {
// parse ls results
String outputLine = capturedOutput.getOutputLines().get(0);
if (logger.isDebugEnabled())
logger.debug("ls output = " + outputLine);
StringTokenizer outputTokens = new StringTokenizer(outputLine);
if (outputTokens.countTokens() < 5) {
throw new RuntimeIOException("ls -ld " + getPath() + " returned output that contains less than the expected 5 tokens: " + outputLine);
}
String permissions = outputTokens.nextToken();
@SuppressWarnings("unused")
String inodelinkes = outputTokens.nextToken();
@SuppressWarnings("unused")
String owner = outputTokens.nextToken();
@SuppressWarnings("unused")
String group = outputTokens.nextToken();
String size = outputTokens.nextToken();
results.isFile = permissions.length() >= 1 && permissions.charAt(0) == '-';
results.isDirectory = permissions.length() >= 1 && permissions.charAt(0) == 'd';
results.canRead = permissions.length() >= 2 && permissions.charAt(1) == 'r';
results.canWrite = permissions.length() >= 3 && permissions.charAt(2) == 'w';
results.canExecute = permissions.length() >= 4 && permissions.charAt(3) == 'x';
try {
results.length = Integer.parseInt(size);
} catch (NumberFormatException exc) {
logger.warn("Cannot parse length of " + this.getPath() + " from ls output: " + outputLine + ". Length will be reported as -1.", exc);
}
}
} else {
results.exists = false;
}
if (logger.isDebugEnabled())
logger.debug("Listed file " + this + ": exists=" + results.exists + ", isDirectory=" + results.isDirectory + ", length=" + results.length
+ ", canRead=" + results.canRead + ", canWrite=" + results.canWrite + ", canExecute=" + results.canExecute);
return results;
}
| public LsResults getFileInfo() throws RuntimeIOException {
LsResults results = new LsResults();
CapturingOverthereProcessOutputHandler capturedOutput = capturingHandler();
int errno = executeCommand(capturedOutput, CmdLine.build("ls", "-ld", getPath()));
if (errno == 0) {
results.exists = true;
if (capturedOutput.getOutputLines().size() > 0) {
// parse ls results
String outputLine = capturedOutput.getOutputLines().get(capturedOutput.getOutputLines().size() - 1);
if (logger.isDebugEnabled())
logger.debug("ls output = " + outputLine);
StringTokenizer outputTokens = new StringTokenizer(outputLine);
if (outputTokens.countTokens() < 5) {
throw new RuntimeIOException("ls -ld " + getPath() + " returned output that contains less than the expected 5 tokens: " + outputLine);
}
String permissions = outputTokens.nextToken();
@SuppressWarnings("unused")
String inodelinkes = outputTokens.nextToken();
@SuppressWarnings("unused")
String owner = outputTokens.nextToken();
@SuppressWarnings("unused")
String group = outputTokens.nextToken();
String size = outputTokens.nextToken();
results.isFile = permissions.length() >= 1 && permissions.charAt(0) == '-';
results.isDirectory = permissions.length() >= 1 && permissions.charAt(0) == 'd';
results.canRead = permissions.length() >= 2 && permissions.charAt(1) == 'r';
results.canWrite = permissions.length() >= 3 && permissions.charAt(2) == 'w';
results.canExecute = permissions.length() >= 4 && permissions.charAt(3) == 'x';
try {
results.length = Integer.parseInt(size);
} catch (NumberFormatException exc) {
logger.warn("Cannot parse length of " + this.getPath() + " from ls output: " + outputLine + ". Length will be reported as -1.", exc);
}
}
} else {
results.exists = false;
}
if (logger.isDebugEnabled())
logger.debug("Listed file " + this + ": exists=" + results.exists + ", isDirectory=" + results.isDirectory + ", length=" + results.length
+ ", canRead=" + results.canRead + ", canWrite=" + results.canWrite + ", canExecute=" + results.canExecute);
return results;
}
|
diff --git a/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/model/TCFBreakpointsModel.java b/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/model/TCFBreakpointsModel.java
index 3e3dbb5c9..d0a65394d 100644
--- a/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/model/TCFBreakpointsModel.java
+++ b/plugins/org.eclipse.tm.tcf.debug/src/org/eclipse/tm/internal/tcf/debug/model/TCFBreakpointsModel.java
@@ -1,454 +1,454 @@
/*******************************************************************************
* Copyright (c) 2007, 2011 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.internal.tcf.debug.model;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IBreakpointListener;
import org.eclipse.debug.core.IBreakpointManager;
import org.eclipse.debug.core.IBreakpointManagerListener;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.tm.internal.tcf.debug.Activator;
import org.eclipse.tm.tcf.protocol.IChannel;
import org.eclipse.tm.tcf.protocol.IToken;
import org.eclipse.tm.tcf.protocol.Protocol;
import org.eclipse.tm.tcf.services.IBreakpoints;
/**
* TCFBreakpointsModel class handles breakpoints for all active TCF launches.
* It downloads initial set of breakpoint data when launch is activated,
* listens for Eclipse breakpoint manager events and propagates breakpoint changes to TCF targets.
*/
public class TCFBreakpointsModel implements IBreakpointListener, IBreakpointManagerListener {
private final IBreakpointManager bp_manager = DebugPlugin.getDefault().getBreakpointManager();
private final HashSet<IChannel> channels = new HashSet<IChannel>();
private final HashMap<String,IBreakpoint> id2bp = new HashMap<String,IBreakpoint>();
private boolean disposed;
public static TCFBreakpointsModel getBreakpointsModel() {
return Activator.getBreakpointsModel();
}
public void dispose() {
bp_manager.removeBreakpointListener(this);
bp_manager.removeBreakpointManagerListener(this);
channels.clear();
disposed = true;
}
public boolean isSupported(IChannel channel, IBreakpoint bp) {
// TODO: implement per-channel breakpoint filtering
return true;
}
/**
* Get TCF ID of a breakpoint.
* @param bp - IBreakpoint object.
* @return TCF ID of the breakpoint.
* @throws CoreException
*/
public String getBreakpointID(IBreakpoint bp) throws CoreException {
IMarker marker = bp.getMarker();
String id = (String)marker.getAttributes().get(ITCFConstants.ID_TCF_DEBUG_MODEL + '.' + IBreakpoints.PROP_ID);
if (id != null) return id;
id = marker.getResource().getLocationURI().toString();
if (id == null) return null;
return id + ':' + marker.getId();
}
/**
* Get IBreakpoint for given TCF breakpoint ID.
* The mapping works only for breakpoints that were sent to a debug target.
* It can be used to map target responses to IBreakpoint objects.
* @param id - TCF breakpoint ID.
* @return IBreakpoint object associated with the ID, or null.
*/
public IBreakpoint getBreakpoint(String id) {
assert Protocol.isDispatchThread();
return id2bp.get(id);
}
@SuppressWarnings("unchecked")
public void downloadBreakpoints(final IChannel channel, final Runnable done) throws IOException, CoreException {
assert Protocol.isDispatchThread();
assert !disposed;
IBreakpoints service = channel.getRemoteService(IBreakpoints.class);
if (service != null) {
if (channels.isEmpty()) {
bp_manager.addBreakpointListener(this);
bp_manager.addBreakpointManagerListener(this);
}
channels.add(channel);
channel.addChannelListener(new IChannel.IChannelListener() {
public void congestionLevel(int level) {
}
public void onChannelClosed(Throwable error) {
if (disposed) return;
channels.remove(channel);
if (channels.isEmpty()) {
bp_manager.removeBreakpointListener(TCFBreakpointsModel.this);
bp_manager.removeBreakpointManagerListener(TCFBreakpointsModel.this);
id2bp.clear();
}
}
public void onChannelOpened() {
}
});
IBreakpoint[] arr = bp_manager.getBreakpoints();
if (arr != null && arr.length > 0) {
List<Map<String,Object>> bps = new ArrayList<Map<String,Object>>(arr.length);
for (int i = 0; i < arr.length; i++) {
if (!isSupported(channel, arr[i])) continue;
String id = getBreakpointID(arr[i]);
if (id == null) continue;
if (!arr[i].isPersisted()) continue;
IMarker marker = arr[i].getMarker();
String file = getFilePath(marker.getResource());
bps.add(toBreakpointAttributes(id, file, marker.getType(), marker.getAttributes()));
id2bp.put(id, arr[i]);
}
if (!bps.isEmpty()) {
Map<String, Object>[] bpArr = (Map<String,Object>[]) bps.toArray(new Map[bps.size()]);
service.set(bpArr, new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error == null) done.run();
else channel.terminate(error);
}
});
return;
}
}
}
Protocol.invokeLater(done);
}
public void breakpointManagerEnablementChanged(final boolean enabled) {
try {
IBreakpoint[] arr = bp_manager.getBreakpoints();
if (arr == null || arr.length == 0) return;
final Map<String,IBreakpoint> map = new HashMap<String,IBreakpoint>();
for (int i = 0; i < arr.length; i++) {
IMarker marker = arr[i].getMarker();
Boolean b = marker.getAttribute(IBreakpoint.ENABLED, Boolean.FALSE);
if (!b.booleanValue()) continue;
String id = getBreakpointID(arr[i]);
if (id == null) continue;
map.put(id, arr[i]);
}
if (map.isEmpty()) return;
Runnable r = new Runnable() {
public void run() {
if (disposed) return;
for (final IChannel channel : channels) {
IBreakpoints service = channel.getRemoteService(IBreakpoints.class);
Set<String> ids = new HashSet<String>();
for (String id : map.keySet()) {
IBreakpoint bp = map.get(id);
if (isSupported(channel, bp)) ids.add(id);
}
IBreakpoints.DoneCommand done = new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) channel.terminate(error);
}
};
if (enabled) {
service.enable(ids.toArray(new String[ids.size()]), done);
}
else {
service.disable(ids.toArray(new String[ids.size()]), done);
}
}
Protocol.sync(new Runnable() {
public void run() {
synchronized (map) {
map.notify();
}
}
});
}
};
synchronized (map) {
assert !Protocol.isDispatchThread();
Protocol.invokeLater(r);
map.wait();
}
}
catch (Throwable x) {
Activator.log("Unhandled exception in breakpoint listener", x);
}
}
private abstract class BreakpointUpdate implements Runnable {
private final IBreakpoint breakpoint;
protected final Map<String,Object> marker_attrs;
private final String marker_file;
private final String marker_type;
private final String marker_id;
IBreakpoints service;
IBreakpoints.DoneCommand done;
Map<String,Object> tcf_attrs;
@SuppressWarnings("unchecked")
BreakpointUpdate(IBreakpoint breakpoint) throws CoreException, IOException {
this.breakpoint = breakpoint;
marker_attrs = new HashMap<String,Object>(breakpoint.getMarker().getAttributes());
marker_file = getFilePath(breakpoint.getMarker().getResource());
marker_type = breakpoint.getMarker().getType();
marker_id = getBreakpointID(breakpoint);
}
synchronized void exec() throws InterruptedException {
assert !Protocol.isDispatchThread();
if (marker_id != null) {
Protocol.invokeLater(this);
wait();
}
}
public void run() {
if (disposed) return;
tcf_attrs = toBreakpointAttributes(marker_id, marker_file, marker_type, marker_attrs);
for (final IChannel channel : channels) {
service = channel.getRemoteService(IBreakpoints.class);
if (!isSupported(channel, breakpoint)) continue;
done = new IBreakpoints.DoneCommand() {
public void doneCommand(IToken token, Exception error) {
if (error != null) channel.terminate(error);
}
};
update();
}
Protocol.sync(new Runnable() {
public void run() {
synchronized (BreakpointUpdate.this) {
BreakpointUpdate.this.notify();
}
}
});
};
abstract void update();
}
private String getFilePath(IResource resource) throws IOException {
if (resource == ResourcesPlugin.getWorkspace().getRoot()) return null;
IPath p = resource.getRawLocation();
if (p == null) return null;
return p.toFile().getCanonicalPath();
}
public void breakpointAdded(final IBreakpoint breakpoint) {
try {
new BreakpointUpdate(breakpoint) {
@Override
void update() {
if (!Boolean.FALSE.equals(marker_attrs.get(IBreakpoint.PERSISTED))) {
service.add(tcf_attrs, done);
}
id2bp.put((String)tcf_attrs.get(IBreakpoints.PROP_ID), breakpoint);
}
}.exec();
}
catch (Throwable x) {
Activator.log("Unhandled exception in breakpoint listener", x);
}
}
@SuppressWarnings("unchecked")
private Set<String> calcMarkerDeltaKeys(IMarker marker, IMarkerDelta delta) throws CoreException {
Set<String> keys = new HashSet<String>();
if (delta == null) return keys;
Map<String,Object> m0 = delta.getAttributes();
Map<String,Object> m1 = marker.getAttributes();
if (m0 != null) keys.addAll(m0.keySet());
if (m1 != null) keys.addAll(m1.keySet());
for (Iterator<String> i = keys.iterator(); i.hasNext();) {
String key = i.next();
Object v0 = m0 != null ? m0.get(key) : null;
Object v1 = m1 != null ? m1.get(key) : null;
if (v0 instanceof String && ((String)v0).length() == 0) v0 = null;
if (v1 instanceof String && ((String)v1).length() == 0) v1 = null;
if (v0 instanceof Boolean && !((Boolean)v0).booleanValue()) v0 = null;
if (v1 instanceof Boolean && !((Boolean)v1).booleanValue()) v1 = null;
if ((v0 == null) != (v1 == null)) continue;
if (v0 != null && !v0.equals(v1)) continue;
i.remove();
}
keys.remove("org.eclipse.cdt.debug.core.installCount");
return keys;
}
public void breakpointChanged(final IBreakpoint breakpoint, IMarkerDelta delta) {
try {
final Set<String> s = calcMarkerDeltaKeys(breakpoint.getMarker(), delta);
if (s.isEmpty()) return;
new BreakpointUpdate(breakpoint) {
@Override
void update() {
String id = (String)tcf_attrs.get(IBreakpoints.PROP_ID);
if (s.size() == 1 && s.contains(IBreakpoint.ENABLED)) {
Boolean enabled = (Boolean)tcf_attrs.get(IBreakpoints.PROP_ENABLED);
if (enabled == null || !enabled.booleanValue()) {
service.disable(new String[]{ id }, done);
}
else {
service.enable(new String[]{ id }, done);
}
}
else {
service.change(tcf_attrs, done);
}
id2bp.put(id, breakpoint);
}
}.exec();
}
catch (Throwable x) {
Activator.log("Unhandled exception in breakpoint listener", x);
}
}
public void breakpointRemoved(IBreakpoint breakpoint, IMarkerDelta delta) {
try {
new BreakpointUpdate(breakpoint) {
@Override
void update() {
String id = (String)tcf_attrs.get(IBreakpoints.PROP_ID);
if (!Boolean.FALSE.equals(marker_attrs.get(IBreakpoint.PERSISTED))) {
service.remove(new String[]{ id }, done);
}
id2bp.remove(id);
}
}.exec();
}
catch (Throwable x) {
Activator.log("Unhandled exception in breakpoint listener", x);
}
}
public Map<String,Object> toMarkerAttributes(Map<String,Object> p) {
assert !disposed;
assert Protocol.isDispatchThread();
Map<String,Object> m = new HashMap<String,Object>();
for (Iterator<Map.Entry<String,Object>> i = p.entrySet().iterator(); i.hasNext();) {
Map.Entry<String,Object> e = i.next();
String key = e.getKey();
Object val = e.getValue();
if (key.equals(IBreakpoints.PROP_ENABLED)) continue;
if (key.equals(IBreakpoints.PROP_FILE)) continue;
if (key.equals(IBreakpoints.PROP_LINE)) continue;
if (key.equals(IBreakpoints.PROP_COLUMN)) continue;
m.put(ITCFConstants.ID_TCF_DEBUG_MODEL + '.' + key, val);
}
Boolean enabled = (Boolean)p.get(IBreakpoints.PROP_ENABLED);
if (enabled == null) m.put(IBreakpoint.ENABLED, Boolean.FALSE);
else m.put(IBreakpoint.ENABLED, enabled);
m.put(IBreakpoint.REGISTERED, Boolean.TRUE);
m.put(IBreakpoint.PERSISTED, Boolean.TRUE);
m.put(IBreakpoint.ID, ITCFConstants.ID_TCF_DEBUG_MODEL);
String msg = "";
if (p.get(IBreakpoints.PROP_LOCATION) != null) msg += p.get(IBreakpoints.PROP_LOCATION);
m.put(IMarker.MESSAGE, "Breakpoint: " + msg);
Number line = (Number)p.get(IBreakpoints.PROP_LINE);
if (line != null) {
m.put(IMarker.LINE_NUMBER, new Integer(line.intValue()));
Number column = (Number)p.get(IBreakpoints.PROP_COLUMN);
if (column != null) {
m.put(IMarker.CHAR_START, new Integer(column.intValue()));
m.put(IMarker.CHAR_END, new Integer(column.intValue() + 1));
}
}
return m;
}
public Map<String,Object> toBreakpointAttributes(String id, String file, String type, Map<String,Object> p) {
assert !disposed;
assert Protocol.isDispatchThread();
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, id);
for (Iterator<Map.Entry<String,Object>> i = p.entrySet().iterator(); i.hasNext();) {
Map.Entry<String,Object> e = i.next();
String key = e.getKey();
Object val = e.getValue();
if (!key.startsWith(ITCFConstants.ID_TCF_DEBUG_MODEL)) continue;
String tcfKey = key.substring(ITCFConstants.ID_TCF_DEBUG_MODEL.length() + 1);
if (IBreakpoints.PROP_CONTEXTIDS.equals(tcfKey)) {
val = ((String) val).split(",\\s*");
}
m.put(tcfKey, val);
}
Boolean enabled = (Boolean)p.get(IBreakpoint.ENABLED);
if (enabled != null && enabled.booleanValue() && bp_manager.isEnabled()) {
m.put(IBreakpoints.PROP_ENABLED, enabled);
}
if (file == null) file = (String)p.get("org.eclipse.cdt.debug.core.sourceHandle");
- if (file != null) {
+ if (file != null && file.length() > 0) {
// Map file path to remote file system
int i = file.lastIndexOf('/');
int j = file.lastIndexOf('\\');
String name = file;
if (i > j) name = file.substring(i + 1);
else if (i < j) name = file.substring(j + 1);
m.put(IBreakpoints.PROP_FILE, name);
Integer line = (Integer)p.get(IMarker.LINE_NUMBER);
if (line != null) {
m.put(IBreakpoints.PROP_LINE, new Integer(line.intValue()));
Integer column = (Integer)p.get(IMarker.CHAR_START);
if (column != null) m.put(IBreakpoints.PROP_COLUMN, column);
}
}
if ("org.eclipse.cdt.debug.core.cWatchpointMarker".equals(type)) {
String expr = (String)p.get("org.eclipse.cdt.debug.core.expression");
if (expr != null && expr.length() != 0) {
boolean writeAccess = Boolean.TRUE.equals(p.get("org.eclipse.cdt.debug.core.write"));
boolean readAccess = Boolean.TRUE.equals(p.get("org.eclipse.cdt.debug.core.read"));
int accessMode = 0;
if (readAccess) accessMode |= IBreakpoints.ACCESSMODE_READ;
if (writeAccess) accessMode |= IBreakpoints.ACCESSMODE_WRITE;
m.put(IBreakpoints.PROP_ACCESSMODE, Integer.valueOf(accessMode));
m.put(IBreakpoints.PROP_LOCATION, "&(" + expr + ')');
}
}
else if ("org.eclipse.cdt.debug.core.cFunctionBreakpointMarker".equals(type)) {
String expr = (String)p.get("org.eclipse.cdt.debug.core.function");
if (expr != null && expr.length() != 0) {
m.put(IBreakpoints.PROP_LOCATION, expr);
}
}
else if (file == null) {
String address = (String)p.get("org.eclipse.cdt.debug.core.address");
if (address != null && address.length() > 0) m.put(IBreakpoints.PROP_LOCATION, address);
}
String condition = (String)p.get("org.eclipse.cdt.debug.core.condition");
if (condition != null && condition.length() > 0) m.put(IBreakpoints.PROP_CONDITION, condition);
Integer skip_count = (Integer)p.get("org.eclipse.cdt.debug.core.ignoreCount");
if (skip_count != null && skip_count.intValue() > 0) m.put(IBreakpoints.PROP_IGNORECOUNT, skip_count);
return m;
}
}
| true | true | public Map<String,Object> toBreakpointAttributes(String id, String file, String type, Map<String,Object> p) {
assert !disposed;
assert Protocol.isDispatchThread();
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, id);
for (Iterator<Map.Entry<String,Object>> i = p.entrySet().iterator(); i.hasNext();) {
Map.Entry<String,Object> e = i.next();
String key = e.getKey();
Object val = e.getValue();
if (!key.startsWith(ITCFConstants.ID_TCF_DEBUG_MODEL)) continue;
String tcfKey = key.substring(ITCFConstants.ID_TCF_DEBUG_MODEL.length() + 1);
if (IBreakpoints.PROP_CONTEXTIDS.equals(tcfKey)) {
val = ((String) val).split(",\\s*");
}
m.put(tcfKey, val);
}
Boolean enabled = (Boolean)p.get(IBreakpoint.ENABLED);
if (enabled != null && enabled.booleanValue() && bp_manager.isEnabled()) {
m.put(IBreakpoints.PROP_ENABLED, enabled);
}
if (file == null) file = (String)p.get("org.eclipse.cdt.debug.core.sourceHandle");
if (file != null) {
// Map file path to remote file system
int i = file.lastIndexOf('/');
int j = file.lastIndexOf('\\');
String name = file;
if (i > j) name = file.substring(i + 1);
else if (i < j) name = file.substring(j + 1);
m.put(IBreakpoints.PROP_FILE, name);
Integer line = (Integer)p.get(IMarker.LINE_NUMBER);
if (line != null) {
m.put(IBreakpoints.PROP_LINE, new Integer(line.intValue()));
Integer column = (Integer)p.get(IMarker.CHAR_START);
if (column != null) m.put(IBreakpoints.PROP_COLUMN, column);
}
}
if ("org.eclipse.cdt.debug.core.cWatchpointMarker".equals(type)) {
String expr = (String)p.get("org.eclipse.cdt.debug.core.expression");
if (expr != null && expr.length() != 0) {
boolean writeAccess = Boolean.TRUE.equals(p.get("org.eclipse.cdt.debug.core.write"));
boolean readAccess = Boolean.TRUE.equals(p.get("org.eclipse.cdt.debug.core.read"));
int accessMode = 0;
if (readAccess) accessMode |= IBreakpoints.ACCESSMODE_READ;
if (writeAccess) accessMode |= IBreakpoints.ACCESSMODE_WRITE;
m.put(IBreakpoints.PROP_ACCESSMODE, Integer.valueOf(accessMode));
m.put(IBreakpoints.PROP_LOCATION, "&(" + expr + ')');
}
}
else if ("org.eclipse.cdt.debug.core.cFunctionBreakpointMarker".equals(type)) {
String expr = (String)p.get("org.eclipse.cdt.debug.core.function");
if (expr != null && expr.length() != 0) {
m.put(IBreakpoints.PROP_LOCATION, expr);
}
}
else if (file == null) {
String address = (String)p.get("org.eclipse.cdt.debug.core.address");
if (address != null && address.length() > 0) m.put(IBreakpoints.PROP_LOCATION, address);
}
String condition = (String)p.get("org.eclipse.cdt.debug.core.condition");
if (condition != null && condition.length() > 0) m.put(IBreakpoints.PROP_CONDITION, condition);
Integer skip_count = (Integer)p.get("org.eclipse.cdt.debug.core.ignoreCount");
if (skip_count != null && skip_count.intValue() > 0) m.put(IBreakpoints.PROP_IGNORECOUNT, skip_count);
return m;
}
| public Map<String,Object> toBreakpointAttributes(String id, String file, String type, Map<String,Object> p) {
assert !disposed;
assert Protocol.isDispatchThread();
Map<String,Object> m = new HashMap<String,Object>();
m.put(IBreakpoints.PROP_ID, id);
for (Iterator<Map.Entry<String,Object>> i = p.entrySet().iterator(); i.hasNext();) {
Map.Entry<String,Object> e = i.next();
String key = e.getKey();
Object val = e.getValue();
if (!key.startsWith(ITCFConstants.ID_TCF_DEBUG_MODEL)) continue;
String tcfKey = key.substring(ITCFConstants.ID_TCF_DEBUG_MODEL.length() + 1);
if (IBreakpoints.PROP_CONTEXTIDS.equals(tcfKey)) {
val = ((String) val).split(",\\s*");
}
m.put(tcfKey, val);
}
Boolean enabled = (Boolean)p.get(IBreakpoint.ENABLED);
if (enabled != null && enabled.booleanValue() && bp_manager.isEnabled()) {
m.put(IBreakpoints.PROP_ENABLED, enabled);
}
if (file == null) file = (String)p.get("org.eclipse.cdt.debug.core.sourceHandle");
if (file != null && file.length() > 0) {
// Map file path to remote file system
int i = file.lastIndexOf('/');
int j = file.lastIndexOf('\\');
String name = file;
if (i > j) name = file.substring(i + 1);
else if (i < j) name = file.substring(j + 1);
m.put(IBreakpoints.PROP_FILE, name);
Integer line = (Integer)p.get(IMarker.LINE_NUMBER);
if (line != null) {
m.put(IBreakpoints.PROP_LINE, new Integer(line.intValue()));
Integer column = (Integer)p.get(IMarker.CHAR_START);
if (column != null) m.put(IBreakpoints.PROP_COLUMN, column);
}
}
if ("org.eclipse.cdt.debug.core.cWatchpointMarker".equals(type)) {
String expr = (String)p.get("org.eclipse.cdt.debug.core.expression");
if (expr != null && expr.length() != 0) {
boolean writeAccess = Boolean.TRUE.equals(p.get("org.eclipse.cdt.debug.core.write"));
boolean readAccess = Boolean.TRUE.equals(p.get("org.eclipse.cdt.debug.core.read"));
int accessMode = 0;
if (readAccess) accessMode |= IBreakpoints.ACCESSMODE_READ;
if (writeAccess) accessMode |= IBreakpoints.ACCESSMODE_WRITE;
m.put(IBreakpoints.PROP_ACCESSMODE, Integer.valueOf(accessMode));
m.put(IBreakpoints.PROP_LOCATION, "&(" + expr + ')');
}
}
else if ("org.eclipse.cdt.debug.core.cFunctionBreakpointMarker".equals(type)) {
String expr = (String)p.get("org.eclipse.cdt.debug.core.function");
if (expr != null && expr.length() != 0) {
m.put(IBreakpoints.PROP_LOCATION, expr);
}
}
else if (file == null) {
String address = (String)p.get("org.eclipse.cdt.debug.core.address");
if (address != null && address.length() > 0) m.put(IBreakpoints.PROP_LOCATION, address);
}
String condition = (String)p.get("org.eclipse.cdt.debug.core.condition");
if (condition != null && condition.length() > 0) m.put(IBreakpoints.PROP_CONDITION, condition);
Integer skip_count = (Integer)p.get("org.eclipse.cdt.debug.core.ignoreCount");
if (skip_count != null && skip_count.intValue() > 0) m.put(IBreakpoints.PROP_IGNORECOUNT, skip_count);
return m;
}
|
diff --git a/src/main/java/org/atlasapi/equiv/generators/RadioTimesFilmEquivalenceGenerator.java b/src/main/java/org/atlasapi/equiv/generators/RadioTimesFilmEquivalenceGenerator.java
index 7496bc3fe..09f293a99 100644
--- a/src/main/java/org/atlasapi/equiv/generators/RadioTimesFilmEquivalenceGenerator.java
+++ b/src/main/java/org/atlasapi/equiv/generators/RadioTimesFilmEquivalenceGenerator.java
@@ -1,54 +1,54 @@
package org.atlasapi.equiv.generators;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.atlasapi.equiv.results.description.ResultDescription;
import org.atlasapi.equiv.results.scores.DefaultScoredEquivalents;
import org.atlasapi.equiv.results.scores.DefaultScoredEquivalents.ScoredEquivalentsBuilder;
import org.atlasapi.equiv.results.scores.Score;
import org.atlasapi.equiv.results.scores.ScoredEquivalents;
import org.atlasapi.media.entity.Film;
import org.atlasapi.media.entity.Identified;
import org.atlasapi.media.entity.Item;
import org.atlasapi.persistence.content.ContentResolver;
import com.google.common.collect.ImmutableSet;
import com.metabroadcast.common.base.Maybe;
public class RadioTimesFilmEquivalenceGenerator implements ContentEquivalenceGenerator<Item> {
private final Pattern rtFilmUriPattern = Pattern.compile("http://radiotimes.com/films/(\\d+)");
private final String paFilmUriPrefix = "http://pressassociation.com/films/";
private final ContentResolver resolver;
public RadioTimesFilmEquivalenceGenerator(ContentResolver resolver) {
this.resolver = resolver;
}
@Override
public ScoredEquivalents<Item> generate(Item content, ResultDescription desc) {
checkArgument(content instanceof Film, "Content not Film:" + content.getCanonicalUri());
- ScoredEquivalentsBuilder<Item> results = DefaultScoredEquivalents.fromSource("Film");
+ ScoredEquivalentsBuilder<Item> results = DefaultScoredEquivalents.fromSource("RT->PA");
Matcher uriMatcher = rtFilmUriPattern.matcher(content.getCanonicalUri());
if (uriMatcher.matches()) {
String paUri = paFilmUriPrefix + uriMatcher.group(1);
Maybe<Identified> resolvedContent = resolver.findByCanonicalUris(ImmutableSet.of(paUri)).get(paUri);
if (resolvedContent.hasValue() && resolvedContent.requireValue() instanceof Film) {
results.addEquivalent((Film)resolvedContent.requireValue(), Score.ONE);
}
}
return results.build();
}
@Override
public String toString() {
return "RadioTimes Film Generator";
}
}
| true | true | public ScoredEquivalents<Item> generate(Item content, ResultDescription desc) {
checkArgument(content instanceof Film, "Content not Film:" + content.getCanonicalUri());
ScoredEquivalentsBuilder<Item> results = DefaultScoredEquivalents.fromSource("Film");
Matcher uriMatcher = rtFilmUriPattern.matcher(content.getCanonicalUri());
if (uriMatcher.matches()) {
String paUri = paFilmUriPrefix + uriMatcher.group(1);
Maybe<Identified> resolvedContent = resolver.findByCanonicalUris(ImmutableSet.of(paUri)).get(paUri);
if (resolvedContent.hasValue() && resolvedContent.requireValue() instanceof Film) {
results.addEquivalent((Film)resolvedContent.requireValue(), Score.ONE);
}
}
return results.build();
}
| public ScoredEquivalents<Item> generate(Item content, ResultDescription desc) {
checkArgument(content instanceof Film, "Content not Film:" + content.getCanonicalUri());
ScoredEquivalentsBuilder<Item> results = DefaultScoredEquivalents.fromSource("RT->PA");
Matcher uriMatcher = rtFilmUriPattern.matcher(content.getCanonicalUri());
if (uriMatcher.matches()) {
String paUri = paFilmUriPrefix + uriMatcher.group(1);
Maybe<Identified> resolvedContent = resolver.findByCanonicalUris(ImmutableSet.of(paUri)).get(paUri);
if (resolvedContent.hasValue() && resolvedContent.requireValue() instanceof Film) {
results.addEquivalent((Film)resolvedContent.requireValue(), Score.ONE);
}
}
return results.build();
}
|
diff --git a/src/com/ichi2/libanki/Models.java b/src/com/ichi2/libanki/Models.java
index ff132f10..89377eb1 100644
--- a/src/com/ichi2/libanki/Models.java
+++ b/src/com/ichi2/libanki/Models.java
@@ -1,1068 +1,1068 @@
/****************************************************************************************
* Copyright (c) 2009 Daniel Svärd <[email protected]> *
* Copyright (c) 2010 Rick Gruber-Riemer <[email protected]> *
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import com.ichi2.anki.AnkiDb;
import com.ichi2.anki.AnkiDroidApp;
import com.mindprod.common11.StringTools;
import com.samskivert.mustache.Mustache;
import com.samskivert.mustache.Template;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Models {
private static final String defaultModel =
"{'sortf': 0, " +
"'did': 1, " +
"'latexPre': \"" +
"\\\\documentclass[12pt]{article} " +
"\\\\special{papersize=3in,5in} " +
"\\\\usepackage[utf8]{inputenc} " +
"\\\\usepackage{amssymb,amsmath} " +
"\\\\pagestyle{empty} " +
"\\\\setlength{\\\\parindent}{0in} " +
"\\\\begin{document} " +
"\", " +
"'latexPost': \"\\\\end{document}\", " +
"'mod': 9, " +
"'usn': 9, " +
"'vers': [] }";
private static final String defaultField =
"{'name': \"\", " +
"'ord': None, " +
"'sticky': False, " +
// the following alter editing, and are used as defaults for the template wizard
"'rtl': False, " +
"'font': \"Arial\", " +
"'size': 20, " +
// reserved for future use
"'media': [] }";
private static final String defaultTemplate =
"{'name': \"\", " +
"'ord': None, " +
"'qfmt': \"\", " +
"'afmt': \"\", " +
"'did': None, " +
"'css': \".card { " +
" font-family: arial;" +
" font-size: 20px;" +
" text-align: center;" +
" color: black;" +
" background-color: white;" +
" }" +
"\"}";
// /** Regex pattern used in removing tags from text before diff */
// private static final Pattern sFactPattern = Pattern.compile("%\\([tT]ags\\)s");
// private static final Pattern sModelPattern = Pattern.compile("%\\(modelTags\\)s");
// private static final Pattern sTemplPattern = Pattern.compile("%\\(cardModel\\)s");
private Collection mCol;
private boolean mChanged;
private HashMap<Long, JSONObject> mModels;
// BEGIN SQL table entries
private int mId;
private String mName = "";
private long mCrt = Utils.intNow();
private long mMod = Utils.intNow();
private JSONObject mConf;
private String mCss = "";
private JSONArray mFields;
private JSONArray mTemplates;
// BEGIN SQL table entries
// private Decks mDeck;
// private AnkiDb mDb;
//
/** Map for compiled Mustache Templates */
private HashMap<Long, HashMap<Integer, Template[]>> mCmpldTemplateMap = new HashMap<Long, HashMap<Integer, Template[]>>();
//
// /** Map for convenience and speed which contains FieldNames from current model */
// private TreeMap<String, Integer> mFieldMap = new TreeMap<String, Integer>();
//
// /** Map for convenience and speed which contains Templates from current model */
// private TreeMap<Integer, JSONObject> mTemplateMap = new TreeMap<Integer, JSONObject>();
//
// /** Map for convenience and speed which contains the CSS code related to a Template */
// private HashMap<Integer, String> mCssTemplateMap = new HashMap<Integer, String>();
//
// /**
// * The percentage chosen in preferences for font sizing at the time when the css for the CardModels related to this
// * Model was calculated in prepareCSSForCardModels.
// */
// private transient int mDisplayPercentage = 0;
// private boolean mNightMode = false;
/**
* Saving/loading registry
* ***********************************************************************************************
*/
public Models(Collection col) {
mCol = col;
}
/**
* Load registry from JSON.
*/
public void load(String json) {
mChanged = false;
mModels = new HashMap<Long, JSONObject>();
try {
JSONObject modelarray = new JSONObject(json);
JSONArray ids = modelarray.names();
for (int i = 0; i < ids.length(); i++) {
String id = ids.getString(i);
JSONObject o = modelarray.getJSONObject(id);
mModels.put(o.getLong("id"), o);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Mark M modified if provided, and schedule registry flush.
*/
public void save() {
save(null, false);
}
public void save(JSONObject m) {
save(m, false);
}
public void save(JSONObject m, boolean templates) {
if (m != null && m.has("id")) {
try {
m.put("mod", Utils.intNow());
m.put("usn", mCol.usn());
// TODO: fix empty id problem on _updaterequired (needed for model adding)
if (m.getLong("id") != 0) {
_updateRequired(m);
}
if (templates) {
_syncTemplates(m);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
mChanged = true;
}
/**
* Flush the registry if any models were changed.
*/
public void flush() {
if (mChanged) {
JSONObject array = new JSONObject();
try {
for (Map.Entry<Long, JSONObject> o : mModels.entrySet()) {
array.put(Long.toString(o.getKey()), o.getValue());
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
ContentValues val = new ContentValues();
val.put("models", array.toString());
mCol.getDb().update("col", val);
mChanged = false;
}
}
/**
* Retrieving and creating models
* ***********************************************************************************************
*/
/**
* Get current model.
*/
public JSONObject current() {
JSONObject m;
try {
m = get(mCol.getConf().getLong("curModel"));
if (m != null) {
return m;
} else {
if (!mModels.isEmpty()) {
return mModels.values().iterator().next();
} else {
return null;
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public void setCurrent(JSONObject m) {
try {
mCol.getConf().put("curModel", m.get("id"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCol.setMod();
}
/** get model with ID, or none. */
public JSONObject get(long id) {
if (mModels.containsKey(id)) {
return mModels.get(id);
} else {
return null;
}
}
/** get all models */
public ArrayList<JSONObject> all() {
ArrayList<JSONObject> models = new ArrayList<JSONObject>();
Iterator<JSONObject> it = mModels.values().iterator();
while(it.hasNext()) {
models.add(it.next());
}
return models;
}
/** get model with NAME. */
public JSONObject byName(String name) {
for (JSONObject m : mModels.values()) {
try {
if (m.getString("name").equalsIgnoreCase(name)) {
return m;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return null;
}
/** Create a new model, save it in the registry, and return it. */
public JSONObject newModel(String name) {
// caller should call save() after modifying
JSONObject m;
try {
m = new JSONObject(defaultModel);
m.put("name", name);
m.put("mod", Utils.intNow());
m.put("flds", new JSONArray());
m.put("tmpls", new JSONArray());
m.put("tags", new JSONArray());
m.put("id", 0);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return m;
}
/** Delete model, and all its cards/notes. */
public void rem(JSONObject m) {
mCol.modSchema();
try {
long id = m.getLong("id");
boolean current = current().getLong("id") == id;
// delete notes/cards
mCol.remCards(Utils.arrayList2array(mCol.getDb().queryColumn(Long.class, "SELECT id FROM cards WHERE nid IN (SELECT id FROM notes WHERE mid = " + id + ")", 0)));
// then the model
mModels.remove(id);
save();
// GUI should ensure last model is not deleted
if (current) {
setCurrent(mModels.values().iterator().next());
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public void add(JSONObject m, boolean setCurrent) {
_setID(m);
update(m);
if (setCurrent) {
setCurrent(m);
}
save(m);
}
/** Add or update an existing model. Used for syncing and merging. */
public void update(JSONObject m) {
try {
mModels.put(m.getLong("id"), m);
} catch (JSONException e) {
throw new RuntimeException(e);
}
// mark registry changed, but don't bump mod time
save();
}
private void _setID(JSONObject m) {
long id = Utils.intNow();
while (mModels.containsKey(id)) {
id = Utils.intNow();
}
try {
m.put("id", id);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public boolean have(long id) {
return mModels.containsKey(id);
}
/**
* Tools
* ***********************************************************************************************
*/
/** Note ids for M */
public ArrayList<Long> nids(JSONObject m) {
try {
return mCol.getDb().queryColumn(Long.class, "SELECT id FROM notes WHERE mid = " + m.getLong("id"), 0);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
// usecounts
/**
* Copying
* ***********************************************************************************************
*/
// copy
/**
* Fields
* ***********************************************************************************************
*/
public JSONObject newField(String name) {
JSONObject f;
try {
f = new JSONObject(defaultField);
f.put("name", name);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return f;
}
// /** Mapping of field name --> (ord, field). */
// public TreeMap<String, Object[]> fieldMap(JSONObject m) {
// JSONArray ja;
// try {
// ja = m.getJSONArray("flds");
// TreeMap<String, Object[]> map = new TreeMap<String, Object[]>();
// for (int i = 0; i < ja.length(); i++) {
// JSONObject f = ja.getJSONObject(i);
// map.put(f.getString("name"), new Object[]{f.getInt("ord"), f});
// }
// return map;
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
public String[] orderedFields(JSONObject m) {
JSONArray ja;
try {
ja = m.getJSONArray("flds");
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
for (int i = 0; i < ja.length(); i++) {
JSONObject f = ja.getJSONObject(i);
map.put(f.getInt("ord"), f.getString("name"));
}
String[] result = new String[map.size()];
for (int i = 0; i < map.size(); i++) {
result[i] = map.get(i);
}
return result;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public ArrayList<String> fieldNames(JSONObject m) {
JSONArray ja;
try {
ja = m.getJSONArray("flds");
ArrayList<String> names = new ArrayList<String>();
for (int i = 0; i < ja.length(); i++) {
names.add(ja.getJSONObject(i).getString("name"));
}
return names;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public int sortIdx(JSONObject m) {
try {
return m.getInt("sortf");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
// public int setSortIdx(JSONObject m, int idx) {
// try {
// mCol.modSchema();
// m.put("sortf", idx);
// mCol.updateFieldCache(nids(m));
// save(m);
// } catch (JSONException e) {
// throw new RuntimeException(e);
// }
// }
public void addField(JSONObject m, JSONObject field) {
// only mod schema if model isn't new
try {
if (m.getLong("id") != 0) {
mCol.modSchema();
}
JSONArray ja = m.getJSONArray("flds");
ja.put(field);
m.put("flds", ja);
_updateFieldOrds(m);
save(m);
_transformFields(m); //, Method add);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//remfield
//movefield
//renamefield
public void _updateFieldOrds(JSONObject m) {
JSONArray ja;
try {
ja = m.getJSONArray("flds");
for (int i = 0; i < ja.length(); i++) {
JSONObject f = ja.getJSONObject(i);
f.put("ord", i);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public void _transformFields(JSONObject m) { // Method fn) {
// model hasn't been added yet?
try {
if (m.getLong("id") == 0) {
return;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// TODO
}
/**
* Templates
* ***********************************************************************************************
*/
public JSONObject newTemplate(String name) {
JSONObject t;
try {
t = new JSONObject(defaultTemplate);
t.put("name", name);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return t;
}
/** Note: should col.genCards() afterwards. */
public void addTemplate(JSONObject m, JSONObject template) {
try {
if (m.getLong("id") != 0) {
mCol.modSchema();
}
JSONArray ja = m.getJSONArray("tmpls");
ja.put(template);
m.put("tmpls", ja);
_updateTemplOrds(m);
save(m);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//remtemplate
public void _updateTemplOrds(JSONObject m) {
JSONArray ja;
try {
ja = m.getJSONArray("tmpls");
for (int i = 0; i < ja.length(); i++) {
JSONObject f = ja.getJSONObject(i);
f.put("ord", i);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//movetemplate
private void _syncTemplates(JSONObject m) {
ArrayList<Long> rem = mCol.genCards(Utils.arrayList2array(nids(m)));
mCol.remEmptyCards(Utils.arrayList2array(rem));
}
// public TreeMap<Integer, JSONObject> getTemplates() {
// return mTemplateMap;
// }
//
//
// public JSONObject getTemplate(int ord) {
// return mTemplateMap.get(ord);
// }
// not in libanki
public Template[] getCmpldTemplate(long modelId, int ord) {
if (!mCmpldTemplateMap.containsKey(modelId)) {
mCmpldTemplateMap.put(modelId, new HashMap<Integer, Template[]>());
}
if (!mCmpldTemplateMap.get(modelId).containsKey(ord)) {
mCmpldTemplateMap.get(modelId).put(ord, compileTemplate(modelId, ord));
}
return mCmpldTemplateMap.get(modelId).get(ord);
}
// not in libanki
private Template[] compileTemplate(long modelId, int ord) {
JSONObject model = mModels.get(modelId);
JSONObject template;
Template[] t = new Template[2];
try {
template = model.getJSONArray("tmpls").getJSONObject(ord);
String format = template.getString("qfmt").replace("cloze:", "cq:");
Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + format + "\"");
t[0] = Mustache.compiler().compile(format);
format = template.getString("afmt").replace("cloze:", "ca:");
Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + format + "\"");
t[1] = Mustache.compiler().compile(format);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return t;
}
// not in libanki
// Handle fields fetched from templates and any anki-specific formatting
protected static class fieldParser implements Mustache.VariableFetcher {
private Map <String, String> _fields;
private String rubyr = " ?([^ ]+?)\\[(.+?)\\]";
public fieldParser (Map<String, String> fields) {
_fields = fields;
}
public Object get (Object ctx, String name) throws Exception {
if (name.length() == 0) {
return null;
}
String txt = _fields.get(name);
if (txt != null) {
return txt;
}
// field modifier handling as taken from template.py
String[] parts = name.split(":", 3);
String mod = null, extra = null, tag = null;
if (parts.length == 1 || parts[0].length() == 0) {
return null;
} else if (parts.length == 2) {
mod = parts[0];
tag = parts[1];
} else if (parts.length == 3) {
mod = parts[0];
extra = parts[1];
tag = parts[2];
}
txt = _fields.get(tag);
Log.d(AnkiDroidApp.TAG, "Processing field modifier " + mod + ": extra = " + extra + ", field " + tag + " = " + txt);
// built-in modifiers
// including furigana/ruby text handling
if (mod.equals("text")) {
// strip html
if (txt != null) {
return Utils.stripHTML(txt);
}
return "";
} else if (mod.equals("type")) {
// TODO: handle type field modifier
Log.e(AnkiDroidApp.TAG, "Unimplemented field modifier: " + mod);
return null;
} else if (mod.equals("cq") || mod.equals("ca")) {
// cloze handling
if (txt == null || extra == null) return "";
int ord;
try {
ord = Integer.parseInt(extra);
} catch (NumberFormatException e) {
return "";
}
if (ord < 0) return "";
String rx = "\\{\\{c"+ord+"::(.*?)(?:::(.*?))?\\}\\}";
Matcher m = Pattern.compile(rx).matcher(txt);
String clozetxt = null;
if (mod.equals("ca")) {
// in answer
clozetxt = m.replaceAll("<span class=\"cloze\">$1</span>");
} else {
// in question
// unfortunately, Android's java implementation replaces
// non-matching captures with "null", requiring this ugly little loop
StringBuffer sb = new StringBuffer();
while (m.find()) {
if (m.group(2) != null) {
m.appendReplacement(sb, "<span class=\"cloze\">[...$2]</span>");
} else {
m.appendReplacement(sb, "<span class=\"cloze\">[...]</span>");
}
}
m.appendTail(sb);
clozetxt = sb.toString();
}
if (clozetxt.equals(txt)) {
// cloze wasn't found; return empty
return "";
}
// display any other clozes normally
clozetxt = clozetxt.replaceAll("\\{\\{c[0-9]+::(.*?)(?:::(.*?))?\\}\\}", "$1");
Log.d(AnkiDroidApp.TAG, "Cloze: ord=" + ord + ", txt=" + clozetxt);
return clozetxt;
} else if (mod.equals("kanjionly")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "$1");
} else if (mod.equals("readingonly")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "$2");
} else if (mod.equals("furigana")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "<ruby><rb>$1</rb><rt>$2</rt></ruby>");
} else {
Log.w(AnkiDroidApp.TAG, "Unknown field modifier: " + mod);
return txt;
}
}
}
// /**
// * This function recompiles the templates for question and answer. It should be called everytime we change mQformat
// * or mAformat, so if in the future we create set(Q|A)Format setters, we should include a call to this.
// */
// private void refreshTemplates(int ord) {
// // Question template
// StringBuffer sb = new StringBuffer();
// Matcher m = sOldStylePattern.matcher(mQformat);
// while (m.find()) {
// // Convert old style
// m.appendReplacement(sb, "{{" + m.group(1) + "}}");
// }
// m.appendTail(sb);
// Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + sb.toString() + "\"");
// mQTemplate = Mustache.compiler().compile(sb.toString());
//
// // Answer template
// sb = new StringBuffer();
// m = sOldStylePattern.matcher(mAformat);
// while (m.find()) {
// // Convert old style
// m.appendReplacement(sb, "{{" + m.group(1) + "}}");
// }
// m.appendTail(sb);
// Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + sb.toString() + "\"");
// mATemplate = Mustache.compiler().compile(sb.toString());
// }
/**
* Model changing
* ***********************************************************************************************
*/
// change
//_changeNotes
//_changeCards
/**
* Schema hash
* ***********************************************************************************************
*/
//scmhash
/**
* Required field/text cache
* ***********************************************************************************************
*/
private void _updateRequired(JSONObject m) {
JSONArray req = new JSONArray();
ArrayList<String> flds = new ArrayList<String>();
JSONArray fields;
try {
fields = m.getJSONArray("flds");
for (int i = 0; i < fields.length(); i++) {
flds.add(fields.getJSONObject(i).getString("name"));
}
boolean cloze = false;
JSONArray templates = m.getJSONArray("tmpls");
for (int i = 0; i < templates.length(); i++) {
JSONObject t = templates.getJSONObject(i);
Object[] ret = _reqForTemplate(m, flds, t);
if (((JSONArray)ret[2]).length() > 0) {
cloze = true;
}
JSONArray r = new JSONArray();
r.put(t.getInt("ord"));
r.put(ret[0]);
r.put(ret[1]);
r.put(ret[2]);
req.put(r);
}
m.put("req", req);
m.put("cloze", cloze);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) {
try {
ArrayList<String> a = new ArrayList<String> ();
ArrayList<String> b = new ArrayList<String> ();
String cloze = "";
JSONArray reqstrs = new JSONArray();
if (t.has("cloze")) {
// need a cloze-specific filler
// TODO
}
for (String f : flds) {
a.add(cloze.length() > 0 ? cloze : "1");
b.add("");
}
Object[] data;
data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()]))};
String full = mCol._renderQA(data).get("q");
data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()]))};
String empty = mCol._renderQA(data).get("q");
// if full and empty are the same, the template is invalid and there is no way to satisfy it
if (full.equals(empty)) {
return new Object[] {"none", new JSONArray(), new JSONArray()};
}
String type = "all";
JSONArray req = new JSONArray();
ArrayList<String> tmp = new ArrayList<String>();
for (int i = 0; i < flds.size(); i++) {
tmp.clear();
tmp.addAll(a);
tmp.remove(i);
tmp.add(i, "");
data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()]));
// if the result is same as empty, field is required
if (mCol._renderQA(data).get("q").equals(empty)) {
req.put(i);
}
}
if (req.length() > 0) {
return new Object[] {type, req, reqstrs};
}
// if there are no required fields, switch to any mode
type = "any";
req = new JSONArray();
for (int i = 0; i < flds.size(); i++) {
tmp.clear();
tmp.addAll(b);
tmp.remove(i);
tmp.add(i, "1");
data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()]));
// if not the same as empty, this field can make the card non-blank
if (mCol._renderQA(data).get("q").equals(empty)) {
req.put(i);
}
}
return new Object[]{ type, req, reqstrs};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/** Given a joined field string, return available template ordinals */
public ArrayList<Integer> availOrds(JSONObject m, String flds) {
String[] fields = Utils.splitFields(flds);
for (String f : fields) {
f = f.trim();
}
ArrayList<Integer> avail = new ArrayList<Integer>();
try {
JSONArray reqArray = m.getJSONArray("req");
for (int i = 0; i < reqArray.length(); i++) {
JSONArray sr = reqArray.getJSONArray(i);
int ord = sr.getInt(0);
String type = sr.getString(1);
JSONArray req = sr.getJSONArray(2);
JSONArray reqstrs = sr.getJSONArray(3);
if (type.equals("none")) {
// unsatisfiable template
continue;
} else if (type.equals("all")) {
// AND requirement?
boolean ok = true;
for (int j = 0; j < req.length(); j++) {
if (fields.length <= j || fields[j] == null || fields[j].length() == 0) {
// missing and was required
ok = false;
break;
}
}
if (!ok) {
continue;
}
} else if (type.equals("any")) {
// OR requirement?
boolean ok = false;
for (int j = 0; j < req.length(); j++) {
if (fields.length <= j || fields[j] == null || fields[j].length() == 0) {
// missing and was required
ok = true;
break;
}
}
if (!ok) {
continue;
}
}
// extra cloze requirement?
boolean ok = true;
for (int j = 0; j < reqstrs.length(); j++) {
if (!flds.matches(reqstrs.getString(i))) {
// required cloze string was missing
ok = false;
break;
}
}
if (!ok) {
continue;
}
avail.add(ord);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return avail;
}
/**
* Sync handling
* ***********************************************************************************************
*/
public void beforeUpload() {
try {
for (JSONObject m : all()) {
m.put("usn", 0);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
save();
}
/**
* Routines from Stdmodels.py
* ***********************************************************************************************
*/
public JSONObject addBasicModel(String name, boolean setCurrent) {
JSONObject m = newModel(name);
JSONObject fm = newField("Front");
addField(m, fm);
fm = newField("Back");
addField(m, fm);
JSONObject t = newTemplate("Forward");
try {
t.put("qfmt", "{{Front}}");
t.put("afmt", t.getString("qfmt") + "\n\n<hr id=answer>\n\n{{Back}}");
} catch (JSONException e) {
throw new RuntimeException(e);
}
addTemplate(m, t);
add(m, setCurrent);
return m;
}
// addClozeModel
/**
* Other stuff
* NOT IN LIBANKI
* ***********************************************************************************************
*/
public void setChanged() {
mChanged = true;
}
/**
* Returns a string where all colors have been inverted.
* It applies to anything that is in a tag and looks like #FFFFFF
*
* Example: Here only #000000 will be replaced (#777777 is content)
* <span style="color: #000000;">Code #777777 is the grey color</span>
*
* This is done with a state machine with 2 states:
* - 0: within content
* - 1: within a tag
*/
public static String invertColors(String text) {
- final String[] colors = {"white", "black"};
- final String[] htmlColors = {"#000000", "#ffffff"};
+ final String[] colors = {"color=\"white\"", "color=\"black\""};
+ final String[] htmlColors = {"color=\"#000000\"", "color=\"#ffffff\""};
for (int i = 0; i < colors.length; i++) {
text = text.replace(colors[i], htmlColors[i]);
}
int state = 0;
StringBuffer inverted = new StringBuffer(text.length());
for(int i=0; i<text.length(); i++) {
char character = text.charAt(i);
if (state == 1 && character == '#') {
// TODO: handle shorter html-colors too (e.g. #0000)
inverted.append(invertColor(text.substring(i+1, i+7)));
}
else {
if (character == '<') {
state = 1;
}
if (character == '>') {
state = 0;
}
inverted.append(character);
}
}
return inverted.toString();
}
private static String invertColor(String color) {
if (color.length() != 0) {
color = StringTools.toUpperCase(color);
}
final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final char[] tmpItems = {'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'};
for (int i = 0; i < 16; i++) {
color = color.replace(items[i], tmpItems[15-i]);
}
for (int i = 0; i < 16; i++) {
color = color.replace(tmpItems[i], items[i]);
}
return color;
}
public HashMap<Long, HashMap<Integer, String>> getTemplateNames() {
HashMap<Long, HashMap<Integer, String>> result = new HashMap<Long, HashMap<Integer, String>>();
for (JSONObject m : mModels.values()) {
JSONArray templates;
try {
templates = m.getJSONArray("tmpls");
HashMap<Integer, String> names = new HashMap<Integer, String>();
for (int i = 0; i < templates.length(); i++) {
JSONObject t = templates.getJSONObject(i);
names.put(t.getInt("ord"), t.getString("name"));
}
result.put(m.getLong("id"), names);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* @return the ID
*/
public int getId() {
return mId;
}
/**
* @return the name
*/
public String getName() {
return mName;
}
}
| true | true | public void _transformFields(JSONObject m) { // Method fn) {
// model hasn't been added yet?
try {
if (m.getLong("id") == 0) {
return;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// TODO
}
/**
* Templates
* ***********************************************************************************************
*/
public JSONObject newTemplate(String name) {
JSONObject t;
try {
t = new JSONObject(defaultTemplate);
t.put("name", name);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return t;
}
/** Note: should col.genCards() afterwards. */
public void addTemplate(JSONObject m, JSONObject template) {
try {
if (m.getLong("id") != 0) {
mCol.modSchema();
}
JSONArray ja = m.getJSONArray("tmpls");
ja.put(template);
m.put("tmpls", ja);
_updateTemplOrds(m);
save(m);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//remtemplate
public void _updateTemplOrds(JSONObject m) {
JSONArray ja;
try {
ja = m.getJSONArray("tmpls");
for (int i = 0; i < ja.length(); i++) {
JSONObject f = ja.getJSONObject(i);
f.put("ord", i);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//movetemplate
private void _syncTemplates(JSONObject m) {
ArrayList<Long> rem = mCol.genCards(Utils.arrayList2array(nids(m)));
mCol.remEmptyCards(Utils.arrayList2array(rem));
}
// public TreeMap<Integer, JSONObject> getTemplates() {
// return mTemplateMap;
// }
//
//
// public JSONObject getTemplate(int ord) {
// return mTemplateMap.get(ord);
// }
// not in libanki
public Template[] getCmpldTemplate(long modelId, int ord) {
if (!mCmpldTemplateMap.containsKey(modelId)) {
mCmpldTemplateMap.put(modelId, new HashMap<Integer, Template[]>());
}
if (!mCmpldTemplateMap.get(modelId).containsKey(ord)) {
mCmpldTemplateMap.get(modelId).put(ord, compileTemplate(modelId, ord));
}
return mCmpldTemplateMap.get(modelId).get(ord);
}
// not in libanki
private Template[] compileTemplate(long modelId, int ord) {
JSONObject model = mModels.get(modelId);
JSONObject template;
Template[] t = new Template[2];
try {
template = model.getJSONArray("tmpls").getJSONObject(ord);
String format = template.getString("qfmt").replace("cloze:", "cq:");
Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + format + "\"");
t[0] = Mustache.compiler().compile(format);
format = template.getString("afmt").replace("cloze:", "ca:");
Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + format + "\"");
t[1] = Mustache.compiler().compile(format);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return t;
}
// not in libanki
// Handle fields fetched from templates and any anki-specific formatting
protected static class fieldParser implements Mustache.VariableFetcher {
private Map <String, String> _fields;
private String rubyr = " ?([^ ]+?)\\[(.+?)\\]";
public fieldParser (Map<String, String> fields) {
_fields = fields;
}
public Object get (Object ctx, String name) throws Exception {
if (name.length() == 0) {
return null;
}
String txt = _fields.get(name);
if (txt != null) {
return txt;
}
// field modifier handling as taken from template.py
String[] parts = name.split(":", 3);
String mod = null, extra = null, tag = null;
if (parts.length == 1 || parts[0].length() == 0) {
return null;
} else if (parts.length == 2) {
mod = parts[0];
tag = parts[1];
} else if (parts.length == 3) {
mod = parts[0];
extra = parts[1];
tag = parts[2];
}
txt = _fields.get(tag);
Log.d(AnkiDroidApp.TAG, "Processing field modifier " + mod + ": extra = " + extra + ", field " + tag + " = " + txt);
// built-in modifiers
// including furigana/ruby text handling
if (mod.equals("text")) {
// strip html
if (txt != null) {
return Utils.stripHTML(txt);
}
return "";
} else if (mod.equals("type")) {
// TODO: handle type field modifier
Log.e(AnkiDroidApp.TAG, "Unimplemented field modifier: " + mod);
return null;
} else if (mod.equals("cq") || mod.equals("ca")) {
// cloze handling
if (txt == null || extra == null) return "";
int ord;
try {
ord = Integer.parseInt(extra);
} catch (NumberFormatException e) {
return "";
}
if (ord < 0) return "";
String rx = "\\{\\{c"+ord+"::(.*?)(?:::(.*?))?\\}\\}";
Matcher m = Pattern.compile(rx).matcher(txt);
String clozetxt = null;
if (mod.equals("ca")) {
// in answer
clozetxt = m.replaceAll("<span class=\"cloze\">$1</span>");
} else {
// in question
// unfortunately, Android's java implementation replaces
// non-matching captures with "null", requiring this ugly little loop
StringBuffer sb = new StringBuffer();
while (m.find()) {
if (m.group(2) != null) {
m.appendReplacement(sb, "<span class=\"cloze\">[...$2]</span>");
} else {
m.appendReplacement(sb, "<span class=\"cloze\">[...]</span>");
}
}
m.appendTail(sb);
clozetxt = sb.toString();
}
if (clozetxt.equals(txt)) {
// cloze wasn't found; return empty
return "";
}
// display any other clozes normally
clozetxt = clozetxt.replaceAll("\\{\\{c[0-9]+::(.*?)(?:::(.*?))?\\}\\}", "$1");
Log.d(AnkiDroidApp.TAG, "Cloze: ord=" + ord + ", txt=" + clozetxt);
return clozetxt;
} else if (mod.equals("kanjionly")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "$1");
} else if (mod.equals("readingonly")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "$2");
} else if (mod.equals("furigana")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "<ruby><rb>$1</rb><rt>$2</rt></ruby>");
} else {
Log.w(AnkiDroidApp.TAG, "Unknown field modifier: " + mod);
return txt;
}
}
}
// /**
// * This function recompiles the templates for question and answer. It should be called everytime we change mQformat
// * or mAformat, so if in the future we create set(Q|A)Format setters, we should include a call to this.
// */
// private void refreshTemplates(int ord) {
// // Question template
// StringBuffer sb = new StringBuffer();
// Matcher m = sOldStylePattern.matcher(mQformat);
// while (m.find()) {
// // Convert old style
// m.appendReplacement(sb, "{{" + m.group(1) + "}}");
// }
// m.appendTail(sb);
// Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + sb.toString() + "\"");
// mQTemplate = Mustache.compiler().compile(sb.toString());
//
// // Answer template
// sb = new StringBuffer();
// m = sOldStylePattern.matcher(mAformat);
// while (m.find()) {
// // Convert old style
// m.appendReplacement(sb, "{{" + m.group(1) + "}}");
// }
// m.appendTail(sb);
// Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + sb.toString() + "\"");
// mATemplate = Mustache.compiler().compile(sb.toString());
// }
/**
* Model changing
* ***********************************************************************************************
*/
// change
//_changeNotes
//_changeCards
/**
* Schema hash
* ***********************************************************************************************
*/
//scmhash
/**
* Required field/text cache
* ***********************************************************************************************
*/
private void _updateRequired(JSONObject m) {
JSONArray req = new JSONArray();
ArrayList<String> flds = new ArrayList<String>();
JSONArray fields;
try {
fields = m.getJSONArray("flds");
for (int i = 0; i < fields.length(); i++) {
flds.add(fields.getJSONObject(i).getString("name"));
}
boolean cloze = false;
JSONArray templates = m.getJSONArray("tmpls");
for (int i = 0; i < templates.length(); i++) {
JSONObject t = templates.getJSONObject(i);
Object[] ret = _reqForTemplate(m, flds, t);
if (((JSONArray)ret[2]).length() > 0) {
cloze = true;
}
JSONArray r = new JSONArray();
r.put(t.getInt("ord"));
r.put(ret[0]);
r.put(ret[1]);
r.put(ret[2]);
req.put(r);
}
m.put("req", req);
m.put("cloze", cloze);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) {
try {
ArrayList<String> a = new ArrayList<String> ();
ArrayList<String> b = new ArrayList<String> ();
String cloze = "";
JSONArray reqstrs = new JSONArray();
if (t.has("cloze")) {
// need a cloze-specific filler
// TODO
}
for (String f : flds) {
a.add(cloze.length() > 0 ? cloze : "1");
b.add("");
}
Object[] data;
data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()]))};
String full = mCol._renderQA(data).get("q");
data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()]))};
String empty = mCol._renderQA(data).get("q");
// if full and empty are the same, the template is invalid and there is no way to satisfy it
if (full.equals(empty)) {
return new Object[] {"none", new JSONArray(), new JSONArray()};
}
String type = "all";
JSONArray req = new JSONArray();
ArrayList<String> tmp = new ArrayList<String>();
for (int i = 0; i < flds.size(); i++) {
tmp.clear();
tmp.addAll(a);
tmp.remove(i);
tmp.add(i, "");
data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()]));
// if the result is same as empty, field is required
if (mCol._renderQA(data).get("q").equals(empty)) {
req.put(i);
}
}
if (req.length() > 0) {
return new Object[] {type, req, reqstrs};
}
// if there are no required fields, switch to any mode
type = "any";
req = new JSONArray();
for (int i = 0; i < flds.size(); i++) {
tmp.clear();
tmp.addAll(b);
tmp.remove(i);
tmp.add(i, "1");
data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()]));
// if not the same as empty, this field can make the card non-blank
if (mCol._renderQA(data).get("q").equals(empty)) {
req.put(i);
}
}
return new Object[]{ type, req, reqstrs};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/** Given a joined field string, return available template ordinals */
public ArrayList<Integer> availOrds(JSONObject m, String flds) {
String[] fields = Utils.splitFields(flds);
for (String f : fields) {
f = f.trim();
}
ArrayList<Integer> avail = new ArrayList<Integer>();
try {
JSONArray reqArray = m.getJSONArray("req");
for (int i = 0; i < reqArray.length(); i++) {
JSONArray sr = reqArray.getJSONArray(i);
int ord = sr.getInt(0);
String type = sr.getString(1);
JSONArray req = sr.getJSONArray(2);
JSONArray reqstrs = sr.getJSONArray(3);
if (type.equals("none")) {
// unsatisfiable template
continue;
} else if (type.equals("all")) {
// AND requirement?
boolean ok = true;
for (int j = 0; j < req.length(); j++) {
if (fields.length <= j || fields[j] == null || fields[j].length() == 0) {
// missing and was required
ok = false;
break;
}
}
if (!ok) {
continue;
}
} else if (type.equals("any")) {
// OR requirement?
boolean ok = false;
for (int j = 0; j < req.length(); j++) {
if (fields.length <= j || fields[j] == null || fields[j].length() == 0) {
// missing and was required
ok = true;
break;
}
}
if (!ok) {
continue;
}
}
// extra cloze requirement?
boolean ok = true;
for (int j = 0; j < reqstrs.length(); j++) {
if (!flds.matches(reqstrs.getString(i))) {
// required cloze string was missing
ok = false;
break;
}
}
if (!ok) {
continue;
}
avail.add(ord);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return avail;
}
/**
* Sync handling
* ***********************************************************************************************
*/
public void beforeUpload() {
try {
for (JSONObject m : all()) {
m.put("usn", 0);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
save();
}
/**
* Routines from Stdmodels.py
* ***********************************************************************************************
*/
public JSONObject addBasicModel(String name, boolean setCurrent) {
JSONObject m = newModel(name);
JSONObject fm = newField("Front");
addField(m, fm);
fm = newField("Back");
addField(m, fm);
JSONObject t = newTemplate("Forward");
try {
t.put("qfmt", "{{Front}}");
t.put("afmt", t.getString("qfmt") + "\n\n<hr id=answer>\n\n{{Back}}");
} catch (JSONException e) {
throw new RuntimeException(e);
}
addTemplate(m, t);
add(m, setCurrent);
return m;
}
// addClozeModel
/**
* Other stuff
* NOT IN LIBANKI
* ***********************************************************************************************
*/
public void setChanged() {
mChanged = true;
}
/**
* Returns a string where all colors have been inverted.
* It applies to anything that is in a tag and looks like #FFFFFF
*
* Example: Here only #000000 will be replaced (#777777 is content)
* <span style="color: #000000;">Code #777777 is the grey color</span>
*
* This is done with a state machine with 2 states:
* - 0: within content
* - 1: within a tag
*/
public static String invertColors(String text) {
final String[] colors = {"white", "black"};
final String[] htmlColors = {"#000000", "#ffffff"};
for (int i = 0; i < colors.length; i++) {
text = text.replace(colors[i], htmlColors[i]);
}
int state = 0;
StringBuffer inverted = new StringBuffer(text.length());
for(int i=0; i<text.length(); i++) {
char character = text.charAt(i);
if (state == 1 && character == '#') {
// TODO: handle shorter html-colors too (e.g. #0000)
inverted.append(invertColor(text.substring(i+1, i+7)));
}
else {
if (character == '<') {
state = 1;
}
if (character == '>') {
state = 0;
}
inverted.append(character);
}
}
return inverted.toString();
}
private static String invertColor(String color) {
if (color.length() != 0) {
color = StringTools.toUpperCase(color);
}
final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final char[] tmpItems = {'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'};
for (int i = 0; i < 16; i++) {
color = color.replace(items[i], tmpItems[15-i]);
}
for (int i = 0; i < 16; i++) {
color = color.replace(tmpItems[i], items[i]);
}
return color;
}
public HashMap<Long, HashMap<Integer, String>> getTemplateNames() {
HashMap<Long, HashMap<Integer, String>> result = new HashMap<Long, HashMap<Integer, String>>();
for (JSONObject m : mModels.values()) {
JSONArray templates;
try {
templates = m.getJSONArray("tmpls");
HashMap<Integer, String> names = new HashMap<Integer, String>();
for (int i = 0; i < templates.length(); i++) {
JSONObject t = templates.getJSONObject(i);
names.put(t.getInt("ord"), t.getString("name"));
}
result.put(m.getLong("id"), names);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* @return the ID
*/
public int getId() {
return mId;
}
/**
* @return the name
*/
public String getName() {
return mName;
}
}
| public void _transformFields(JSONObject m) { // Method fn) {
// model hasn't been added yet?
try {
if (m.getLong("id") == 0) {
return;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// TODO
}
/**
* Templates
* ***********************************************************************************************
*/
public JSONObject newTemplate(String name) {
JSONObject t;
try {
t = new JSONObject(defaultTemplate);
t.put("name", name);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return t;
}
/** Note: should col.genCards() afterwards. */
public void addTemplate(JSONObject m, JSONObject template) {
try {
if (m.getLong("id") != 0) {
mCol.modSchema();
}
JSONArray ja = m.getJSONArray("tmpls");
ja.put(template);
m.put("tmpls", ja);
_updateTemplOrds(m);
save(m);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//remtemplate
public void _updateTemplOrds(JSONObject m) {
JSONArray ja;
try {
ja = m.getJSONArray("tmpls");
for (int i = 0; i < ja.length(); i++) {
JSONObject f = ja.getJSONObject(i);
f.put("ord", i);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//movetemplate
private void _syncTemplates(JSONObject m) {
ArrayList<Long> rem = mCol.genCards(Utils.arrayList2array(nids(m)));
mCol.remEmptyCards(Utils.arrayList2array(rem));
}
// public TreeMap<Integer, JSONObject> getTemplates() {
// return mTemplateMap;
// }
//
//
// public JSONObject getTemplate(int ord) {
// return mTemplateMap.get(ord);
// }
// not in libanki
public Template[] getCmpldTemplate(long modelId, int ord) {
if (!mCmpldTemplateMap.containsKey(modelId)) {
mCmpldTemplateMap.put(modelId, new HashMap<Integer, Template[]>());
}
if (!mCmpldTemplateMap.get(modelId).containsKey(ord)) {
mCmpldTemplateMap.get(modelId).put(ord, compileTemplate(modelId, ord));
}
return mCmpldTemplateMap.get(modelId).get(ord);
}
// not in libanki
private Template[] compileTemplate(long modelId, int ord) {
JSONObject model = mModels.get(modelId);
JSONObject template;
Template[] t = new Template[2];
try {
template = model.getJSONArray("tmpls").getJSONObject(ord);
String format = template.getString("qfmt").replace("cloze:", "cq:");
Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + format + "\"");
t[0] = Mustache.compiler().compile(format);
format = template.getString("afmt").replace("cloze:", "ca:");
Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + format + "\"");
t[1] = Mustache.compiler().compile(format);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return t;
}
// not in libanki
// Handle fields fetched from templates and any anki-specific formatting
protected static class fieldParser implements Mustache.VariableFetcher {
private Map <String, String> _fields;
private String rubyr = " ?([^ ]+?)\\[(.+?)\\]";
public fieldParser (Map<String, String> fields) {
_fields = fields;
}
public Object get (Object ctx, String name) throws Exception {
if (name.length() == 0) {
return null;
}
String txt = _fields.get(name);
if (txt != null) {
return txt;
}
// field modifier handling as taken from template.py
String[] parts = name.split(":", 3);
String mod = null, extra = null, tag = null;
if (parts.length == 1 || parts[0].length() == 0) {
return null;
} else if (parts.length == 2) {
mod = parts[0];
tag = parts[1];
} else if (parts.length == 3) {
mod = parts[0];
extra = parts[1];
tag = parts[2];
}
txt = _fields.get(tag);
Log.d(AnkiDroidApp.TAG, "Processing field modifier " + mod + ": extra = " + extra + ", field " + tag + " = " + txt);
// built-in modifiers
// including furigana/ruby text handling
if (mod.equals("text")) {
// strip html
if (txt != null) {
return Utils.stripHTML(txt);
}
return "";
} else if (mod.equals("type")) {
// TODO: handle type field modifier
Log.e(AnkiDroidApp.TAG, "Unimplemented field modifier: " + mod);
return null;
} else if (mod.equals("cq") || mod.equals("ca")) {
// cloze handling
if (txt == null || extra == null) return "";
int ord;
try {
ord = Integer.parseInt(extra);
} catch (NumberFormatException e) {
return "";
}
if (ord < 0) return "";
String rx = "\\{\\{c"+ord+"::(.*?)(?:::(.*?))?\\}\\}";
Matcher m = Pattern.compile(rx).matcher(txt);
String clozetxt = null;
if (mod.equals("ca")) {
// in answer
clozetxt = m.replaceAll("<span class=\"cloze\">$1</span>");
} else {
// in question
// unfortunately, Android's java implementation replaces
// non-matching captures with "null", requiring this ugly little loop
StringBuffer sb = new StringBuffer();
while (m.find()) {
if (m.group(2) != null) {
m.appendReplacement(sb, "<span class=\"cloze\">[...$2]</span>");
} else {
m.appendReplacement(sb, "<span class=\"cloze\">[...]</span>");
}
}
m.appendTail(sb);
clozetxt = sb.toString();
}
if (clozetxt.equals(txt)) {
// cloze wasn't found; return empty
return "";
}
// display any other clozes normally
clozetxt = clozetxt.replaceAll("\\{\\{c[0-9]+::(.*?)(?:::(.*?))?\\}\\}", "$1");
Log.d(AnkiDroidApp.TAG, "Cloze: ord=" + ord + ", txt=" + clozetxt);
return clozetxt;
} else if (mod.equals("kanjionly")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "$1");
} else if (mod.equals("readingonly")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "$2");
} else if (mod.equals("furigana")) {
if (txt == null) return txt;
return txt.replaceAll(rubyr, "<ruby><rb>$1</rb><rt>$2</rt></ruby>");
} else {
Log.w(AnkiDroidApp.TAG, "Unknown field modifier: " + mod);
return txt;
}
}
}
// /**
// * This function recompiles the templates for question and answer. It should be called everytime we change mQformat
// * or mAformat, so if in the future we create set(Q|A)Format setters, we should include a call to this.
// */
// private void refreshTemplates(int ord) {
// // Question template
// StringBuffer sb = new StringBuffer();
// Matcher m = sOldStylePattern.matcher(mQformat);
// while (m.find()) {
// // Convert old style
// m.appendReplacement(sb, "{{" + m.group(1) + "}}");
// }
// m.appendTail(sb);
// Log.i(AnkiDroidApp.TAG, "Compiling question template \"" + sb.toString() + "\"");
// mQTemplate = Mustache.compiler().compile(sb.toString());
//
// // Answer template
// sb = new StringBuffer();
// m = sOldStylePattern.matcher(mAformat);
// while (m.find()) {
// // Convert old style
// m.appendReplacement(sb, "{{" + m.group(1) + "}}");
// }
// m.appendTail(sb);
// Log.i(AnkiDroidApp.TAG, "Compiling answer template \"" + sb.toString() + "\"");
// mATemplate = Mustache.compiler().compile(sb.toString());
// }
/**
* Model changing
* ***********************************************************************************************
*/
// change
//_changeNotes
//_changeCards
/**
* Schema hash
* ***********************************************************************************************
*/
//scmhash
/**
* Required field/text cache
* ***********************************************************************************************
*/
private void _updateRequired(JSONObject m) {
JSONArray req = new JSONArray();
ArrayList<String> flds = new ArrayList<String>();
JSONArray fields;
try {
fields = m.getJSONArray("flds");
for (int i = 0; i < fields.length(); i++) {
flds.add(fields.getJSONObject(i).getString("name"));
}
boolean cloze = false;
JSONArray templates = m.getJSONArray("tmpls");
for (int i = 0; i < templates.length(); i++) {
JSONObject t = templates.getJSONObject(i);
Object[] ret = _reqForTemplate(m, flds, t);
if (((JSONArray)ret[2]).length() > 0) {
cloze = true;
}
JSONArray r = new JSONArray();
r.put(t.getInt("ord"));
r.put(ret[0]);
r.put(ret[1]);
r.put(ret[2]);
req.put(r);
}
m.put("req", req);
m.put("cloze", cloze);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private Object[] _reqForTemplate(JSONObject m, ArrayList<String> flds, JSONObject t) {
try {
ArrayList<String> a = new ArrayList<String> ();
ArrayList<String> b = new ArrayList<String> ();
String cloze = "";
JSONArray reqstrs = new JSONArray();
if (t.has("cloze")) {
// need a cloze-specific filler
// TODO
}
for (String f : flds) {
a.add(cloze.length() > 0 ? cloze : "1");
b.add("");
}
Object[] data;
data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(a.toArray(new String[a.size()]))};
String full = mCol._renderQA(data).get("q");
data = new Object[]{1l, 1l, m.getLong("id"), 1l, t.getInt("ord"), "", Utils.joinFields(b.toArray(new String[b.size()]))};
String empty = mCol._renderQA(data).get("q");
// if full and empty are the same, the template is invalid and there is no way to satisfy it
if (full.equals(empty)) {
return new Object[] {"none", new JSONArray(), new JSONArray()};
}
String type = "all";
JSONArray req = new JSONArray();
ArrayList<String> tmp = new ArrayList<String>();
for (int i = 0; i < flds.size(); i++) {
tmp.clear();
tmp.addAll(a);
tmp.remove(i);
tmp.add(i, "");
data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()]));
// if the result is same as empty, field is required
if (mCol._renderQA(data).get("q").equals(empty)) {
req.put(i);
}
}
if (req.length() > 0) {
return new Object[] {type, req, reqstrs};
}
// if there are no required fields, switch to any mode
type = "any";
req = new JSONArray();
for (int i = 0; i < flds.size(); i++) {
tmp.clear();
tmp.addAll(b);
tmp.remove(i);
tmp.add(i, "1");
data[6] = Utils.joinFields(tmp.toArray(new String[tmp.size()]));
// if not the same as empty, this field can make the card non-blank
if (mCol._renderQA(data).get("q").equals(empty)) {
req.put(i);
}
}
return new Object[]{ type, req, reqstrs};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/** Given a joined field string, return available template ordinals */
public ArrayList<Integer> availOrds(JSONObject m, String flds) {
String[] fields = Utils.splitFields(flds);
for (String f : fields) {
f = f.trim();
}
ArrayList<Integer> avail = new ArrayList<Integer>();
try {
JSONArray reqArray = m.getJSONArray("req");
for (int i = 0; i < reqArray.length(); i++) {
JSONArray sr = reqArray.getJSONArray(i);
int ord = sr.getInt(0);
String type = sr.getString(1);
JSONArray req = sr.getJSONArray(2);
JSONArray reqstrs = sr.getJSONArray(3);
if (type.equals("none")) {
// unsatisfiable template
continue;
} else if (type.equals("all")) {
// AND requirement?
boolean ok = true;
for (int j = 0; j < req.length(); j++) {
if (fields.length <= j || fields[j] == null || fields[j].length() == 0) {
// missing and was required
ok = false;
break;
}
}
if (!ok) {
continue;
}
} else if (type.equals("any")) {
// OR requirement?
boolean ok = false;
for (int j = 0; j < req.length(); j++) {
if (fields.length <= j || fields[j] == null || fields[j].length() == 0) {
// missing and was required
ok = true;
break;
}
}
if (!ok) {
continue;
}
}
// extra cloze requirement?
boolean ok = true;
for (int j = 0; j < reqstrs.length(); j++) {
if (!flds.matches(reqstrs.getString(i))) {
// required cloze string was missing
ok = false;
break;
}
}
if (!ok) {
continue;
}
avail.add(ord);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return avail;
}
/**
* Sync handling
* ***********************************************************************************************
*/
public void beforeUpload() {
try {
for (JSONObject m : all()) {
m.put("usn", 0);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
save();
}
/**
* Routines from Stdmodels.py
* ***********************************************************************************************
*/
public JSONObject addBasicModel(String name, boolean setCurrent) {
JSONObject m = newModel(name);
JSONObject fm = newField("Front");
addField(m, fm);
fm = newField("Back");
addField(m, fm);
JSONObject t = newTemplate("Forward");
try {
t.put("qfmt", "{{Front}}");
t.put("afmt", t.getString("qfmt") + "\n\n<hr id=answer>\n\n{{Back}}");
} catch (JSONException e) {
throw new RuntimeException(e);
}
addTemplate(m, t);
add(m, setCurrent);
return m;
}
// addClozeModel
/**
* Other stuff
* NOT IN LIBANKI
* ***********************************************************************************************
*/
public void setChanged() {
mChanged = true;
}
/**
* Returns a string where all colors have been inverted.
* It applies to anything that is in a tag and looks like #FFFFFF
*
* Example: Here only #000000 will be replaced (#777777 is content)
* <span style="color: #000000;">Code #777777 is the grey color</span>
*
* This is done with a state machine with 2 states:
* - 0: within content
* - 1: within a tag
*/
public static String invertColors(String text) {
final String[] colors = {"color=\"white\"", "color=\"black\""};
final String[] htmlColors = {"color=\"#000000\"", "color=\"#ffffff\""};
for (int i = 0; i < colors.length; i++) {
text = text.replace(colors[i], htmlColors[i]);
}
int state = 0;
StringBuffer inverted = new StringBuffer(text.length());
for(int i=0; i<text.length(); i++) {
char character = text.charAt(i);
if (state == 1 && character == '#') {
// TODO: handle shorter html-colors too (e.g. #0000)
inverted.append(invertColor(text.substring(i+1, i+7)));
}
else {
if (character == '<') {
state = 1;
}
if (character == '>') {
state = 0;
}
inverted.append(character);
}
}
return inverted.toString();
}
private static String invertColor(String color) {
if (color.length() != 0) {
color = StringTools.toUpperCase(color);
}
final char[] items = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final char[] tmpItems = {'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v'};
for (int i = 0; i < 16; i++) {
color = color.replace(items[i], tmpItems[15-i]);
}
for (int i = 0; i < 16; i++) {
color = color.replace(tmpItems[i], items[i]);
}
return color;
}
public HashMap<Long, HashMap<Integer, String>> getTemplateNames() {
HashMap<Long, HashMap<Integer, String>> result = new HashMap<Long, HashMap<Integer, String>>();
for (JSONObject m : mModels.values()) {
JSONArray templates;
try {
templates = m.getJSONArray("tmpls");
HashMap<Integer, String> names = new HashMap<Integer, String>();
for (int i = 0; i < templates.length(); i++) {
JSONObject t = templates.getJSONObject(i);
names.put(t.getInt("ord"), t.getString("name"));
}
result.put(m.getLong("id"), names);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* @return the ID
*/
public int getId() {
return mId;
}
/**
* @return the name
*/
public String getName() {
return mName;
}
}
|
diff --git a/raw/src/CustomLogging.java b/raw/src/CustomLogging.java
index b6f103b..d151f28 100644
--- a/raw/src/CustomLogging.java
+++ b/raw/src/CustomLogging.java
@@ -1,45 +1,45 @@
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class CustomLogging {
private static final Logger LOGGER = LogManager.getLogger();
/**
* Called from net.minecraft.command.server.CommandMessage.processCommand()
*
* @param from
* @param to
* @param message
*/
public static void logWhisper(fa from, fa to, fa message) {
StringBuilder builder = new StringBuilder();
builder.append("[CHAT] ");
builder.append(from.c());
- builder.append(" whispers (chats) to ");
+ builder.append(" whispers to ");
builder.append(to.c());
builder.append(" ");
builder.append(message.c());
builder.append(": ");
LOGGER.info(builder.toString());
}
/**
* Called from net.minecraft.network.NetHandlerPlayServer.func_147354_a()
*
* @param from
* @param message
*/
public static void logChat(fa from, String message) {
StringBuilder builder = new StringBuilder();
builder.append("[CHAT] ");
builder.append(from.c());
builder.append(" ");
builder.append(message);
LOGGER.info(builder.toString());
}
}
| true | true | public static void logWhisper(fa from, fa to, fa message) {
StringBuilder builder = new StringBuilder();
builder.append("[CHAT] ");
builder.append(from.c());
builder.append(" whispers (chats) to ");
builder.append(to.c());
builder.append(" ");
builder.append(message.c());
builder.append(": ");
LOGGER.info(builder.toString());
}
| public static void logWhisper(fa from, fa to, fa message) {
StringBuilder builder = new StringBuilder();
builder.append("[CHAT] ");
builder.append(from.c());
builder.append(" whispers to ");
builder.append(to.c());
builder.append(" ");
builder.append(message.c());
builder.append(": ");
LOGGER.info(builder.toString());
}
|
diff --git a/src/it/example/storygame/partenzza.java b/src/it/example/storygame/partenzza.java
index 7ee8edd..89e35c7 100644
--- a/src/it/example/storygame/partenzza.java
+++ b/src/it/example/storygame/partenzza.java
@@ -1,388 +1,388 @@
package it.example.storygame;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class partenzza extends Activity {
TextView textview;
Button avanti;
Button second;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.partenzza);
second = (Button)findViewById(R.id.indietro);
//second.setVisibility(View.INVISIBLE);
//inizio
textview = (TextView) findViewById(R.id.story1);
textview.setMovementMethod(new ScrollingMovementMethod());
textview.setText("Apro la borsa e dentro ci inserisco 10 corone d'oro, affero una razione alimentare dallo scafale in alto e lo apoggio" +
" con cura dentro la borsa poi afferro la mia spada e indosso il corpetto di pelle. Finalmente sono pronto, scendo nella " +
"stalla e inizia a sentirsi il rumore assordante della campana d'oro. Salgo al cavallo e parto per il campo d'adestramento." +
" Scendo a cavallo per il ripido sentiero che si inoltra nella foresta di Freylund, e prima di entrare nel fito bosco mi diro " +
" a guardare la campana d'oro inalzata sopra una tore. Una volta uscito dalla foresta procedo verso sud sulla \"Strada dei Predoni Maledetti\"" +
", l'unica che collega il paese con il campo d'adestramento. All'improviso vengo assalito da una banda di fuorilegge " +
" che vuole rapinarmi del mio oro.");
avanti = (Button)findViewById(R.id.avanti);
avanti.setText("Combati contro la banda!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//seconda schermata
textview = (TextView) findViewById(R.id.story1);
textview.setText("Pur preso alla sprovista affero la spada e colpisco il primo malvivente che mi capita a tiro stacandogli un" +
" braccio, e mentre il secondo malvivente si avvicina mi sbrigo a tirare fuori lo scudo e intanto do il colpo di " +
"grazia alla mia prima vitima che giaceve imobile per terra e senza fiatto, rendendolo inofensivo per sempre." +
" Intanto gli altri tre malfattori scappano terrorizzati , dopo aver'visto che ero un boccone troppo duro per loro." );
//1 prima scelta
avanti.setText("Insegui i malviventi!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textview = (TextView) findViewById(R.id.story1);
textview.setText("Furioso mi lancio al inseguimento dei malfattori, dopo tutto sono un cavagliere e ne va della mi " +
" reputazione rendere giustizia, dando ai malfattori cio' che si meritano.E l'uncia pena che dovrebbero avere" +
" per le loro malefatte e' la morte. Arrivo alle spalle del piu' lento, il quale ignaro della mia posizione," +
" credeva di avermi seminato, e lo attaco alle spalle con la spada. Il malvivente cade per terra senza vita." );
avanti.setText("Continua a seguire i malviventi!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview = (TextView) findViewById(R.id.story1);
textview.setText("Senza fermarmi neanche per un attimo, continuo l'inseguimento dei restanti malviventi, sono a pochi passi" +
" da loro quando ne ho abbastanza del inseguimento, tiro fuori l'arco e con la mano destra afferro un freccia, " +
" prendo la mira e lancio la freccia. Manco il bersaglio e la frecia si confica nel albero, alla destra del mio bersaglio.Intanto mi acorgo che il secondo " +
" malvivente non era piu' sulla mia visuale, ignaro del pericolo in cui mi stavo imbatendo continuo l'inseguimento come se nulla fosse." +
" Al improvisso il mio bersaglio si ferma di colpo, estrago la spada e li vado in contro anche io , pensando che ne" +
" avesse abbastanza di scapare e che finalmente voleva arrendersi e andare in contro alla morte. Quando ero a pochi passi dal mio " +
" bersaglio 10 uomini armati mi circondano quatro dei quali mi tenevano sotto tiro con l'arco. Ero finito in trapola, una frecia mi " +
" colpisce , trapassandomi una spalla. Questa era la fine per me, intanto il malvivente che stavo inseguendo si avvicina a me e tria fuori " +
- " un mazza, si ferma davanti a me e sussura poche parole che non riesco a capire, dopo di che i da il colpo di grazia.");
+ " un mazza, si ferma davanti a me e sussura poche parole che non riesco a capire, dopo di che mi da il colpo di grazia.");
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
avanti.setVisibility(View.VISIBLE);
}
});
//second.setVisibility(View.VISIBLE);
second.setText("Prosegui per il campo, dopo la lezione data ai malviventi.!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO an other activity
textview=(TextView)findViewById(R.id.story1);
textview.setText("Dopo una lunga galopata ecco che finalmente appare davanti ai miei occhi il campo d'adestramento. Appena sorpasso il cancello vedo quatro soldati seduti che stano bevendo birra, e raccontano le loro imprese con impeto esagerato." +
" Sono tutti mezzi ubriachi e parlano a voce molto alta, ma quando mi vedono tacciono imediatamente e si alzano in piedi in segno di saluto..");
avanti.setText("Unisciti ai soldati!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Mi siedo vicino ai quatro soldati formando un cerchio, e uno dei quatro iniza a parlare. Ora mi ricordo di lui. " +
" Il suo nome e caspian e ha combatuto sotto il mio comando tra le rovine della citta-fantasma di Quaren.L'uomo ho una grossa " +
" cicatrice in volto, fa un lungo sospiro e inizia a racontare una storia.");
avanti.setText("Ascolta la storia!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("L'uomo inizia a raccontare la storia della Pietra del potere. La pietra era stata" +
" forgiata dalla fusione del oro con il diamante, nell'era della Luna nera nella citta di Paressa. Centinai di anni fa fu rubata da " +
" un re di nome broly, che la incastono' nella sua lancia e la uso' in battagli come strumento ispiratore dei suoi fanatici seguaci. Egli credeva che la pietra l'avesse reso invulnerabile, ma le cose non stavano cosi." +
" Durante una batagli preso il fiume Ridhan il re fu ucciso, e la lancia dorata gli cade di mano inabissandosi nelle profondit� delle acque del fiume e la pietra'andro perduita.");
avanti.setVisibility(View.INVISIBLE);
}
});
}
});
second.setText("Prosegui dopo avere ricambiato il saluto!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Mi inoltro nel campo e mi accorgo che un grupo di persone si sono riunite davanti a un grande cartello. Il cartello e tropo lontano e non riesco a leggere cosa c'e scritto, " +
" per questo decido di avvicinarmi. Quando arrivo vicino al cartello leggo a voce alta \n \"TORNEO DI TIRO CON L'ARCO \" \n QUOTA D'ISCIRZIONE:2 CORONE D'ORO \n PRIMO PREMIO:L'ARCO D'ARGENTO DI BROLY.");
avanti.setVisibility(View.VISIBLE);
second.setVisibility(View.INVISIBLE);
avanti.setText("Continua!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Continuo a inoltrarmi nel campo fino ad arrivare davanti alla \"Taverna del rospo\", e la taverna pi� famosa del villaggio proprio perch� e qui che servono la birra pi� buona, " +
" ma e anche grazie a questo che smpre piena di malintenzionati e di delinquenti. Appena entro nel cortile un garzone apparso dal nulla mia da il benvenuto, prende il mio cavallo e mi mostra l'entrata " +
" della taverna. All'interno , nonostante sia mattina presto, e piena di gente. In mezzo alla sala c'e un grande camino, con sopra tutta la carne che cucoce. L'odore della carne si sente in ogni angolo della taverna e fa venire l'acquolinba in bocca.");
avanti.setText("Vai al bancone per prendere una birra!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Arrivo davanti al balcone, e il proprietario della taverna, un uomo basso e cicciotello mi porgie un bocale" +
" e subito dopo lo riempie di bira. \"Se lo goda con calma signore\" dice \"questa e la miglior birra che potr� trovare in tutto il paese\", " +
" li faccio un ceno di consenso con la testa e poi inizio a sorsegiare la birra. \"Mio figlio mi ha deto di aver dato da bere e da mangiare al suo" +
" cavallo , non si deve preoccupare , � in buone mani , le nostre sono le stalle pi� sicure di tutto il paese\". Pago due corone d'oro per la " +
" birra ");
avanti.setText("Esci dalla taverna!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Esco dalla taverna, per poi entrare nella stalla a prendere il mio cavallo." +
" Un rumore asordante inizia a farsi sentire da tutte le parti. Il rumore era talmente forte che rimango stordito per qualche secondo. Appena mi riprendo vedo che tutta le persone, che fino " +
" a qualche istante fa erano intorno a me, ora scapavno senza avere una meta precisa.Il rumore assordante veniva da tutte le campane, questo significava una cosa sola, ci stavano attacando.");
avanti.setText("Torna dentro la taverna!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Corro dentro la taverna in cerca di protezione, ma passato qualceh minuto al interno della " +
" taverna, tra il fuggi fuggi generale, il fuoco inizia a inghiotire tutta la taverna. Due cavalieri nemici avevano dato fuoco alla taverna condanando tutti al suo interno alla morte.");
second.setVisibility(View.VISIBLE);
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
avanti.setText("Precipita nella zona dell'armamento!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
- textview.setBackgroundResource(R.drawable.death);
+ //textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Dopo essere salito a cavallo, mi dirigo verso la zona d'armamento, spingo il cavallo a correre come non aveva mai fato. " +
" Appena arrivo davanti alle garandi sale d'armamento, in lontananza vedo l'esercito nemico che avanzava, " +
" mentre il generale Ardrus aveva prepartao un piccolo esercito di cavallieri per contrattacare il nemico, " +
" o per lo meno per tenerlo occupato affinche gli altri avvesero il tempo per prepararsi e dare man forte in battaglia.");
avanti.setText(" Unisciti al esercito di Ardus!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("to be continued....");
//attacarlo alla prima attivita del secondo gamestory
second.setVisibility(View.VISIBLE);
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
second.setVisibility(View.VISIBLE);
second.setText("Arrenditi ai nemici");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Arrendendomi ai nemici significava andare incontro a morte certa, ma in quel momento non vedevo altra soluzione. " +
"Due cavalieri si fermano dinanzi a me.Erano grossi e impetuosi, la loro corazza color argento respingevano i raggi " +
"del sole che andavano a sbaterci contro, da lontano sembravano quasi due angeli. Butto la spada e lo scudo a terra ,in " +
" segno d'arresa. Uno dei due cavalieri avanza , mi gira intorno, poi alza la lancia e mi trafigge in pieno petto. Non faccio in " +
" tempo ad alzare gli occhi per guardare in faccia un ultima volta \"il cavaliere dei signori delle tenebre\" che ero a terra senza forze.");
//attacarlo alla prima attivita del secondo gamestory
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
}
});
}
});
}
});
}
});
}
});
}
});
}
});
//second.setVisibility(View.VISIBLE);
second.setText("Fuggi in gropa al cavallo!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO an other activity
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Senza fermarmi neanche per un attimo, continuo fugire dei restanti malviventi, sono a pochi passi da loro" +
" quando ne ho abbastanza del inseguimento, tiro fuori l'arco e con la mano destra afferro un freccia, prendo la mira e lancio la freccia." +
" Manco il bersaglio e la frecia si confica nel albero, alla destra del mio bersaglio.Intanto mi acorgo che il secondo malvivente" +
" non era piu' sulla mia visuale, ignaro del pericolo in cui mi stavo imbatendo continuo a fuggire come se nulla fosse. " +
" Al improvisso mifermo di colpo, estrago la spada e li vado in contro , pensando di averne abbastanza di scapare e che finalmente voleva " +
" arrendermi e andare in contro alla morte. Quando ero a pochi passi dal mio bersaglio 10 uomini armati mi circondano quatro dei quali mi " +
" tenevano sotto tiro con l'arco. Ero finito in trapola, una frecia mi colpisce , trapassandomi una spalla. Questa era la fine per me, " +
" intanto il malvivente che stavo inseguendo si avvicina a me e tria fuori un mazza, si ferma davanti a me e sussura poche parole che non" +
" riesco a capire, dopo di che mi da il colpo di grazia.");
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.partenzza);
second = (Button)findViewById(R.id.indietro);
//second.setVisibility(View.INVISIBLE);
//inizio
textview = (TextView) findViewById(R.id.story1);
textview.setMovementMethod(new ScrollingMovementMethod());
textview.setText("Apro la borsa e dentro ci inserisco 10 corone d'oro, affero una razione alimentare dallo scafale in alto e lo apoggio" +
" con cura dentro la borsa poi afferro la mia spada e indosso il corpetto di pelle. Finalmente sono pronto, scendo nella " +
"stalla e inizia a sentirsi il rumore assordante della campana d'oro. Salgo al cavallo e parto per il campo d'adestramento." +
" Scendo a cavallo per il ripido sentiero che si inoltra nella foresta di Freylund, e prima di entrare nel fito bosco mi diro " +
" a guardare la campana d'oro inalzata sopra una tore. Una volta uscito dalla foresta procedo verso sud sulla \"Strada dei Predoni Maledetti\"" +
", l'unica che collega il paese con il campo d'adestramento. All'improviso vengo assalito da una banda di fuorilegge " +
" che vuole rapinarmi del mio oro.");
avanti = (Button)findViewById(R.id.avanti);
avanti.setText("Combati contro la banda!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//seconda schermata
textview = (TextView) findViewById(R.id.story1);
textview.setText("Pur preso alla sprovista affero la spada e colpisco il primo malvivente che mi capita a tiro stacandogli un" +
" braccio, e mentre il secondo malvivente si avvicina mi sbrigo a tirare fuori lo scudo e intanto do il colpo di " +
"grazia alla mia prima vitima che giaceve imobile per terra e senza fiatto, rendendolo inofensivo per sempre." +
" Intanto gli altri tre malfattori scappano terrorizzati , dopo aver'visto che ero un boccone troppo duro per loro." );
//1 prima scelta
avanti.setText("Insegui i malviventi!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textview = (TextView) findViewById(R.id.story1);
textview.setText("Furioso mi lancio al inseguimento dei malfattori, dopo tutto sono un cavagliere e ne va della mi " +
" reputazione rendere giustizia, dando ai malfattori cio' che si meritano.E l'uncia pena che dovrebbero avere" +
" per le loro malefatte e' la morte. Arrivo alle spalle del piu' lento, il quale ignaro della mia posizione," +
" credeva di avermi seminato, e lo attaco alle spalle con la spada. Il malvivente cade per terra senza vita." );
avanti.setText("Continua a seguire i malviventi!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview = (TextView) findViewById(R.id.story1);
textview.setText("Senza fermarmi neanche per un attimo, continuo l'inseguimento dei restanti malviventi, sono a pochi passi" +
" da loro quando ne ho abbastanza del inseguimento, tiro fuori l'arco e con la mano destra afferro un freccia, " +
" prendo la mira e lancio la freccia. Manco il bersaglio e la frecia si confica nel albero, alla destra del mio bersaglio.Intanto mi acorgo che il secondo " +
" malvivente non era piu' sulla mia visuale, ignaro del pericolo in cui mi stavo imbatendo continuo l'inseguimento come se nulla fosse." +
" Al improvisso il mio bersaglio si ferma di colpo, estrago la spada e li vado in contro anche io , pensando che ne" +
" avesse abbastanza di scapare e che finalmente voleva arrendersi e andare in contro alla morte. Quando ero a pochi passi dal mio " +
" bersaglio 10 uomini armati mi circondano quatro dei quali mi tenevano sotto tiro con l'arco. Ero finito in trapola, una frecia mi " +
" colpisce , trapassandomi una spalla. Questa era la fine per me, intanto il malvivente che stavo inseguendo si avvicina a me e tria fuori " +
" un mazza, si ferma davanti a me e sussura poche parole che non riesco a capire, dopo di che i da il colpo di grazia.");
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
avanti.setVisibility(View.VISIBLE);
}
});
//second.setVisibility(View.VISIBLE);
second.setText("Prosegui per il campo, dopo la lezione data ai malviventi.!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO an other activity
textview=(TextView)findViewById(R.id.story1);
textview.setText("Dopo una lunga galopata ecco che finalmente appare davanti ai miei occhi il campo d'adestramento. Appena sorpasso il cancello vedo quatro soldati seduti che stano bevendo birra, e raccontano le loro imprese con impeto esagerato." +
" Sono tutti mezzi ubriachi e parlano a voce molto alta, ma quando mi vedono tacciono imediatamente e si alzano in piedi in segno di saluto..");
avanti.setText("Unisciti ai soldati!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Mi siedo vicino ai quatro soldati formando un cerchio, e uno dei quatro iniza a parlare. Ora mi ricordo di lui. " +
" Il suo nome e caspian e ha combatuto sotto il mio comando tra le rovine della citta-fantasma di Quaren.L'uomo ho una grossa " +
" cicatrice in volto, fa un lungo sospiro e inizia a racontare una storia.");
avanti.setText("Ascolta la storia!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("L'uomo inizia a raccontare la storia della Pietra del potere. La pietra era stata" +
" forgiata dalla fusione del oro con il diamante, nell'era della Luna nera nella citta di Paressa. Centinai di anni fa fu rubata da " +
" un re di nome broly, che la incastono' nella sua lancia e la uso' in battagli come strumento ispiratore dei suoi fanatici seguaci. Egli credeva che la pietra l'avesse reso invulnerabile, ma le cose non stavano cosi." +
" Durante una batagli preso il fiume Ridhan il re fu ucciso, e la lancia dorata gli cade di mano inabissandosi nelle profondit� delle acque del fiume e la pietra'andro perduita.");
avanti.setVisibility(View.INVISIBLE);
}
});
}
});
second.setText("Prosegui dopo avere ricambiato il saluto!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Mi inoltro nel campo e mi accorgo che un grupo di persone si sono riunite davanti a un grande cartello. Il cartello e tropo lontano e non riesco a leggere cosa c'e scritto, " +
" per questo decido di avvicinarmi. Quando arrivo vicino al cartello leggo a voce alta \n \"TORNEO DI TIRO CON L'ARCO \" \n QUOTA D'ISCIRZIONE:2 CORONE D'ORO \n PRIMO PREMIO:L'ARCO D'ARGENTO DI BROLY.");
avanti.setVisibility(View.VISIBLE);
second.setVisibility(View.INVISIBLE);
avanti.setText("Continua!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Continuo a inoltrarmi nel campo fino ad arrivare davanti alla \"Taverna del rospo\", e la taverna pi� famosa del villaggio proprio perch� e qui che servono la birra pi� buona, " +
" ma e anche grazie a questo che smpre piena di malintenzionati e di delinquenti. Appena entro nel cortile un garzone apparso dal nulla mia da il benvenuto, prende il mio cavallo e mi mostra l'entrata " +
" della taverna. All'interno , nonostante sia mattina presto, e piena di gente. In mezzo alla sala c'e un grande camino, con sopra tutta la carne che cucoce. L'odore della carne si sente in ogni angolo della taverna e fa venire l'acquolinba in bocca.");
avanti.setText("Vai al bancone per prendere una birra!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Arrivo davanti al balcone, e il proprietario della taverna, un uomo basso e cicciotello mi porgie un bocale" +
" e subito dopo lo riempie di bira. \"Se lo goda con calma signore\" dice \"questa e la miglior birra che potr� trovare in tutto il paese\", " +
" li faccio un ceno di consenso con la testa e poi inizio a sorsegiare la birra. \"Mio figlio mi ha deto di aver dato da bere e da mangiare al suo" +
" cavallo , non si deve preoccupare , � in buone mani , le nostre sono le stalle pi� sicure di tutto il paese\". Pago due corone d'oro per la " +
" birra ");
avanti.setText("Esci dalla taverna!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Esco dalla taverna, per poi entrare nella stalla a prendere il mio cavallo." +
" Un rumore asordante inizia a farsi sentire da tutte le parti. Il rumore era talmente forte che rimango stordito per qualche secondo. Appena mi riprendo vedo che tutta le persone, che fino " +
" a qualche istante fa erano intorno a me, ora scapavno senza avere una meta precisa.Il rumore assordante veniva da tutte le campane, questo significava una cosa sola, ci stavano attacando.");
avanti.setText("Torna dentro la taverna!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Corro dentro la taverna in cerca di protezione, ma passato qualceh minuto al interno della " +
" taverna, tra il fuggi fuggi generale, il fuoco inizia a inghiotire tutta la taverna. Due cavalieri nemici avevano dato fuoco alla taverna condanando tutti al suo interno alla morte.");
second.setVisibility(View.VISIBLE);
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
avanti.setText("Precipita nella zona dell'armamento!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Dopo essere salito a cavallo, mi dirigo verso la zona d'armamento, spingo il cavallo a correre come non aveva mai fato. " +
" Appena arrivo davanti alle garandi sale d'armamento, in lontananza vedo l'esercito nemico che avanzava, " +
" mentre il generale Ardrus aveva prepartao un piccolo esercito di cavallieri per contrattacare il nemico, " +
" o per lo meno per tenerlo occupato affinche gli altri avvesero il tempo per prepararsi e dare man forte in battaglia.");
avanti.setText(" Unisciti al esercito di Ardus!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("to be continued....");
//attacarlo alla prima attivita del secondo gamestory
second.setVisibility(View.VISIBLE);
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
second.setVisibility(View.VISIBLE);
second.setText("Arrenditi ai nemici");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Arrendendomi ai nemici significava andare incontro a morte certa, ma in quel momento non vedevo altra soluzione. " +
"Due cavalieri si fermano dinanzi a me.Erano grossi e impetuosi, la loro corazza color argento respingevano i raggi " +
"del sole che andavano a sbaterci contro, da lontano sembravano quasi due angeli. Butto la spada e lo scudo a terra ,in " +
" segno d'arresa. Uno dei due cavalieri avanza , mi gira intorno, poi alza la lancia e mi trafigge in pieno petto. Non faccio in " +
" tempo ad alzare gli occhi per guardare in faccia un ultima volta \"il cavaliere dei signori delle tenebre\" che ero a terra senza forze.");
//attacarlo alla prima attivita del secondo gamestory
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
}
});
}
});
}
});
}
});
}
});
}
});
}
});
//second.setVisibility(View.VISIBLE);
second.setText("Fuggi in gropa al cavallo!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO an other activity
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Senza fermarmi neanche per un attimo, continuo fugire dei restanti malviventi, sono a pochi passi da loro" +
" quando ne ho abbastanza del inseguimento, tiro fuori l'arco e con la mano destra afferro un freccia, prendo la mira e lancio la freccia." +
" Manco il bersaglio e la frecia si confica nel albero, alla destra del mio bersaglio.Intanto mi acorgo che il secondo malvivente" +
" non era piu' sulla mia visuale, ignaro del pericolo in cui mi stavo imbatendo continuo a fuggire come se nulla fosse. " +
" Al improvisso mifermo di colpo, estrago la spada e li vado in contro , pensando di averne abbastanza di scapare e che finalmente voleva " +
" arrendermi e andare in contro alla morte. Quando ero a pochi passi dal mio bersaglio 10 uomini armati mi circondano quatro dei quali mi " +
" tenevano sotto tiro con l'arco. Ero finito in trapola, una frecia mi colpisce , trapassandomi una spalla. Questa era la fine per me, " +
" intanto il malvivente che stavo inseguendo si avvicina a me e tria fuori un mazza, si ferma davanti a me e sussura poche parole che non" +
" riesco a capire, dopo di che mi da il colpo di grazia.");
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.partenzza);
second = (Button)findViewById(R.id.indietro);
//second.setVisibility(View.INVISIBLE);
//inizio
textview = (TextView) findViewById(R.id.story1);
textview.setMovementMethod(new ScrollingMovementMethod());
textview.setText("Apro la borsa e dentro ci inserisco 10 corone d'oro, affero una razione alimentare dallo scafale in alto e lo apoggio" +
" con cura dentro la borsa poi afferro la mia spada e indosso il corpetto di pelle. Finalmente sono pronto, scendo nella " +
"stalla e inizia a sentirsi il rumore assordante della campana d'oro. Salgo al cavallo e parto per il campo d'adestramento." +
" Scendo a cavallo per il ripido sentiero che si inoltra nella foresta di Freylund, e prima di entrare nel fito bosco mi diro " +
" a guardare la campana d'oro inalzata sopra una tore. Una volta uscito dalla foresta procedo verso sud sulla \"Strada dei Predoni Maledetti\"" +
", l'unica che collega il paese con il campo d'adestramento. All'improviso vengo assalito da una banda di fuorilegge " +
" che vuole rapinarmi del mio oro.");
avanti = (Button)findViewById(R.id.avanti);
avanti.setText("Combati contro la banda!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//seconda schermata
textview = (TextView) findViewById(R.id.story1);
textview.setText("Pur preso alla sprovista affero la spada e colpisco il primo malvivente che mi capita a tiro stacandogli un" +
" braccio, e mentre il secondo malvivente si avvicina mi sbrigo a tirare fuori lo scudo e intanto do il colpo di " +
"grazia alla mia prima vitima che giaceve imobile per terra e senza fiatto, rendendolo inofensivo per sempre." +
" Intanto gli altri tre malfattori scappano terrorizzati , dopo aver'visto che ero un boccone troppo duro per loro." );
//1 prima scelta
avanti.setText("Insegui i malviventi!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textview = (TextView) findViewById(R.id.story1);
textview.setText("Furioso mi lancio al inseguimento dei malfattori, dopo tutto sono un cavagliere e ne va della mi " +
" reputazione rendere giustizia, dando ai malfattori cio' che si meritano.E l'uncia pena che dovrebbero avere" +
" per le loro malefatte e' la morte. Arrivo alle spalle del piu' lento, il quale ignaro della mia posizione," +
" credeva di avermi seminato, e lo attaco alle spalle con la spada. Il malvivente cade per terra senza vita." );
avanti.setText("Continua a seguire i malviventi!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview = (TextView) findViewById(R.id.story1);
textview.setText("Senza fermarmi neanche per un attimo, continuo l'inseguimento dei restanti malviventi, sono a pochi passi" +
" da loro quando ne ho abbastanza del inseguimento, tiro fuori l'arco e con la mano destra afferro un freccia, " +
" prendo la mira e lancio la freccia. Manco il bersaglio e la frecia si confica nel albero, alla destra del mio bersaglio.Intanto mi acorgo che il secondo " +
" malvivente non era piu' sulla mia visuale, ignaro del pericolo in cui mi stavo imbatendo continuo l'inseguimento come se nulla fosse." +
" Al improvisso il mio bersaglio si ferma di colpo, estrago la spada e li vado in contro anche io , pensando che ne" +
" avesse abbastanza di scapare e che finalmente voleva arrendersi e andare in contro alla morte. Quando ero a pochi passi dal mio " +
" bersaglio 10 uomini armati mi circondano quatro dei quali mi tenevano sotto tiro con l'arco. Ero finito in trapola, una frecia mi " +
" colpisce , trapassandomi una spalla. Questa era la fine per me, intanto il malvivente che stavo inseguendo si avvicina a me e tria fuori " +
" un mazza, si ferma davanti a me e sussura poche parole che non riesco a capire, dopo di che mi da il colpo di grazia.");
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
avanti.setVisibility(View.VISIBLE);
}
});
//second.setVisibility(View.VISIBLE);
second.setText("Prosegui per il campo, dopo la lezione data ai malviventi.!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO an other activity
textview=(TextView)findViewById(R.id.story1);
textview.setText("Dopo una lunga galopata ecco che finalmente appare davanti ai miei occhi il campo d'adestramento. Appena sorpasso il cancello vedo quatro soldati seduti che stano bevendo birra, e raccontano le loro imprese con impeto esagerato." +
" Sono tutti mezzi ubriachi e parlano a voce molto alta, ma quando mi vedono tacciono imediatamente e si alzano in piedi in segno di saluto..");
avanti.setText("Unisciti ai soldati!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Mi siedo vicino ai quatro soldati formando un cerchio, e uno dei quatro iniza a parlare. Ora mi ricordo di lui. " +
" Il suo nome e caspian e ha combatuto sotto il mio comando tra le rovine della citta-fantasma di Quaren.L'uomo ho una grossa " +
" cicatrice in volto, fa un lungo sospiro e inizia a racontare una storia.");
avanti.setText("Ascolta la storia!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("L'uomo inizia a raccontare la storia della Pietra del potere. La pietra era stata" +
" forgiata dalla fusione del oro con il diamante, nell'era della Luna nera nella citta di Paressa. Centinai di anni fa fu rubata da " +
" un re di nome broly, che la incastono' nella sua lancia e la uso' in battagli come strumento ispiratore dei suoi fanatici seguaci. Egli credeva che la pietra l'avesse reso invulnerabile, ma le cose non stavano cosi." +
" Durante una batagli preso il fiume Ridhan il re fu ucciso, e la lancia dorata gli cade di mano inabissandosi nelle profondit� delle acque del fiume e la pietra'andro perduita.");
avanti.setVisibility(View.INVISIBLE);
}
});
}
});
second.setText("Prosegui dopo avere ricambiato il saluto!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Mi inoltro nel campo e mi accorgo che un grupo di persone si sono riunite davanti a un grande cartello. Il cartello e tropo lontano e non riesco a leggere cosa c'e scritto, " +
" per questo decido di avvicinarmi. Quando arrivo vicino al cartello leggo a voce alta \n \"TORNEO DI TIRO CON L'ARCO \" \n QUOTA D'ISCIRZIONE:2 CORONE D'ORO \n PRIMO PREMIO:L'ARCO D'ARGENTO DI BROLY.");
avanti.setVisibility(View.VISIBLE);
second.setVisibility(View.INVISIBLE);
avanti.setText("Continua!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Continuo a inoltrarmi nel campo fino ad arrivare davanti alla \"Taverna del rospo\", e la taverna pi� famosa del villaggio proprio perch� e qui che servono la birra pi� buona, " +
" ma e anche grazie a questo che smpre piena di malintenzionati e di delinquenti. Appena entro nel cortile un garzone apparso dal nulla mia da il benvenuto, prende il mio cavallo e mi mostra l'entrata " +
" della taverna. All'interno , nonostante sia mattina presto, e piena di gente. In mezzo alla sala c'e un grande camino, con sopra tutta la carne che cucoce. L'odore della carne si sente in ogni angolo della taverna e fa venire l'acquolinba in bocca.");
avanti.setText("Vai al bancone per prendere una birra!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Arrivo davanti al balcone, e il proprietario della taverna, un uomo basso e cicciotello mi porgie un bocale" +
" e subito dopo lo riempie di bira. \"Se lo goda con calma signore\" dice \"questa e la miglior birra che potr� trovare in tutto il paese\", " +
" li faccio un ceno di consenso con la testa e poi inizio a sorsegiare la birra. \"Mio figlio mi ha deto di aver dato da bere e da mangiare al suo" +
" cavallo , non si deve preoccupare , � in buone mani , le nostre sono le stalle pi� sicure di tutto il paese\". Pago due corone d'oro per la " +
" birra ");
avanti.setText("Esci dalla taverna!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("Esco dalla taverna, per poi entrare nella stalla a prendere il mio cavallo." +
" Un rumore asordante inizia a farsi sentire da tutte le parti. Il rumore era talmente forte che rimango stordito per qualche secondo. Appena mi riprendo vedo che tutta le persone, che fino " +
" a qualche istante fa erano intorno a me, ora scapavno senza avere una meta precisa.Il rumore assordante veniva da tutte le campane, questo significava una cosa sola, ci stavano attacando.");
avanti.setText("Torna dentro la taverna!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Corro dentro la taverna in cerca di protezione, ma passato qualceh minuto al interno della " +
" taverna, tra il fuggi fuggi generale, il fuoco inizia a inghiotire tutta la taverna. Due cavalieri nemici avevano dato fuoco alla taverna condanando tutti al suo interno alla morte.");
second.setVisibility(View.VISIBLE);
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
avanti.setText("Precipita nella zona dell'armamento!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Dopo essere salito a cavallo, mi dirigo verso la zona d'armamento, spingo il cavallo a correre come non aveva mai fato. " +
" Appena arrivo davanti alle garandi sale d'armamento, in lontananza vedo l'esercito nemico che avanzava, " +
" mentre il generale Ardrus aveva prepartao un piccolo esercito di cavallieri per contrattacare il nemico, " +
" o per lo meno per tenerlo occupato affinche gli altri avvesero il tempo per prepararsi e dare man forte in battaglia.");
avanti.setText(" Unisciti al esercito di Ardus!");
avanti.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview=(TextView)findViewById(R.id.story1);
textview.setText("to be continued....");
//attacarlo alla prima attivita del secondo gamestory
second.setVisibility(View.VISIBLE);
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
second.setVisibility(View.VISIBLE);
second.setText("Arrenditi ai nemici");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Arrendendomi ai nemici significava andare incontro a morte certa, ma in quel momento non vedevo altra soluzione. " +
"Due cavalieri si fermano dinanzi a me.Erano grossi e impetuosi, la loro corazza color argento respingevano i raggi " +
"del sole che andavano a sbaterci contro, da lontano sembravano quasi due angeli. Butto la spada e lo scudo a terra ,in " +
" segno d'arresa. Uno dei due cavalieri avanza , mi gira intorno, poi alza la lancia e mi trafigge in pieno petto. Non faccio in " +
" tempo ad alzare gli occhi per guardare in faccia un ultima volta \"il cavaliere dei signori delle tenebre\" che ero a terra senza forze.");
//attacarlo alla prima attivita del secondo gamestory
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
}
});
}
});
}
});
}
});
}
});
}
});
}
});
//second.setVisibility(View.VISIBLE);
second.setText("Fuggi in gropa al cavallo!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO an other activity
textview.setBackgroundResource(R.drawable.death);
textview=(TextView)findViewById(R.id.story1);
textview.setText("Senza fermarmi neanche per un attimo, continuo fugire dei restanti malviventi, sono a pochi passi da loro" +
" quando ne ho abbastanza del inseguimento, tiro fuori l'arco e con la mano destra afferro un freccia, prendo la mira e lancio la freccia." +
" Manco il bersaglio e la frecia si confica nel albero, alla destra del mio bersaglio.Intanto mi acorgo che il secondo malvivente" +
" non era piu' sulla mia visuale, ignaro del pericolo in cui mi stavo imbatendo continuo a fuggire come se nulla fosse. " +
" Al improvisso mifermo di colpo, estrago la spada e li vado in contro , pensando di averne abbastanza di scapare e che finalmente voleva " +
" arrendermi e andare in contro alla morte. Quando ero a pochi passi dal mio bersaglio 10 uomini armati mi circondano quatro dei quali mi " +
" tenevano sotto tiro con l'arco. Ero finito in trapola, una frecia mi colpisce , trapassandomi una spalla. Questa era la fine per me, " +
" intanto il malvivente che stavo inseguendo si avvicina a me e tria fuori un mazza, si ferma davanti a me e sussura poche parole che non" +
" riesco a capire, dopo di che mi da il colpo di grazia.");
second.setText("Fine!");
second.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent finish = new Intent(partenzza.this, Read.class);
startActivity(finish);
}
});
avanti.setVisibility(View.INVISIBLE);
}
});
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/token/AstTokenAdapter.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/token/AstTokenAdapter.java
index ac444292..fd89c808 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/token/AstTokenAdapter.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/ast/token/AstTokenAdapter.java
@@ -1,148 +1,148 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.ast.token;
/**
* {@link AstToken}�̃A�_�v�^�N���X.
* AstToken�Ő錾����Ă���S�Ẵ��\�b�h�ɂ��āCfalse��Ԃ������̃f�t�H���g����������.
*
* @author kou-tngt
*
*/
public class AstTokenAdapter implements AstToken {
/**
* �w�肳�ꂽ������������g�[�N�����쐬����R���X�g���N�^.
* @param text
* @throws NullPointerException text��null�̏ꍇ
* @throws IllegalArgumentException text������̏ꍇ
*/
public AstTokenAdapter(final String text) {
- if (null != text){
+ if (null == text){
throw new NullPointerException("text is null");
}
if (text.length() == 0){
throw new IllegalArgumentException("text must not be empty string.");
}
this.text = text;
}
public boolean isAccessModifier() {
return false;
}
public boolean isArrayDeclarator() {
return false;
}
public boolean isAssignmentOperator() {
return false;
}
public boolean isBlock() {
return false;
}
public boolean isClassBlock() {
return false;
}
public boolean isClassDefinition() {
return false;
}
public boolean isConstructorDefinition() {
return false;
}
public boolean isExpression() {
return false;
}
public boolean isInheritanceDescription() {
return false;
}
public boolean isFieldDefinition() {
return false;
}
public boolean isIdentifier() {
return false;
}
public boolean isInstantiation() {
return false;
}
public boolean isLocalParameterDefinition() {
return false;
}
public boolean isLocalVariableDefinition() {
return false;
}
public boolean isMethodCall() {
return false;
}
public boolean isMethodDefinition() {
return false;
}
public boolean isMethodParameterDefinition() {
return false;
}
public boolean isModifier() {
return this.isAccessModifier();
}
public boolean isModifiersDefinition() {
return false;
}
public boolean isNameDescription() {
return false;
}
public boolean isNameSeparator() {
return false;
}
public boolean isNameSpaceDefinition() {
return false;
}
public boolean isNameUsingDefinition() {
return false;
}
public boolean isOperator() {
return false;
}
public boolean isPrimitiveType() {
return false;
}
public boolean isTypeDescription() {
return false;
}
public boolean isVoidType() {
return false;
}
@Override
public String toString() {
return this.text;
}
/**
* ���̃g�[�N���̕�����
*/
private final String text;
}
| true | true | public AstTokenAdapter(final String text) {
if (null != text){
throw new NullPointerException("text is null");
}
if (text.length() == 0){
throw new IllegalArgumentException("text must not be empty string.");
}
this.text = text;
}
| public AstTokenAdapter(final String text) {
if (null == text){
throw new NullPointerException("text is null");
}
if (text.length() == 0){
throw new IllegalArgumentException("text must not be empty string.");
}
this.text = text;
}
|
diff --git a/src/fi/dy/esav/EreSeller/MainActivity.java b/src/fi/dy/esav/EreSeller/MainActivity.java
index 6f9161a..19e0083 100644
--- a/src/fi/dy/esav/EreSeller/MainActivity.java
+++ b/src/fi/dy/esav/EreSeller/MainActivity.java
@@ -1,123 +1,123 @@
package fi.dy.esav.EreSeller;
import java.lang.Exception;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText i_money, i_buy_p, i_sell_p, i_cust_tax, i_ticket;
RadioGroup i_tax;
RadioButton i_tax_none, i_tax_cust;
TextView o_result;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private void init() {
i_money = (EditText) findViewById(R.id.money);
addTextListener(i_money);
i_buy_p = (EditText) findViewById(R.id.buy_price);
addTextListener(i_buy_p);
i_sell_p = (EditText) findViewById(R.id.sell_price);
addTextListener(i_sell_p);
i_cust_tax = (EditText) findViewById(R.id.tax_cust_value);
addTextListener(i_cust_tax);
i_ticket = (EditText) findViewById(R.id.ticket);
addTextListener(i_ticket);
o_result = (TextView) findViewById(R.id.output);
i_tax = (RadioGroup) findViewById(R.id.tax_radiogroup);
i_tax.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
update();
}
});
i_tax_none = (RadioButton) findViewById(R.id.tax_none);
i_tax_cust = (RadioButton) findViewById(R.id.tax_cust);
}
private void addTextListener(EditText et) {
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
update();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
private void update() {
o_result.setText(calculate());
}
private String calculate() {
double money, buy_p, sell_p, ticket, tax;
try {
money = Double.parseDouble(i_money.getText().toString());
buy_p = Double.parseDouble(i_buy_p.getText().toString());
sell_p = Double.parseDouble(i_sell_p.getText().toString());
if(i_tax.getCheckedRadioButtonId() == i_tax_none.getId()) {
tax = 0;
} else if(i_tax.getCheckedRadioButtonId() == i_tax_cust.getId()) {
tax = Double.parseDouble(i_cust_tax.getText().toString());
} else {
tax = 0;
}
ticket = Double.parseDouble(i_ticket.getText().toString());
} catch (NumberFormatException e) {
return "Please fill with valid information";
}
int amount = (int) Math.floor(money / buy_p);
- double expenditure = amount * buy_p - 2 * ticket;
+ double expenditure = amount * buy_p + 2 * ticket;
double revenue_taxless = amount * sell_p;
double revenue = amount * sell_p * (1 / (1 + tax / 100));
double income = revenue - expenditure;
return "You get: " + amount + " items\n" +
"They cost (inc. travel): " + expenditure + "\n" +
"They sell for: " + revenue_taxless + "\n" +
"Profit: " + income;
}
}
| true | true | private String calculate() {
double money, buy_p, sell_p, ticket, tax;
try {
money = Double.parseDouble(i_money.getText().toString());
buy_p = Double.parseDouble(i_buy_p.getText().toString());
sell_p = Double.parseDouble(i_sell_p.getText().toString());
if(i_tax.getCheckedRadioButtonId() == i_tax_none.getId()) {
tax = 0;
} else if(i_tax.getCheckedRadioButtonId() == i_tax_cust.getId()) {
tax = Double.parseDouble(i_cust_tax.getText().toString());
} else {
tax = 0;
}
ticket = Double.parseDouble(i_ticket.getText().toString());
} catch (NumberFormatException e) {
return "Please fill with valid information";
}
int amount = (int) Math.floor(money / buy_p);
double expenditure = amount * buy_p - 2 * ticket;
double revenue_taxless = amount * sell_p;
double revenue = amount * sell_p * (1 / (1 + tax / 100));
double income = revenue - expenditure;
return "You get: " + amount + " items\n" +
"They cost (inc. travel): " + expenditure + "\n" +
"They sell for: " + revenue_taxless + "\n" +
"Profit: " + income;
}
| private String calculate() {
double money, buy_p, sell_p, ticket, tax;
try {
money = Double.parseDouble(i_money.getText().toString());
buy_p = Double.parseDouble(i_buy_p.getText().toString());
sell_p = Double.parseDouble(i_sell_p.getText().toString());
if(i_tax.getCheckedRadioButtonId() == i_tax_none.getId()) {
tax = 0;
} else if(i_tax.getCheckedRadioButtonId() == i_tax_cust.getId()) {
tax = Double.parseDouble(i_cust_tax.getText().toString());
} else {
tax = 0;
}
ticket = Double.parseDouble(i_ticket.getText().toString());
} catch (NumberFormatException e) {
return "Please fill with valid information";
}
int amount = (int) Math.floor(money / buy_p);
double expenditure = amount * buy_p + 2 * ticket;
double revenue_taxless = amount * sell_p;
double revenue = amount * sell_p * (1 / (1 + tax / 100));
double income = revenue - expenditure;
return "You get: " + amount + " items\n" +
"They cost (inc. travel): " + expenditure + "\n" +
"They sell for: " + revenue_taxless + "\n" +
"Profit: " + income;
}
|
diff --git a/gora-core/src/main/java/org/gora/compiler/GoraCompiler.java b/gora-core/src/main/java/org/gora/compiler/GoraCompiler.java
index 8f4a7e0..3ef35a3 100644
--- a/gora-core/src/main/java/org/gora/compiler/GoraCompiler.java
+++ b/gora-core/src/main/java/org/gora/compiler/GoraCompiler.java
@@ -1,369 +1,369 @@
package org.gora.compiler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.avro.Protocol;
import org.apache.avro.Schema;
import org.apache.avro.Protocol.Message;
import org.apache.avro.specific.SpecificData;
/** Generate specific Java interfaces and classes for protocols and schemas. */
public class GoraCompiler {
private File dest;
private Writer out;
private Set<Schema> queue = new HashSet<Schema>();
private GoraCompiler(File dest) {
this.dest = dest; // root directory for output
}
/** Generates Java interface and classes for a protocol.
* @param src the source Avro protocol file
* @param dest the directory to place generated files in
*/
public static void compileProtocol(File src, File dest) throws IOException {
GoraCompiler compiler = new GoraCompiler(dest);
Protocol protocol = Protocol.parse(src);
for (Schema s : protocol.getTypes()) // enqueue types
compiler.enqueue(s);
compiler.compileInterface(protocol); // generate interface
compiler.compile(); // generate classes for types
}
/** Generates Java classes for a schema. */
public static void compileSchema(File src, File dest) throws IOException {
GoraCompiler compiler = new GoraCompiler(dest);
compiler.enqueue(Schema.parse(src)); // enqueue types
compiler.compile(); // generate classes for types
}
private static String camelCasify(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/** Recursively enqueue schemas that need a class generated. */
private void enqueue(Schema schema) throws IOException {
if (queue.contains(schema)) return;
switch (schema.getType()) {
case RECORD:
queue.add(schema);
for (Map.Entry<String, Schema> field : schema.getFieldSchemas())
enqueue(field.getValue());
break;
case MAP:
enqueue(schema.getValueType());
break;
case ARRAY:
enqueue(schema.getElementType());
break;
case UNION:
for (Schema s : schema.getTypes())
enqueue(s);
break;
case ENUM:
case FIXED:
queue.add(schema);
break;
case STRING: case BYTES:
case INT: case LONG:
case FLOAT: case DOUBLE:
case BOOLEAN: case NULL:
break;
default: throw new RuntimeException("Unknown type: "+schema);
}
}
/** Generate java classes for enqueued schemas. */
private void compile() throws IOException {
for (Schema schema : queue)
compile(schema);
}
private void compileInterface(Protocol protocol) throws IOException {
startFile(protocol.getName(), protocol.getNamespace());
try {
line(0, "public interface "+protocol.getName()+" {");
out.append("\n");
for (Map.Entry<String,Message> e : protocol.getMessages().entrySet()) {
String name = e.getKey();
Message message = e.getValue();
Schema request = message.getRequest();
Schema response = message.getResponse();
line(1, unbox(response)+" "+name+"("+params(request)+")");
line(2,"throws AvroRemoteException"+errors(message.getErrors())+";");
}
line(0, "}");
} finally {
out.close();
}
}
private void startFile(String name, String space) throws IOException {
File dir = new File(dest, space.replace('.', File.separatorChar));
if (!dir.exists())
if (!dir.mkdirs())
throw new IOException("Unable to create " + dir);
name = cap(name) + ".java";
out = new OutputStreamWriter(new FileOutputStream(new File(dir, name)));
header(space);
}
private void header(String namespace) throws IOException {
if(namespace != null) {
line(0, "package "+namespace+";\n");
}
line(0, "import java.nio.ByteBuffer;");
line(0, "import java.util.Map;");
line(0, "import org.apache.avro.Protocol;");
line(0, "import org.apache.avro.Schema;");
line(0, "import org.apache.avro.AvroRuntimeException;");
line(0, "import org.apache.avro.Protocol;");
line(0, "import org.apache.avro.util.Utf8;");
line(0, "import org.apache.avro.ipc.AvroRemoteException;");
line(0, "import org.apache.avro.generic.GenericArray;");
line(0, "import org.apache.avro.specific.SpecificExceptionBase;");
line(0, "import org.apache.avro.specific.SpecificRecordBase;");
line(0, "import org.apache.avro.specific.SpecificRecord;");
line(0, "import org.apache.avro.specific.SpecificFixed;");
line(0, "import org.apache.avro.reflect.FixedSize;");
line(0, "import org.gora.persistency.Persistent;");
line(0, "import org.gora.persistency.StateManager;");
line(0, "import org.gora.persistency.impl.PersistentBase;");
line(0, "import org.gora.persistency.impl.StateManagerImpl;");
line(0, "import org.gora.util.StatefulHashMap;");
for (Schema s : queue)
if (namespace == null
? (s.getNamespace() != null)
: !namespace.equals(s.getNamespace()))
line(0, "import "+SpecificData.get().getClassName(s)+";");
line(0, "");
line(0, "@SuppressWarnings(\"all\")");
}
private String params(Schema request) throws IOException {
StringBuilder b = new StringBuilder();
int count = 0;
for (Map.Entry<String, Schema> param : request.getFieldSchemas()) {
String paramName = param.getKey();
b.append(unbox(param.getValue()));
b.append(" ");
b.append(paramName);
if (++count < request.getFields().size())
b.append(", ");
}
return b.toString();
}
private String errors(Schema errs) throws IOException {
StringBuilder b = new StringBuilder();
for (Schema error : errs.getTypes().subList(1, errs.getTypes().size())) {
b.append(", ");
b.append(error.getName());
}
return b.toString();
}
private void compile(Schema schema) throws IOException {
startFile(schema.getName(), schema.getNamespace());
try {
switch (schema.getType()) {
case RECORD:
String type = type(schema);
line(0, "public class "+ type
+" extends PersistentBase {");
// schema definition
line(1, "public static final Schema _SCHEMA = Schema.parse(\""
+esc(schema)+"\");");
// field declations
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
line(1,"private "+unbox(field.getValue())+" "+field.getKey()+";");
}
//constructors
line(1, "public " + type + "() {");
line(2, "this(new StateManagerImpl());");
line(1, "}");
line(1, "public " + type + "(StateManager stateManager) {");
line(2, "super(stateManager);");
line(2, "stateManager.setManagedPersistent(this);");
line(1, "}");
//newInstance(StateManager)
line(1, "public " + type + " newInstance(StateManager stateManager) {");
line(2, "return new " + type + "(stateManager);" );
line(1, "}");
// schema method
line(1, "public Schema getSchema() { return _SCHEMA; }");
// get method
line(1, "public Object get(int _field) {");
line(2, "switch (_field) {");
int i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas())
line(2, "case "+(i++)+": return "+field.getKey()+";");
line(2, "default: throw new AvroRuntimeException(\"Bad index\");");
line(2, "}");
line(1, "}");
// set method
line(1, "@SuppressWarnings(value=\"unchecked\")");
line(1, "public void set(int _field, Object _value) {");
line(2, "getStateManager().setDirty(this, _field);");
line(2, "switch (_field) {");
i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
line(2, "case "+i+":"+field.getKey()+" = ("+
type(field.getValue())+")_value; break;");
i++;
}
line(2, "default: throw new AvroRuntimeException(\"Bad index\");");
line(2, "}");
line(1, "}");
// java bean style getters and setters
i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
String camelKey = camelCasify(field.getKey());
Schema fieldSchema = field.getValue();
switch (fieldSchema.getType()) {
case INT:case LONG:case FLOAT:case DOUBLE:
case BOOLEAN:case BYTES:case STRING: case ENUM:
String unboxed = unbox(fieldSchema);
line(1, "public "+unboxed+" get" +camelKey+"() {");
line(2, "return ("+type(field.getValue())+") get("+i+");");
line(1, "}");
line(1, "public void set"+camelKey+"("+unboxed+" value) {");
line(2, "set("+i+", value);");
line(1, "}");
break;
case ARRAY:
String valueType = type(fieldSchema.getElementType());
unboxed = unbox(fieldSchema.getElementType());
break;
case MAP:
valueType = type(fieldSchema.getValueType());
unboxed = unbox(fieldSchema.getValueType());
line(1, "public Map<Utf8, "+unboxed+"> get"+camelKey+"() {");
line(2, "return (Map<Utf8, "+unboxed+">) get("+i+");");
line(1, "}");
line(1, "public "+unboxed+" getFrom"+camelKey+"(Utf8 key) {");
line(2, "if ("+field.getKey()+" == null) { return null; }");
line(2, "return "+field.getKey()+".get(key);");
line(1, "}");
line(1, "public void putTo"+camelKey+"(Utf8 key, "+unboxed+" value) {");
line(2, "if ("+field.getKey()+" == null) {");
line(3, field.getKey()+" = new StatefulHashMap<Utf8,"+valueType+">();");
line(2, "}");
- line(2, "stateManager.setDirty(this, "+i+");");
+ line(2, "getStateManager().setDirty(this, "+i+");");
line(2, field.getKey()+".put(key, value);");
line(1, "}");
line(1, "public "+unboxed+" removeFrom"+camelKey+"(Utf8 key) {");
line(2, "if ("+field.getKey()+" == null) { return null; }");
- line(2, "stateManager.setDirty(this, "+i+");");
+ line(2, "getStateManager().setDirty(this, "+i+");");
line(2, "return "+field.getKey()+".remove(key);");
line(1, "}");
}
i++;
}
line(0, "}");
break;
case ENUM:
line(0, "public enum "+type(schema)+" { ");
StringBuilder b = new StringBuilder();
int count = 0;
for (String symbol : schema.getEnumSymbols()) {
b.append(symbol);
if (++count < schema.getEnumSymbols().size())
b.append(", ");
}
line(1, b.toString());
line(0, "}");
break;
case FIXED:
line(0, "@FixedSize("+schema.getFixedSize()+")");
line(0, "public class "+type(schema)+" extends SpecificFixed {}");
break;
case MAP: case ARRAY: case UNION: case STRING: case BYTES:
case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case NULL:
break;
default: throw new RuntimeException("Unknown type: "+schema);
}
} finally {
out.close();
}
}
private static final Schema NULL_SCHEMA = Schema.create(Schema.Type.NULL);
public static String type(Schema schema) {
switch (schema.getType()) {
case RECORD:
case ENUM:
case FIXED:
return schema.getName();
case ARRAY:
return "GenericArray<"+type(schema.getElementType())+">";
case MAP:
return "Map<Utf8,"+type(schema.getValueType())+">";
case UNION:
List<Schema> types = schema.getTypes(); // elide unions with null
if ((types.size() == 2) && types.contains(NULL_SCHEMA))
return type(types.get(types.get(0).equals(NULL_SCHEMA) ? 1 : 0));
return "Object";
case STRING: return "Utf8";
case BYTES: return "ByteBuffer";
case INT: return "Integer";
case LONG: return "Long";
case FLOAT: return "Float";
case DOUBLE: return "Double";
case BOOLEAN: return "Boolean";
case NULL: return "Void";
default: throw new RuntimeException("Unknown type: "+schema);
}
}
public static String unbox(Schema schema) {
switch (schema.getType()) {
case INT: return "int";
case LONG: return "long";
case FLOAT: return "float";
case DOUBLE: return "double";
case BOOLEAN: return "boolean";
default: return type(schema);
}
}
private void line(int indent, String text) throws IOException {
for (int i = 0; i < indent; i ++) {
out.append(" ");
}
out.append(text);
out.append("\n");
}
static String cap(String name) {
return name.substring(0,1).toUpperCase()+name.substring(1,name.length());
}
private static String esc(Object o) {
return o.toString().replace("\"", "\\\"");
}
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: SpecificCompiler <schema file> <output dir>");
System.exit(1);
}
compileSchema(new File(args[0]), new File(args[1]));
}
}
| false | true | private void compile(Schema schema) throws IOException {
startFile(schema.getName(), schema.getNamespace());
try {
switch (schema.getType()) {
case RECORD:
String type = type(schema);
line(0, "public class "+ type
+" extends PersistentBase {");
// schema definition
line(1, "public static final Schema _SCHEMA = Schema.parse(\""
+esc(schema)+"\");");
// field declations
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
line(1,"private "+unbox(field.getValue())+" "+field.getKey()+";");
}
//constructors
line(1, "public " + type + "() {");
line(2, "this(new StateManagerImpl());");
line(1, "}");
line(1, "public " + type + "(StateManager stateManager) {");
line(2, "super(stateManager);");
line(2, "stateManager.setManagedPersistent(this);");
line(1, "}");
//newInstance(StateManager)
line(1, "public " + type + " newInstance(StateManager stateManager) {");
line(2, "return new " + type + "(stateManager);" );
line(1, "}");
// schema method
line(1, "public Schema getSchema() { return _SCHEMA; }");
// get method
line(1, "public Object get(int _field) {");
line(2, "switch (_field) {");
int i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas())
line(2, "case "+(i++)+": return "+field.getKey()+";");
line(2, "default: throw new AvroRuntimeException(\"Bad index\");");
line(2, "}");
line(1, "}");
// set method
line(1, "@SuppressWarnings(value=\"unchecked\")");
line(1, "public void set(int _field, Object _value) {");
line(2, "getStateManager().setDirty(this, _field);");
line(2, "switch (_field) {");
i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
line(2, "case "+i+":"+field.getKey()+" = ("+
type(field.getValue())+")_value; break;");
i++;
}
line(2, "default: throw new AvroRuntimeException(\"Bad index\");");
line(2, "}");
line(1, "}");
// java bean style getters and setters
i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
String camelKey = camelCasify(field.getKey());
Schema fieldSchema = field.getValue();
switch (fieldSchema.getType()) {
case INT:case LONG:case FLOAT:case DOUBLE:
case BOOLEAN:case BYTES:case STRING: case ENUM:
String unboxed = unbox(fieldSchema);
line(1, "public "+unboxed+" get" +camelKey+"() {");
line(2, "return ("+type(field.getValue())+") get("+i+");");
line(1, "}");
line(1, "public void set"+camelKey+"("+unboxed+" value) {");
line(2, "set("+i+", value);");
line(1, "}");
break;
case ARRAY:
String valueType = type(fieldSchema.getElementType());
unboxed = unbox(fieldSchema.getElementType());
break;
case MAP:
valueType = type(fieldSchema.getValueType());
unboxed = unbox(fieldSchema.getValueType());
line(1, "public Map<Utf8, "+unboxed+"> get"+camelKey+"() {");
line(2, "return (Map<Utf8, "+unboxed+">) get("+i+");");
line(1, "}");
line(1, "public "+unboxed+" getFrom"+camelKey+"(Utf8 key) {");
line(2, "if ("+field.getKey()+" == null) { return null; }");
line(2, "return "+field.getKey()+".get(key);");
line(1, "}");
line(1, "public void putTo"+camelKey+"(Utf8 key, "+unboxed+" value) {");
line(2, "if ("+field.getKey()+" == null) {");
line(3, field.getKey()+" = new StatefulHashMap<Utf8,"+valueType+">();");
line(2, "}");
line(2, "stateManager.setDirty(this, "+i+");");
line(2, field.getKey()+".put(key, value);");
line(1, "}");
line(1, "public "+unboxed+" removeFrom"+camelKey+"(Utf8 key) {");
line(2, "if ("+field.getKey()+" == null) { return null; }");
line(2, "stateManager.setDirty(this, "+i+");");
line(2, "return "+field.getKey()+".remove(key);");
line(1, "}");
}
i++;
}
line(0, "}");
break;
case ENUM:
line(0, "public enum "+type(schema)+" { ");
StringBuilder b = new StringBuilder();
int count = 0;
for (String symbol : schema.getEnumSymbols()) {
b.append(symbol);
if (++count < schema.getEnumSymbols().size())
b.append(", ");
}
line(1, b.toString());
line(0, "}");
break;
case FIXED:
line(0, "@FixedSize("+schema.getFixedSize()+")");
line(0, "public class "+type(schema)+" extends SpecificFixed {}");
break;
case MAP: case ARRAY: case UNION: case STRING: case BYTES:
case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case NULL:
break;
default: throw new RuntimeException("Unknown type: "+schema);
}
} finally {
out.close();
}
}
| private void compile(Schema schema) throws IOException {
startFile(schema.getName(), schema.getNamespace());
try {
switch (schema.getType()) {
case RECORD:
String type = type(schema);
line(0, "public class "+ type
+" extends PersistentBase {");
// schema definition
line(1, "public static final Schema _SCHEMA = Schema.parse(\""
+esc(schema)+"\");");
// field declations
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
line(1,"private "+unbox(field.getValue())+" "+field.getKey()+";");
}
//constructors
line(1, "public " + type + "() {");
line(2, "this(new StateManagerImpl());");
line(1, "}");
line(1, "public " + type + "(StateManager stateManager) {");
line(2, "super(stateManager);");
line(2, "stateManager.setManagedPersistent(this);");
line(1, "}");
//newInstance(StateManager)
line(1, "public " + type + " newInstance(StateManager stateManager) {");
line(2, "return new " + type + "(stateManager);" );
line(1, "}");
// schema method
line(1, "public Schema getSchema() { return _SCHEMA; }");
// get method
line(1, "public Object get(int _field) {");
line(2, "switch (_field) {");
int i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas())
line(2, "case "+(i++)+": return "+field.getKey()+";");
line(2, "default: throw new AvroRuntimeException(\"Bad index\");");
line(2, "}");
line(1, "}");
// set method
line(1, "@SuppressWarnings(value=\"unchecked\")");
line(1, "public void set(int _field, Object _value) {");
line(2, "getStateManager().setDirty(this, _field);");
line(2, "switch (_field) {");
i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
line(2, "case "+i+":"+field.getKey()+" = ("+
type(field.getValue())+")_value; break;");
i++;
}
line(2, "default: throw new AvroRuntimeException(\"Bad index\");");
line(2, "}");
line(1, "}");
// java bean style getters and setters
i = 0;
for (Map.Entry<String, Schema> field : schema.getFieldSchemas()) {
String camelKey = camelCasify(field.getKey());
Schema fieldSchema = field.getValue();
switch (fieldSchema.getType()) {
case INT:case LONG:case FLOAT:case DOUBLE:
case BOOLEAN:case BYTES:case STRING: case ENUM:
String unboxed = unbox(fieldSchema);
line(1, "public "+unboxed+" get" +camelKey+"() {");
line(2, "return ("+type(field.getValue())+") get("+i+");");
line(1, "}");
line(1, "public void set"+camelKey+"("+unboxed+" value) {");
line(2, "set("+i+", value);");
line(1, "}");
break;
case ARRAY:
String valueType = type(fieldSchema.getElementType());
unboxed = unbox(fieldSchema.getElementType());
break;
case MAP:
valueType = type(fieldSchema.getValueType());
unboxed = unbox(fieldSchema.getValueType());
line(1, "public Map<Utf8, "+unboxed+"> get"+camelKey+"() {");
line(2, "return (Map<Utf8, "+unboxed+">) get("+i+");");
line(1, "}");
line(1, "public "+unboxed+" getFrom"+camelKey+"(Utf8 key) {");
line(2, "if ("+field.getKey()+" == null) { return null; }");
line(2, "return "+field.getKey()+".get(key);");
line(1, "}");
line(1, "public void putTo"+camelKey+"(Utf8 key, "+unboxed+" value) {");
line(2, "if ("+field.getKey()+" == null) {");
line(3, field.getKey()+" = new StatefulHashMap<Utf8,"+valueType+">();");
line(2, "}");
line(2, "getStateManager().setDirty(this, "+i+");");
line(2, field.getKey()+".put(key, value);");
line(1, "}");
line(1, "public "+unboxed+" removeFrom"+camelKey+"(Utf8 key) {");
line(2, "if ("+field.getKey()+" == null) { return null; }");
line(2, "getStateManager().setDirty(this, "+i+");");
line(2, "return "+field.getKey()+".remove(key);");
line(1, "}");
}
i++;
}
line(0, "}");
break;
case ENUM:
line(0, "public enum "+type(schema)+" { ");
StringBuilder b = new StringBuilder();
int count = 0;
for (String symbol : schema.getEnumSymbols()) {
b.append(symbol);
if (++count < schema.getEnumSymbols().size())
b.append(", ");
}
line(1, b.toString());
line(0, "}");
break;
case FIXED:
line(0, "@FixedSize("+schema.getFixedSize()+")");
line(0, "public class "+type(schema)+" extends SpecificFixed {}");
break;
case MAP: case ARRAY: case UNION: case STRING: case BYTES:
case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case NULL:
break;
default: throw new RuntimeException("Unknown type: "+schema);
}
} finally {
out.close();
}
}
|
diff --git a/brix-core/src/main/java/brix/jcr/ThreadLocalSessionFactory.java b/brix-core/src/main/java/brix/jcr/ThreadLocalSessionFactory.java
index b9cb339..e23b32f 100644
--- a/brix-core/src/main/java/brix/jcr/ThreadLocalSessionFactory.java
+++ b/brix-core/src/main/java/brix/jcr/ThreadLocalSessionFactory.java
@@ -1,81 +1,82 @@
package brix.jcr;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Credentials;
import javax.jcr.Repository;
import javax.jcr.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThreadLocalSessionFactory implements JcrSessionFactory
{
private static final Logger logger = LoggerFactory.getLogger(ThreadLocalSessionFactory.class);
private ThreadLocal<Map<String, Session>> container = new ThreadLocal<Map<String, Session>>()
{
@Override
protected Map<String, Session> initialValue()
{
return new HashMap<String, Session>();
}
};
private final Repository repository;
private final Credentials credentials;
public ThreadLocalSessionFactory(Repository repository, Credentials credentials)
{
if (repository == null)
{
throw new IllegalArgumentException("repository cannot be null");
}
if (credentials == null)
{
throw new IllegalArgumentException("credentials cannot be null");
}
this.credentials = credentials;
this.repository = repository;
}
public Session getCurrentSession(String workspace)
{
final Map<String, Session> map = container.get();
Session session = map.get(workspace);
if (session != null && !session.isLive())
{
session = null;
}
if (session == null)
{
try
{
logger.debug("Opening jcr session to workspace: {} with credentials: {}",
workspace, credentials);
session = repository.login(credentials, workspace);
}
catch (Exception e)
{
throw new CannotOpenJcrSessionException(workspace, e);
}
map.put(workspace, session);
+ container.set(map);
}
return session;
}
public void cleanupLocalSessions()
{
for (Session session : container.get().values())
{
if (session.isLive())
{
session.logout();
}
}
}
}
| true | true | public Session getCurrentSession(String workspace)
{
final Map<String, Session> map = container.get();
Session session = map.get(workspace);
if (session != null && !session.isLive())
{
session = null;
}
if (session == null)
{
try
{
logger.debug("Opening jcr session to workspace: {} with credentials: {}",
workspace, credentials);
session = repository.login(credentials, workspace);
}
catch (Exception e)
{
throw new CannotOpenJcrSessionException(workspace, e);
}
map.put(workspace, session);
}
return session;
}
| public Session getCurrentSession(String workspace)
{
final Map<String, Session> map = container.get();
Session session = map.get(workspace);
if (session != null && !session.isLive())
{
session = null;
}
if (session == null)
{
try
{
logger.debug("Opening jcr session to workspace: {} with credentials: {}",
workspace, credentials);
session = repository.login(credentials, workspace);
}
catch (Exception e)
{
throw new CannotOpenJcrSessionException(workspace, e);
}
map.put(workspace, session);
container.set(map);
}
return session;
}
|
diff --git a/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java b/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java
index 388e949a6..47621c0f0 100644
--- a/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java
+++ b/srcj/com/sun/electric/tool/user/tecEditWizard/TechEditWizardData.java
@@ -1,3184 +1,3184 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: TechEditWizardData.java
* Create an Electric XML Technology from a simple numeric description of design rules
* Written in Perl by Andrew Wewist, translated to Java by Steven Rubin.
*
* Copyright (c) 2008 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user.tecEditWizard;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.geometry.*;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.IOTool;
import com.sun.electric.tool.user.dialogs.OpenFile;
import com.sun.electric.tool.user.User;
import com.sun.electric.technology.*;
import java.awt.Color;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
/**
* Class to handle the "Technology Creation Wizard" dialog.
*/
public class TechEditWizardData
{
/************************************** THE DATA **************************************/
private String tech_name;
private String tech_description;
private int num_metal_layers;
private int stepsize;
private boolean pWellFlag = true; // to control if process is a pwell process or not. If true, Tech Creation Wizard will not create pwell layers
private boolean horizontalFlag = true; // to control if transistor gates are aligned horizontally. True by default . If transistors are horizontal -> M1 is horizontal?
private boolean extraInfoFlag = false; // to control if protection polys are added to transistors. False by default
// DIFFUSION RULES
private WizardField diff_width = new WizardField();
private WizardField diff_poly_overhang = new WizardField(); // min. diff overhang from gate edge
private WizardField diff_contact_overhang = new WizardField(); // min. diff overhang contact
private WizardField diff_contact_overhang_min_short = new WizardField(); // diff overhang contact. It should hold the min short value
private WizardField diff_contact_overhang_min_long = new WizardField(); // diff overhang contact. It should hold the min long value
private WizardField diff_spacing = new WizardField();
// POLY RULES
private WizardField poly_width = new WizardField();
private WizardField poly_endcap = new WizardField(); // min. poly gate extension from edge of diffusion
private WizardField poly_spacing = new WizardField();
private WizardField poly_diff_spacing = new WizardField(); // min. spacing between poly and diffusion
private WizardField poly_protection_spacing = new WizardField(); // min. spacing between poly and dummy poly
// GATE RULES
private WizardField gate_length = new WizardField(); // min. transistor gate length
private WizardField gate_width = new WizardField(); // min. transistor gate width
private WizardField gate_spacing = new WizardField(); // min. gate to gate spacing on diffusion
private WizardField gate_contact_spacing = new WizardField(); // min. spacing from gate edge to contact inside diffusion
// Special rules for OD18 transistors if specified.
private WizardField gate_od18_length = new WizardField(); // transistor gate length for OD18 transistors
private WizardField gate_od18_width = new WizardField(); // transistor gate width for OD18 transistors
private WizardField[] od18_diff_overhang = new WizardField[]{new WizardField(), new WizardField()}; // OD18 X and Y overhang
// Special rules for native transistors if speficied
private WizardField gate_nt_length = new WizardField(); // transistor gate length for native transistors
private WizardField gate_nt_width = new WizardField(); // transistor gate width for OD18 transistors
private WizardField poly_nt_endcap = new WizardField(); // gate extension from edge of diffusion for native transistors
private WizardField nt_diff_overhang = new WizardField(); // extension from OD
// CONTACT RULES
private WizardField contact_size = new WizardField();
private WizardField contact_spacing = new WizardField();
private WizardField contact_array_spacing = new WizardField();
private WizardField contact_metal_overhang_inline_only = new WizardField(); // metal overhang when overhanging contact from two sides only
private WizardField contact_metal_overhang_all_sides = new WizardField(); // metal overhang when surrounding contact
private WizardField contact_poly_overhang = new WizardField(); // poly overhang contact. It should hold the recommended value
private WizardField polycon_diff_spacing = new WizardField(); // spacing between poly-metal contact edge and diffusion
// WELL AND IMPLANT RULES
private WizardField nplus_width = new WizardField();
private WizardField nplus_overhang_diff = new WizardField();
private WizardField nplus_overhang_poly = new WizardField();
private WizardField nplus_spacing = new WizardField();
private WizardField pplus_width = new WizardField();
private WizardField pplus_overhang_diff = new WizardField();
private WizardField pplus_overhang_poly = new WizardField();
private WizardField pplus_spacing = new WizardField();
private WizardField nwell_width = new WizardField();
private WizardField nwell_overhang_diff_p = new WizardField();
private WizardField nwell_overhang_diff_n = new WizardField();
private WizardField nwell_spacing = new WizardField();
// METAL RULES
private WizardField [] metal_width;
private WizardField [] metal_spacing;
// VIA RULES
private WizardField [] via_size;
private WizardField [] via_inline_spacing;
private WizardField [] via_array_spacing;
private WizardField [] via_overhang;
// generic cross contacts
private static class ContactNode
{
String layer;
WizardField overX; // overhang X value
WizardField overY; // overhang Y value
ContactNode(String l, double overXV, String overXS, double overYV, String overYS)
{
layer = l;
overX = new WizardField(overXV, overXS);
overY = new WizardField(overYV, overYS);
}
}
private static class Contact
{
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String prefix;
List<ContactNode> layers;
// odd metals go vertical
Contact (String p)
{
prefix = p;
layers = new ArrayList<ContactNode>();
}
}
private Map<String,List<Contact>> metalContacts;
private Map<String,List<Contact>> otherContacts;
private static class PaletteGroup
{
String name;
List<Xml.ArcProto> arcs;
List<Xml.MenuNodeInst> pins;
List<Xml.MenuNodeInst> elements; // contact or transistor
void addArc(Xml.ArcProto arc)
{
if (arcs == null)
{
arcs = new ArrayList<Xml.ArcProto>();
}
arcs.add(arc);
}
void addPin(Xml.PrimitiveNodeGroup pin)
{
if (pins == null)
{
pins = new ArrayList<Xml.MenuNodeInst>();
}
assert pin.isSingleton;
Xml.PrimitiveNode pn = pin.nodes.get(0);
Xml.MenuNodeInst n = new Xml.MenuNodeInst();
n.protoName = pn.name;
n.function = pn.function;
pins.add(n);
}
void addElement(Xml.PrimitiveNodeGroup element, String shortName)
{
if (elements == null)
{
elements = new ArrayList<Xml.MenuNodeInst>();
}
assert element.isSingleton;
Xml.PrimitiveNode pn = element.nodes.get(0);
Xml.MenuNodeInst n = new Xml.MenuNodeInst();
n.protoName = pn.name;
n.function = pn.function;
if (shortName != null)
{
n.text = shortName;
}
elements.add(n);
}
}
// ANTENNA RULES
private double poly_antenna_ratio;
private double [] metal_antenna_ratio;
// GDS-II LAYERS
public static class LayerInfo
{
String name;
int value; // normal value
int type; // datatype of the normal value
int pin; // pin value
int pinType; // pin datatype
int text; // text value
int textType; // text datatype
String graphicsTemplate; // uses other template for the graphics
Color graphicsColor; // uses this color with no fill
EGraphics.Outline graphicsOutline; // uses this outline with graphicsColor
int [] graphicsPattern; // uses this pattern with graphicsColor
LayerInfo(String n)
{
name = n;
}
String getValueWithType() {return (type != 0) ? value + "/" + type : value + "";}
String getPinWithType() {return (pinType != 0) ? pin + "/" + pinType : pin + "";}
String getTextWithType() {return (textType != 0) ? text + "/" + textType : text + "";}
void setData(int[] vals)
{
assert(vals.length == 6);
value = vals[0];
type = vals[1];
pin = vals[2];
pinType = vals[3];
text = vals[4];
textType = vals[5];
}
void setGraphicsTemplate(String s)
{
if (s.startsWith("[")) // color
{
StringTokenizer p = new StringTokenizer(s, ", []", false);
int[] colors = new int[3];
String outlineOrPattern = null; // EGraphics.Outline.NOPAT.name(); // default
int itemCount = 0;
while (p.hasMoreTokens())
{
String str = p.nextToken();
if (itemCount < 3)
colors[itemCount++] = Integer.parseInt(str);
else
outlineOrPattern = str;
assert(itemCount < 4);
}
EGraphics.Outline outline = EGraphics.Outline.findOutline(EGraphics.Outline.NOPAT.name());
int[] pattern = new int[16];
graphicsColor = new Color(colors[0], colors[1], colors[2]);
if (outlineOrPattern != null)
{
EGraphics.Outline out = EGraphics.Outline.findOutline(outlineOrPattern);
if (out != null) // manages to parse a valid Outline
outline = out;
else
{
assert(outlineOrPattern.startsWith("{"));
// Pattern information
StringTokenizer pat = new StringTokenizer(outlineOrPattern, "/ {}", false);
int count = 0;
while (pat.hasMoreTokens())
{
String str = pat.nextToken();
int num = Integer.parseInt(str);
assert(count < 16);
pattern[count++] = num;
}
assert(count == 16);
}
}
graphicsOutline = outline;
graphicsPattern = pattern;
}
else
graphicsTemplate = s;
}
public String toString()
{
String val = getValueWithType(); // useful datatype
if (pin != 0)
{
val = val + "," + getPinWithType() + "p";
}
if (text != 0)
{
val = val + "," + getTextWithType() + "t";
}
return val;
}
}
private LayerInfo gds_diff_layer = new LayerInfo("Diff");
private LayerInfo gds_poly_layer = new LayerInfo("Poly");
private LayerInfo gds_nplus_layer = new LayerInfo("NPlus");
private LayerInfo gds_pplus_layer = new LayerInfo("PPlus");
private LayerInfo gds_nwell_layer = new LayerInfo("N-Well");
private LayerInfo gds_contact_layer = new LayerInfo("Contact");
private LayerInfo [] gds_metal_layer;
private LayerInfo [] gds_via_layer;
private LayerInfo gds_marking_layer = new LayerInfo("Marking"); // Device marking layer
// extra layers
private List<LayerInfo> extraLayers;
LayerInfo[] getBasicLayers()
{
List<LayerInfo> layers = new ArrayList<LayerInfo>();
layers.add(gds_diff_layer);
layers.add(gds_poly_layer);
if (getExtraInfoFlag())
layers.addAll(extraLayers);
layers.add(gds_nplus_layer);
layers.add(gds_pplus_layer);
layers.add(gds_nwell_layer);
layers.add(gds_contact_layer);
layers.add(gds_marking_layer);
LayerInfo[] array = new LayerInfo[layers.size()];
layers.toArray(array);
return array;
}
public TechEditWizardData()
{
stepsize = 100;
num_metal_layers = 2;
metal_width = new WizardField[num_metal_layers];
metal_spacing = new WizardField[num_metal_layers];
via_size = new WizardField[num_metal_layers-1];
via_inline_spacing = new WizardField[num_metal_layers-1];
via_array_spacing = new WizardField[num_metal_layers-1];
via_overhang = new WizardField[num_metal_layers-1];
metal_antenna_ratio = new double[num_metal_layers];
metalContacts = new HashMap<String,List<Contact>>();
otherContacts = new HashMap<String,List<Contact>>();
gds_metal_layer = new LayerInfo[num_metal_layers];
gds_via_layer = new LayerInfo[num_metal_layers-1];
for(int i=0; i<num_metal_layers; i++)
{
metal_width[i] = new WizardField();
metal_spacing[i] = new WizardField();
gds_metal_layer[i] = new LayerInfo("Metal-"+(i+1));
}
for(int i=0; i<num_metal_layers-1; i++)
{
via_size[i] = new WizardField();
via_inline_spacing[i] = new WizardField();
via_array_spacing[i] = new WizardField();
via_overhang[i] = new WizardField();
gds_via_layer[i] = new LayerInfo("Via-"+(i+1));
}
// extra layers
extraLayers = new ArrayList<LayerInfo>();
}
/************************************** ACCESSOR METHODS **************************************/
public String getTechName() { return tech_name; }
public void setTechName(String s) { tech_name = s; }
public String getTechDescription() { return tech_description; }
public void setTechDescription(String s) { tech_description = s; }
public int getStepSize() { return stepsize; }
public void setStepSize(int n) { stepsize = n; }
public int getNumMetalLayers() { return num_metal_layers; }
public void setNumMetalLayers(int n)
{
int smallest = Math.min(n, num_metal_layers);
WizardField [] new_metal_width = new WizardField[n];
for(int i=0; i<smallest; i++) new_metal_width[i] = metal_width[i];
for(int i=smallest; i<n; i++) new_metal_width[i] = new WizardField();
metal_width = new_metal_width;
WizardField [] new_metal_spacing = new WizardField[n];
for(int i=0; i<smallest; i++) new_metal_spacing[i] = metal_spacing[i];
for(int i=smallest; i<n; i++) new_metal_spacing[i] = new WizardField();
metal_spacing = new_metal_spacing;
WizardField [] new_via_size = new WizardField[n-1];
for(int i=0; i<smallest-1; i++) new_via_size[i] = via_size[i];
for(int i=smallest-1; i<n-1; i++) new_via_size[i] = new WizardField();
via_size = new_via_size;
WizardField [] new_via_spacing = new WizardField[n-1];
for(int i=0; i<smallest-1; i++) new_via_spacing[i] = via_inline_spacing[i];
for(int i=smallest-1; i<n-1; i++) new_via_spacing[i] = new WizardField();
via_inline_spacing = new_via_spacing;
WizardField [] new_via_array_spacing = new WizardField[n-1];
for(int i=0; i<smallest-1; i++) new_via_array_spacing[i] = via_array_spacing[i];
for(int i=smallest-1; i<n-1; i++) new_via_array_spacing[i] = new WizardField();
via_array_spacing = new_via_array_spacing;
WizardField [] new_via_overhang_inline = new WizardField[n-1];
for(int i=0; i<smallest-1; i++) new_via_overhang_inline[i] = via_overhang[i];
for(int i=smallest-1; i<n-1; i++) new_via_overhang_inline[i] = new WizardField();
via_overhang = new_via_overhang_inline;
double [] new_metal_antenna_ratio = new double[n];
for(int i=0; i<smallest; i++) new_metal_antenna_ratio[i] = metal_antenna_ratio[i];
metal_antenna_ratio = new_metal_antenna_ratio;
LayerInfo [] new_gds_metal_layer = new LayerInfo[n];
for(int i=0; i<smallest; i++)
{
new_gds_metal_layer[i] = gds_metal_layer[i];
}
for(int i=smallest-1; i<n; i++)
{
new_gds_metal_layer[i] = new LayerInfo("Metal-"+(i+1));
}
gds_metal_layer = new_gds_metal_layer;
LayerInfo [] new_gds_via_layer = new LayerInfo[n-1];
for(int i=0; i<smallest-1; i++) new_gds_via_layer[i] = gds_via_layer[i];
for(int i=smallest-1; i<n-1; i++) new_gds_via_layer[i] = new LayerInfo("Via-"+(i+1));
gds_via_layer = new_gds_via_layer;
num_metal_layers = n;
}
// Flags
boolean getPWellProcess() { return pWellFlag;}
void setPWellProcess(boolean b) { pWellFlag = b; }
boolean getHorizontalTransistors() { return horizontalFlag;}
void setHorizontalTransistors(boolean b) { horizontalFlag = b; }
boolean getExtraInfoFlag() { return extraInfoFlag;}
void setExtraInfoFlag(boolean b) { extraInfoFlag = b; }
// DIFFUSION RULES
WizardField getDiffWidth() { return diff_width; }
void setDiffWidth(WizardField v) { diff_width = v; }
WizardField getDiffPolyOverhang() { return diff_poly_overhang; }
void setDiffPolyOverhang(WizardField v) { diff_poly_overhang = v; }
WizardField getDiffContactOverhang() { return diff_contact_overhang; }
void setDiffContactOverhang(WizardField v) { diff_contact_overhang = v; }
WizardField getDiffSpacing() { return diff_spacing; }
void setDiffSpacing(WizardField v) { diff_spacing = v; }
// POLY RULES
WizardField getPolyWidth() { return poly_width; }
void setPolyWidth(WizardField v) { poly_width = v; }
WizardField getPolyEndcap() { return poly_endcap; }
void setPolyEndcap(WizardField v) { poly_endcap = v; }
WizardField getPolySpacing() { return poly_spacing; }
void setPolySpacing(WizardField v) { poly_spacing = v; }
WizardField getPolyDiffSpacing() { return poly_diff_spacing; }
void setPolyDiffSpacing(WizardField v) { poly_diff_spacing = v; }
WizardField getPolyProtectionSpacing() { return poly_protection_spacing; }
void setPolyProtectionSpacing(WizardField v) { poly_protection_spacing = v; }
// GATE RULES
WizardField getGateLength() { return gate_length; }
void setGateLength(WizardField v) { gate_length = v; }
WizardField getGateWidth() { return gate_width; }
void setGateWidth(WizardField v) { gate_width = v; }
WizardField getGateSpacing() { return gate_spacing; }
void setGateSpacing(WizardField v) { gate_spacing = v; }
WizardField getGateContactSpacing() { return gate_contact_spacing; }
void setGateContactSpacing(WizardField v) { gate_contact_spacing = v; }
// CONTACT RULES
WizardField getContactSize() { return contact_size; }
void setContactSize(WizardField v) { contact_size = v; }
WizardField getContactSpacing() { return contact_spacing; }
void setContactSpacing(WizardField v) { contact_spacing = v; }
WizardField getContactArraySpacing() { return contact_array_spacing; }
void setContactArraySpacing(WizardField v) { contact_array_spacing = v; }
WizardField getContactMetalOverhangInlineOnly() { return contact_metal_overhang_inline_only; }
void setContactMetalOverhangInlineOnly(WizardField v) { contact_metal_overhang_inline_only = v; }
WizardField getContactMetalOverhangAllSides() { return contact_metal_overhang_all_sides; }
void setContactMetalOverhangAllSides(WizardField v) { contact_metal_overhang_all_sides = v; }
WizardField getContactPolyOverhang() { return contact_poly_overhang; }
void setContactPolyOverhang(WizardField v) { contact_poly_overhang = v; }
WizardField getPolyconDiffSpacing() { return polycon_diff_spacing; }
void setPolyconDiffSpacing(WizardField v) { polycon_diff_spacing = v; }
// WELL AND IMPLANT RULES
WizardField getNPlusWidth() { return nplus_width; }
void setNPlusWidth(WizardField v) { nplus_width = v; }
WizardField getNPlusOverhangDiff() { return nplus_overhang_diff; }
void setNPlusOverhangDiff(WizardField v) { nplus_overhang_diff = v; }
WizardField getNPlusOverhangPoly() { return nplus_overhang_poly; }
void setNPlusOverhangPoly(WizardField v) { nplus_overhang_poly = v; }
WizardField getNPlusSpacing() { return nplus_spacing; }
void setNPlusSpacing(WizardField v) { nplus_spacing = v; }
WizardField getPPlusWidth() { return pplus_width; }
void setPPlusWidth(WizardField v) { pplus_width = v; }
WizardField getPPlusOverhangDiff() { return pplus_overhang_diff; }
void setPPlusOverhangDiff(WizardField v) { pplus_overhang_diff = v; }
WizardField getPPlusOverhangPoly() { return pplus_overhang_poly; }
void setPPlusOverhangPoly(WizardField v) { pplus_overhang_poly = v; }
WizardField getPPlusSpacing() { return pplus_spacing; }
void setPPlusSpacing(WizardField v) { pplus_spacing = v; }
WizardField getNWellWidth() { return nwell_width; }
void setNWellWidth(WizardField v) { nwell_width = v; }
WizardField getNWellOverhangDiffP() { return nwell_overhang_diff_p; }
void setNWellOverhangDiffP(WizardField v) { nwell_overhang_diff_p = v; }
WizardField getNWellOverhangDiffN() { return nwell_overhang_diff_n; }
void setNWellOverhangDiffN(WizardField v) { nwell_overhang_diff_n = v; }
WizardField getNWellSpacing() { return nwell_spacing; }
void setNWellSpacing(WizardField v) { nwell_spacing = v; }
// METAL RULES
WizardField [] getMetalWidth() { return metal_width; }
void setMetalWidth(int met, WizardField value) { metal_width[met] = value; }
WizardField [] getMetalSpacing() { return metal_spacing; }
void setMetalSpacing(int met, WizardField value) { metal_spacing[met] = value; }
// VIA RULES
WizardField [] getViaSize() { return via_size; }
void setViaSize(int via, WizardField value) { via_size[via] = value; }
WizardField [] getViaSpacing() { return via_inline_spacing; }
void setViaSpacing(int via, WizardField value) { via_inline_spacing[via] = value; }
WizardField [] getViaArraySpacing() { return via_array_spacing; }
void setViaArraySpacing(int via, WizardField value) { via_array_spacing[via] = value; }
WizardField [] getViaOverhangInline() { return via_overhang; }
void setViaOverhangInline(int via, WizardField value) { via_overhang[via] = value; }
// ANTENNA RULES
public double getPolyAntennaRatio() { return poly_antenna_ratio; }
void setPolyAntennaRatio(double v) { poly_antenna_ratio = v; }
public double [] getMetalAntennaRatio() { return metal_antenna_ratio; }
void setMetalAntennaRatio(int met, double value) { metal_antenna_ratio[met] = value; }
// GDS-II LAYERS
static int[] getGDSValuesFromString(String s)
{
int[] vals = new int[6];
StringTokenizer parse = new StringTokenizer(s, ",", false);
while (parse.hasMoreTokens())
{
String v = parse.nextToken();
int pos = 0;
int index = v.indexOf("/");
if (v.contains("p")) // pin section
{
pos = 2;
} else if (v.contains("t")) // text section
{
pos = 4;
}
if (index != -1) // datatype value
{
vals[pos] = TextUtils.atoi(v.substring(0, index));
vals[pos+1] = TextUtils.atoi(v.substring(index+1));
}
else
vals[pos] = TextUtils.atoi(v);
}
return vals;
}
TechEditWizardData.LayerInfo [] getGDSMetal() { return gds_metal_layer; }
TechEditWizardData.LayerInfo [] getGDSVia() { return gds_via_layer; }
private String errorInData()
{
// check the General data
if (tech_name == null || tech_name.length() == 0) return "General panel: No technology name";
if (stepsize == 0) return "General panel: Invalid unit size";
// check the Active data
if (diff_width.v == 0) return "Active panel: Invalid width";
// check the Poly data
if (poly_width.v == 0) return "Poly panel: Invalid width";
// check the Gate data
if (gate_width.v == 0) return "Gate panel: Invalid width";
if (gate_length.v == 0) return "Gate panel: Invalid length";
// check the Contact data
if (contact_size.v == 0) return "Contact panel: Invalid size";
// check the Well/Implant data
if (nplus_width.v == 0) return "Well/Implant panel: Invalid NPlus width";
if (pplus_width.v == 0) return "Well/Implant panel: Invalid PPlus width";
if (nwell_width.v == 0) return "Well/Implant panel: Invalid NWell width";
// check the Metal data
for(int i=0; i<num_metal_layers; i++)
if (metal_width[i].v == 0) return "Metal panel: Invalid Metal-" + (i+1) + " width";
// check the Via data
for(int i=0; i<num_metal_layers-1; i++)
if (via_size[i].v == 0) return "Via panel: Invalid Via-" + (i+1) + " size";
return null;
}
/************************************** IMPORT RAW NUMBERS FROM DISK **************************************/
/**
* Method to import data from a file to this object.
* @return true on success; false on failure.
*/
boolean importData()
{
String fileName = OpenFile.chooseInputFile(FileType.ANY, "Technology Wizard File");
if (fileName == null) return false;
return importData(fileName);
}
/**
* Method to import data from a given file to this object. It is also in the regression so
* keep the access.
* @param fileName the name of the file to import.
* @return true on success; false on failure.
*/
public boolean importData(String fileName)
{
URL url = TextUtils.makeURLToFile(fileName);
// clean arrays first
metalContacts.clear();
otherContacts.clear();
extraLayers.clear();
try
{
URLConnection urlCon = url.openConnection();
InputStreamReader is = new InputStreamReader(urlCon.getInputStream());
LineNumberReader lineReader = new LineNumberReader(is);
for(;;)
{
String buf = lineReader.readLine();
if (buf == null) break;
buf = buf.trim();
if (buf.length() == 0 || buf.startsWith("#")) continue;
// parse the assignment
if (buf.startsWith("$") || buf.startsWith("@"))
{
int spacePos = buf.indexOf(' ');
int equalsPos = buf.indexOf('=');
if (equalsPos < 0)
{
Job.getUserInterface().showErrorMessage("Missing '=' on line " + lineReader.getLineNumber(),
"Syntax Error In Technology File");
break;
}
if (spacePos < 0) spacePos = equalsPos; else
spacePos = Math.min(spacePos, equalsPos);
String varName = buf.substring(1, spacePos);
int semiPos = buf.indexOf(';');
if (semiPos < 0)
{
Job.getUserInterface().showErrorMessage("Missing ';' on line " + lineReader.getLineNumber(),
"Syntax Error In Technology File");
break;
}
equalsPos++;
while (equalsPos < semiPos && buf.charAt(equalsPos) == ' ') equalsPos++;
String varValue = buf.substring(equalsPos, semiPos);
// now figure out what to assign
if (varName.equalsIgnoreCase("tech_libname")) { } else
if (varName.equalsIgnoreCase("tech_name")) setTechName(stripQuotes(varValue)); else
if (varName.equalsIgnoreCase("tech_description")) setTechDescription(stripQuotes(varValue)); else
if (varName.equalsIgnoreCase("num_metal_layers")) setNumMetalLayers(TextUtils.atoi(varValue)); else
if (varName.equalsIgnoreCase("pwell_process")) setPWellProcess(Boolean.valueOf(varValue)); else
if (varName.equalsIgnoreCase("horizontal_transistors")) setHorizontalTransistors(Boolean.valueOf(varValue)); else
if (varName.equalsIgnoreCase("extra_info")) setExtraInfoFlag(Boolean.valueOf(varValue)); else
if (varName.equalsIgnoreCase("stepsize")) setStepSize(TextUtils.atoi(varValue)); else
if (varName.equalsIgnoreCase("diff_width")) diff_width.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("diff_width_rule")) diff_width.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("diff_poly_overhang")) diff_poly_overhang.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("diff_poly_overhang_rule")) diff_poly_overhang.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("diff_contact_overhang")) diff_contact_overhang.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("diff_contact_overhang_rule")) diff_contact_overhang.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("diff_contact_overhang_short_min")) diff_contact_overhang_min_short.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("diff_contact_overhang_short_min_rule")) diff_contact_overhang_min_short.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("diff_contact_overhang_long_min")) diff_contact_overhang_min_long.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("diff_contact_overhang_long_min_rule")) diff_contact_overhang_min_long.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("diff_spacing")) diff_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("diff_spacing_rule")) diff_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("poly_width")) poly_width.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("poly_width_rule")) poly_width.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("poly_endcap")) poly_endcap.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("poly_endcap_rule")) poly_endcap.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("poly_spacing")) poly_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("poly_spacing_rule")) poly_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("poly_diff_spacing")) poly_diff_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("poly_diff_spacing_rule")) poly_diff_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("poly_protection_spacing")) poly_protection_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("poly_protection_spacing_rule")) poly_protection_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("gate_length")) gate_length.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("gate_length_rule")) gate_length.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("gate_width")) gate_width.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("gate_width_rule")) gate_width.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("gate_spacing")) gate_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("gate_spacing_rule")) gate_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("gate_contact_spacing")) gate_contact_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("gate_contact_spacing_rule")) gate_contact_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("gate_od18_length")) fillRule(varValue, gate_od18_length); else
if (varName.equalsIgnoreCase("gate_od18_width")) fillRule(varValue, gate_od18_width); else
if (varName.equalsIgnoreCase("od18_diff_overhang")) fillRule(varValue, od18_diff_overhang); else
if (varName.equalsIgnoreCase("gate_nt_length")) fillRule(varValue, gate_nt_length); else
if (varName.equalsIgnoreCase("gate_nt_width")) fillRule(varValue, gate_nt_width); else
if (varName.equalsIgnoreCase("poly_nt_endcap")) fillRule(varValue, poly_nt_endcap); else
if (varName.equalsIgnoreCase("nt_diff_overhang")) fillRule(varValue, nt_diff_overhang); else
if (varName.equalsIgnoreCase("contact_size")) contact_size.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("contact_size_rule")) contact_size.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("contact_spacing")) contact_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("contact_spacing_rule")) contact_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("contact_array_spacing")) contact_array_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("contact_array_spacing_rule")) contact_array_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("contact_metal_overhang_inline_only")) contact_metal_overhang_inline_only.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("contact_metal_overhang_inline_only_rule")) contact_metal_overhang_inline_only.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("contact_metal_overhang_all_sides")) contact_metal_overhang_all_sides.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("contact_metal_overhang_all_sides_rule")) contact_metal_overhang_all_sides.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("contact_poly_overhang")) contact_poly_overhang.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("contact_poly_overhang_rule")) contact_poly_overhang.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("polycon_diff_spacing")) polycon_diff_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("polycon_diff_spacing_rule")) polycon_diff_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nplus_width")) nplus_width.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nplus_width_rule")) nplus_width.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nplus_overhang_diff")) nplus_overhang_diff.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nplus_overhang_diff_rule")) nplus_overhang_diff.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nplus_overhang_poly")) nplus_overhang_poly.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nplus_overhang_poly_rule")) nplus_overhang_poly.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nplus_spacing")) nplus_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nplus_spacing_rule")) nplus_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("pplus_width")) pplus_width.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("pplus_width_rule")) pplus_width.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("pplus_overhang_diff")) pplus_overhang_diff.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("pplus_overhang_diff_rule")) pplus_overhang_diff.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("pplus_overhang_poly")) pplus_overhang_poly.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("pplus_overhang_poly_rule")) pplus_overhang_poly.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("pplus_spacing")) pplus_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("pplus_spacing_rule")) pplus_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nwell_width")) nwell_width.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nwell_width_rule")) nwell_width.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nwell_overhang_diff_p")) nwell_overhang_diff_p.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nwell_overhang_diff_rule_p")) nwell_overhang_diff_p.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nwell_overhang_diff_n")) nwell_overhang_diff_n.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nwell_overhang_diff_rule_n")) nwell_overhang_diff_n.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("nwell_spacing")) nwell_spacing.v = TextUtils.atof(varValue); else
if (varName.equalsIgnoreCase("nwell_spacing_rule")) nwell_spacing.rule = stripQuotes(varValue); else
if (varName.equalsIgnoreCase("metal_width")) fillWizardArray(varValue, metal_width, num_metal_layers, false); else
if (varName.equalsIgnoreCase("metal_width_rule")) fillWizardArray(varValue, metal_width, num_metal_layers, true); else
if (varName.equalsIgnoreCase("metal_spacing")) fillWizardArray(varValue, metal_spacing, num_metal_layers, false); else
if (varName.equalsIgnoreCase("metal_spacing_rule")) fillWizardArray(varValue, metal_spacing, num_metal_layers, true); else
if (varName.equalsIgnoreCase("via_size")) fillWizardArray(varValue, via_size, num_metal_layers-1, false); else
if (varName.equalsIgnoreCase("via_size_rule")) fillWizardArray(varValue, via_size, num_metal_layers-1, true); else
if (varName.equalsIgnoreCase("via_spacing")) fillWizardArray(varValue, via_inline_spacing, num_metal_layers-1, false); else
if (varName.equalsIgnoreCase("via_spacing_rule")) fillWizardArray(varValue, via_inline_spacing, num_metal_layers-1, true); else
if (varName.equalsIgnoreCase("via_array_spacing")) fillWizardArray(varValue, via_array_spacing, num_metal_layers-1, false); else
if (varName.equalsIgnoreCase("via_array_spacing_rule")) fillWizardArray(varValue, via_array_spacing, num_metal_layers-1, true); else
if (varName.equalsIgnoreCase("via_overhang_inline")) fillWizardArray(varValue, via_overhang, num_metal_layers-1, false); else
if (varName.equalsIgnoreCase("via_overhang_inline_rule")) fillWizardArray(varValue, via_overhang, num_metal_layers-1, true); else
if (varName.equalsIgnoreCase("metal_contacts_series")) fillContactSeries(varValue, metalContacts); else
if (varName.equalsIgnoreCase("contacts_series")) fillContactSeries(varValue, otherContacts); else
// Special layers
if (varName.equalsIgnoreCase("gds_layers")) fillLayerSeries(varValue, extraLayers); else
if (varName.equalsIgnoreCase("poly_antenna_ratio")) setPolyAntennaRatio(TextUtils.atof(varValue)); else
if (varName.equalsIgnoreCase("metal_antenna_ratio")) metal_antenna_ratio = makeDoubleArray(varValue); else
if (varName.equalsIgnoreCase("gds_diff_layer")) gds_diff_layer.setData(getGDSValuesFromString(varValue)); else
if (varName.equalsIgnoreCase("gds_poly_layer")) gds_poly_layer.setData(getGDSValuesFromString(varValue)); else
if (varName.equalsIgnoreCase("gds_nplus_layer")) gds_nplus_layer.setData(getGDSValuesFromString(varValue)); else
if (varName.equalsIgnoreCase("gds_pplus_layer")) gds_pplus_layer.setData(getGDSValuesFromString(varValue)); else
if (varName.equalsIgnoreCase("gds_nwell_layer")) gds_nwell_layer.setData(getGDSValuesFromString(varValue)); else
if (varName.equalsIgnoreCase("gds_contact_layer")) gds_contact_layer.setData(getGDSValuesFromString(varValue)); else
if (varName.equalsIgnoreCase("gds_metal_layer")) gds_metal_layer = makeLayerInfoArray(varValue, num_metal_layers, "Metal-"); else
if (varName.equalsIgnoreCase("gds_via_layer")) gds_via_layer = makeLayerInfoArray(varValue, num_metal_layers - 1, "Via-"); else
if (varName.equalsIgnoreCase("gds_marking_layer")) gds_marking_layer.setData(getGDSValuesFromString(varValue)); else
{
Job.getUserInterface().showErrorMessage("Unknown keyword '" + varName + "' on line " + lineReader.getLineNumber(),
"Syntax Error In Technology File");
break;
}
}
}
lineReader.close();
} catch (IOException e)
{
System.out.println("Error reading " + fileName);
return false;
}
return true;
}
private String stripQuotes(String str)
{
if (str.startsWith("\"") && str.endsWith("\""))
return str.substring(1, str.length()-1);
return str;
}
private LayerInfo [] makeLayerInfoArray(String str, int len, String extra)
{
LayerInfo [] foundArray = new LayerInfo[len];
for(int i=0; i<len; i++) foundArray[i] = new LayerInfo(extra + (i+1));
StringTokenizer parse = new StringTokenizer(str, "( \")", false);
int count = 0;
while (parse.hasMoreTokens())
{
if (count >= len)
{
System.out.println("More GDS values than metal layers in TechEditWizardData");
break;
}
else
{
String value = parse.nextToken();
// array delimeters must be discarded here because GDS string may
// contain "," for the pin/text definition ("," can't be used in the StringTokenizer
if (!value.equals(","))
foundArray[count++].setData(getGDSValuesFromString(value));
}
}
return foundArray;
}
private double [] makeDoubleArray(String str)
{
WizardField [] foundArray = new WizardField[num_metal_layers];
for(int i=0; i<num_metal_layers; i++) foundArray[i] = new WizardField();
fillWizardArray(str, foundArray, num_metal_layers, false);
double [] retArray = new double[foundArray.length];
for(int i=0; i<foundArray.length; i++)
retArray[i] = foundArray[i].v;
return retArray;
}
private void fillWizardArray(String str, WizardField [] fieldArray, int expectedLength, boolean getRule)
{
if (!str.startsWith("("))
{
Job.getUserInterface().showErrorMessage("Array does not start with '(' on " + str,
"Syntax Error In Technology File");
return;
}
int pos = 1;
int index = 0;
for(;;)
{
while (pos < str.length() && str.charAt(pos) == ' ') pos++;
if (index >= fieldArray.length)
{
// Job.getUserInterface().showErrorMessage("Invalid metal index: " + index,
// "Syntax Error In Technology File");
return;
}
if (getRule)
{
if (str.charAt(pos) != '"')
{
Job.getUserInterface().showErrorMessage("Rule element does not start with quote on " + str,
"Syntax Error In Technology File");
return;
}
pos++;
int end = pos;
while (end < str.length() && str.charAt(end) != '"') end++;
if (str.charAt(end) != '"')
{
Job.getUserInterface().showErrorMessage("Rule element does not end with quote on " + str,
"Syntax Error In Technology File");
return;
}
fieldArray[index++].rule = str.substring(pos, end);
pos = end+1;
} else
{
double v = TextUtils.atof(str.substring(pos));
fieldArray[index++].v = v;
}
while (pos < str.length() && str.charAt(pos) != ',' && str.charAt(pos) != ')') pos++;
if (str.charAt(pos) != ',') break;
pos++;
}
}
// fillRule
private void fillRule(String str, WizardField... rules)
{
StringTokenizer parse = new StringTokenizer(str, "(,)", false);
int count = 0;
int pos = 0;
while (parse.hasMoreTokens())
{
String value = parse.nextToken();
switch (count)
{
case 0:
case 2:
rules[pos].v = Double.parseDouble(value);
break;
case 1:
case 3:
rules[pos].rule = value;
break;
default:
assert(false); // only 2 values
}
count++;
if (count == 2) pos++;
}
}
// fillLayerSeries
private void fillLayerSeries(String str, List<LayerInfo> layersList)
{
StringTokenizer parse = new StringTokenizer(str, "()", false);
while (parse.hasMoreTokens())
{
String value = parse.nextToken();
if (!value.contains(",")) // only white space
continue;
// Sequence ("layer name", "GDS value")
StringTokenizer p = new StringTokenizer(value, " \"", false);
int itemCount = 0; // 2 max items: layer name and GDS value
LayerInfo layer = null;
while (p.hasMoreTokens())
{
String s = p.nextToken();
if (s.startsWith(",")) continue; // skipping comma. Not in the parser because of the color
switch (itemCount)
{
case 0:
layer = new LayerInfo(s);
layersList.add(layer);
break;
case 1:
layer.setData(getGDSValuesFromString(s));
break;
case 2:
layer.setGraphicsTemplate(s);
break;
default:
assert(false);
}
itemCount++;
}
if (itemCount != 2 && itemCount != 3)
assert(itemCount == 2 || itemCount == 3);
}
}
// to get general contact
private void fillContactSeries(String str, Map<String,List<Contact>> contactMap)
{
StringTokenizer parse = new StringTokenizer(str, "[]", false);
List<ContactNode> nodeList = new ArrayList<ContactNode>();
while (parse.hasMoreTokens())
{
String value = parse.nextToken();
if (value.equals(";")) // end of line
continue;
// checking the metal pair lists.
// overhang values should be in by now
if (value.contains("{"))
{
assert(nodeList.size() > 0);
int index = value.indexOf("{");
assert(index != -1); // it should come with a prefix name
String prefix = value.substring(0, index);
String v = value.substring(index);
StringTokenizer p = new StringTokenizer(v, "{}", false);
while (p.hasMoreTokens())
{
String pair = p.nextToken();
// getting metal numbers {a,b,c}
StringTokenizer n = new StringTokenizer(pair, ", ", false); // getting the layer names
List<String> layerNames = new ArrayList<String>();
while (n.hasMoreTokens())
{
String l = n.nextToken();
layerNames.add(l);
}
assert (nodeList.size() == layerNames.size());
Contact cont = new Contact(prefix);
for (int i = 0; i < layerNames.size(); i++)
{
String name = layerNames.get(i);
ContactNode tmp = nodeList.get(i);
ContactNode node = new ContactNode(name, tmp.overX.v, tmp.overX.rule,
tmp.overY.v, tmp.overY.rule);
cont.layers.add(node);
}
String layer1 = layerNames.get(0);
String layer2 = layerNames.get(1); // n/p plus regions should go at the end
// Always store them by lowMetal-highMetal if happens
if (layer1.compareToIgnoreCase(layer2) > 0) // layer1 name is second
{
String temp = layer1;
layer1 = layer2;
layer2 = temp;
}
String key = layer1 + "-" + layer2;
List<Contact> l = contactMap.get(key);
if (l == null)
{
l = new ArrayList<Contact>();
contactMap.put(key, l);
}
l.add(cont);
}
}
else
{
// syntax: A(overX, overXS, overY, overYS)(Layer2, overX, overXS, overY, overYS)
// pair of layers found
StringTokenizer p = new StringTokenizer(value, "()", false);
while (p.hasMoreTokens())
{
String s = p.nextToken();
// layer info
int itemCount = 0; // 4 max items: metal layer, overhang X, overhang X rule, overhang Y, overhang Y rule
StringTokenizer x = new StringTokenizer(s, ", ", false);
double overX = 0, overY = 0;
String overXS = null, overYS = null;
while (x.hasMoreTokens() && itemCount < 4)
{
String item = x.nextToken();
switch (itemCount)
{
case 0: // overhang X value
overX = Double.valueOf(item);
break;
case 1: // overhang X rule name
overXS = item;
break;
case 2: // overhang Y value
overY = Double.valueOf(item);
break;
case 3: // overhang Y rule name
overYS = item;
break;
}
itemCount++;
}
assert(itemCount == 4);
ContactNode node = new ContactNode("", overX, overXS, overY, overYS);
nodeList.add(node);
}
}
}
}
/************************************** EXPORT RAW NUMBERS TO DISK **************************************/
void exportData()
{
String fileName = OpenFile.chooseOutputFile(FileType.TEXT, "Technology Wizard File", "Technology.txt");
if (fileName == null) return;
try
{
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
dumpNumbers(printWriter);
printWriter.close();
} catch (IOException e)
{
System.out.println("Error writing XML file");
return;
}
}
private void dumpNumbers(PrintWriter pw)
{
pw.print("#### Electric(tm) VLSI Design System, version ");
if (User.isIncludeDateAndVersionInOutput())
{
pw.println(com.sun.electric.database.text.Version.getVersion());
} else
{
pw.println();
}
pw.println("#### ");
pw.println("#### Technology wizard data file");
pw.println("####");
pw.println("#### All dimensions in nanometers.");
if (IOTool.isUseCopyrightMessage())
{
String str = IOTool.getCopyrightMessage();
int start = 0;
while (start < str.length())
{
int endPos = str.indexOf('\n', start);
if (endPos < 0) endPos = str.length();
String oneLine = str.substring(start, endPos);
pw.println("#### " + oneLine);
start = endPos+1;
}
}
pw.println();
pw.println("$tech_name = \"" + tech_name + "\";");
pw.println("$tech_description = \"" + tech_description + "\";");
pw.println("$num_metal_layers = " + num_metal_layers + ";");
pw.println("$pwell_process = " + pWellFlag + ";");
pw.println("$horizontal_transistors = " + horizontalFlag + ";");
pw.println("$extra_info = " + extraInfoFlag + ";");
pw.println();
pw.println("## stepsize is minimum granularity that will be used as movement grid");
pw.println("## set to manufacturing grid or lowest common denominator with design rules");
pw.println("$stepsize = " + stepsize + ";");
pw.println();
pw.println("###### DIFFUSION RULES #####");
pw.println("$diff_width = " + TextUtils.formatDouble(diff_width.v) + ";");
pw.println("$diff_width_rule = \"" + diff_width.rule + "\";");
pw.println("$diff_poly_overhang = " + TextUtils.formatDouble(diff_poly_overhang.v) + "; # min. diff overhang from gate edge");
pw.println("$diff_poly_overhang_rule = \"" + diff_poly_overhang.rule + "\"; # min. diff overhang from gate edge");
pw.println("$diff_contact_overhang = " + TextUtils.formatDouble(diff_contact_overhang.v) + "; # min. diff overhang contact");
pw.println("$diff_contact_overhang_rule = \"" + diff_contact_overhang.rule + "\"; # min. diff overhang contact");
pw.println("$diff_spacing = " + TextUtils.formatDouble(diff_spacing.v) + ";");
pw.println("$diff_spacing_rule = \"" + diff_spacing.rule + "\";");
pw.println();
pw.println("###### POLY RULES #####");
pw.println("$poly_width = " + TextUtils.formatDouble(poly_width.v) + ";");
pw.println("$poly_width_rule = \"" + poly_width.rule + "\";");
pw.println("$poly_endcap = " + TextUtils.formatDouble(poly_endcap.v) + "; # min. poly gate extension from edge of diffusion");
pw.println("$poly_endcap_rule = \"" + poly_endcap.rule + "\"; # min. poly gate extension from edge of diffusion");
pw.println("$poly_spacing = " + TextUtils.formatDouble(poly_spacing.v) + ";");
pw.println("$poly_spacing_rule = \"" + poly_spacing.rule + "\";");
pw.println("$poly_diff_spacing = " + TextUtils.formatDouble(poly_diff_spacing.v) + "; # min. spacing between poly and diffusion");
pw.println("$poly_diff_spacing_rule = \"" + poly_diff_spacing.rule + "\"; # min. spacing between poly and diffusion");
pw.println("$poly_protection_spacing = " + TextUtils.formatDouble(poly_protection_spacing.v) + "; # min. spacing between poly and dummy poly");
pw.println("$poly_protection_spacing_rule = \"" + poly_protection_spacing.rule + "\"; # min. spacing between poly and dummy poly");
pw.println();
pw.println("###### GATE RULES #####");
pw.println("$gate_length = " + TextUtils.formatDouble(gate_length.v) + "; # min. transistor gate length");
pw.println("$gate_length_rule = \"" + gate_length.rule + "\"; # min. transistor gate length");
pw.println("$gate_width = " + TextUtils.formatDouble(gate_width.v) + "; # min. transistor gate width");
pw.println("$gate_width_rule = \"" + gate_width.rule + "\"; # min. transistor gate width");
pw.println("$gate_spacing = " + TextUtils.formatDouble(gate_spacing.v) + "; # min. gate to gate spacing on diffusion");
pw.println("$gate_spacing_rule = \"" + gate_spacing.rule + "\"; # min. gate to gate spacing on diffusion");
pw.println("$gate_contact_spacing = " + TextUtils.formatDouble(gate_contact_spacing.v) + "; # min. spacing from gate edge to contact inside diffusion");
pw.println("$gate_contact_spacing_rule = \"" + gate_contact_spacing.rule + "\"; # min. spacing from gate edge to contact inside diffusion");
pw.println();
pw.println("###### CONTACT RULES #####");
pw.println("$contact_size = " + TextUtils.formatDouble(contact_size.v) + ";");
pw.println("$contact_size_rule = \"" + contact_size.rule + "\";");
pw.println("$contact_spacing = " + TextUtils.formatDouble(contact_spacing.v) + ";");
pw.println("$contact_spacing_rule = \"" + contact_spacing.rule + "\";");
pw.println("$contact_array_spacing = " + TextUtils.formatDouble(contact_array_spacing.v) + ";");
pw.println("$contact_array_spacing_rule = \"" + contact_array_spacing.rule + "\";");
pw.println("$contact_metal_overhang_inline_only = " + TextUtils.formatDouble(contact_metal_overhang_inline_only.v) + "; # metal overhang when overhanging contact from two sides only");
pw.println("$contact_metal_overhang_inline_only_rule = \"" + contact_metal_overhang_inline_only.rule + "\"; # metal overhang when overhanging contact from two sides only");
pw.println("$contact_metal_overhang_all_sides = " + TextUtils.formatDouble(contact_metal_overhang_all_sides.v) + "; # metal overhang when surrounding contact");
pw.println("$contact_metal_overhang_all_sides_rule = \"" + contact_metal_overhang_all_sides.rule + "\"; # metal overhang when surrounding contact");
pw.println("$contact_poly_overhang = " + TextUtils.formatDouble(contact_poly_overhang.v) + "; # poly overhang contact, recommended value");
pw.println("$contact_poly_overhang_rule = \"" + contact_poly_overhang.rule + "\"; # poly overhang contact, recommended value");
pw.println("$polycon_diff_spacing = " + TextUtils.formatDouble(polycon_diff_spacing.v) + "; # spacing between poly-metal contact edge and diffusion");
pw.println("$polycon_diff_spacing_rule = \"" + polycon_diff_spacing.rule + "\"; # spacing between poly-metal contact edge and diffusion");
pw.println();
pw.println("###### WELL AND IMPLANT RULES #####");
pw.println("$nplus_width = " + TextUtils.formatDouble(nplus_width.v) + ";");
pw.println("$nplus_width_rule = \"" + nplus_width.rule + "\";");
pw.println("$nplus_overhang_diff = " + TextUtils.formatDouble(nplus_overhang_diff.v) + ";");
pw.println("$nplus_overhang_diff_rule = \"" + nplus_overhang_diff.rule + "\";");
pw.println("$nplus_overhang_poly = " + TextUtils.formatDouble(nplus_overhang_poly.v) + ";");
pw.println("$nplus_overhang_poly_rule = \"" + nplus_overhang_poly.rule + "\";");
pw.println("$nplus_spacing = " + TextUtils.formatDouble(nplus_spacing.v) + ";");
pw.println("$nplus_spacing_rule = \"" + nplus_spacing.rule + "\";");
pw.println();
pw.println("$pplus_width = " + TextUtils.formatDouble(pplus_width.v) + ";");
pw.println("$pplus_width_rule = \"" + pplus_width.rule + "\";");
pw.println("$pplus_overhang_diff = " + TextUtils.formatDouble(pplus_overhang_diff.v) + ";");
pw.println("$pplus_overhang_diff_rule = \"" + pplus_overhang_diff.rule + "\";");
pw.println("$pplus_overhang_poly = " + TextUtils.formatDouble(pplus_overhang_poly.v) + ";");
pw.println("$pplus_overhang_poly_rule = \"" + pplus_overhang_poly.rule + "\";");
pw.println("$pplus_spacing = " + TextUtils.formatDouble(pplus_spacing.v) + ";");
pw.println("$pplus_spacing_rule = \"" + pplus_spacing.rule + "\";");
pw.println();
pw.println("$nwell_width = " + TextUtils.formatDouble(nwell_width.v) + ";");
pw.println("$nwell_width_rule = \"" + nwell_width.rule + "\";");
pw.println("$nwell_overhang_diff_p = " + TextUtils.formatDouble(nwell_overhang_diff_p.v) + ";");
pw.println("$nwell_overhang_diff_rule_p = \"" + nwell_overhang_diff_p.rule + "\";");
pw.println("$nwell_overhang_diff_n = " + TextUtils.formatDouble(nwell_overhang_diff_n.v) + ";");
pw.println("$nwell_overhang_diff_rule_n = \"" + nwell_overhang_diff_n.rule + "\";");
pw.println("$nwell_spacing = " + TextUtils.formatDouble(nwell_spacing.v) + ";");
pw.println("$nwell_spacing_rule = \"" + nwell_spacing.rule + "\";");
pw.println();
pw.println("###### METAL RULES #####");
pw.print("@metal_width = (");
for(int i=0; i<num_metal_layers; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(metal_width[i].v));
}
pw.println(");");
pw.print("@metal_width_rule = (");
for(int i=0; i<num_metal_layers; i++)
{
if (i > 0) pw.print(", ");
pw.print("\"" + metal_width[i].rule + "\"");
}
pw.println(");");
pw.print("@metal_spacing = (");
for(int i=0; i<num_metal_layers; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(metal_spacing[i].v));
}
pw.println(");");
pw.print("@metal_spacing_rule = (");
for(int i=0; i<num_metal_layers; i++)
{
if (i > 0) pw.print(", ");
pw.print("\"" + metal_spacing[i].rule + "\"");
}
pw.println(");");
pw.println();
pw.println("###### VIA RULES #####");
pw.print("@via_size = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(via_size[i].v));
}
pw.println(");");
pw.print("@via_size_rule = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print("\"" + via_size[i].rule + "\"");
}
pw.println(");");
pw.print("@via_spacing = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(via_inline_spacing[i].v));
}
pw.println(");");
pw.print("@via_spacing_rule = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print("\"" + via_inline_spacing[i].rule + "\"");
}
pw.println(");");
pw.println();
pw.println("## \"sep2d\" spacing, close proximity via array spacing");
pw.print("@via_array_spacing = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(via_array_spacing[i].v));
}
pw.println(");");
pw.print("@via_array_spacing_rule = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print("\"" + via_array_spacing[i].rule + "\"");
}
pw.println(");");
pw.print("@via_overhang_inline = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(via_overhang[i].v));
}
pw.println(");");
pw.print("@via_overhang_inline_rule = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print("\"" + via_overhang[i].rule + "\"");
}
pw.println(");");
pw.println();
pw.println("###### ANTENNA RULES #####");
pw.println("$poly_antenna_ratio = " + TextUtils.formatDouble(poly_antenna_ratio) + ";");
pw.print("@metal_antenna_ratio = (");
for(int i=0; i<num_metal_layers; i++)
{
if (i > 0) pw.print(", ");
pw.print(TextUtils.formatDouble(metal_antenna_ratio[i]));
}
pw.println(");");
pw.println();
pw.println("###### GDS-II LAYERS #####");
pw.println("$gds_diff_layer = " + gds_diff_layer + ";");
pw.println("$gds_poly_layer = " + gds_poly_layer + ";");
pw.println("$gds_nplus_layer = " + gds_nplus_layer + ";");
pw.println("$gds_pplus_layer = " + gds_pplus_layer + ";");
pw.println("$gds_nwell_layer = " + gds_nwell_layer + ";");
pw.println("$gds_contact_layer = " + gds_contact_layer + ";");
pw.print("@gds_metal_layer = (");
for(int i=0; i<num_metal_layers; i++)
{
if (i > 0) pw.print(", ");
pw.print(gds_metal_layer[i]);
}
pw.println(");");
pw.print("@gds_via_layer = (");
for(int i=0; i<num_metal_layers-1; i++)
{
if (i > 0) pw.print(", ");
pw.print(gds_via_layer[i]);
}
pw.println(");");
pw.println();
pw.println("## Device marking layer");
pw.println("$gds_marking_layer = " + gds_marking_layer + ";");
pw.println();
pw.println("# End of techfile");
}
/************************************** WRITE XML FILE **************************************/
void writeXML()
{
String errorMessage = errorInData();
if (errorMessage != null)
{
Job.getUserInterface().showErrorMessage("ERROR: " + errorMessage,
"Missing Technology Data");
return;
}
String suggestedName = getTechName() + ".xml";
String fileName = OpenFile.chooseOutputFile(FileType.XML, "Technology XML File", suggestedName); //"Technology.xml");
if (fileName == null) return;
try
{
dumpXMLFile(fileName);
} catch (IOException e)
{
System.out.println("Error writing XML file");
return;
}
}
/**
* Method to create the XML version of a PrimitiveNode representing a pin
* @return
*/
private Xml.PrimitiveNodeGroup makeXmlPrimitivePin(Xml.Technology t, String name, double size,
SizeOffset so, Xml.NodeLayer... list)
{
List<Xml.NodeLayer> nodesList = new ArrayList<Xml.NodeLayer>(list.length);
List<Xml.PrimitivePort> nodePorts = new ArrayList<Xml.PrimitivePort>();
List<String> portNames = new ArrayList<String>();
for (Xml.NodeLayer lb : list)
{
if (lb == null) continue; // in case the pwell layer off
nodesList.add(lb);
}
portNames.add(name);
nodePorts.add(makeXmlPrimitivePort(name.toLowerCase(), 0, 180, 0, null, 0, -1, 0, 1, 0, -1, 0, 1, portNames));
Xml.PrimitiveNodeGroup n = makeXmlPrimitive(t.nodeGroups, name + "-Pin", PrimitiveNode.Function.PIN, size, size, 0, 0,
so, nodesList, nodePorts, null, true);
return n;
}
/**
* Method to creat the XML version of a PrimitiveNode representing a contact
* @return
*/
private Xml.PrimitiveNodeGroup makeXmlPrimitiveCon(List<Xml.PrimitiveNodeGroup> nodeGroups, String name,
PrimitiveNode.Function function, double sizeX, double sizeY,
SizeOffset so, List<String> portNames, Xml.NodeLayer... list)
{
List<Xml.NodeLayer> nodesList = new ArrayList<Xml.NodeLayer>(list.length);
List<Xml.PrimitivePort> nodePorts = new ArrayList<Xml.PrimitivePort>();
for (Xml.NodeLayer lb : list)
{
if (lb == null) continue; // in case the pwell layer off
nodesList.add(lb);
}
nodePorts.add(makeXmlPrimitivePort(name.toLowerCase(), 0, 180, 0, null, 0, -1, 0, 1, 0, -1, 0, 1, portNames));
return makeXmlPrimitive(nodeGroups, name + "-Con", function, sizeX, sizeY, 0, 0,
so, nodesList, nodePorts, null, false);
}
/**
* Method to create the XML version of a PrimitiveNode
* @return
*/
private Xml.PrimitiveNodeGroup makeXmlPrimitive(List<Xml.PrimitiveNodeGroup> nodeGroups,
String name, PrimitiveNode.Function function,
double width, double height,
double ppLeft, double ppBottom,
SizeOffset so, List<Xml.NodeLayer> nodeLayers,
List<Xml.PrimitivePort> nodePorts,
PrimitiveNode.NodeSizeRule nodeSizeRule, boolean isArcsShrink)
{
Xml.PrimitiveNodeGroup ng = new Xml.PrimitiveNodeGroup();
ng.isSingleton = true;
Xml.PrimitiveNode n = new Xml.PrimitiveNode();
n.name = name;
n.function = function;
ng.nodes.add(n);
ng.shrinkArcs = isArcsShrink;
// n.square = isSquare();
// n.canBeZeroSize = isCanBeZeroSize();
// n.wipes = isWipeOn1or2();
// n.lockable = isLockedPrim();
// n.edgeSelect = isEdgeSelect();
// n.skipSizeInPalette = isSkipSizeInPalette();
// n.notUsed = isNotUsed();
// n.lowVt = isNodeBitOn(PrimitiveNode.LOWVTBIT);
// n.highVt = isNodeBitOn(PrimitiveNode.HIGHVTBIT);
// n.nativeBit = isNodeBitOn(PrimitiveNode.NATIVEBIT);
// n.od18 = isNodeBitOn(PrimitiveNode.OD18BIT);
// n.od25 = isNodeBitOn(PrimitiveNode.OD25BIT);
// n.od33 = isNodeBitOn(PrimitiveNode.OD33BIT);
// PrimitiveNode.NodeSizeRule nodeSizeRule = getMinSizeRule();
// EPoint minFullSize = nodeSizeRule != null ?
// EPoint.fromLambda(0.5*nodeSizeRule.getWidth(), 0.5*nodeSizeRule.getHeight()) :
// EPoint.fromLambda(0.5*getDefWidth(), 0.5*getDefHeight());
// EPoint minFullSize = EPoint.fromLambda(0.5*width, 0.5*height);
EPoint topLeft = EPoint.fromLambda(ppLeft, ppBottom + height);
EPoint size = EPoint.fromLambda(width, height);
double getDefWidth = width, getDefHeight = height;
if (function == PrimitiveNode.Function.PIN && isArcsShrink) {
// assert getNumPorts() == 1;
// assert nodeSizeRule == null;
// PrimitivePort pp = getPort(0);
// assert pp.getLeft().getMultiplier() == -0.5 && pp.getRight().getMultiplier() == 0.5 && pp.getBottom().getMultiplier() == -0.5 && pp.getTop().getMultiplier() == 0.5;
// assert pp.getLeft().getAdder() == -pp.getRight().getAdder() && pp.getBottom().getAdder() == -pp.getTop().getAdder();
// minFullSize = EPoint.fromLambda(ppLeft, ppBottom);
}
// DRCTemplate nodeSize = xmlRules.getRule(pnp.getPrimNodeIndexInTech(), DRCTemplate.DRCRuleType.NODSIZ);
// SizeOffset so = getProtoSizeOffset();
if (so != null &&
(so.getLowXOffset() == 0 && so.getHighXOffset() == 0 &&
so.getLowYOffset() == 0 && so.getHighYOffset() == 0))
so = null;
ERectangle base = calcBaseRectangle(so, nodeLayers, nodeSizeRule);
ng.baseLX.value = base.getLambdaMinX();
ng.baseHX.value = base.getLambdaMaxX();
ng.baseLY.value = base.getLambdaMinY();
ng.baseHY.value = base.getLambdaMaxY();
// n.sizeOffset = so;
// if (!minFullSize.equals(EPoint.ORIGIN))
// n.diskOffset = minFullSize;
// if (so != null) {
// EPoint p2 = EPoint.fromGrid(
// minFullSize.getGridX() - ((so.getLowXGridOffset() + so.getHighXGridOffset()) >> 1),
// minFullSize.getGridY() - ((so.getLowYGridOffset() + so.getHighYGridOffset()) >> 1));
// n.diskOffset.put(Integer.valueOf(1), minFullSize);
// n.diskOffset.put(Integer.valueOf(2), p2);
// n.diskOffset.put(Integer.valueOf(2), minFullSize);
// }
// n.defaultWidth.addLambda(DBMath.round(getDefWidth)); // - 2*minFullSize.getLambdaX());
// n.defaultHeight.addLambda(DBMath.round(getDefHeight)); // - 2*minFullSize.getLambdaY());
ERectangle baseRectangle = ERectangle.fromGrid(topLeft.getGridX(), topLeft.getGridY(),
size.getGridX(), size.getGridY());
/* n.nodeBase = baseRectangle;*/
// List<Technology.NodeLayer> nodeLayers = Arrays.asList(getLayers());
// List<Technology.NodeLayer> electricalNodeLayers = nodeLayers;
// if (getElectricalLayers() != null)
// electricalNodeLayers = Arrays.asList(getElectricalLayers());
boolean isSerp = false; //getSpecialType() == PrimitiveNode.SERPTRANS;
if (nodeLayers != null)
ng.nodeLayers.addAll(nodeLayers);
// int m = 0;
// for (Technology.NodeLayer nld: electricalNodeLayers) {
// int j = nodeLayers.indexOf(nld);
// if (j < 0) {
// n.nodeLayers.add(nld.makeXml(isSerp, minFullSize, false, true));
// continue;
// }
// while (m < j)
// n.nodeLayers.add(nodeLayers.get(m++).makeXml(isSerp, minFullSize, true, false));
// n.nodeLayers.add(nodeLayers.get(m++).makeXml(isSerp, minFullSize, true, true));
// }
// while (m < nodeLayers.size())
// n.nodeLayers.add(nodeLayers.get(m++).makeXml(isSerp, minFullSize, true, false));
// for (Iterator<PrimitivePort> pit = getPrimitivePorts(); pit.hasNext(); ) {
// PrimitivePort pp = pit.next();
// n.ports.add(pp.makeXml(minFullSize));
// }
ng.specialType = PrimitiveNode.NORMAL; // getSpecialType();
// if (getSpecialValues() != null)
// n.specialValues = getSpecialValues().clone();
if (nodeSizeRule != null) {
ng.nodeSizeRule = new Xml.NodeSizeRule();
ng.nodeSizeRule.width = nodeSizeRule.getWidth();
ng.nodeSizeRule.height = nodeSizeRule.getHeight();
ng.nodeSizeRule.rule = nodeSizeRule.getRuleName();
}
// n.spiceTemplate = "";//getSpiceTemplate();
// ports
ng.ports.addAll(nodePorts);
nodeGroups.add(ng);
return ng;
}
private ERectangle calcBaseRectangle(SizeOffset so, List<Xml.NodeLayer> nodeLayers, PrimitiveNode.NodeSizeRule nodeSizeRule) {
long lx, hx, ly, hy;
if (nodeSizeRule != null) {
hx = DBMath.lambdaToGrid(0.5*nodeSizeRule.getWidth());
lx = -hx;
hy = DBMath.lambdaToGrid(0.5*nodeSizeRule.getHeight());
ly = -hy;
} else {
lx = Long.MAX_VALUE;
hx = Long.MIN_VALUE;
ly = Long.MAX_VALUE;
hy = Long.MIN_VALUE;
for (int i = 0; i < nodeLayers.size(); i++) {
Xml.NodeLayer nl = nodeLayers.get(i);
long x, y;
if (nl.representation == Technology.NodeLayer.BOX || nl.representation == Technology.NodeLayer.MULTICUTBOX) {
x = DBMath.lambdaToGrid(nl.lx.value);
lx = Math.min(lx, x);
hx = Math.max(hx, x);
x = DBMath.lambdaToGrid(nl.hx.value);
lx = Math.min(lx, x);
hx = Math.max(hx, x);
y = DBMath.lambdaToGrid(nl.ly.value);
ly = Math.min(ly, y);
hy = Math.max(hy, y);
y = DBMath.lambdaToGrid(nl.hy.value);
ly = Math.min(ly, y);
hy = Math.max(hy, y);
} else {
for (Technology.TechPoint p: nl.techPoints) {
x = p.getX().getGridAdder();
lx = Math.min(lx, x);
hx = Math.max(hx, x);
y = p.getY().getGridAdder();
ly = Math.min(ly, y);
hy = Math.max(hy, y);
}
}
}
}
if (so != null) {
lx += so.getLowXGridOffset();
hx -= so.getHighXGridOffset();
ly += so.getLowYGridOffset();
hy -= so.getHighYGridOffset();
}
return ERectangle.fromGrid(lx, ly, hx - lx, hy - ly);
}
/**
* Method to create the XML version of a ArcProto
* @param name
* @param function
* @return
*/
private Xml.ArcProto makeXmlArc(Xml.Technology t, String name, com.sun.electric.technology.ArcProto.Function function,
double ant, Xml.ArcLayer ... arcLayers)
{
Xml.ArcProto a = new Xml.ArcProto();
a.name = name;
a.function = function;
a.wipable = true;
// a.curvable = false;
// a.special = false;
// a.notUsed = false;
// a.skipSizeInPalette = false;
// a.elibWidthOffset = getLambdaElibWidthOffset();
a.extended = true;
a.fixedAngle = true;
a.angleIncrement = 90;
a.antennaRatio = DBMath.round(ant);
for (Xml.ArcLayer al: arcLayers)
{
if (al == null) continue; // in case the pwell layer off
a.arcLayers.add(al);
}
t.arcs.add(a);
return a;
}
private Xml.Layer makeXmlLayer(List<Xml.Layer> layers, Map<Xml.Layer, WizardField> layer_width, String name,
Layer.Function function, int extraf, EGraphics graph,
WizardField width, boolean pureLayerNode, boolean pureLayerPortArc)
{
Xml.Layer l = makeXmlLayer(layers, name, function, extraf, graph, width.v, pureLayerNode, pureLayerPortArc);
layer_width.put(l, width);
return l;
}
/**
* Method to create the XML version of a Layer.
* @return
*/
private Xml.Layer makeXmlLayer(List<Xml.Layer> layers, String name,
Layer.Function function, int extraf, EGraphics graph,
double width, boolean pureLayerNode, boolean pureLayerPortArc)
{
Xml.Layer l = new Xml.Layer();
l.name = name;
l.function = function;
l.extraFunction = extraf;
graph = graph.withTransparencyMode(EGraphics.J3DTransparencyOption.NONE);
graph = graph.withTransparencyFactor(1);
l.desc = graph;
l.thick3D = 1;
l.height3D = 1;
l.cif = "Not set"; //"C" + cifLetter + cifLetter;
l.skill = name;
l.resistance = 1;
l.capacitance = 0;
l.edgeCapacitance = 0;
// if (layer.getPseudoLayer() != null)
// l.pseudoLayer = layer.getPseudoLayer().getName();
// if pureLayerNode is false, pureLayerPortArc must be false
assert(pureLayerNode || !pureLayerPortArc);
if (pureLayerNode) {
l.pureLayerNode = new Xml.PureLayerNode();
l.pureLayerNode.name = name + "-Node";
l.pureLayerNode.style = Poly.Type.FILLED;
l.pureLayerNode.size.addLambda(scaledValue(width));
l.pureLayerNode.port = "Port_" + name;
/* l.pureLayerNode.size.addRule(width.rule, 1);*/
if (pureLayerPortArc)
l.pureLayerNode.portArcs.add(name);
// for (ArcProto ap: pureLayerNode.getPort(0).getConnections()) {
// if (ap.getTechnology() != tech) continue;
// l.pureLayerNode.portArcs.add(ap.getName());
// }
}
layers.add(l);
return l;
}
/**
* Method to create the XML version of NodeLayer
*/
private Xml.NodeLayer makeXmlNodeLayer(double lx, double hx, double ly, double hy, Xml.Layer lb, Poly.Type style)
{
return makeXmlNodeLayerSpecial(lx, hx, ly, hy, lb, style, true, true, 0);
}
/**
* Method to create the XML version of NodeLayer either graphical or electrical.
* makeXmlNodeLayer is the default one where layer is available in both mode.
*/
private Xml.NodeLayer makeXmlNodeLayerSpecial(double lx, double hx, double ly, double hy, Xml.Layer lb, Poly.Type style,
boolean inLayers, boolean electricalLayers, int port)
{
Xml.NodeLayer nl = new Xml.NodeLayer();
nl.layer = lb.name;
nl.style = style;
nl.portNum = port;
nl.inLayers = inLayers;
nl.inElectricalLayers = electricalLayers;
nl.representation = Technology.NodeLayer.BOX;
nl.lx.k = -1; nl.hx.k = 1; nl.ly.k = -1; nl.hy.k = 1;
nl.lx.addLambda(-lx); nl.hx.addLambda(hx); nl.ly.addLambda(-ly); nl.hy.addLambda(hy);
return nl;
}
private Xml.NodeLayer makeXmlMulticut(Xml.Layer lb, double sizeRule, double sepRule, double sepRule2D) {
Xml.NodeLayer nl = new Xml.NodeLayer();
nl.layer = lb.name;
nl.style = Poly.Type.FILLED;
nl.inLayers = nl.inElectricalLayers = true;
nl.representation = Technology.NodeLayer.MULTICUTBOX;
nl.lx.k = -1; nl.hx.k = 1; nl.ly.k = -1; nl.hy.k = 1;
// nl.sizeRule = sizeRule;
nl.sizex = sizeRule;
nl.sizey = sizeRule;
nl.sep1d = sepRule;
nl.sep2d = sepRule2D;
return nl;
}
/**
* Method to create the XML versio nof PrimitivePort
* @return New Xml.PrimitivePort
*/
private Xml.PrimitivePort makeXmlPrimitivePort(String name, int portAngle, int portRange, int portTopology,
EPoint minFullSize,
double lx, int slx, double hx, int shx,
double ly, int sly, double hy, int shy, List<String> portArcs)
{
Xml.PrimitivePort ppd = new Xml.PrimitivePort();
double lambdaX = (minFullSize != null) ? minFullSize.getLambdaX() : 0;
double lambdaY = (minFullSize != null) ? minFullSize.getLambdaY() : 0;
ppd.name = name;
ppd.portAngle = portAngle;
ppd.portRange = portRange;
ppd.portTopology = portTopology;
ppd.lx.k = slx;//-1; //getLeft().getMultiplier()*2;
ppd.lx.addLambda(DBMath.round(lx + lambdaX*ppd.lx.k));
ppd.hx.k = shx;//1; //getRight().getMultiplier()*2;
ppd.hx.addLambda(DBMath.round(hx + lambdaX*ppd.hx.k));
ppd.ly.k = sly;//-1; // getBottom().getMultiplier()*2;
ppd.ly.addLambda(DBMath.round(ly + lambdaY*ppd.ly.k));
ppd.hy.k = shy;//1; // getTop().getMultiplier()*2;
ppd.hy.addLambda(DBMath.round(hy + lambdaY*ppd.hy.k));
if (portArcs != null) {
for (String s: portArcs)
{
ppd.portArcs.add(s);
}
}
return ppd;
}
/**
* To create zero, cross, aligned and squared contacts from the same set of rules
*/
private Xml.PrimitiveNodeGroup makeContactSeries(List<Xml.PrimitiveNodeGroup> nodeGroups, String composeName,
double contSize, Xml.Layer conLayer, double spacing, double arraySpacing,
double extLayer1, Xml.Layer layer1,
double extLayer2, Xml.Layer layer2)
{
List<String> portNames = new ArrayList<String>();
portNames.add(layer1.name);
portNames.add(layer2.name);
// align contact
double hlaLong1 = DBMath.round(contSize/2 + extLayer1);
double hlaLong2 = DBMath.round(contSize/2 + extLayer2);
double longD = DBMath.isGreaterThan(extLayer1, extLayer2) ? extLayer1 : extLayer2;
// long square contact. Standard ones
return (makeXmlPrimitiveCon(nodeGroups, composeName, PrimitiveNode.Function.CONTACT, -1, -1,
null, /*new SizeOffset(longD, longD, longD, longD),*/ portNames,
makeXmlNodeLayer(hlaLong1, hlaLong1, hlaLong1, hlaLong1, layer1, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(hlaLong2, hlaLong2, hlaLong2, hlaLong2, layer2, Poly.Type.FILLED), // layer2
makeXmlMulticut(conLayer, contSize, spacing, arraySpacing))); // contact
}
/**
* Leave as oublic for the regression.
* @param fileName
* @throws IOException
*/
public void dumpXMLFile(String fileName)
throws IOException
{
Xml.Technology t = new Xml.Technology();
t.techName = getTechName();
t.shortTechName = getTechName();
t.description = getTechDescription();
t.minNumMetals = t.maxNumMetals = t.defaultNumMetals = getNumMetalLayers();
t.scaleValue = getStepSize();
t.scaleRelevant = true;
// t.scaleRelevant = isScaleRelevant();
t.defaultFoundry = "NONE";
t.minResistance = 1.0;
t.minCapacitance = 0.1;
// menus
t.menuPalette = new Xml.MenuPalette();
t.menuPalette.numColumns = 3;
/** RULES **/
Xml.Foundry f = new Xml.Foundry();
f.name = Foundry.Type.NONE.getName();
t.foundries.add(f);
// LAYER COLOURS
Color [] metal_colour = new Color[]
{
new Color(0,150,255), // cyan/blue
new Color(148,0,211), // purple
new Color(255,215,0), // yellow
new Color(132,112,255), // mauve
new Color(255,160,122), // salmon
new Color(34,139,34), // dull green
new Color(178,34,34), // dull red
new Color(34,34,178), // dull blue
new Color(153,153,153), // light gray
new Color(102,102,102) // dark gray
};
Color poly_colour = new Color(255,155,192); // pink
Color diff_colour = new Color(107,226,96); // light green
Color via_colour = new Color(205,205,205); // lighter gray
Color contact_colour = new Color(100,100,100); // darker gray
Color nplus_colour = new Color(224,238,224);
Color pplus_colour = new Color(224,224,120);
Color nwell_colour = new Color(140,140,140);
// Five transparent colors: poly_colour, diff_colour, metal_colour[0->2]
Color[] colorMap = {poly_colour, diff_colour, metal_colour[0], metal_colour[1], metal_colour[2]};
for (int i = 0; i < colorMap.length; i++) {
Color transparentColor = colorMap[i];
t.transparentLayers.add(transparentColor);
}
// Layers
List<Xml.Layer> metalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> dummyMetalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> exclusionMetalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> viaLayers = new ArrayList<Xml.Layer>();
Map<Xml.Layer,WizardField> layer_width = new LinkedHashMap<Xml.Layer,WizardField>();
int[] nullPattern = new int[] {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000};
int[] dexclPattern = new int[] {
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808}; // X X
for (int i = 0; i < num_metal_layers; i++)
{
// Adding the metal
int metalNum = i + 1;
double opacity = (75 - metalNum * 5)/100.0;
int metLayHigh = i / 10;
int metLayDig = i % 10;
int r = metal_colour[metLayDig].getRed() * (10-metLayHigh) / 10;
int g = metal_colour[metLayDig].getGreen() * (10-metLayHigh) / 10;
int b = metal_colour[metLayDig].getBlue() * (10-metLayHigh) / 10;
int tcol = 0;
int[] pattern = null;
switch (metLayDig)
{
case 0: tcol = 3; break;
case 1: tcol = 4; break;
case 2: tcol = 5; break;
case 3: pattern = new int[] {0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000}; break;
case 4: pattern = new int[] { 0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444};
break;
case 5: pattern = new int[] { 0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555};
break;
case 6: pattern = new int[] { 0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111};
break;
case 7: pattern = new int[] { 0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000};
break;
case 8: pattern = new int[] {0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888}; // X X X X
break;
case 9: pattern = new int[] { 0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555};
break;
}
boolean onDisplay = true, onPrinter = true;
if (pattern == null)
{
pattern = nullPattern;
onDisplay = false; onPrinter = false;
}
EGraphics graph = new EGraphics(onDisplay, onPrinter, null, tcol, r, g, b, opacity, true, pattern);
Layer.Function fun = Layer.Function.getMetal(metalNum);
if (fun == null)
throw new IOException("invalid number of metals");
String metalName = "Metal-"+metalNum;
Xml.Layer layer = makeXmlLayer(t.layers, layer_width, metalName, fun, 0, graph,
metal_width[i], true, true);
metalLayers.add(layer);
if (getExtraInfoFlag())
{
// dummy layers
graph = new EGraphics(true, true, null, tcol, r, g, b, opacity, false, nullPattern);
layer = makeXmlLayer(t.layers, "DMY-"+metalName, Layer.Function.getDummyMetal(metalNum), 0, graph,
5*metal_width[i].v, true, false);
dummyMetalLayers.add(layer);
// exclusion layers for metals
graph = new EGraphics(true, true, null, tcol, r, g, b, opacity, true, dexclPattern);
layer = makeXmlLayer(t.layers, "DEXCL-"+metalName, Layer.Function.getDummyExclMetal(i), 0, graph,
2*metal_width[i].v, true, false);
exclusionMetalLayers.add(layer);
}
}
// Vias
for (int i = 0; i < num_metal_layers - 1; i++)
{
// Adding the metal
int metalNum = i + 1;
// adding the via
int r = via_colour.getRed();
int g = via_colour.getGreen();
int b = via_colour.getBlue();
double opacity = 0.7;
EGraphics graph = new EGraphics(false, false, null, 0, r, g, b, opacity, true, nullPattern);
Layer.Function fun = Layer.Function.getContact(metalNum+1); //via contact starts with CONTACT2
if (fun == null)
throw new IOException("invalid number of vias");
viaLayers.add(makeXmlLayer(t.layers, layer_width, "Via-"+metalNum, fun, Layer.Function.CONMETAL,
graph, via_size[i], true, false));
}
// Poly
String polyN = gds_poly_layer.name;
EGraphics graph = new EGraphics(false, false, null, 1, 0, 0, 0, 1, true, nullPattern);
Xml.Layer polyLayer = makeXmlLayer(t.layers, layer_width, polyN, Layer.Function.POLY1, 0, graph,
poly_width, true, true);
// PolyGate
Xml.Layer polyGateLayer = makeXmlLayer(t.layers, layer_width, polyN+"Gate", Layer.Function.GATE, 0, graph,
poly_width, true, false); // false for the port otherwise it won't find any type
if (getExtraInfoFlag())
{
// exclusion layer poly
graph = new EGraphics(true, true, null, 1, 0, 0, 0, 1, true, dexclPattern);
Xml.Layer exclusionPolyLayer = makeXmlLayer(t.layers, "DEXCL-"+polyN, Layer.Function.DEXCLPOLY1, 0, graph,
2*poly_width.v, true, false);
makeLayerGDS(t, exclusionPolyLayer, "150/21");
}
// PolyCon and DiffCon
graph = new EGraphics(false, false, null, 0, contact_colour.getRed(), contact_colour.getGreen(),
contact_colour.getBlue(), 0.5, true, nullPattern);
// PolyCon
Xml.Layer polyConLayer = makeXmlLayer(t.layers, layer_width, "Poly-Cut", Layer.Function.CONTACT1,
Layer.Function.CONPOLY, graph, contact_size, true, false);
// DiffCon
Xml.Layer diffConLayer = makeXmlLayer(t.layers, layer_width, gds_diff_layer.name+"-Cut", Layer.Function.CONTACT1,
Layer.Function.CONDIFF, graph, contact_size, true, false);
// P-Diff and N-Diff
graph = new EGraphics(false, false, null, 2, 0, 0, 0, 1, true, nullPattern);
// N-Diff
Xml.Layer diffNLayer = makeXmlLayer(t.layers, layer_width, "N-"+gds_diff_layer.name, Layer.Function.DIFFN, 0, graph,
diff_width, true, true);
// P-Diff
Xml.Layer diffPLayer = makeXmlLayer(t.layers, layer_width, "P-"+gds_diff_layer.name, Layer.Function.DIFFP, 0, graph,
diff_width, true, true);
if (getExtraInfoFlag())
{
// exclusion layer N/P diff
graph = new EGraphics(true, true, null, 2, 0, 0, 0, 1, true, dexclPattern);
Xml.Layer exclusionDiffPLayer = makeXmlLayer(t.layers, "DEXCL-P-"+gds_diff_layer.name, Layer.Function.DEXCLDIFF, 0, graph,
2*diff_width.v, true, false);
Xml.Layer exclusionDiffNLayer = makeXmlLayer(t.layers, "DEXCL-N-"+gds_diff_layer.name, Layer.Function.DEXCLDIFF, 0, graph,
2*diff_width.v, true, false);
makeLayerGDS(t, exclusionDiffPLayer, "150/20");
makeLayerGDS(t, exclusionDiffNLayer, "150/20");
}
// NPlus and PPlus
int [] patternSlash = new int[] { 0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x0101, // X X
0x0202, // X X
0x0404, // X X
0x0808, // X X
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x0101, // X X
0x0202, // X X
0x0404, // X X
0x0808};
int [] patternBackSlash = new int[] { 0x0202, // X X
0x0101, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x0404, // X X
0x0202, // X X
0x0101, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x0404};
int[] patternDots = new int[] {
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000}; //
int[] patternSparseDots = new int[] {
0x0200, // X
0x0000, //
0x0020, // X
0x0000, //
0x0002, // X
0x0000, //
0x2000, // X
0x0000, //
0x0200, // X
0x0000, //
0x0020, // X
0x0000, //
0x0002, // X
0x0000, //
0x2000, // X
0x0000}; //
// NPlus
graph = new EGraphics(true, true, null, 0, nplus_colour.getRed(), nplus_colour.getGreen(),
nplus_colour.getBlue(), 1, true, patternSlash);
Xml.Layer nplusLayer = makeXmlLayer(t.layers, layer_width, gds_nplus_layer.name, Layer.Function.IMPLANTN, 0, graph,
nplus_width, true, false);
// PPlus
graph = new EGraphics(true, true, null, 0, pplus_colour.getRed(), pplus_colour.getGreen(),
pplus_colour.getBlue(), 1, true, patternDots);
Xml.Layer pplusLayer = makeXmlLayer(t.layers, layer_width, gds_pplus_layer.name, Layer.Function.IMPLANTP, 0, graph,
pplus_width, true, false);
// N-Well
graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(),
nwell_colour.getBlue(), 1, true, patternDots);
Xml.Layer nwellLayer = makeXmlLayer(t.layers, layer_width, gds_nwell_layer.name, Layer.Function.WELLN, 0, graph,
nwell_width, true, false);
// P-Well
graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(),
nwell_colour.getBlue(), 1, true, patternBackSlash);
Xml.Layer pwellLayer = makeXmlLayer(t.layers, layer_width, "P-Well", Layer.Function.WELLP, 0, graph,
nwell_width, true, false);
// DeviceMark
graph = new EGraphics(false, false, null, 0, 255, 0, 0, 0.4, true, nullPattern);
Xml.Layer deviceMarkLayer = makeXmlLayer(t.layers, layer_width, "DeviceMark", Layer.Function.CONTROL, 0, graph,
nplus_width, true, false);
// Extra layers
if (getExtraInfoFlag())
{
for (LayerInfo info : extraLayers)
{
graph = null;
// either color or template
assert (info.graphicsTemplate == null || info.graphicsColor == null);
if (info.graphicsTemplate != null)
{
// look for layer name and get its EGraphics
for (Xml.Layer l : t.layers)
{
if (l.name.equals(info.graphicsTemplate))
{
graph = l.desc;
break;
}
}
if (graph == null)
System.out.println("No template layer " + info.graphicsTemplate + " found");
}
else if (info.graphicsColor != null)
{
graph = new EGraphics(true, true, info.graphicsOutline, 0,
info.graphicsColor.getRed(), info.graphicsColor.getGreen(), info.graphicsColor.getBlue(),
1, true, info.graphicsPattern);
}
if (graph == null)
graph = new EGraphics(false, false, null, 0, 255, 0, 0, 0.4, true, nullPattern);
Xml.Layer layer = makeXmlLayer(t.layers, layer_width, info.name, Layer.Function.ART, 0, graph,
nplus_width, true, false);
makeLayerGDS(t, layer, String.valueOf(info));
}
}
// Palette elements should be added at the end so they will appear in groups
PaletteGroup[] metalPalette = new PaletteGroup[num_metal_layers];
// write arcs
// metal arcs
for(int i=1; i<=num_metal_layers; i++)
{
double ant = (int)Math.round(metal_antenna_ratio[i-1]) | 200;
PaletteGroup group = new PaletteGroup();
metalPalette[i-1] = group;
group.addArc(makeXmlArc(t, "Metal-"+i, ArcProto.Function.getContact(i), ant,
makeXmlArcLayer(metalLayers.get(i-1), metal_width[i-1])));
}
List<String> portNames = new ArrayList<String>();
/**************************** POLY Nodes/Arcs ***********************************************/
// poly arc
double ant = (int)Math.round(poly_antenna_ratio) | 200;
PaletteGroup polyGroup = new PaletteGroup();
polyGroup.addArc(makeXmlArc(t, polyLayer.name, ArcProto.Function.getPoly(1), ant,
makeXmlArcLayer(polyLayer, poly_width)));
// poly pin
double hla = scaledValue(poly_width.v / 2);
polyGroup.addPin(makeXmlPrimitivePin(t, polyLayer.name, hla, null, // new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, polyLayer, Poly.Type.CROSSED)));
// poly contact
portNames.clear();
portNames.add(polyLayer.name);
portNames.add(metalLayers.get(0).name);
hla = scaledValue((contact_size.v/2 + contact_poly_overhang.v));
Xml.Layer m1Layer = metalLayers.get(0);
double contSize = scaledValue(contact_size.v);
double contSpacing = scaledValue(contact_spacing.v);
double contArraySpacing = scaledValue(contact_array_spacing.v);
double metal1Over = scaledValue(contact_size.v/2 + contact_metal_overhang_all_sides.v);
// only for standard cases when getProtectionPoly() is false
if (!getExtraInfoFlag())
{
polyGroup.addElement(makeContactSeries(t.nodeGroups, polyLayer.name, contSize, polyConLayer, contSpacing, contArraySpacing,
scaledValue(contact_poly_overhang.v), polyLayer,
scaledValue(via_overhang[0].v), m1Layer), null);
}
/**************************** N/P-Diff Nodes/Arcs/Group ***********************************************/
PaletteGroup[] diffPalette = new PaletteGroup[2];
diffPalette[0] = new PaletteGroup(); diffPalette[1] = new PaletteGroup();
// ndiff/pdiff pins
hla = scaledValue((contact_size.v/2 + diff_contact_overhang.v));
double nsel = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nplus_overhang_diff.v);
double psel = scaledValue(contact_size.v/2 + diff_contact_overhang.v + pplus_overhang_diff.v);
double nwell = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nwell_overhang_diff_p.v);
double nso = scaledValue(nwell_overhang_diff_p.v /*+ diff_contact_overhang.v*/); // valid for elements that have nwell layers
double pso = (!pWellFlag)?nso:scaledValue(nplus_overhang_diff.v/* + diff_contact_overhang.v*/);
// ndiff/pdiff contacts
String[] diffNames = {"P", "N"};
double[] sos = {nso, pso};
double[] sels = {psel, nsel};
Xml.Layer[] diffLayers = {diffPLayer, diffNLayer};
Xml.Layer[] plusLayers = {pplusLayer, nplusLayer};
// Active and poly contacts. They are defined first that the Full types
for (Map.Entry<String,List<Contact>> e : otherContacts.entrySet())
{
// generic contacts
String name = null;
for (Contact c : e.getValue())
{
Xml.Layer ly = null, lx = null;
Xml.Layer conLay = diffConLayer;
PaletteGroup g = null;
ContactNode metalLayer = c.layers.get(0);
ContactNode otherLayer = c.layers.get(1);
if (!TextUtils.isANumber(metalLayer.layer)) // horizontal must be!
{
assert (TextUtils.isANumber(otherLayer.layer));
metalLayer = c.layers.get(1);
otherLayer = c.layers.get(0);
}
int m1 = Integer.valueOf(metalLayer.layer);
ly = metalLayers.get(m1-1);
String layerName = otherLayer.layer;
if (layerName.equals(diffLayers[0].name))
{
lx = diffLayers[0];
g = diffPalette[0];
}
else if (layerName.equals(diffLayers[1].name))
{
lx = diffLayers[1];
g = diffPalette[1];
}
else if (layerName.equals(polyLayer.name))
{
lx = polyLayer;
conLay = polyConLayer;
g = polyGroup;
}
else
assert(false); // it should not happen
name = ly.name + "-" + lx.name;
double h1x = scaledValue(contact_size.v/2 + metalLayer.overX.v);
double h1y = scaledValue(contact_size.v/2 + metalLayer.overY.v);
double h2x = scaledValue(contact_size.v/2 + otherLayer.overX.v);
double h2y = scaledValue(contact_size.v/2 + otherLayer.overY.v);
double longX = (Math.abs(metalLayer.overX.v - otherLayer.overX.v));
double longY = (Math.abs(metalLayer.overY.v - otherLayer.overY.v));
portNames.clear();
portNames.add(lx.name);
portNames.add(ly.name);
Xml.NodeLayer extraN = null;
if (c.layers.size() == 3) // easy solution for now
{
ContactNode node = c.layers.get(2);
Xml.Layer lz = (diffLayers[0] == lx) ? plusLayers[0] : plusLayers[1];
double h3x = scaledValue(contact_size.v/2 + node.overX.v);
double h3y = scaledValue(contact_size.v/2 + node.overY.v);
extraN = makeXmlNodeLayer(h3x, h3x, h3y, h3y, lz, Poly.Type.FILLED);
// This assumes no well is defined
longX = (Math.abs(node.overX.v - otherLayer.overX.v));
longY = (Math.abs(node.overY.v - otherLayer.overY.v));
}
longX = scaledValue(longX);
longY = scaledValue(longY);
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String p = (c.prefix == null || c.prefix.equals("")) ? "" : c.prefix + "-";
g.addElement(makeXmlPrimitiveCon(t.nodeGroups, p + name, PrimitiveNode.Function.CONTACT, -1, -1,
new SizeOffset(longX, longX, longY, longY), portNames,
makeXmlNodeLayer(h1x, h1x, h1y, h1y, ly, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(h2x, h2x, h2y, h2y, lx, Poly.Type.FILLED), // layer2
extraN,
makeXmlMulticut(conLay, contSize, contSpacing, contArraySpacing)), c.prefix); // contact
}
}
// ndiff/pdiff contact
for (int i = 0; i < 2; i++)
{
portNames.clear();
portNames.add(diffLayers[i].name);
portNames.add(m1Layer.name);
String composeName = diffNames[i] + "-" + gds_diff_layer.name; //Diff";
Xml.NodeLayer wellNode, wellNodePin;
ArcProto.Function arcF;
Xml.ArcLayer arcL;
WizardField arcVal;
if (i == Technology.P_TYPE)
{
wellNodePin = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.CROSSED);
wellNode = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.FILLED);
arcF = ArcProto.Function.DIFFP;
arcL = makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff_p);
arcVal = pplus_overhang_diff;
}
else
{
wellNodePin = (!pWellFlag)?makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.CROSSED):null;
wellNode = (!pWellFlag)?makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.FILLED):null;
arcF = ArcProto.Function.DIFFN;
arcL = (!pWellFlag)?makeXmlArcLayer(pwellLayer, diff_width, nwell_overhang_diff_p):null;
arcVal = nplus_overhang_diff;
}
PaletteGroup diffG = diffPalette[i];
// active arc
diffG.addArc(makeXmlArc(t, composeName, arcF, 0,
makeXmlArcLayer(diffLayers[i], diff_width),
makeXmlArcLayer(plusLayers[i], diff_width, arcVal),
arcL));
// active pin
diffG.addPin(makeXmlPrimitivePin(t, composeName, hla,
new SizeOffset(sos[i], sos[i], sos[i], sos[i]),
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.CROSSED),
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.CROSSED),
wellNodePin));
// F stands for full (all layers)
diffG.addElement(makeXmlPrimitiveCon(t.nodeGroups, "F-"+composeName, PrimitiveNode.Function.CONTACT,
hla, hla, new SizeOffset(sos[i], sos[i], sos[i], sos[i]), portNames,
makeXmlNodeLayer(metal1Over, metal1Over, metal1Over, metal1Over, m1Layer, Poly.Type.FILLED), // meta1 layer
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.FILLED), // active layer
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.FILLED), // select layer
wellNode, // well layer
makeXmlMulticut(diffConLayer, contSize, contSpacing, contArraySpacing)), "Full-" + diffNames[i]); // contact
}
/**************************** N/P-Well Contacts ***********************************************/
nwell = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nwell_overhang_diff_n.v);
nso = scaledValue(/*diff_contact_overhang.v +*/ nwell_overhang_diff_n.v); // valid for elements that have nwell layers
pso = (!pWellFlag)?nso:scaledValue(/*diff_contact_overhang.v +*/ nplus_overhang_diff.v);
double[] wellSos = {pso, nso};
PaletteGroup[] wellPalette = new PaletteGroup[2];
Xml.Layer[] wellLayers = {pwellLayer, nwellLayer};
// nwell/pwell contact
for (int i = 0; i < 2; i++)
{
String composeName = diffNames[i] + "-Well";
Xml.NodeLayer wellNodeLayer = null, wellNodePinLayer = null;
PaletteGroup g = new PaletteGroup();
PrimitiveNode.Function func = null;
Xml.ArcLayer arcL;
WizardField arcVal;
wellPalette[i] = g;
portNames.clear();
if (i == Technology.P_TYPE)
{
if (!pWellFlag)
{
portNames.add(pwellLayer.name);
wellNodePinLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.CROSSED);
wellNodeLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.FILLED);
}
func = PrimitiveNode.Function.WELL;
arcL = (!pWellFlag)?makeXmlArcLayer(pwellLayer, diff_width, nwell_overhang_diff_p):null;
arcVal = pplus_overhang_diff;
}
else
{
portNames.add(nwellLayer.name);
wellNodePinLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.CROSSED);
wellNodeLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.FILLED);
func = PrimitiveNode.Function.SUBSTRATE;
arcL = makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff_p);
arcVal = nplus_overhang_diff;
}
portNames.add(m1Layer.name);
// simple arc. S for simple
g.addArc(makeXmlArc(t, "S-"+composeName, ArcProto.Function.WELL, 0,
makeXmlArcLayer(wellLayers[i], diff_width, nwell_overhang_diff_p)));
// three layers arcs
g.addArc(makeXmlArc(t, composeName, ArcProto.Function.WELL, 0,
makeXmlArcLayer(diffLayers[i], diff_width),
makeXmlArcLayer(plusLayers[i], diff_width, arcVal),
arcL));
// well pin
g.addPin(makeXmlPrimitivePin(t, composeName, hla,
new SizeOffset(wellSos[i], wellSos[i], wellSos[i], wellSos[i]),
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.CROSSED),
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.CROSSED),
wellNodePinLayer));
// well contact
// F stands for full
g.addElement(makeXmlPrimitiveCon(t.nodeGroups, "F-"+composeName, func,
hla, hla, new SizeOffset(wellSos[i], wellSos[i], wellSos[i], wellSos[i]), portNames,
makeXmlNodeLayer(metal1Over, metal1Over, metal1Over, metal1Over, m1Layer, Poly.Type.FILLED), // meta1 layer
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.FILLED), // active layer
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.FILLED), // select layer
wellNodeLayer, // well layer
makeXmlMulticut(diffConLayer, contSize, contSpacing, contArraySpacing)), "Full-"+diffNames[i] + "W"); // contact
}
/**************************** Metals Nodes/Arcs ***********************************************/
// Pins and contacts
for(int i=1; i<num_metal_layers; i++)
{
hla = scaledValue(metal_width[i-1].v / 2);
Xml.Layer lb = metalLayers.get(i-1);
Xml.Layer lt = metalLayers.get(i);
PaletteGroup group = metalPalette[i-1]; // structure created by the arc definition
// Pin bottom metal
group.addPin(makeXmlPrimitivePin(t, lb.name, hla, null, //new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, lb, Poly.Type.CROSSED)));
if (i == num_metal_layers - 1) // last pin!
{
metalPalette[i].addPin(makeXmlPrimitivePin(t, lt.name, hla, null, //new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, lt, Poly.Type.CROSSED)));
}
if (!getExtraInfoFlag())
{
// original contact Square
// via
Xml.Layer via = viaLayers.get(i-1);
double viaSize = scaledValue(via_size[i-1].v);
double viaSpacing = scaledValue(via_inline_spacing[i-1].v);
double viaArraySpacing = scaledValue(via_array_spacing[i-1].v);
String name = lb.name + "-" + lt.name;
double longDist = scaledValue(via_overhang[i-1].v);
group.addElement(makeContactSeries(t.nodeGroups, name, viaSize, via, viaSpacing, viaArraySpacing,
longDist, lt, longDist, lb), null);
}
}
// metal contacts
for (Map.Entry<String,List<Contact>> e : metalContacts.entrySet())
{
// generic contacts
for (Contact c : e.getValue())
{
// We know those layer names are numbers!
assert(c.layers.size() == 2);
ContactNode verticalLayer = c.layers.get(0);
ContactNode horizontalLayer = c.layers.get(1);
int i = Integer.valueOf(verticalLayer.layer);
int j = Integer.valueOf(horizontalLayer.layer);
Xml.Layer ly = metalLayers.get(i-1);
Xml.Layer lx = metalLayers.get(j-1);
String name = (j>i)?ly.name + "-" + lx.name:lx.name + "-" + ly.name;
int via = (j>i)?i:j;
double metalContSize = scaledValue(via_size[via-1].v);
double spacing = scaledValue(via_inline_spacing[via-1].v);
double arraySpacing = scaledValue(via_array_spacing[via-1].v);
Xml.Layer metalConLayer = viaLayers.get(via-1);
double h1x = scaledValue(via_size[via-1].v/2 + verticalLayer.overX.v);
double h1y = scaledValue(via_size[via-1].v/2 + verticalLayer.overY.v);
double h2x = scaledValue(via_size[via-1].v/2 + horizontalLayer.overX.v);
double h2y = scaledValue(via_size[via-1].v/2 + horizontalLayer.overY.v);
// double longX = scaledValue(DBMath.isGreaterThan(verticalLayer.overX.v, horizontalLayer.overX.v) ? verticalLayer.overX.v : horizontalLayer.overX.v);
// double longY = scaledValue(DBMath.isGreaterThan(verticalLayer.overY.v, horizontalLayer.overY.v) ? verticalLayer.overY.v : horizontalLayer.overY.v);
double longX = scaledValue(Math.abs(verticalLayer.overX.v - horizontalLayer.overX.v));
double longY = scaledValue(Math.abs(verticalLayer.overY.v - horizontalLayer.overY.v));
portNames.clear();
portNames.add(lx.name);
portNames.add(ly.name);
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String p = (c.prefix == null || c.prefix.equals("")) ? "" : c.prefix + "-";
metalPalette[via-1].addElement(makeXmlPrimitiveCon(t.nodeGroups, p + name, PrimitiveNode.Function.CONTACT, -1, -1,
new SizeOffset(longX, longX, longY, longY),
portNames,
makeXmlNodeLayer(h1x, h1x, h1y, h1y, ly, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(h2x, h2x, h2y, h2y, lx, Poly.Type.FILLED), // layer2
makeXmlMulticut(metalConLayer, metalContSize, spacing, arraySpacing)), c.prefix); // contact
}
}
/**************************** Transistors ***********************************************/
/** Transistors **/
// write the transistors
List<Xml.NodeLayer> nodesList = new ArrayList<Xml.NodeLayer>();
List<Xml.PrimitivePort> nodePorts = new ArrayList<Xml.PrimitivePort>();
EPoint minFullSize = null; //EPoint.fromLambda(0, 0); // default zero horizontalFlag
PaletteGroup[] transPalette = new PaletteGroup[2];
for(int i = 0; i < 2; i++)
{
String name;
double selecty = 0, selectx = 0;
Xml.Layer wellLayer = null, activeLayer, selectLayer;
double sox = 0, soy = 0;
double impx = scaledValue((gate_width.v)/2);
double impy = scaledValue((gate_length.v+diff_poly_overhang.v*2)/2);
double nwell_overhangX = 0, nwell_overhangY = 0;
PaletteGroup g = new PaletteGroup();
transPalette[i] = g;
double protectDist = scaledValue(poly_protection_spacing.v);
double extraSelX = 0, extraSelY = 0;
PrimitiveNode.Function func = null;
if (i==Technology.P_TYPE)
{
name = "P";
nwell_overhangY = nwell_overhangX = nwell_overhang_diff_n.v;
wellLayer = nwellLayer;
activeLayer = diffPLayer;
selectLayer = pplusLayer;
extraSelX = pplus_overhang_poly.v;
extraSelY = pplus_overhang_diff.v;
func = PrimitiveNode.Function.TRAPMOS;
}
else
{
name = "N";
activeLayer = diffNLayer;
selectLayer = nplusLayer;
extraSelX = nplus_overhang_poly.v;
extraSelY = nplus_overhang_diff.v;
func = PrimitiveNode.Function.TRANMOS;
if (!pWellFlag)
{
nwell_overhangY = nwell_overhangX = nwell_overhang_diff_p.v;
wellLayer = pwellLayer;
}
else
{
nwell_overhangX = poly_endcap.v+extraSelX;
nwell_overhangY = extraSelY;
}
}
selectx = scaledValue(gate_width.v/2+poly_endcap.v+extraSelX);
selecty = scaledValue(gate_length.v/2+diff_poly_overhang.v+extraSelY);
// Using P values in transistors
double wellx = scaledValue((gate_width.v/2+nwell_overhangX));
double welly = scaledValue((gate_length.v/2+diff_poly_overhang.v+nwell_overhangY));
sox = scaledValue(nwell_overhangX);
soy = scaledValue(diff_poly_overhang.v+nwell_overhangY);
if (DBMath.isLessThan(wellx, selectx))
{
sox = scaledValue(poly_endcap.v+extraSelX);
wellx = selectx;
}
if (DBMath.isLessThan(welly, selecty))
{
soy = scaledValue(diff_poly_overhang.v+extraSelY);
welly = selecty;
}
nodesList.clear();
nodePorts.clear();
portNames.clear();
// Gate layer Electrical
double gatey = scaledValue(gate_length.v/2);
double gatex = impx;
// Poly layers
// left electrical
double endPolyx = scaledValue((gate_width.v+poly_endcap.v*2)/2);
double endPolyy = gatey;
double endLeftOrRight = -impx; // for horizontal transistors. Default
double endTopOrBotton = endPolyy; // for horizontal transistors. Default
double diffX = 0, diffY = scaledValue(gate_length.v/2+gate_contact_spacing.v+contact_size.v/2); // impy
double xSign = 1, ySign = -1;
double polyX = endPolyx, polyY = 0;
if (!horizontalFlag) // swap the numbers to get vertical transistors
{
double tmp;
tmp = impx; impx = impy; impy = tmp;
tmp = wellx; wellx = welly; welly = tmp;
tmp = sox; sox = soy; soy = tmp;
tmp = selectx; selectx = selecty; selecty = tmp;
tmp = gatex; gatex = gatey; gatey = tmp;
tmp = endPolyx; endPolyx = endPolyy; endPolyy = tmp;
tmp = diffX; diffX = diffY; diffY = tmp;
tmp = polyX; polyX = polyY; polyY = tmp;
tmp = xSign; xSign = ySign; ySign = tmp;
endLeftOrRight = endPolyx;
endTopOrBotton = -impx;
}
// Well layer
Xml.NodeLayer xTranWellLayer = null;
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(wellx, wellx, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
// Active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, impy, activeLayer, Poly.Type.FILLED, true, false, -1));
// electrical active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, 0, activeLayer, Poly.Type.FILLED, false, true, 3)); // bottom
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, 0, impy, activeLayer, Poly.Type.FILLED, false, true, 1)); // top
// Diff port
portNames.clear();
portNames.add(activeLayer.name);
Xml.PrimitivePort diffTopPort = makeXmlPrimitivePort("diff-top", 90, 90, 1, minFullSize,
diffX, -1, diffX, 1, diffY, 1, diffY, 1, portNames);
// bottom port
Xml.PrimitivePort diffBottomPort = makeXmlPrimitivePort("diff-bottom", 270, 90, 2, minFullSize,
xSign*diffX, -1, xSign*diffX, 1, ySign*diffY, -1, ySign*diffY, -1, portNames);
// Electric layers
// Gate layer Electrical
nodesList.add(makeXmlNodeLayerSpecial(gatex, gatex, gatey, gatey, polyGateLayer, Poly.Type.FILLED, false, true, -1));
// Poly layers
// left electrical
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endLeftOrRight, endPolyy, endTopOrBotton, polyLayer,
Poly.Type.FILLED, false, true, 0));
// right electrical
nodesList.add(makeXmlNodeLayerSpecial(endLeftOrRight, endPolyx, endTopOrBotton, endPolyy, polyLayer,
Poly.Type.FILLED, false, true, 2));
// non-electrical poly (just one poly layer)
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endPolyx, endPolyy, endPolyy, polyLayer, Poly.Type.FILLED, true, false, -1));
// Poly port
portNames.clear();
portNames.add(polyLayer.name);
Xml.PrimitivePort polyLeftPort = makeXmlPrimitivePort("poly-left", 180, 90, 0, minFullSize,
ySign*polyX, -1, ySign*polyX,
-1, xSign*polyY, -1, xSign*polyY, 1, portNames);
// right port
Xml.PrimitivePort polyRightPort = makeXmlPrimitivePort("poly-right", 0, 180, 0, minFullSize,
polyX, 1, polyX, 1, polyY, -1, polyY, 1, portNames);
// Select layer
Xml.NodeLayer xTranSelLayer = (makeXmlNodeLayer(selectx, selectx, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
//One (undocumented) requirement of transistors is that the ports must appear in the
//order: Poly-left, Diff-top, Poly-right, Diff-bottom. This requirement is
//because of the methods Technology.getTransistorGatePort(),
//Technology.getTransistorAltGatePort(), Technology.getTransistorSourcePort(),
//and Technology.getTransistorDrainPort().
// diff-top = 1, diff-bottom = 2, polys=0
// ports in the correct order: Poly-left, Diff-top, Poly-right, Diff-bottom
nodePorts.add(polyLeftPort);
nodePorts.add(diffTopPort);
nodePorts.add(polyRightPort);
nodePorts.add(diffBottomPort);
// Standard Transistor
Xml.PrimitiveNodeGroup n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
// Extra transistors which don't have select nor well
// Extra protection poly. No ports are necessary.
if (getExtraInfoFlag())
{
// removing well and select for simplicity
// nodesList.remove(xTranSelLayer);
// nodesList.remove(xTranWellLayer);
// // new sox and soy
// sox = scaledValue(poly_endcap.v);
// soy = scaledValue(diff_poly_overhang.v);
// n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-S", PrimitiveNode.Function.TRANMOS, 0, 0, 0, 0,
// new SizeOffset(sox, sox, soy, soy), nodesListW, nodePorts, null, false);
// g.addElement(n);
/*************************************/
// Short transistors
// Adding extra transistors whose select and well are aligned with poly along the X axis
nodesList.remove(xTranSelLayer);
double shortSelectX = scaledValue(gate_width.v/2+poly_endcap.v);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
double shortSox = sox;
shortSox = scaledValue(poly_endcap.v);
if (wellLayer != null)
{
nodesList.remove(xTranWellLayer);
xTranWellLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-S", func, 0, 0, 0, 0,
new SizeOffset(shortSox, shortSox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-S");
/*************************************/
// Transistors with extra polys
// different select for those with extra protection layers
nodesList.remove(xTranSelLayer);
double endOfProtectionY = gate_length.v + poly_protection_spacing.v;
double selectExtraY = scaledValue(gate_length.v/2 + endOfProtectionY + extraSelX); // actually is extraSelX because of the poly distance!
xTranSelLayer = (makeXmlNodeLayer(selectx, selectx, selectExtraY, selectExtraY, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// not sure which condition to apply. It doesn't apply nwell_overhang_diff due to the extra poly
if (DBMath.isLessThan(welly, selectExtraY))
{
welly = selectExtraY;
soy = scaledValue(endOfProtectionY + extraSelX);
}
if (wellLayer != null)
{
nodesList.remove(xTranWellLayer);
xTranWellLayer = (makeXmlNodeLayer(wellx, wellx, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
if (!horizontalFlag)
{
System.out.println("Not working with !horizontal");
assert(false);
}
portNames.clear();
portNames.add(polyLayer.name);
// bottom or left
Xml.NodeLayer bOrL = (makeXmlNodeLayerSpecial(gatex, gatex,
DBMath.round((protectDist + 3*endPolyy)),
-DBMath.round(endPolyy + protectDist),
polyLayer, Poly.Type.FILLED, true, false, -1/*3*/)); // port 3 for left/bottom extra poly lb=left bottom
// Adding left
nodesList.add(bOrL);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-B", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-B");
// top or right
Xml.NodeLayer tOrR = (makeXmlNodeLayerSpecial(gatex, gatex,
-DBMath.round(endPolyy + protectDist),
DBMath.round((protectDist + 3*endPolyy)),
polyLayer, Poly.Type.FILLED, true, false, -1/*4*/)); // port 4 for right/top extra poly rt=right top
// Adding both
nodesList.add(tOrR);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-TB", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-TB");
// Adding right
nodesList.remove(bOrL);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-T", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name +"-T");
/*************************************/
// Short transistors woth OD18
double od18x = scaledValue(gate_od18_width.v/2+od18_diff_overhang[0].v);
double od18y = scaledValue(gate_od18_length.v/2+diff_poly_overhang.v+od18_diff_overhang[1].v);
nodePorts.clear();
nodesList.clear();
prepareTransistor(gate_od18_width.v, gate_od18_length.v, poly_endcap.v, diff_poly_overhang.v,
gate_contact_spacing.v, contact_size.v, activeLayer, polyLayer, polyGateLayer, nodesList, nodePorts);
// OD18
Xml.Layer od18Layer = t.findLayer("OD_18");
nodesList.add(makeXmlNodeLayer(od18x, od18x, od18y, od18y, od18Layer, Poly.Type.FILLED));
// adding short select
shortSelectX = scaledValue(gate_od18_width.v/2+poly_endcap.v);
selecty = scaledValue(gate_od18_length.v/2+diff_poly_overhang.v+extraSelY);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// adding well
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(od18x, od18x, od18y, od18y, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
sox = scaledValue(od18_diff_overhang[0].v);
soy = scaledValue(diff_poly_overhang.v+od18_diff_overhang[1].v);
n = makeXmlPrimitive(t.nodeGroups, "OD18-" + name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
/*************************************/
// Short transistors with native
if (i==Technology.N_TYPE)
{
double ntx = scaledValue(gate_nt_width.v/2+nt_diff_overhang.v);
double nty = scaledValue(gate_nt_length.v/2+diff_poly_overhang.v+nt_diff_overhang.v);
nodePorts.clear();
nodesList.clear();
prepareTransistor(gate_nt_width.v, gate_nt_length.v, poly_nt_endcap.v, diff_poly_overhang.v,
gate_contact_spacing.v, contact_size.v, activeLayer, polyLayer, polyGateLayer, nodesList, nodePorts);
// NT-N
Xml.Layer ntLayer = t.findLayer("NT-N");
nodesList.add(makeXmlNodeLayer(ntx, ntx, nty, nty, ntLayer, Poly.Type.FILLED));
// adding short select
shortSelectX = scaledValue(gate_nt_width.v/2+poly_nt_endcap.v);
selecty = scaledValue(gate_nt_length.v/2+diff_poly_overhang.v+extraSelY);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// adding well
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(ntx, ntx, nty, nty, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
- sox = scaledValue(diff_poly_overhang.v);
+ sox = scaledValue(poly_nt_endcap.v);
soy = scaledValue(diff_poly_overhang.v+nt_diff_overhang.v);
n = makeXmlPrimitive(t.nodeGroups, "NT-" + name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
}
}
}
// Aggregating all palette groups into one
List<PaletteGroup> allGroups = new ArrayList<PaletteGroup>();
allGroups.add(transPalette[0]); allGroups.add(transPalette[1]);
allGroups.add(diffPalette[0]); allGroups.add(diffPalette[1]);
allGroups.add(wellPalette[0]); allGroups.add(wellPalette[1]);
allGroups.add(polyGroup);
for (PaletteGroup g : metalPalette)
allGroups.add(g);
// Adding elements in palette
for (PaletteGroup o : allGroups)
{
t.menuPalette.menuBoxes.add(o.arcs); // arcs
t.menuPalette.menuBoxes.add(o.pins); // pins
t.menuPalette.menuBoxes.add(o.elements); // contacts
}
// Writting GDS values
makeLayerGDS(t, diffPLayer, String.valueOf(gds_diff_layer));
makeLayerGDS(t, diffNLayer, String.valueOf(gds_diff_layer));
makeLayerGDS(t, pplusLayer, String.valueOf(gds_pplus_layer));
makeLayerGDS(t, nplusLayer, String.valueOf(gds_nplus_layer));
makeLayerGDS(t, nwellLayer, String.valueOf(gds_nwell_layer));
makeLayerGDS(t, deviceMarkLayer, String.valueOf(gds_marking_layer));
makeLayerGDS(t, polyConLayer, String.valueOf(gds_contact_layer));
makeLayerGDS(t, diffConLayer, String.valueOf(gds_contact_layer));
makeLayerGDS(t, polyLayer, String.valueOf(gds_poly_layer));
makeLayerGDS(t, polyGateLayer, String.valueOf(gds_poly_layer));
for (int i = 0; i < num_metal_layers; i++) {
Xml.Layer met = metalLayers.get(i);
makeLayerGDS(t, met, String.valueOf(gds_metal_layer[i]));
if (getExtraInfoFlag())
{
// Type is always 1
makeLayerGDS(t, dummyMetalLayers.get(i), gds_metal_layer[i].value + "/1");
// exclusion always takes 150
makeLayerGDS(t, exclusionMetalLayers.get(i), "150/" + (i + 1));
}
if (i > num_metal_layers - 2) continue;
Xml.Layer via = viaLayers.get(i);
makeLayerGDS(t, via, String.valueOf(gds_via_layer[i]));
}
// Writting Layer Rules
for (Xml.Layer l : diffLayers)
{
makeLayerRuleMinWid(t, l, diff_width);
makeLayersRule(t, l, DRCTemplate.DRCRuleType.SPACING, diff_spacing);
}
WizardField[] plus_diff = {pplus_overhang_diff, nplus_overhang_diff};
WizardField[] plus_width = {pplus_width, nplus_width};
WizardField[] plus_spacing = {pplus_spacing, nplus_spacing};
for (int i = 0; i < plusLayers.length; i++)
{
makeLayerRuleMinWid(t, plusLayers[i], plus_width[i]);
makeLayersRuleSurround(t, plusLayers[i], diffLayers[i], plus_diff[i]);
makeLayersRule(t, plusLayers[i], DRCTemplate.DRCRuleType.SPACING, plus_spacing[i]);
}
Xml.Layer[] wells = {pwellLayer, nwellLayer};
for (Xml.Layer w : wells)
{
makeLayerRuleMinWid(t, w, nwell_width);
makeLayersRuleSurround(t, w, diffPLayer, nwell_overhang_diff_p);
makeLayersRuleSurround(t, w, diffNLayer, nwell_overhang_diff_n);
makeLayersRule(t, w, DRCTemplate.DRCRuleType.SPACING, nwell_spacing);
}
Xml.Layer[] polys = {polyLayer, polyGateLayer};
for (Xml.Layer w : polys)
{
makeLayerRuleMinWid(t, w, poly_width);
makeLayersRule(t, w, DRCTemplate.DRCRuleType.SPACING, poly_spacing);
}
for (int i = 0; i < num_metal_layers; i++) {
Xml.Layer met = metalLayers.get(i);
makeLayerRuleMinWid(t, met, metal_width[i]);
if (i >= num_metal_layers - 1) continue;
Xml.Layer via = viaLayers.get(i);
makeLayerRuleMinWid(t, via, via_size[i]);
makeLayersRule(t, via, DRCTemplate.DRCRuleType.CONSPA, via_inline_spacing[i]);
makeLayersRule(t, via, DRCTemplate.DRCRuleType.UCONSPA2D, via_array_spacing[i]);
}
// Finish menu with Pure, Misc and Cell
List<Object> l = new ArrayList<Object>();
l.add(new String("Pure"));
t.menuPalette.menuBoxes.add(l);
l = new ArrayList<Object>();
l.add(new String("Misc."));
t.menuPalette.menuBoxes.add(l);
l = new ArrayList<Object>();
l.add(new String("Cell"));
t.menuPalette.menuBoxes.add(l);
// write finally the file
boolean includeDateAndVersion = User.isIncludeDateAndVersionInOutput();
String copyrightMessage = IOTool.isUseCopyrightMessage() ? IOTool.getCopyrightMessage() : null;
t.writeXml(fileName, includeDateAndVersion, copyrightMessage);
}
private void prepareTransistor(double gateWidth, double gateLength, double polyEndcap, double diffPolyOverhang,
double gateContactSpacing, double contactSize,
Xml.Layer activeLayer, Xml.Layer polyLayer, Xml.Layer polyGateLayer,
List<Xml.NodeLayer> nodesList, List<Xml.PrimitivePort> nodePorts)
{
double impx = scaledValue((gateWidth)/2);
double impy = scaledValue((gateLength+diffPolyOverhang*2)/2);
double diffY = scaledValue(gateLength/2+gateContactSpacing+contactSize/2); // impy
double diffX = 0;
double xSign = 1, ySign = -1;
// Active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, impy, activeLayer, Poly.Type.FILLED, true, false, -1));
// electrical active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, 0, activeLayer, Poly.Type.FILLED, false, true, 3)); // bottom
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, 0, impy, activeLayer, Poly.Type.FILLED, false, true, 1)); // top
// Diff port
List<String> portNames = new ArrayList<String>();
portNames.add(activeLayer.name);
// top port
Xml.PrimitivePort diffTopPort = makeXmlPrimitivePort("diff-top", 90, 90, 1, null,
diffX, -1, diffX, 1, diffY, 1, diffY, 1, portNames);
// bottom port
Xml.PrimitivePort diffBottomPort = makeXmlPrimitivePort("diff-bottom", 270, 90, 2, null,
xSign*diffX, -1, xSign*diffX, 1, ySign*diffY, -1, ySign*diffY, -1, portNames);
// Electric layers
// Gate layer Electrical
double gatey = scaledValue(gateLength/2);
double gatex = impx;
double endPolyx = scaledValue((gateWidth+polyEndcap*2)/2);
double endPolyy = gatey;
double endLeftOrRight = -impx;
double endTopOrBotton = endPolyy;
double polyX = endPolyx;
double polyY = 0;
nodesList.add(makeXmlNodeLayerSpecial(gatex, gatex, gatey, gatey, polyGateLayer, Poly.Type.FILLED, false, true, -1));
// Poly layers
// left electrical
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endLeftOrRight, endPolyy, endTopOrBotton, polyLayer,
Poly.Type.FILLED, false, true, 0));
// right electrical
nodesList.add(makeXmlNodeLayerSpecial(endLeftOrRight, endPolyx, endTopOrBotton, endPolyy, polyLayer,
Poly.Type.FILLED, false, true, 2));
// non-electrical poly (just one poly layer)
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endPolyx, endPolyy, endPolyy, polyLayer, Poly.Type.FILLED, true, false, -1));
// Poly port
portNames.clear();
portNames.add(polyLayer.name);
Xml.PrimitivePort polyLeftPort = makeXmlPrimitivePort("poly-left", 180, 90, 0, null,
ySign*polyX, -1, ySign*polyX,
-1, xSign*polyY, -1, xSign*polyY, 1, portNames);
// right port
Xml.PrimitivePort polyRightPort = makeXmlPrimitivePort("poly-right", 0, 180, 0, null,
polyX, 1, polyX, 1, polyY, -1, polyY, 1, portNames);
nodePorts.clear();
nodePorts.add(polyLeftPort);
nodePorts.add(diffTopPort);
nodePorts.add(polyRightPort);
nodePorts.add(diffBottomPort);
}
private Xml.ArcLayer makeXmlArcLayer(Xml.Layer layer, WizardField ... flds) {
Xml.ArcLayer al = new Xml.ArcLayer();
al.layer = layer.name;
al.style = Poly.Type.FILLED;
for (int i = 0; i < flds.length; i++)
al.extend.addLambda(scaledValue(flds[i].v/2));
return al;
}
// private Technology.Distance makeXmlDistance(WizardField ... flds) {
// Technology.Distance dist = new Technology.Distance();
// dist.addRule(flds[0].rule, 0.5);
// for (int i = 1; i < flds.length; i++)
// dist.addRule(flds[i].rule, 1);
// return dist;
// }
private void makeLayerGDS(Xml.Technology t, Xml.Layer l, String gdsVal) {
for (Xml.Foundry f: t.foundries) {
f.layerGds.put(l.name, gdsVal);
}
}
private void makeLayerRuleMinWid(Xml.Technology t, Xml.Layer l, WizardField fld) {
for (Xml.Foundry f: t.foundries) {
f.rules.add(new DRCTemplate(fld.rule, DRCTemplate.DRCMode.ALL.mode(), DRCTemplate.DRCRuleType.MINWID,
l.name, null, new double[] {scaledValue(fld.v)}, null, null));
}
}
private void makeLayersRule(Xml.Technology t, Xml.Layer l, DRCTemplate.DRCRuleType ruleType, WizardField fld) {
for (Xml.Foundry f: t.foundries) {
f.rules.add(new DRCTemplate(fld.rule, DRCTemplate.DRCMode.ALL.mode(), ruleType,
l.name, l.name, new double[] {scaledValue(fld.v)}, null, null));
}
}
private void makeLayersRuleSurround(Xml.Technology t, Xml.Layer l1, Xml.Layer l2, WizardField fld) {
double value = scaledValue(fld.v);
for (Xml.Foundry f: t.foundries) {
f.rules.add(new DRCTemplate(fld.rule, DRCTemplate.DRCMode.ALL.mode(), DRCTemplate.DRCRuleType.SURROUND,
l1.name, l2.name, new double[] {value, value}, null, null));
}
}
private double scaledValue(double val) { return DBMath.round(val / stepsize); }
}
| true | true | public void dumpXMLFile(String fileName)
throws IOException
{
Xml.Technology t = new Xml.Technology();
t.techName = getTechName();
t.shortTechName = getTechName();
t.description = getTechDescription();
t.minNumMetals = t.maxNumMetals = t.defaultNumMetals = getNumMetalLayers();
t.scaleValue = getStepSize();
t.scaleRelevant = true;
// t.scaleRelevant = isScaleRelevant();
t.defaultFoundry = "NONE";
t.minResistance = 1.0;
t.minCapacitance = 0.1;
// menus
t.menuPalette = new Xml.MenuPalette();
t.menuPalette.numColumns = 3;
/** RULES **/
Xml.Foundry f = new Xml.Foundry();
f.name = Foundry.Type.NONE.getName();
t.foundries.add(f);
// LAYER COLOURS
Color [] metal_colour = new Color[]
{
new Color(0,150,255), // cyan/blue
new Color(148,0,211), // purple
new Color(255,215,0), // yellow
new Color(132,112,255), // mauve
new Color(255,160,122), // salmon
new Color(34,139,34), // dull green
new Color(178,34,34), // dull red
new Color(34,34,178), // dull blue
new Color(153,153,153), // light gray
new Color(102,102,102) // dark gray
};
Color poly_colour = new Color(255,155,192); // pink
Color diff_colour = new Color(107,226,96); // light green
Color via_colour = new Color(205,205,205); // lighter gray
Color contact_colour = new Color(100,100,100); // darker gray
Color nplus_colour = new Color(224,238,224);
Color pplus_colour = new Color(224,224,120);
Color nwell_colour = new Color(140,140,140);
// Five transparent colors: poly_colour, diff_colour, metal_colour[0->2]
Color[] colorMap = {poly_colour, diff_colour, metal_colour[0], metal_colour[1], metal_colour[2]};
for (int i = 0; i < colorMap.length; i++) {
Color transparentColor = colorMap[i];
t.transparentLayers.add(transparentColor);
}
// Layers
List<Xml.Layer> metalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> dummyMetalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> exclusionMetalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> viaLayers = new ArrayList<Xml.Layer>();
Map<Xml.Layer,WizardField> layer_width = new LinkedHashMap<Xml.Layer,WizardField>();
int[] nullPattern = new int[] {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000};
int[] dexclPattern = new int[] {
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808}; // X X
for (int i = 0; i < num_metal_layers; i++)
{
// Adding the metal
int metalNum = i + 1;
double opacity = (75 - metalNum * 5)/100.0;
int metLayHigh = i / 10;
int metLayDig = i % 10;
int r = metal_colour[metLayDig].getRed() * (10-metLayHigh) / 10;
int g = metal_colour[metLayDig].getGreen() * (10-metLayHigh) / 10;
int b = metal_colour[metLayDig].getBlue() * (10-metLayHigh) / 10;
int tcol = 0;
int[] pattern = null;
switch (metLayDig)
{
case 0: tcol = 3; break;
case 1: tcol = 4; break;
case 2: tcol = 5; break;
case 3: pattern = new int[] {0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000}; break;
case 4: pattern = new int[] { 0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444};
break;
case 5: pattern = new int[] { 0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555};
break;
case 6: pattern = new int[] { 0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111};
break;
case 7: pattern = new int[] { 0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000};
break;
case 8: pattern = new int[] {0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888}; // X X X X
break;
case 9: pattern = new int[] { 0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555};
break;
}
boolean onDisplay = true, onPrinter = true;
if (pattern == null)
{
pattern = nullPattern;
onDisplay = false; onPrinter = false;
}
EGraphics graph = new EGraphics(onDisplay, onPrinter, null, tcol, r, g, b, opacity, true, pattern);
Layer.Function fun = Layer.Function.getMetal(metalNum);
if (fun == null)
throw new IOException("invalid number of metals");
String metalName = "Metal-"+metalNum;
Xml.Layer layer = makeXmlLayer(t.layers, layer_width, metalName, fun, 0, graph,
metal_width[i], true, true);
metalLayers.add(layer);
if (getExtraInfoFlag())
{
// dummy layers
graph = new EGraphics(true, true, null, tcol, r, g, b, opacity, false, nullPattern);
layer = makeXmlLayer(t.layers, "DMY-"+metalName, Layer.Function.getDummyMetal(metalNum), 0, graph,
5*metal_width[i].v, true, false);
dummyMetalLayers.add(layer);
// exclusion layers for metals
graph = new EGraphics(true, true, null, tcol, r, g, b, opacity, true, dexclPattern);
layer = makeXmlLayer(t.layers, "DEXCL-"+metalName, Layer.Function.getDummyExclMetal(i), 0, graph,
2*metal_width[i].v, true, false);
exclusionMetalLayers.add(layer);
}
}
// Vias
for (int i = 0; i < num_metal_layers - 1; i++)
{
// Adding the metal
int metalNum = i + 1;
// adding the via
int r = via_colour.getRed();
int g = via_colour.getGreen();
int b = via_colour.getBlue();
double opacity = 0.7;
EGraphics graph = new EGraphics(false, false, null, 0, r, g, b, opacity, true, nullPattern);
Layer.Function fun = Layer.Function.getContact(metalNum+1); //via contact starts with CONTACT2
if (fun == null)
throw new IOException("invalid number of vias");
viaLayers.add(makeXmlLayer(t.layers, layer_width, "Via-"+metalNum, fun, Layer.Function.CONMETAL,
graph, via_size[i], true, false));
}
// Poly
String polyN = gds_poly_layer.name;
EGraphics graph = new EGraphics(false, false, null, 1, 0, 0, 0, 1, true, nullPattern);
Xml.Layer polyLayer = makeXmlLayer(t.layers, layer_width, polyN, Layer.Function.POLY1, 0, graph,
poly_width, true, true);
// PolyGate
Xml.Layer polyGateLayer = makeXmlLayer(t.layers, layer_width, polyN+"Gate", Layer.Function.GATE, 0, graph,
poly_width, true, false); // false for the port otherwise it won't find any type
if (getExtraInfoFlag())
{
// exclusion layer poly
graph = new EGraphics(true, true, null, 1, 0, 0, 0, 1, true, dexclPattern);
Xml.Layer exclusionPolyLayer = makeXmlLayer(t.layers, "DEXCL-"+polyN, Layer.Function.DEXCLPOLY1, 0, graph,
2*poly_width.v, true, false);
makeLayerGDS(t, exclusionPolyLayer, "150/21");
}
// PolyCon and DiffCon
graph = new EGraphics(false, false, null, 0, contact_colour.getRed(), contact_colour.getGreen(),
contact_colour.getBlue(), 0.5, true, nullPattern);
// PolyCon
Xml.Layer polyConLayer = makeXmlLayer(t.layers, layer_width, "Poly-Cut", Layer.Function.CONTACT1,
Layer.Function.CONPOLY, graph, contact_size, true, false);
// DiffCon
Xml.Layer diffConLayer = makeXmlLayer(t.layers, layer_width, gds_diff_layer.name+"-Cut", Layer.Function.CONTACT1,
Layer.Function.CONDIFF, graph, contact_size, true, false);
// P-Diff and N-Diff
graph = new EGraphics(false, false, null, 2, 0, 0, 0, 1, true, nullPattern);
// N-Diff
Xml.Layer diffNLayer = makeXmlLayer(t.layers, layer_width, "N-"+gds_diff_layer.name, Layer.Function.DIFFN, 0, graph,
diff_width, true, true);
// P-Diff
Xml.Layer diffPLayer = makeXmlLayer(t.layers, layer_width, "P-"+gds_diff_layer.name, Layer.Function.DIFFP, 0, graph,
diff_width, true, true);
if (getExtraInfoFlag())
{
// exclusion layer N/P diff
graph = new EGraphics(true, true, null, 2, 0, 0, 0, 1, true, dexclPattern);
Xml.Layer exclusionDiffPLayer = makeXmlLayer(t.layers, "DEXCL-P-"+gds_diff_layer.name, Layer.Function.DEXCLDIFF, 0, graph,
2*diff_width.v, true, false);
Xml.Layer exclusionDiffNLayer = makeXmlLayer(t.layers, "DEXCL-N-"+gds_diff_layer.name, Layer.Function.DEXCLDIFF, 0, graph,
2*diff_width.v, true, false);
makeLayerGDS(t, exclusionDiffPLayer, "150/20");
makeLayerGDS(t, exclusionDiffNLayer, "150/20");
}
// NPlus and PPlus
int [] patternSlash = new int[] { 0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x0101, // X X
0x0202, // X X
0x0404, // X X
0x0808, // X X
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x0101, // X X
0x0202, // X X
0x0404, // X X
0x0808};
int [] patternBackSlash = new int[] { 0x0202, // X X
0x0101, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x0404, // X X
0x0202, // X X
0x0101, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x0404};
int[] patternDots = new int[] {
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000}; //
int[] patternSparseDots = new int[] {
0x0200, // X
0x0000, //
0x0020, // X
0x0000, //
0x0002, // X
0x0000, //
0x2000, // X
0x0000, //
0x0200, // X
0x0000, //
0x0020, // X
0x0000, //
0x0002, // X
0x0000, //
0x2000, // X
0x0000}; //
// NPlus
graph = new EGraphics(true, true, null, 0, nplus_colour.getRed(), nplus_colour.getGreen(),
nplus_colour.getBlue(), 1, true, patternSlash);
Xml.Layer nplusLayer = makeXmlLayer(t.layers, layer_width, gds_nplus_layer.name, Layer.Function.IMPLANTN, 0, graph,
nplus_width, true, false);
// PPlus
graph = new EGraphics(true, true, null, 0, pplus_colour.getRed(), pplus_colour.getGreen(),
pplus_colour.getBlue(), 1, true, patternDots);
Xml.Layer pplusLayer = makeXmlLayer(t.layers, layer_width, gds_pplus_layer.name, Layer.Function.IMPLANTP, 0, graph,
pplus_width, true, false);
// N-Well
graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(),
nwell_colour.getBlue(), 1, true, patternDots);
Xml.Layer nwellLayer = makeXmlLayer(t.layers, layer_width, gds_nwell_layer.name, Layer.Function.WELLN, 0, graph,
nwell_width, true, false);
// P-Well
graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(),
nwell_colour.getBlue(), 1, true, patternBackSlash);
Xml.Layer pwellLayer = makeXmlLayer(t.layers, layer_width, "P-Well", Layer.Function.WELLP, 0, graph,
nwell_width, true, false);
// DeviceMark
graph = new EGraphics(false, false, null, 0, 255, 0, 0, 0.4, true, nullPattern);
Xml.Layer deviceMarkLayer = makeXmlLayer(t.layers, layer_width, "DeviceMark", Layer.Function.CONTROL, 0, graph,
nplus_width, true, false);
// Extra layers
if (getExtraInfoFlag())
{
for (LayerInfo info : extraLayers)
{
graph = null;
// either color or template
assert (info.graphicsTemplate == null || info.graphicsColor == null);
if (info.graphicsTemplate != null)
{
// look for layer name and get its EGraphics
for (Xml.Layer l : t.layers)
{
if (l.name.equals(info.graphicsTemplate))
{
graph = l.desc;
break;
}
}
if (graph == null)
System.out.println("No template layer " + info.graphicsTemplate + " found");
}
else if (info.graphicsColor != null)
{
graph = new EGraphics(true, true, info.graphicsOutline, 0,
info.graphicsColor.getRed(), info.graphicsColor.getGreen(), info.graphicsColor.getBlue(),
1, true, info.graphicsPattern);
}
if (graph == null)
graph = new EGraphics(false, false, null, 0, 255, 0, 0, 0.4, true, nullPattern);
Xml.Layer layer = makeXmlLayer(t.layers, layer_width, info.name, Layer.Function.ART, 0, graph,
nplus_width, true, false);
makeLayerGDS(t, layer, String.valueOf(info));
}
}
// Palette elements should be added at the end so they will appear in groups
PaletteGroup[] metalPalette = new PaletteGroup[num_metal_layers];
// write arcs
// metal arcs
for(int i=1; i<=num_metal_layers; i++)
{
double ant = (int)Math.round(metal_antenna_ratio[i-1]) | 200;
PaletteGroup group = new PaletteGroup();
metalPalette[i-1] = group;
group.addArc(makeXmlArc(t, "Metal-"+i, ArcProto.Function.getContact(i), ant,
makeXmlArcLayer(metalLayers.get(i-1), metal_width[i-1])));
}
List<String> portNames = new ArrayList<String>();
/**************************** POLY Nodes/Arcs ***********************************************/
// poly arc
double ant = (int)Math.round(poly_antenna_ratio) | 200;
PaletteGroup polyGroup = new PaletteGroup();
polyGroup.addArc(makeXmlArc(t, polyLayer.name, ArcProto.Function.getPoly(1), ant,
makeXmlArcLayer(polyLayer, poly_width)));
// poly pin
double hla = scaledValue(poly_width.v / 2);
polyGroup.addPin(makeXmlPrimitivePin(t, polyLayer.name, hla, null, // new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, polyLayer, Poly.Type.CROSSED)));
// poly contact
portNames.clear();
portNames.add(polyLayer.name);
portNames.add(metalLayers.get(0).name);
hla = scaledValue((contact_size.v/2 + contact_poly_overhang.v));
Xml.Layer m1Layer = metalLayers.get(0);
double contSize = scaledValue(contact_size.v);
double contSpacing = scaledValue(contact_spacing.v);
double contArraySpacing = scaledValue(contact_array_spacing.v);
double metal1Over = scaledValue(contact_size.v/2 + contact_metal_overhang_all_sides.v);
// only for standard cases when getProtectionPoly() is false
if (!getExtraInfoFlag())
{
polyGroup.addElement(makeContactSeries(t.nodeGroups, polyLayer.name, contSize, polyConLayer, contSpacing, contArraySpacing,
scaledValue(contact_poly_overhang.v), polyLayer,
scaledValue(via_overhang[0].v), m1Layer), null);
}
/**************************** N/P-Diff Nodes/Arcs/Group ***********************************************/
PaletteGroup[] diffPalette = new PaletteGroup[2];
diffPalette[0] = new PaletteGroup(); diffPalette[1] = new PaletteGroup();
// ndiff/pdiff pins
hla = scaledValue((contact_size.v/2 + diff_contact_overhang.v));
double nsel = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nplus_overhang_diff.v);
double psel = scaledValue(contact_size.v/2 + diff_contact_overhang.v + pplus_overhang_diff.v);
double nwell = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nwell_overhang_diff_p.v);
double nso = scaledValue(nwell_overhang_diff_p.v /*+ diff_contact_overhang.v*/); // valid for elements that have nwell layers
double pso = (!pWellFlag)?nso:scaledValue(nplus_overhang_diff.v/* + diff_contact_overhang.v*/);
// ndiff/pdiff contacts
String[] diffNames = {"P", "N"};
double[] sos = {nso, pso};
double[] sels = {psel, nsel};
Xml.Layer[] diffLayers = {diffPLayer, diffNLayer};
Xml.Layer[] plusLayers = {pplusLayer, nplusLayer};
// Active and poly contacts. They are defined first that the Full types
for (Map.Entry<String,List<Contact>> e : otherContacts.entrySet())
{
// generic contacts
String name = null;
for (Contact c : e.getValue())
{
Xml.Layer ly = null, lx = null;
Xml.Layer conLay = diffConLayer;
PaletteGroup g = null;
ContactNode metalLayer = c.layers.get(0);
ContactNode otherLayer = c.layers.get(1);
if (!TextUtils.isANumber(metalLayer.layer)) // horizontal must be!
{
assert (TextUtils.isANumber(otherLayer.layer));
metalLayer = c.layers.get(1);
otherLayer = c.layers.get(0);
}
int m1 = Integer.valueOf(metalLayer.layer);
ly = metalLayers.get(m1-1);
String layerName = otherLayer.layer;
if (layerName.equals(diffLayers[0].name))
{
lx = diffLayers[0];
g = diffPalette[0];
}
else if (layerName.equals(diffLayers[1].name))
{
lx = diffLayers[1];
g = diffPalette[1];
}
else if (layerName.equals(polyLayer.name))
{
lx = polyLayer;
conLay = polyConLayer;
g = polyGroup;
}
else
assert(false); // it should not happen
name = ly.name + "-" + lx.name;
double h1x = scaledValue(contact_size.v/2 + metalLayer.overX.v);
double h1y = scaledValue(contact_size.v/2 + metalLayer.overY.v);
double h2x = scaledValue(contact_size.v/2 + otherLayer.overX.v);
double h2y = scaledValue(contact_size.v/2 + otherLayer.overY.v);
double longX = (Math.abs(metalLayer.overX.v - otherLayer.overX.v));
double longY = (Math.abs(metalLayer.overY.v - otherLayer.overY.v));
portNames.clear();
portNames.add(lx.name);
portNames.add(ly.name);
Xml.NodeLayer extraN = null;
if (c.layers.size() == 3) // easy solution for now
{
ContactNode node = c.layers.get(2);
Xml.Layer lz = (diffLayers[0] == lx) ? plusLayers[0] : plusLayers[1];
double h3x = scaledValue(contact_size.v/2 + node.overX.v);
double h3y = scaledValue(contact_size.v/2 + node.overY.v);
extraN = makeXmlNodeLayer(h3x, h3x, h3y, h3y, lz, Poly.Type.FILLED);
// This assumes no well is defined
longX = (Math.abs(node.overX.v - otherLayer.overX.v));
longY = (Math.abs(node.overY.v - otherLayer.overY.v));
}
longX = scaledValue(longX);
longY = scaledValue(longY);
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String p = (c.prefix == null || c.prefix.equals("")) ? "" : c.prefix + "-";
g.addElement(makeXmlPrimitiveCon(t.nodeGroups, p + name, PrimitiveNode.Function.CONTACT, -1, -1,
new SizeOffset(longX, longX, longY, longY), portNames,
makeXmlNodeLayer(h1x, h1x, h1y, h1y, ly, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(h2x, h2x, h2y, h2y, lx, Poly.Type.FILLED), // layer2
extraN,
makeXmlMulticut(conLay, contSize, contSpacing, contArraySpacing)), c.prefix); // contact
}
}
// ndiff/pdiff contact
for (int i = 0; i < 2; i++)
{
portNames.clear();
portNames.add(diffLayers[i].name);
portNames.add(m1Layer.name);
String composeName = diffNames[i] + "-" + gds_diff_layer.name; //Diff";
Xml.NodeLayer wellNode, wellNodePin;
ArcProto.Function arcF;
Xml.ArcLayer arcL;
WizardField arcVal;
if (i == Technology.P_TYPE)
{
wellNodePin = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.CROSSED);
wellNode = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.FILLED);
arcF = ArcProto.Function.DIFFP;
arcL = makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff_p);
arcVal = pplus_overhang_diff;
}
else
{
wellNodePin = (!pWellFlag)?makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.CROSSED):null;
wellNode = (!pWellFlag)?makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.FILLED):null;
arcF = ArcProto.Function.DIFFN;
arcL = (!pWellFlag)?makeXmlArcLayer(pwellLayer, diff_width, nwell_overhang_diff_p):null;
arcVal = nplus_overhang_diff;
}
PaletteGroup diffG = diffPalette[i];
// active arc
diffG.addArc(makeXmlArc(t, composeName, arcF, 0,
makeXmlArcLayer(diffLayers[i], diff_width),
makeXmlArcLayer(plusLayers[i], diff_width, arcVal),
arcL));
// active pin
diffG.addPin(makeXmlPrimitivePin(t, composeName, hla,
new SizeOffset(sos[i], sos[i], sos[i], sos[i]),
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.CROSSED),
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.CROSSED),
wellNodePin));
// F stands for full (all layers)
diffG.addElement(makeXmlPrimitiveCon(t.nodeGroups, "F-"+composeName, PrimitiveNode.Function.CONTACT,
hla, hla, new SizeOffset(sos[i], sos[i], sos[i], sos[i]), portNames,
makeXmlNodeLayer(metal1Over, metal1Over, metal1Over, metal1Over, m1Layer, Poly.Type.FILLED), // meta1 layer
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.FILLED), // active layer
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.FILLED), // select layer
wellNode, // well layer
makeXmlMulticut(diffConLayer, contSize, contSpacing, contArraySpacing)), "Full-" + diffNames[i]); // contact
}
/**************************** N/P-Well Contacts ***********************************************/
nwell = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nwell_overhang_diff_n.v);
nso = scaledValue(/*diff_contact_overhang.v +*/ nwell_overhang_diff_n.v); // valid for elements that have nwell layers
pso = (!pWellFlag)?nso:scaledValue(/*diff_contact_overhang.v +*/ nplus_overhang_diff.v);
double[] wellSos = {pso, nso};
PaletteGroup[] wellPalette = new PaletteGroup[2];
Xml.Layer[] wellLayers = {pwellLayer, nwellLayer};
// nwell/pwell contact
for (int i = 0; i < 2; i++)
{
String composeName = diffNames[i] + "-Well";
Xml.NodeLayer wellNodeLayer = null, wellNodePinLayer = null;
PaletteGroup g = new PaletteGroup();
PrimitiveNode.Function func = null;
Xml.ArcLayer arcL;
WizardField arcVal;
wellPalette[i] = g;
portNames.clear();
if (i == Technology.P_TYPE)
{
if (!pWellFlag)
{
portNames.add(pwellLayer.name);
wellNodePinLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.CROSSED);
wellNodeLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.FILLED);
}
func = PrimitiveNode.Function.WELL;
arcL = (!pWellFlag)?makeXmlArcLayer(pwellLayer, diff_width, nwell_overhang_diff_p):null;
arcVal = pplus_overhang_diff;
}
else
{
portNames.add(nwellLayer.name);
wellNodePinLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.CROSSED);
wellNodeLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.FILLED);
func = PrimitiveNode.Function.SUBSTRATE;
arcL = makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff_p);
arcVal = nplus_overhang_diff;
}
portNames.add(m1Layer.name);
// simple arc. S for simple
g.addArc(makeXmlArc(t, "S-"+composeName, ArcProto.Function.WELL, 0,
makeXmlArcLayer(wellLayers[i], diff_width, nwell_overhang_diff_p)));
// three layers arcs
g.addArc(makeXmlArc(t, composeName, ArcProto.Function.WELL, 0,
makeXmlArcLayer(diffLayers[i], diff_width),
makeXmlArcLayer(plusLayers[i], diff_width, arcVal),
arcL));
// well pin
g.addPin(makeXmlPrimitivePin(t, composeName, hla,
new SizeOffset(wellSos[i], wellSos[i], wellSos[i], wellSos[i]),
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.CROSSED),
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.CROSSED),
wellNodePinLayer));
// well contact
// F stands for full
g.addElement(makeXmlPrimitiveCon(t.nodeGroups, "F-"+composeName, func,
hla, hla, new SizeOffset(wellSos[i], wellSos[i], wellSos[i], wellSos[i]), portNames,
makeXmlNodeLayer(metal1Over, metal1Over, metal1Over, metal1Over, m1Layer, Poly.Type.FILLED), // meta1 layer
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.FILLED), // active layer
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.FILLED), // select layer
wellNodeLayer, // well layer
makeXmlMulticut(diffConLayer, contSize, contSpacing, contArraySpacing)), "Full-"+diffNames[i] + "W"); // contact
}
/**************************** Metals Nodes/Arcs ***********************************************/
// Pins and contacts
for(int i=1; i<num_metal_layers; i++)
{
hla = scaledValue(metal_width[i-1].v / 2);
Xml.Layer lb = metalLayers.get(i-1);
Xml.Layer lt = metalLayers.get(i);
PaletteGroup group = metalPalette[i-1]; // structure created by the arc definition
// Pin bottom metal
group.addPin(makeXmlPrimitivePin(t, lb.name, hla, null, //new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, lb, Poly.Type.CROSSED)));
if (i == num_metal_layers - 1) // last pin!
{
metalPalette[i].addPin(makeXmlPrimitivePin(t, lt.name, hla, null, //new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, lt, Poly.Type.CROSSED)));
}
if (!getExtraInfoFlag())
{
// original contact Square
// via
Xml.Layer via = viaLayers.get(i-1);
double viaSize = scaledValue(via_size[i-1].v);
double viaSpacing = scaledValue(via_inline_spacing[i-1].v);
double viaArraySpacing = scaledValue(via_array_spacing[i-1].v);
String name = lb.name + "-" + lt.name;
double longDist = scaledValue(via_overhang[i-1].v);
group.addElement(makeContactSeries(t.nodeGroups, name, viaSize, via, viaSpacing, viaArraySpacing,
longDist, lt, longDist, lb), null);
}
}
// metal contacts
for (Map.Entry<String,List<Contact>> e : metalContacts.entrySet())
{
// generic contacts
for (Contact c : e.getValue())
{
// We know those layer names are numbers!
assert(c.layers.size() == 2);
ContactNode verticalLayer = c.layers.get(0);
ContactNode horizontalLayer = c.layers.get(1);
int i = Integer.valueOf(verticalLayer.layer);
int j = Integer.valueOf(horizontalLayer.layer);
Xml.Layer ly = metalLayers.get(i-1);
Xml.Layer lx = metalLayers.get(j-1);
String name = (j>i)?ly.name + "-" + lx.name:lx.name + "-" + ly.name;
int via = (j>i)?i:j;
double metalContSize = scaledValue(via_size[via-1].v);
double spacing = scaledValue(via_inline_spacing[via-1].v);
double arraySpacing = scaledValue(via_array_spacing[via-1].v);
Xml.Layer metalConLayer = viaLayers.get(via-1);
double h1x = scaledValue(via_size[via-1].v/2 + verticalLayer.overX.v);
double h1y = scaledValue(via_size[via-1].v/2 + verticalLayer.overY.v);
double h2x = scaledValue(via_size[via-1].v/2 + horizontalLayer.overX.v);
double h2y = scaledValue(via_size[via-1].v/2 + horizontalLayer.overY.v);
// double longX = scaledValue(DBMath.isGreaterThan(verticalLayer.overX.v, horizontalLayer.overX.v) ? verticalLayer.overX.v : horizontalLayer.overX.v);
// double longY = scaledValue(DBMath.isGreaterThan(verticalLayer.overY.v, horizontalLayer.overY.v) ? verticalLayer.overY.v : horizontalLayer.overY.v);
double longX = scaledValue(Math.abs(verticalLayer.overX.v - horizontalLayer.overX.v));
double longY = scaledValue(Math.abs(verticalLayer.overY.v - horizontalLayer.overY.v));
portNames.clear();
portNames.add(lx.name);
portNames.add(ly.name);
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String p = (c.prefix == null || c.prefix.equals("")) ? "" : c.prefix + "-";
metalPalette[via-1].addElement(makeXmlPrimitiveCon(t.nodeGroups, p + name, PrimitiveNode.Function.CONTACT, -1, -1,
new SizeOffset(longX, longX, longY, longY),
portNames,
makeXmlNodeLayer(h1x, h1x, h1y, h1y, ly, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(h2x, h2x, h2y, h2y, lx, Poly.Type.FILLED), // layer2
makeXmlMulticut(metalConLayer, metalContSize, spacing, arraySpacing)), c.prefix); // contact
}
}
/**************************** Transistors ***********************************************/
/** Transistors **/
// write the transistors
List<Xml.NodeLayer> nodesList = new ArrayList<Xml.NodeLayer>();
List<Xml.PrimitivePort> nodePorts = new ArrayList<Xml.PrimitivePort>();
EPoint minFullSize = null; //EPoint.fromLambda(0, 0); // default zero horizontalFlag
PaletteGroup[] transPalette = new PaletteGroup[2];
for(int i = 0; i < 2; i++)
{
String name;
double selecty = 0, selectx = 0;
Xml.Layer wellLayer = null, activeLayer, selectLayer;
double sox = 0, soy = 0;
double impx = scaledValue((gate_width.v)/2);
double impy = scaledValue((gate_length.v+diff_poly_overhang.v*2)/2);
double nwell_overhangX = 0, nwell_overhangY = 0;
PaletteGroup g = new PaletteGroup();
transPalette[i] = g;
double protectDist = scaledValue(poly_protection_spacing.v);
double extraSelX = 0, extraSelY = 0;
PrimitiveNode.Function func = null;
if (i==Technology.P_TYPE)
{
name = "P";
nwell_overhangY = nwell_overhangX = nwell_overhang_diff_n.v;
wellLayer = nwellLayer;
activeLayer = diffPLayer;
selectLayer = pplusLayer;
extraSelX = pplus_overhang_poly.v;
extraSelY = pplus_overhang_diff.v;
func = PrimitiveNode.Function.TRAPMOS;
}
else
{
name = "N";
activeLayer = diffNLayer;
selectLayer = nplusLayer;
extraSelX = nplus_overhang_poly.v;
extraSelY = nplus_overhang_diff.v;
func = PrimitiveNode.Function.TRANMOS;
if (!pWellFlag)
{
nwell_overhangY = nwell_overhangX = nwell_overhang_diff_p.v;
wellLayer = pwellLayer;
}
else
{
nwell_overhangX = poly_endcap.v+extraSelX;
nwell_overhangY = extraSelY;
}
}
selectx = scaledValue(gate_width.v/2+poly_endcap.v+extraSelX);
selecty = scaledValue(gate_length.v/2+diff_poly_overhang.v+extraSelY);
// Using P values in transistors
double wellx = scaledValue((gate_width.v/2+nwell_overhangX));
double welly = scaledValue((gate_length.v/2+diff_poly_overhang.v+nwell_overhangY));
sox = scaledValue(nwell_overhangX);
soy = scaledValue(diff_poly_overhang.v+nwell_overhangY);
if (DBMath.isLessThan(wellx, selectx))
{
sox = scaledValue(poly_endcap.v+extraSelX);
wellx = selectx;
}
if (DBMath.isLessThan(welly, selecty))
{
soy = scaledValue(diff_poly_overhang.v+extraSelY);
welly = selecty;
}
nodesList.clear();
nodePorts.clear();
portNames.clear();
// Gate layer Electrical
double gatey = scaledValue(gate_length.v/2);
double gatex = impx;
// Poly layers
// left electrical
double endPolyx = scaledValue((gate_width.v+poly_endcap.v*2)/2);
double endPolyy = gatey;
double endLeftOrRight = -impx; // for horizontal transistors. Default
double endTopOrBotton = endPolyy; // for horizontal transistors. Default
double diffX = 0, diffY = scaledValue(gate_length.v/2+gate_contact_spacing.v+contact_size.v/2); // impy
double xSign = 1, ySign = -1;
double polyX = endPolyx, polyY = 0;
if (!horizontalFlag) // swap the numbers to get vertical transistors
{
double tmp;
tmp = impx; impx = impy; impy = tmp;
tmp = wellx; wellx = welly; welly = tmp;
tmp = sox; sox = soy; soy = tmp;
tmp = selectx; selectx = selecty; selecty = tmp;
tmp = gatex; gatex = gatey; gatey = tmp;
tmp = endPolyx; endPolyx = endPolyy; endPolyy = tmp;
tmp = diffX; diffX = diffY; diffY = tmp;
tmp = polyX; polyX = polyY; polyY = tmp;
tmp = xSign; xSign = ySign; ySign = tmp;
endLeftOrRight = endPolyx;
endTopOrBotton = -impx;
}
// Well layer
Xml.NodeLayer xTranWellLayer = null;
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(wellx, wellx, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
// Active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, impy, activeLayer, Poly.Type.FILLED, true, false, -1));
// electrical active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, 0, activeLayer, Poly.Type.FILLED, false, true, 3)); // bottom
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, 0, impy, activeLayer, Poly.Type.FILLED, false, true, 1)); // top
// Diff port
portNames.clear();
portNames.add(activeLayer.name);
Xml.PrimitivePort diffTopPort = makeXmlPrimitivePort("diff-top", 90, 90, 1, minFullSize,
diffX, -1, diffX, 1, diffY, 1, diffY, 1, portNames);
// bottom port
Xml.PrimitivePort diffBottomPort = makeXmlPrimitivePort("diff-bottom", 270, 90, 2, minFullSize,
xSign*diffX, -1, xSign*diffX, 1, ySign*diffY, -1, ySign*diffY, -1, portNames);
// Electric layers
// Gate layer Electrical
nodesList.add(makeXmlNodeLayerSpecial(gatex, gatex, gatey, gatey, polyGateLayer, Poly.Type.FILLED, false, true, -1));
// Poly layers
// left electrical
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endLeftOrRight, endPolyy, endTopOrBotton, polyLayer,
Poly.Type.FILLED, false, true, 0));
// right electrical
nodesList.add(makeXmlNodeLayerSpecial(endLeftOrRight, endPolyx, endTopOrBotton, endPolyy, polyLayer,
Poly.Type.FILLED, false, true, 2));
// non-electrical poly (just one poly layer)
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endPolyx, endPolyy, endPolyy, polyLayer, Poly.Type.FILLED, true, false, -1));
// Poly port
portNames.clear();
portNames.add(polyLayer.name);
Xml.PrimitivePort polyLeftPort = makeXmlPrimitivePort("poly-left", 180, 90, 0, minFullSize,
ySign*polyX, -1, ySign*polyX,
-1, xSign*polyY, -1, xSign*polyY, 1, portNames);
// right port
Xml.PrimitivePort polyRightPort = makeXmlPrimitivePort("poly-right", 0, 180, 0, minFullSize,
polyX, 1, polyX, 1, polyY, -1, polyY, 1, portNames);
// Select layer
Xml.NodeLayer xTranSelLayer = (makeXmlNodeLayer(selectx, selectx, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
//One (undocumented) requirement of transistors is that the ports must appear in the
//order: Poly-left, Diff-top, Poly-right, Diff-bottom. This requirement is
//because of the methods Technology.getTransistorGatePort(),
//Technology.getTransistorAltGatePort(), Technology.getTransistorSourcePort(),
//and Technology.getTransistorDrainPort().
// diff-top = 1, diff-bottom = 2, polys=0
// ports in the correct order: Poly-left, Diff-top, Poly-right, Diff-bottom
nodePorts.add(polyLeftPort);
nodePorts.add(diffTopPort);
nodePorts.add(polyRightPort);
nodePorts.add(diffBottomPort);
// Standard Transistor
Xml.PrimitiveNodeGroup n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
// Extra transistors which don't have select nor well
// Extra protection poly. No ports are necessary.
if (getExtraInfoFlag())
{
// removing well and select for simplicity
// nodesList.remove(xTranSelLayer);
// nodesList.remove(xTranWellLayer);
// // new sox and soy
// sox = scaledValue(poly_endcap.v);
// soy = scaledValue(diff_poly_overhang.v);
// n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-S", PrimitiveNode.Function.TRANMOS, 0, 0, 0, 0,
// new SizeOffset(sox, sox, soy, soy), nodesListW, nodePorts, null, false);
// g.addElement(n);
/*************************************/
// Short transistors
// Adding extra transistors whose select and well are aligned with poly along the X axis
nodesList.remove(xTranSelLayer);
double shortSelectX = scaledValue(gate_width.v/2+poly_endcap.v);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
double shortSox = sox;
shortSox = scaledValue(poly_endcap.v);
if (wellLayer != null)
{
nodesList.remove(xTranWellLayer);
xTranWellLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-S", func, 0, 0, 0, 0,
new SizeOffset(shortSox, shortSox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-S");
/*************************************/
// Transistors with extra polys
// different select for those with extra protection layers
nodesList.remove(xTranSelLayer);
double endOfProtectionY = gate_length.v + poly_protection_spacing.v;
double selectExtraY = scaledValue(gate_length.v/2 + endOfProtectionY + extraSelX); // actually is extraSelX because of the poly distance!
xTranSelLayer = (makeXmlNodeLayer(selectx, selectx, selectExtraY, selectExtraY, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// not sure which condition to apply. It doesn't apply nwell_overhang_diff due to the extra poly
if (DBMath.isLessThan(welly, selectExtraY))
{
welly = selectExtraY;
soy = scaledValue(endOfProtectionY + extraSelX);
}
if (wellLayer != null)
{
nodesList.remove(xTranWellLayer);
xTranWellLayer = (makeXmlNodeLayer(wellx, wellx, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
if (!horizontalFlag)
{
System.out.println("Not working with !horizontal");
assert(false);
}
portNames.clear();
portNames.add(polyLayer.name);
// bottom or left
Xml.NodeLayer bOrL = (makeXmlNodeLayerSpecial(gatex, gatex,
DBMath.round((protectDist + 3*endPolyy)),
-DBMath.round(endPolyy + protectDist),
polyLayer, Poly.Type.FILLED, true, false, -1/*3*/)); // port 3 for left/bottom extra poly lb=left bottom
// Adding left
nodesList.add(bOrL);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-B", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-B");
// top or right
Xml.NodeLayer tOrR = (makeXmlNodeLayerSpecial(gatex, gatex,
-DBMath.round(endPolyy + protectDist),
DBMath.round((protectDist + 3*endPolyy)),
polyLayer, Poly.Type.FILLED, true, false, -1/*4*/)); // port 4 for right/top extra poly rt=right top
// Adding both
nodesList.add(tOrR);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-TB", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-TB");
// Adding right
nodesList.remove(bOrL);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-T", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name +"-T");
/*************************************/
// Short transistors woth OD18
double od18x = scaledValue(gate_od18_width.v/2+od18_diff_overhang[0].v);
double od18y = scaledValue(gate_od18_length.v/2+diff_poly_overhang.v+od18_diff_overhang[1].v);
nodePorts.clear();
nodesList.clear();
prepareTransistor(gate_od18_width.v, gate_od18_length.v, poly_endcap.v, diff_poly_overhang.v,
gate_contact_spacing.v, contact_size.v, activeLayer, polyLayer, polyGateLayer, nodesList, nodePorts);
// OD18
Xml.Layer od18Layer = t.findLayer("OD_18");
nodesList.add(makeXmlNodeLayer(od18x, od18x, od18y, od18y, od18Layer, Poly.Type.FILLED));
// adding short select
shortSelectX = scaledValue(gate_od18_width.v/2+poly_endcap.v);
selecty = scaledValue(gate_od18_length.v/2+diff_poly_overhang.v+extraSelY);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// adding well
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(od18x, od18x, od18y, od18y, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
sox = scaledValue(od18_diff_overhang[0].v);
soy = scaledValue(diff_poly_overhang.v+od18_diff_overhang[1].v);
n = makeXmlPrimitive(t.nodeGroups, "OD18-" + name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
/*************************************/
// Short transistors with native
if (i==Technology.N_TYPE)
{
double ntx = scaledValue(gate_nt_width.v/2+nt_diff_overhang.v);
double nty = scaledValue(gate_nt_length.v/2+diff_poly_overhang.v+nt_diff_overhang.v);
nodePorts.clear();
nodesList.clear();
prepareTransistor(gate_nt_width.v, gate_nt_length.v, poly_nt_endcap.v, diff_poly_overhang.v,
gate_contact_spacing.v, contact_size.v, activeLayer, polyLayer, polyGateLayer, nodesList, nodePorts);
// NT-N
Xml.Layer ntLayer = t.findLayer("NT-N");
nodesList.add(makeXmlNodeLayer(ntx, ntx, nty, nty, ntLayer, Poly.Type.FILLED));
// adding short select
shortSelectX = scaledValue(gate_nt_width.v/2+poly_nt_endcap.v);
selecty = scaledValue(gate_nt_length.v/2+diff_poly_overhang.v+extraSelY);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// adding well
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(ntx, ntx, nty, nty, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
sox = scaledValue(diff_poly_overhang.v);
soy = scaledValue(diff_poly_overhang.v+nt_diff_overhang.v);
n = makeXmlPrimitive(t.nodeGroups, "NT-" + name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
}
}
}
// Aggregating all palette groups into one
List<PaletteGroup> allGroups = new ArrayList<PaletteGroup>();
allGroups.add(transPalette[0]); allGroups.add(transPalette[1]);
allGroups.add(diffPalette[0]); allGroups.add(diffPalette[1]);
allGroups.add(wellPalette[0]); allGroups.add(wellPalette[1]);
allGroups.add(polyGroup);
for (PaletteGroup g : metalPalette)
allGroups.add(g);
// Adding elements in palette
for (PaletteGroup o : allGroups)
{
t.menuPalette.menuBoxes.add(o.arcs); // arcs
t.menuPalette.menuBoxes.add(o.pins); // pins
t.menuPalette.menuBoxes.add(o.elements); // contacts
}
// Writting GDS values
makeLayerGDS(t, diffPLayer, String.valueOf(gds_diff_layer));
makeLayerGDS(t, diffNLayer, String.valueOf(gds_diff_layer));
makeLayerGDS(t, pplusLayer, String.valueOf(gds_pplus_layer));
makeLayerGDS(t, nplusLayer, String.valueOf(gds_nplus_layer));
makeLayerGDS(t, nwellLayer, String.valueOf(gds_nwell_layer));
makeLayerGDS(t, deviceMarkLayer, String.valueOf(gds_marking_layer));
makeLayerGDS(t, polyConLayer, String.valueOf(gds_contact_layer));
makeLayerGDS(t, diffConLayer, String.valueOf(gds_contact_layer));
makeLayerGDS(t, polyLayer, String.valueOf(gds_poly_layer));
makeLayerGDS(t, polyGateLayer, String.valueOf(gds_poly_layer));
for (int i = 0; i < num_metal_layers; i++) {
Xml.Layer met = metalLayers.get(i);
makeLayerGDS(t, met, String.valueOf(gds_metal_layer[i]));
if (getExtraInfoFlag())
{
// Type is always 1
makeLayerGDS(t, dummyMetalLayers.get(i), gds_metal_layer[i].value + "/1");
// exclusion always takes 150
makeLayerGDS(t, exclusionMetalLayers.get(i), "150/" + (i + 1));
}
if (i > num_metal_layers - 2) continue;
Xml.Layer via = viaLayers.get(i);
makeLayerGDS(t, via, String.valueOf(gds_via_layer[i]));
}
// Writting Layer Rules
for (Xml.Layer l : diffLayers)
{
makeLayerRuleMinWid(t, l, diff_width);
makeLayersRule(t, l, DRCTemplate.DRCRuleType.SPACING, diff_spacing);
}
WizardField[] plus_diff = {pplus_overhang_diff, nplus_overhang_diff};
WizardField[] plus_width = {pplus_width, nplus_width};
WizardField[] plus_spacing = {pplus_spacing, nplus_spacing};
for (int i = 0; i < plusLayers.length; i++)
{
makeLayerRuleMinWid(t, plusLayers[i], plus_width[i]);
makeLayersRuleSurround(t, plusLayers[i], diffLayers[i], plus_diff[i]);
makeLayersRule(t, plusLayers[i], DRCTemplate.DRCRuleType.SPACING, plus_spacing[i]);
}
Xml.Layer[] wells = {pwellLayer, nwellLayer};
for (Xml.Layer w : wells)
{
makeLayerRuleMinWid(t, w, nwell_width);
makeLayersRuleSurround(t, w, diffPLayer, nwell_overhang_diff_p);
makeLayersRuleSurround(t, w, diffNLayer, nwell_overhang_diff_n);
makeLayersRule(t, w, DRCTemplate.DRCRuleType.SPACING, nwell_spacing);
}
Xml.Layer[] polys = {polyLayer, polyGateLayer};
for (Xml.Layer w : polys)
{
makeLayerRuleMinWid(t, w, poly_width);
makeLayersRule(t, w, DRCTemplate.DRCRuleType.SPACING, poly_spacing);
}
for (int i = 0; i < num_metal_layers; i++) {
Xml.Layer met = metalLayers.get(i);
makeLayerRuleMinWid(t, met, metal_width[i]);
if (i >= num_metal_layers - 1) continue;
Xml.Layer via = viaLayers.get(i);
makeLayerRuleMinWid(t, via, via_size[i]);
makeLayersRule(t, via, DRCTemplate.DRCRuleType.CONSPA, via_inline_spacing[i]);
makeLayersRule(t, via, DRCTemplate.DRCRuleType.UCONSPA2D, via_array_spacing[i]);
}
// Finish menu with Pure, Misc and Cell
List<Object> l = new ArrayList<Object>();
l.add(new String("Pure"));
t.menuPalette.menuBoxes.add(l);
l = new ArrayList<Object>();
l.add(new String("Misc."));
t.menuPalette.menuBoxes.add(l);
l = new ArrayList<Object>();
l.add(new String("Cell"));
t.menuPalette.menuBoxes.add(l);
// write finally the file
boolean includeDateAndVersion = User.isIncludeDateAndVersionInOutput();
String copyrightMessage = IOTool.isUseCopyrightMessage() ? IOTool.getCopyrightMessage() : null;
t.writeXml(fileName, includeDateAndVersion, copyrightMessage);
}
| public void dumpXMLFile(String fileName)
throws IOException
{
Xml.Technology t = new Xml.Technology();
t.techName = getTechName();
t.shortTechName = getTechName();
t.description = getTechDescription();
t.minNumMetals = t.maxNumMetals = t.defaultNumMetals = getNumMetalLayers();
t.scaleValue = getStepSize();
t.scaleRelevant = true;
// t.scaleRelevant = isScaleRelevant();
t.defaultFoundry = "NONE";
t.minResistance = 1.0;
t.minCapacitance = 0.1;
// menus
t.menuPalette = new Xml.MenuPalette();
t.menuPalette.numColumns = 3;
/** RULES **/
Xml.Foundry f = new Xml.Foundry();
f.name = Foundry.Type.NONE.getName();
t.foundries.add(f);
// LAYER COLOURS
Color [] metal_colour = new Color[]
{
new Color(0,150,255), // cyan/blue
new Color(148,0,211), // purple
new Color(255,215,0), // yellow
new Color(132,112,255), // mauve
new Color(255,160,122), // salmon
new Color(34,139,34), // dull green
new Color(178,34,34), // dull red
new Color(34,34,178), // dull blue
new Color(153,153,153), // light gray
new Color(102,102,102) // dark gray
};
Color poly_colour = new Color(255,155,192); // pink
Color diff_colour = new Color(107,226,96); // light green
Color via_colour = new Color(205,205,205); // lighter gray
Color contact_colour = new Color(100,100,100); // darker gray
Color nplus_colour = new Color(224,238,224);
Color pplus_colour = new Color(224,224,120);
Color nwell_colour = new Color(140,140,140);
// Five transparent colors: poly_colour, diff_colour, metal_colour[0->2]
Color[] colorMap = {poly_colour, diff_colour, metal_colour[0], metal_colour[1], metal_colour[2]};
for (int i = 0; i < colorMap.length; i++) {
Color transparentColor = colorMap[i];
t.transparentLayers.add(transparentColor);
}
// Layers
List<Xml.Layer> metalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> dummyMetalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> exclusionMetalLayers = new ArrayList<Xml.Layer>();
List<Xml.Layer> viaLayers = new ArrayList<Xml.Layer>();
Map<Xml.Layer,WizardField> layer_width = new LinkedHashMap<Xml.Layer,WizardField>();
int[] nullPattern = new int[] {0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000};
int[] dexclPattern = new int[] {
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808}; // X X
for (int i = 0; i < num_metal_layers; i++)
{
// Adding the metal
int metalNum = i + 1;
double opacity = (75 - metalNum * 5)/100.0;
int metLayHigh = i / 10;
int metLayDig = i % 10;
int r = metal_colour[metLayDig].getRed() * (10-metLayHigh) / 10;
int g = metal_colour[metLayDig].getGreen() * (10-metLayHigh) / 10;
int b = metal_colour[metLayDig].getBlue() * (10-metLayHigh) / 10;
int tcol = 0;
int[] pattern = null;
switch (metLayDig)
{
case 0: tcol = 3; break;
case 1: tcol = 4; break;
case 2: tcol = 5; break;
case 3: pattern = new int[] {0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000, //
0xFFFF, // XXXXXXXXXXXXXXXX
0x0000}; break;
case 4: pattern = new int[] { 0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444, // X X X X
0x8888, // X X X X
0x1111, // X X X X
0x2222, // X X X X
0x4444};
break;
case 5: pattern = new int[] { 0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555, // X X X X X X X X
0x1111, // X X X X
0xFFFF, // XXXXXXXXXXXXXXXX
0x1111, // X X X X
0x5555};
break;
case 6: pattern = new int[] { 0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111, // X X X X
0x8888, // X X X X
0x4444, // X X X X
0x2222, // X X X X
0x1111};
break;
case 7: pattern = new int[] { 0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000};
break;
case 8: pattern = new int[] {0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888, // X X X X
0x0000, //
0x2222, // X X X X
0x0000, //
0x8888}; // X X X X
break;
case 9: pattern = new int[] { 0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555, // X X X X X X X X
0x5555};
break;
}
boolean onDisplay = true, onPrinter = true;
if (pattern == null)
{
pattern = nullPattern;
onDisplay = false; onPrinter = false;
}
EGraphics graph = new EGraphics(onDisplay, onPrinter, null, tcol, r, g, b, opacity, true, pattern);
Layer.Function fun = Layer.Function.getMetal(metalNum);
if (fun == null)
throw new IOException("invalid number of metals");
String metalName = "Metal-"+metalNum;
Xml.Layer layer = makeXmlLayer(t.layers, layer_width, metalName, fun, 0, graph,
metal_width[i], true, true);
metalLayers.add(layer);
if (getExtraInfoFlag())
{
// dummy layers
graph = new EGraphics(true, true, null, tcol, r, g, b, opacity, false, nullPattern);
layer = makeXmlLayer(t.layers, "DMY-"+metalName, Layer.Function.getDummyMetal(metalNum), 0, graph,
5*metal_width[i].v, true, false);
dummyMetalLayers.add(layer);
// exclusion layers for metals
graph = new EGraphics(true, true, null, tcol, r, g, b, opacity, true, dexclPattern);
layer = makeXmlLayer(t.layers, "DEXCL-"+metalName, Layer.Function.getDummyExclMetal(i), 0, graph,
2*metal_width[i].v, true, false);
exclusionMetalLayers.add(layer);
}
}
// Vias
for (int i = 0; i < num_metal_layers - 1; i++)
{
// Adding the metal
int metalNum = i + 1;
// adding the via
int r = via_colour.getRed();
int g = via_colour.getGreen();
int b = via_colour.getBlue();
double opacity = 0.7;
EGraphics graph = new EGraphics(false, false, null, 0, r, g, b, opacity, true, nullPattern);
Layer.Function fun = Layer.Function.getContact(metalNum+1); //via contact starts with CONTACT2
if (fun == null)
throw new IOException("invalid number of vias");
viaLayers.add(makeXmlLayer(t.layers, layer_width, "Via-"+metalNum, fun, Layer.Function.CONMETAL,
graph, via_size[i], true, false));
}
// Poly
String polyN = gds_poly_layer.name;
EGraphics graph = new EGraphics(false, false, null, 1, 0, 0, 0, 1, true, nullPattern);
Xml.Layer polyLayer = makeXmlLayer(t.layers, layer_width, polyN, Layer.Function.POLY1, 0, graph,
poly_width, true, true);
// PolyGate
Xml.Layer polyGateLayer = makeXmlLayer(t.layers, layer_width, polyN+"Gate", Layer.Function.GATE, 0, graph,
poly_width, true, false); // false for the port otherwise it won't find any type
if (getExtraInfoFlag())
{
// exclusion layer poly
graph = new EGraphics(true, true, null, 1, 0, 0, 0, 1, true, dexclPattern);
Xml.Layer exclusionPolyLayer = makeXmlLayer(t.layers, "DEXCL-"+polyN, Layer.Function.DEXCLPOLY1, 0, graph,
2*poly_width.v, true, false);
makeLayerGDS(t, exclusionPolyLayer, "150/21");
}
// PolyCon and DiffCon
graph = new EGraphics(false, false, null, 0, contact_colour.getRed(), contact_colour.getGreen(),
contact_colour.getBlue(), 0.5, true, nullPattern);
// PolyCon
Xml.Layer polyConLayer = makeXmlLayer(t.layers, layer_width, "Poly-Cut", Layer.Function.CONTACT1,
Layer.Function.CONPOLY, graph, contact_size, true, false);
// DiffCon
Xml.Layer diffConLayer = makeXmlLayer(t.layers, layer_width, gds_diff_layer.name+"-Cut", Layer.Function.CONTACT1,
Layer.Function.CONDIFF, graph, contact_size, true, false);
// P-Diff and N-Diff
graph = new EGraphics(false, false, null, 2, 0, 0, 0, 1, true, nullPattern);
// N-Diff
Xml.Layer diffNLayer = makeXmlLayer(t.layers, layer_width, "N-"+gds_diff_layer.name, Layer.Function.DIFFN, 0, graph,
diff_width, true, true);
// P-Diff
Xml.Layer diffPLayer = makeXmlLayer(t.layers, layer_width, "P-"+gds_diff_layer.name, Layer.Function.DIFFP, 0, graph,
diff_width, true, true);
if (getExtraInfoFlag())
{
// exclusion layer N/P diff
graph = new EGraphics(true, true, null, 2, 0, 0, 0, 1, true, dexclPattern);
Xml.Layer exclusionDiffPLayer = makeXmlLayer(t.layers, "DEXCL-P-"+gds_diff_layer.name, Layer.Function.DEXCLDIFF, 0, graph,
2*diff_width.v, true, false);
Xml.Layer exclusionDiffNLayer = makeXmlLayer(t.layers, "DEXCL-N-"+gds_diff_layer.name, Layer.Function.DEXCLDIFF, 0, graph,
2*diff_width.v, true, false);
makeLayerGDS(t, exclusionDiffPLayer, "150/20");
makeLayerGDS(t, exclusionDiffNLayer, "150/20");
}
// NPlus and PPlus
int [] patternSlash = new int[] { 0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x0101, // X X
0x0202, // X X
0x0404, // X X
0x0808, // X X
0x1010, // X X
0x2020, // X X
0x4040, // X X
0x8080, // X X
0x0101, // X X
0x0202, // X X
0x0404, // X X
0x0808};
int [] patternBackSlash = new int[] { 0x0202, // X X
0x0101, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x0404, // X X
0x0202, // X X
0x0101, // X X
0x8080, // X X
0x4040, // X X
0x2020, // X X
0x1010, // X X
0x0808, // X X
0x0404};
int[] patternDots = new int[] {
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000, //
0x0202, // X X
0x0000, //
0x2020, // X X
0x0000}; //
int[] patternSparseDots = new int[] {
0x0200, // X
0x0000, //
0x0020, // X
0x0000, //
0x0002, // X
0x0000, //
0x2000, // X
0x0000, //
0x0200, // X
0x0000, //
0x0020, // X
0x0000, //
0x0002, // X
0x0000, //
0x2000, // X
0x0000}; //
// NPlus
graph = new EGraphics(true, true, null, 0, nplus_colour.getRed(), nplus_colour.getGreen(),
nplus_colour.getBlue(), 1, true, patternSlash);
Xml.Layer nplusLayer = makeXmlLayer(t.layers, layer_width, gds_nplus_layer.name, Layer.Function.IMPLANTN, 0, graph,
nplus_width, true, false);
// PPlus
graph = new EGraphics(true, true, null, 0, pplus_colour.getRed(), pplus_colour.getGreen(),
pplus_colour.getBlue(), 1, true, patternDots);
Xml.Layer pplusLayer = makeXmlLayer(t.layers, layer_width, gds_pplus_layer.name, Layer.Function.IMPLANTP, 0, graph,
pplus_width, true, false);
// N-Well
graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(),
nwell_colour.getBlue(), 1, true, patternDots);
Xml.Layer nwellLayer = makeXmlLayer(t.layers, layer_width, gds_nwell_layer.name, Layer.Function.WELLN, 0, graph,
nwell_width, true, false);
// P-Well
graph = new EGraphics(true, true, null, 0, nwell_colour.getRed(), nwell_colour.getGreen(),
nwell_colour.getBlue(), 1, true, patternBackSlash);
Xml.Layer pwellLayer = makeXmlLayer(t.layers, layer_width, "P-Well", Layer.Function.WELLP, 0, graph,
nwell_width, true, false);
// DeviceMark
graph = new EGraphics(false, false, null, 0, 255, 0, 0, 0.4, true, nullPattern);
Xml.Layer deviceMarkLayer = makeXmlLayer(t.layers, layer_width, "DeviceMark", Layer.Function.CONTROL, 0, graph,
nplus_width, true, false);
// Extra layers
if (getExtraInfoFlag())
{
for (LayerInfo info : extraLayers)
{
graph = null;
// either color or template
assert (info.graphicsTemplate == null || info.graphicsColor == null);
if (info.graphicsTemplate != null)
{
// look for layer name and get its EGraphics
for (Xml.Layer l : t.layers)
{
if (l.name.equals(info.graphicsTemplate))
{
graph = l.desc;
break;
}
}
if (graph == null)
System.out.println("No template layer " + info.graphicsTemplate + " found");
}
else if (info.graphicsColor != null)
{
graph = new EGraphics(true, true, info.graphicsOutline, 0,
info.graphicsColor.getRed(), info.graphicsColor.getGreen(), info.graphicsColor.getBlue(),
1, true, info.graphicsPattern);
}
if (graph == null)
graph = new EGraphics(false, false, null, 0, 255, 0, 0, 0.4, true, nullPattern);
Xml.Layer layer = makeXmlLayer(t.layers, layer_width, info.name, Layer.Function.ART, 0, graph,
nplus_width, true, false);
makeLayerGDS(t, layer, String.valueOf(info));
}
}
// Palette elements should be added at the end so they will appear in groups
PaletteGroup[] metalPalette = new PaletteGroup[num_metal_layers];
// write arcs
// metal arcs
for(int i=1; i<=num_metal_layers; i++)
{
double ant = (int)Math.round(metal_antenna_ratio[i-1]) | 200;
PaletteGroup group = new PaletteGroup();
metalPalette[i-1] = group;
group.addArc(makeXmlArc(t, "Metal-"+i, ArcProto.Function.getContact(i), ant,
makeXmlArcLayer(metalLayers.get(i-1), metal_width[i-1])));
}
List<String> portNames = new ArrayList<String>();
/**************************** POLY Nodes/Arcs ***********************************************/
// poly arc
double ant = (int)Math.round(poly_antenna_ratio) | 200;
PaletteGroup polyGroup = new PaletteGroup();
polyGroup.addArc(makeXmlArc(t, polyLayer.name, ArcProto.Function.getPoly(1), ant,
makeXmlArcLayer(polyLayer, poly_width)));
// poly pin
double hla = scaledValue(poly_width.v / 2);
polyGroup.addPin(makeXmlPrimitivePin(t, polyLayer.name, hla, null, // new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, polyLayer, Poly.Type.CROSSED)));
// poly contact
portNames.clear();
portNames.add(polyLayer.name);
portNames.add(metalLayers.get(0).name);
hla = scaledValue((contact_size.v/2 + contact_poly_overhang.v));
Xml.Layer m1Layer = metalLayers.get(0);
double contSize = scaledValue(contact_size.v);
double contSpacing = scaledValue(contact_spacing.v);
double contArraySpacing = scaledValue(contact_array_spacing.v);
double metal1Over = scaledValue(contact_size.v/2 + contact_metal_overhang_all_sides.v);
// only for standard cases when getProtectionPoly() is false
if (!getExtraInfoFlag())
{
polyGroup.addElement(makeContactSeries(t.nodeGroups, polyLayer.name, contSize, polyConLayer, contSpacing, contArraySpacing,
scaledValue(contact_poly_overhang.v), polyLayer,
scaledValue(via_overhang[0].v), m1Layer), null);
}
/**************************** N/P-Diff Nodes/Arcs/Group ***********************************************/
PaletteGroup[] diffPalette = new PaletteGroup[2];
diffPalette[0] = new PaletteGroup(); diffPalette[1] = new PaletteGroup();
// ndiff/pdiff pins
hla = scaledValue((contact_size.v/2 + diff_contact_overhang.v));
double nsel = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nplus_overhang_diff.v);
double psel = scaledValue(contact_size.v/2 + diff_contact_overhang.v + pplus_overhang_diff.v);
double nwell = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nwell_overhang_diff_p.v);
double nso = scaledValue(nwell_overhang_diff_p.v /*+ diff_contact_overhang.v*/); // valid for elements that have nwell layers
double pso = (!pWellFlag)?nso:scaledValue(nplus_overhang_diff.v/* + diff_contact_overhang.v*/);
// ndiff/pdiff contacts
String[] diffNames = {"P", "N"};
double[] sos = {nso, pso};
double[] sels = {psel, nsel};
Xml.Layer[] diffLayers = {diffPLayer, diffNLayer};
Xml.Layer[] plusLayers = {pplusLayer, nplusLayer};
// Active and poly contacts. They are defined first that the Full types
for (Map.Entry<String,List<Contact>> e : otherContacts.entrySet())
{
// generic contacts
String name = null;
for (Contact c : e.getValue())
{
Xml.Layer ly = null, lx = null;
Xml.Layer conLay = diffConLayer;
PaletteGroup g = null;
ContactNode metalLayer = c.layers.get(0);
ContactNode otherLayer = c.layers.get(1);
if (!TextUtils.isANumber(metalLayer.layer)) // horizontal must be!
{
assert (TextUtils.isANumber(otherLayer.layer));
metalLayer = c.layers.get(1);
otherLayer = c.layers.get(0);
}
int m1 = Integer.valueOf(metalLayer.layer);
ly = metalLayers.get(m1-1);
String layerName = otherLayer.layer;
if (layerName.equals(diffLayers[0].name))
{
lx = diffLayers[0];
g = diffPalette[0];
}
else if (layerName.equals(diffLayers[1].name))
{
lx = diffLayers[1];
g = diffPalette[1];
}
else if (layerName.equals(polyLayer.name))
{
lx = polyLayer;
conLay = polyConLayer;
g = polyGroup;
}
else
assert(false); // it should not happen
name = ly.name + "-" + lx.name;
double h1x = scaledValue(contact_size.v/2 + metalLayer.overX.v);
double h1y = scaledValue(contact_size.v/2 + metalLayer.overY.v);
double h2x = scaledValue(contact_size.v/2 + otherLayer.overX.v);
double h2y = scaledValue(contact_size.v/2 + otherLayer.overY.v);
double longX = (Math.abs(metalLayer.overX.v - otherLayer.overX.v));
double longY = (Math.abs(metalLayer.overY.v - otherLayer.overY.v));
portNames.clear();
portNames.add(lx.name);
portNames.add(ly.name);
Xml.NodeLayer extraN = null;
if (c.layers.size() == 3) // easy solution for now
{
ContactNode node = c.layers.get(2);
Xml.Layer lz = (diffLayers[0] == lx) ? plusLayers[0] : plusLayers[1];
double h3x = scaledValue(contact_size.v/2 + node.overX.v);
double h3y = scaledValue(contact_size.v/2 + node.overY.v);
extraN = makeXmlNodeLayer(h3x, h3x, h3y, h3y, lz, Poly.Type.FILLED);
// This assumes no well is defined
longX = (Math.abs(node.overX.v - otherLayer.overX.v));
longY = (Math.abs(node.overY.v - otherLayer.overY.v));
}
longX = scaledValue(longX);
longY = scaledValue(longY);
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String p = (c.prefix == null || c.prefix.equals("")) ? "" : c.prefix + "-";
g.addElement(makeXmlPrimitiveCon(t.nodeGroups, p + name, PrimitiveNode.Function.CONTACT, -1, -1,
new SizeOffset(longX, longX, longY, longY), portNames,
makeXmlNodeLayer(h1x, h1x, h1y, h1y, ly, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(h2x, h2x, h2y, h2y, lx, Poly.Type.FILLED), // layer2
extraN,
makeXmlMulticut(conLay, contSize, contSpacing, contArraySpacing)), c.prefix); // contact
}
}
// ndiff/pdiff contact
for (int i = 0; i < 2; i++)
{
portNames.clear();
portNames.add(diffLayers[i].name);
portNames.add(m1Layer.name);
String composeName = diffNames[i] + "-" + gds_diff_layer.name; //Diff";
Xml.NodeLayer wellNode, wellNodePin;
ArcProto.Function arcF;
Xml.ArcLayer arcL;
WizardField arcVal;
if (i == Technology.P_TYPE)
{
wellNodePin = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.CROSSED);
wellNode = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.FILLED);
arcF = ArcProto.Function.DIFFP;
arcL = makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff_p);
arcVal = pplus_overhang_diff;
}
else
{
wellNodePin = (!pWellFlag)?makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.CROSSED):null;
wellNode = (!pWellFlag)?makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.FILLED):null;
arcF = ArcProto.Function.DIFFN;
arcL = (!pWellFlag)?makeXmlArcLayer(pwellLayer, diff_width, nwell_overhang_diff_p):null;
arcVal = nplus_overhang_diff;
}
PaletteGroup diffG = diffPalette[i];
// active arc
diffG.addArc(makeXmlArc(t, composeName, arcF, 0,
makeXmlArcLayer(diffLayers[i], diff_width),
makeXmlArcLayer(plusLayers[i], diff_width, arcVal),
arcL));
// active pin
diffG.addPin(makeXmlPrimitivePin(t, composeName, hla,
new SizeOffset(sos[i], sos[i], sos[i], sos[i]),
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.CROSSED),
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.CROSSED),
wellNodePin));
// F stands for full (all layers)
diffG.addElement(makeXmlPrimitiveCon(t.nodeGroups, "F-"+composeName, PrimitiveNode.Function.CONTACT,
hla, hla, new SizeOffset(sos[i], sos[i], sos[i], sos[i]), portNames,
makeXmlNodeLayer(metal1Over, metal1Over, metal1Over, metal1Over, m1Layer, Poly.Type.FILLED), // meta1 layer
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.FILLED), // active layer
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.FILLED), // select layer
wellNode, // well layer
makeXmlMulticut(diffConLayer, contSize, contSpacing, contArraySpacing)), "Full-" + diffNames[i]); // contact
}
/**************************** N/P-Well Contacts ***********************************************/
nwell = scaledValue(contact_size.v/2 + diff_contact_overhang.v + nwell_overhang_diff_n.v);
nso = scaledValue(/*diff_contact_overhang.v +*/ nwell_overhang_diff_n.v); // valid for elements that have nwell layers
pso = (!pWellFlag)?nso:scaledValue(/*diff_contact_overhang.v +*/ nplus_overhang_diff.v);
double[] wellSos = {pso, nso};
PaletteGroup[] wellPalette = new PaletteGroup[2];
Xml.Layer[] wellLayers = {pwellLayer, nwellLayer};
// nwell/pwell contact
for (int i = 0; i < 2; i++)
{
String composeName = diffNames[i] + "-Well";
Xml.NodeLayer wellNodeLayer = null, wellNodePinLayer = null;
PaletteGroup g = new PaletteGroup();
PrimitiveNode.Function func = null;
Xml.ArcLayer arcL;
WizardField arcVal;
wellPalette[i] = g;
portNames.clear();
if (i == Technology.P_TYPE)
{
if (!pWellFlag)
{
portNames.add(pwellLayer.name);
wellNodePinLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.CROSSED);
wellNodeLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, pwellLayer, Poly.Type.FILLED);
}
func = PrimitiveNode.Function.WELL;
arcL = (!pWellFlag)?makeXmlArcLayer(pwellLayer, diff_width, nwell_overhang_diff_p):null;
arcVal = pplus_overhang_diff;
}
else
{
portNames.add(nwellLayer.name);
wellNodePinLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.CROSSED);
wellNodeLayer = makeXmlNodeLayer(nwell, nwell, nwell, nwell, nwellLayer, Poly.Type.FILLED);
func = PrimitiveNode.Function.SUBSTRATE;
arcL = makeXmlArcLayer(nwellLayer, diff_width, nwell_overhang_diff_p);
arcVal = nplus_overhang_diff;
}
portNames.add(m1Layer.name);
// simple arc. S for simple
g.addArc(makeXmlArc(t, "S-"+composeName, ArcProto.Function.WELL, 0,
makeXmlArcLayer(wellLayers[i], diff_width, nwell_overhang_diff_p)));
// three layers arcs
g.addArc(makeXmlArc(t, composeName, ArcProto.Function.WELL, 0,
makeXmlArcLayer(diffLayers[i], diff_width),
makeXmlArcLayer(plusLayers[i], diff_width, arcVal),
arcL));
// well pin
g.addPin(makeXmlPrimitivePin(t, composeName, hla,
new SizeOffset(wellSos[i], wellSos[i], wellSos[i], wellSos[i]),
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.CROSSED),
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.CROSSED),
wellNodePinLayer));
// well contact
// F stands for full
g.addElement(makeXmlPrimitiveCon(t.nodeGroups, "F-"+composeName, func,
hla, hla, new SizeOffset(wellSos[i], wellSos[i], wellSos[i], wellSos[i]), portNames,
makeXmlNodeLayer(metal1Over, metal1Over, metal1Over, metal1Over, m1Layer, Poly.Type.FILLED), // meta1 layer
makeXmlNodeLayer(hla, hla, hla, hla, diffLayers[i], Poly.Type.FILLED), // active layer
makeXmlNodeLayer(sels[i], sels[i], sels[i], sels[i], plusLayers[i], Poly.Type.FILLED), // select layer
wellNodeLayer, // well layer
makeXmlMulticut(diffConLayer, contSize, contSpacing, contArraySpacing)), "Full-"+diffNames[i] + "W"); // contact
}
/**************************** Metals Nodes/Arcs ***********************************************/
// Pins and contacts
for(int i=1; i<num_metal_layers; i++)
{
hla = scaledValue(metal_width[i-1].v / 2);
Xml.Layer lb = metalLayers.get(i-1);
Xml.Layer lt = metalLayers.get(i);
PaletteGroup group = metalPalette[i-1]; // structure created by the arc definition
// Pin bottom metal
group.addPin(makeXmlPrimitivePin(t, lb.name, hla, null, //new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, lb, Poly.Type.CROSSED)));
if (i == num_metal_layers - 1) // last pin!
{
metalPalette[i].addPin(makeXmlPrimitivePin(t, lt.name, hla, null, //new SizeOffset(hla, hla, hla, hla),
makeXmlNodeLayer(hla, hla, hla, hla, lt, Poly.Type.CROSSED)));
}
if (!getExtraInfoFlag())
{
// original contact Square
// via
Xml.Layer via = viaLayers.get(i-1);
double viaSize = scaledValue(via_size[i-1].v);
double viaSpacing = scaledValue(via_inline_spacing[i-1].v);
double viaArraySpacing = scaledValue(via_array_spacing[i-1].v);
String name = lb.name + "-" + lt.name;
double longDist = scaledValue(via_overhang[i-1].v);
group.addElement(makeContactSeries(t.nodeGroups, name, viaSize, via, viaSpacing, viaArraySpacing,
longDist, lt, longDist, lb), null);
}
}
// metal contacts
for (Map.Entry<String,List<Contact>> e : metalContacts.entrySet())
{
// generic contacts
for (Contact c : e.getValue())
{
// We know those layer names are numbers!
assert(c.layers.size() == 2);
ContactNode verticalLayer = c.layers.get(0);
ContactNode horizontalLayer = c.layers.get(1);
int i = Integer.valueOf(verticalLayer.layer);
int j = Integer.valueOf(horizontalLayer.layer);
Xml.Layer ly = metalLayers.get(i-1);
Xml.Layer lx = metalLayers.get(j-1);
String name = (j>i)?ly.name + "-" + lx.name:lx.name + "-" + ly.name;
int via = (j>i)?i:j;
double metalContSize = scaledValue(via_size[via-1].v);
double spacing = scaledValue(via_inline_spacing[via-1].v);
double arraySpacing = scaledValue(via_array_spacing[via-1].v);
Xml.Layer metalConLayer = viaLayers.get(via-1);
double h1x = scaledValue(via_size[via-1].v/2 + verticalLayer.overX.v);
double h1y = scaledValue(via_size[via-1].v/2 + verticalLayer.overY.v);
double h2x = scaledValue(via_size[via-1].v/2 + horizontalLayer.overX.v);
double h2y = scaledValue(via_size[via-1].v/2 + horizontalLayer.overY.v);
// double longX = scaledValue(DBMath.isGreaterThan(verticalLayer.overX.v, horizontalLayer.overX.v) ? verticalLayer.overX.v : horizontalLayer.overX.v);
// double longY = scaledValue(DBMath.isGreaterThan(verticalLayer.overY.v, horizontalLayer.overY.v) ? verticalLayer.overY.v : horizontalLayer.overY.v);
double longX = scaledValue(Math.abs(verticalLayer.overX.v - horizontalLayer.overX.v));
double longY = scaledValue(Math.abs(verticalLayer.overY.v - horizontalLayer.overY.v));
portNames.clear();
portNames.add(lx.name);
portNames.add(ly.name);
// some primitives might not have prefix. "-" should not be in the prefix to avoid
// being displayed in the palette
String p = (c.prefix == null || c.prefix.equals("")) ? "" : c.prefix + "-";
metalPalette[via-1].addElement(makeXmlPrimitiveCon(t.nodeGroups, p + name, PrimitiveNode.Function.CONTACT, -1, -1,
new SizeOffset(longX, longX, longY, longY),
portNames,
makeXmlNodeLayer(h1x, h1x, h1y, h1y, ly, Poly.Type.FILLED), // layer1
makeXmlNodeLayer(h2x, h2x, h2y, h2y, lx, Poly.Type.FILLED), // layer2
makeXmlMulticut(metalConLayer, metalContSize, spacing, arraySpacing)), c.prefix); // contact
}
}
/**************************** Transistors ***********************************************/
/** Transistors **/
// write the transistors
List<Xml.NodeLayer> nodesList = new ArrayList<Xml.NodeLayer>();
List<Xml.PrimitivePort> nodePorts = new ArrayList<Xml.PrimitivePort>();
EPoint minFullSize = null; //EPoint.fromLambda(0, 0); // default zero horizontalFlag
PaletteGroup[] transPalette = new PaletteGroup[2];
for(int i = 0; i < 2; i++)
{
String name;
double selecty = 0, selectx = 0;
Xml.Layer wellLayer = null, activeLayer, selectLayer;
double sox = 0, soy = 0;
double impx = scaledValue((gate_width.v)/2);
double impy = scaledValue((gate_length.v+diff_poly_overhang.v*2)/2);
double nwell_overhangX = 0, nwell_overhangY = 0;
PaletteGroup g = new PaletteGroup();
transPalette[i] = g;
double protectDist = scaledValue(poly_protection_spacing.v);
double extraSelX = 0, extraSelY = 0;
PrimitiveNode.Function func = null;
if (i==Technology.P_TYPE)
{
name = "P";
nwell_overhangY = nwell_overhangX = nwell_overhang_diff_n.v;
wellLayer = nwellLayer;
activeLayer = diffPLayer;
selectLayer = pplusLayer;
extraSelX = pplus_overhang_poly.v;
extraSelY = pplus_overhang_diff.v;
func = PrimitiveNode.Function.TRAPMOS;
}
else
{
name = "N";
activeLayer = diffNLayer;
selectLayer = nplusLayer;
extraSelX = nplus_overhang_poly.v;
extraSelY = nplus_overhang_diff.v;
func = PrimitiveNode.Function.TRANMOS;
if (!pWellFlag)
{
nwell_overhangY = nwell_overhangX = nwell_overhang_diff_p.v;
wellLayer = pwellLayer;
}
else
{
nwell_overhangX = poly_endcap.v+extraSelX;
nwell_overhangY = extraSelY;
}
}
selectx = scaledValue(gate_width.v/2+poly_endcap.v+extraSelX);
selecty = scaledValue(gate_length.v/2+diff_poly_overhang.v+extraSelY);
// Using P values in transistors
double wellx = scaledValue((gate_width.v/2+nwell_overhangX));
double welly = scaledValue((gate_length.v/2+diff_poly_overhang.v+nwell_overhangY));
sox = scaledValue(nwell_overhangX);
soy = scaledValue(diff_poly_overhang.v+nwell_overhangY);
if (DBMath.isLessThan(wellx, selectx))
{
sox = scaledValue(poly_endcap.v+extraSelX);
wellx = selectx;
}
if (DBMath.isLessThan(welly, selecty))
{
soy = scaledValue(diff_poly_overhang.v+extraSelY);
welly = selecty;
}
nodesList.clear();
nodePorts.clear();
portNames.clear();
// Gate layer Electrical
double gatey = scaledValue(gate_length.v/2);
double gatex = impx;
// Poly layers
// left electrical
double endPolyx = scaledValue((gate_width.v+poly_endcap.v*2)/2);
double endPolyy = gatey;
double endLeftOrRight = -impx; // for horizontal transistors. Default
double endTopOrBotton = endPolyy; // for horizontal transistors. Default
double diffX = 0, diffY = scaledValue(gate_length.v/2+gate_contact_spacing.v+contact_size.v/2); // impy
double xSign = 1, ySign = -1;
double polyX = endPolyx, polyY = 0;
if (!horizontalFlag) // swap the numbers to get vertical transistors
{
double tmp;
tmp = impx; impx = impy; impy = tmp;
tmp = wellx; wellx = welly; welly = tmp;
tmp = sox; sox = soy; soy = tmp;
tmp = selectx; selectx = selecty; selecty = tmp;
tmp = gatex; gatex = gatey; gatey = tmp;
tmp = endPolyx; endPolyx = endPolyy; endPolyy = tmp;
tmp = diffX; diffX = diffY; diffY = tmp;
tmp = polyX; polyX = polyY; polyY = tmp;
tmp = xSign; xSign = ySign; ySign = tmp;
endLeftOrRight = endPolyx;
endTopOrBotton = -impx;
}
// Well layer
Xml.NodeLayer xTranWellLayer = null;
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(wellx, wellx, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
// Active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, impy, activeLayer, Poly.Type.FILLED, true, false, -1));
// electrical active layers
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, impy, 0, activeLayer, Poly.Type.FILLED, false, true, 3)); // bottom
nodesList.add(makeXmlNodeLayerSpecial(impx, impx, 0, impy, activeLayer, Poly.Type.FILLED, false, true, 1)); // top
// Diff port
portNames.clear();
portNames.add(activeLayer.name);
Xml.PrimitivePort diffTopPort = makeXmlPrimitivePort("diff-top", 90, 90, 1, minFullSize,
diffX, -1, diffX, 1, diffY, 1, diffY, 1, portNames);
// bottom port
Xml.PrimitivePort diffBottomPort = makeXmlPrimitivePort("diff-bottom", 270, 90, 2, minFullSize,
xSign*diffX, -1, xSign*diffX, 1, ySign*diffY, -1, ySign*diffY, -1, portNames);
// Electric layers
// Gate layer Electrical
nodesList.add(makeXmlNodeLayerSpecial(gatex, gatex, gatey, gatey, polyGateLayer, Poly.Type.FILLED, false, true, -1));
// Poly layers
// left electrical
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endLeftOrRight, endPolyy, endTopOrBotton, polyLayer,
Poly.Type.FILLED, false, true, 0));
// right electrical
nodesList.add(makeXmlNodeLayerSpecial(endLeftOrRight, endPolyx, endTopOrBotton, endPolyy, polyLayer,
Poly.Type.FILLED, false, true, 2));
// non-electrical poly (just one poly layer)
nodesList.add(makeXmlNodeLayerSpecial(endPolyx, endPolyx, endPolyy, endPolyy, polyLayer, Poly.Type.FILLED, true, false, -1));
// Poly port
portNames.clear();
portNames.add(polyLayer.name);
Xml.PrimitivePort polyLeftPort = makeXmlPrimitivePort("poly-left", 180, 90, 0, minFullSize,
ySign*polyX, -1, ySign*polyX,
-1, xSign*polyY, -1, xSign*polyY, 1, portNames);
// right port
Xml.PrimitivePort polyRightPort = makeXmlPrimitivePort("poly-right", 0, 180, 0, minFullSize,
polyX, 1, polyX, 1, polyY, -1, polyY, 1, portNames);
// Select layer
Xml.NodeLayer xTranSelLayer = (makeXmlNodeLayer(selectx, selectx, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
//One (undocumented) requirement of transistors is that the ports must appear in the
//order: Poly-left, Diff-top, Poly-right, Diff-bottom. This requirement is
//because of the methods Technology.getTransistorGatePort(),
//Technology.getTransistorAltGatePort(), Technology.getTransistorSourcePort(),
//and Technology.getTransistorDrainPort().
// diff-top = 1, diff-bottom = 2, polys=0
// ports in the correct order: Poly-left, Diff-top, Poly-right, Diff-bottom
nodePorts.add(polyLeftPort);
nodePorts.add(diffTopPort);
nodePorts.add(polyRightPort);
nodePorts.add(diffBottomPort);
// Standard Transistor
Xml.PrimitiveNodeGroup n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
// Extra transistors which don't have select nor well
// Extra protection poly. No ports are necessary.
if (getExtraInfoFlag())
{
// removing well and select for simplicity
// nodesList.remove(xTranSelLayer);
// nodesList.remove(xTranWellLayer);
// // new sox and soy
// sox = scaledValue(poly_endcap.v);
// soy = scaledValue(diff_poly_overhang.v);
// n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-S", PrimitiveNode.Function.TRANMOS, 0, 0, 0, 0,
// new SizeOffset(sox, sox, soy, soy), nodesListW, nodePorts, null, false);
// g.addElement(n);
/*************************************/
// Short transistors
// Adding extra transistors whose select and well are aligned with poly along the X axis
nodesList.remove(xTranSelLayer);
double shortSelectX = scaledValue(gate_width.v/2+poly_endcap.v);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
double shortSox = sox;
shortSox = scaledValue(poly_endcap.v);
if (wellLayer != null)
{
nodesList.remove(xTranWellLayer);
xTranWellLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-S", func, 0, 0, 0, 0,
new SizeOffset(shortSox, shortSox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-S");
/*************************************/
// Transistors with extra polys
// different select for those with extra protection layers
nodesList.remove(xTranSelLayer);
double endOfProtectionY = gate_length.v + poly_protection_spacing.v;
double selectExtraY = scaledValue(gate_length.v/2 + endOfProtectionY + extraSelX); // actually is extraSelX because of the poly distance!
xTranSelLayer = (makeXmlNodeLayer(selectx, selectx, selectExtraY, selectExtraY, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// not sure which condition to apply. It doesn't apply nwell_overhang_diff due to the extra poly
if (DBMath.isLessThan(welly, selectExtraY))
{
welly = selectExtraY;
soy = scaledValue(endOfProtectionY + extraSelX);
}
if (wellLayer != null)
{
nodesList.remove(xTranWellLayer);
xTranWellLayer = (makeXmlNodeLayer(wellx, wellx, welly, welly, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
if (!horizontalFlag)
{
System.out.println("Not working with !horizontal");
assert(false);
}
portNames.clear();
portNames.add(polyLayer.name);
// bottom or left
Xml.NodeLayer bOrL = (makeXmlNodeLayerSpecial(gatex, gatex,
DBMath.round((protectDist + 3*endPolyy)),
-DBMath.round(endPolyy + protectDist),
polyLayer, Poly.Type.FILLED, true, false, -1/*3*/)); // port 3 for left/bottom extra poly lb=left bottom
// Adding left
nodesList.add(bOrL);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-B", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-B");
// top or right
Xml.NodeLayer tOrR = (makeXmlNodeLayerSpecial(gatex, gatex,
-DBMath.round(endPolyy + protectDist),
DBMath.round((protectDist + 3*endPolyy)),
polyLayer, Poly.Type.FILLED, true, false, -1/*4*/)); // port 4 for right/top extra poly rt=right top
// Adding both
nodesList.add(tOrR);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-TB", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name + "-TB");
// Adding right
nodesList.remove(bOrL);
n = makeXmlPrimitive(t.nodeGroups, name + "-Transistor-T", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name +"-T");
/*************************************/
// Short transistors woth OD18
double od18x = scaledValue(gate_od18_width.v/2+od18_diff_overhang[0].v);
double od18y = scaledValue(gate_od18_length.v/2+diff_poly_overhang.v+od18_diff_overhang[1].v);
nodePorts.clear();
nodesList.clear();
prepareTransistor(gate_od18_width.v, gate_od18_length.v, poly_endcap.v, diff_poly_overhang.v,
gate_contact_spacing.v, contact_size.v, activeLayer, polyLayer, polyGateLayer, nodesList, nodePorts);
// OD18
Xml.Layer od18Layer = t.findLayer("OD_18");
nodesList.add(makeXmlNodeLayer(od18x, od18x, od18y, od18y, od18Layer, Poly.Type.FILLED));
// adding short select
shortSelectX = scaledValue(gate_od18_width.v/2+poly_endcap.v);
selecty = scaledValue(gate_od18_length.v/2+diff_poly_overhang.v+extraSelY);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// adding well
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(od18x, od18x, od18y, od18y, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
sox = scaledValue(od18_diff_overhang[0].v);
soy = scaledValue(diff_poly_overhang.v+od18_diff_overhang[1].v);
n = makeXmlPrimitive(t.nodeGroups, "OD18-" + name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
/*************************************/
// Short transistors with native
if (i==Technology.N_TYPE)
{
double ntx = scaledValue(gate_nt_width.v/2+nt_diff_overhang.v);
double nty = scaledValue(gate_nt_length.v/2+diff_poly_overhang.v+nt_diff_overhang.v);
nodePorts.clear();
nodesList.clear();
prepareTransistor(gate_nt_width.v, gate_nt_length.v, poly_nt_endcap.v, diff_poly_overhang.v,
gate_contact_spacing.v, contact_size.v, activeLayer, polyLayer, polyGateLayer, nodesList, nodePorts);
// NT-N
Xml.Layer ntLayer = t.findLayer("NT-N");
nodesList.add(makeXmlNodeLayer(ntx, ntx, nty, nty, ntLayer, Poly.Type.FILLED));
// adding short select
shortSelectX = scaledValue(gate_nt_width.v/2+poly_nt_endcap.v);
selecty = scaledValue(gate_nt_length.v/2+diff_poly_overhang.v+extraSelY);
xTranSelLayer = (makeXmlNodeLayer(shortSelectX, shortSelectX, selecty, selecty, selectLayer, Poly.Type.FILLED));
nodesList.add(xTranSelLayer);
// adding well
if (wellLayer != null)
{
xTranWellLayer = (makeXmlNodeLayer(ntx, ntx, nty, nty, wellLayer, Poly.Type.FILLED));
nodesList.add(xTranWellLayer);
}
sox = scaledValue(poly_nt_endcap.v);
soy = scaledValue(diff_poly_overhang.v+nt_diff_overhang.v);
n = makeXmlPrimitive(t.nodeGroups, "NT-" + name + "-Transistor", func, 0, 0, 0, 0,
new SizeOffset(sox, sox, soy, soy), nodesList, nodePorts, null, false);
g.addElement(n, name);
}
}
}
// Aggregating all palette groups into one
List<PaletteGroup> allGroups = new ArrayList<PaletteGroup>();
allGroups.add(transPalette[0]); allGroups.add(transPalette[1]);
allGroups.add(diffPalette[0]); allGroups.add(diffPalette[1]);
allGroups.add(wellPalette[0]); allGroups.add(wellPalette[1]);
allGroups.add(polyGroup);
for (PaletteGroup g : metalPalette)
allGroups.add(g);
// Adding elements in palette
for (PaletteGroup o : allGroups)
{
t.menuPalette.menuBoxes.add(o.arcs); // arcs
t.menuPalette.menuBoxes.add(o.pins); // pins
t.menuPalette.menuBoxes.add(o.elements); // contacts
}
// Writting GDS values
makeLayerGDS(t, diffPLayer, String.valueOf(gds_diff_layer));
makeLayerGDS(t, diffNLayer, String.valueOf(gds_diff_layer));
makeLayerGDS(t, pplusLayer, String.valueOf(gds_pplus_layer));
makeLayerGDS(t, nplusLayer, String.valueOf(gds_nplus_layer));
makeLayerGDS(t, nwellLayer, String.valueOf(gds_nwell_layer));
makeLayerGDS(t, deviceMarkLayer, String.valueOf(gds_marking_layer));
makeLayerGDS(t, polyConLayer, String.valueOf(gds_contact_layer));
makeLayerGDS(t, diffConLayer, String.valueOf(gds_contact_layer));
makeLayerGDS(t, polyLayer, String.valueOf(gds_poly_layer));
makeLayerGDS(t, polyGateLayer, String.valueOf(gds_poly_layer));
for (int i = 0; i < num_metal_layers; i++) {
Xml.Layer met = metalLayers.get(i);
makeLayerGDS(t, met, String.valueOf(gds_metal_layer[i]));
if (getExtraInfoFlag())
{
// Type is always 1
makeLayerGDS(t, dummyMetalLayers.get(i), gds_metal_layer[i].value + "/1");
// exclusion always takes 150
makeLayerGDS(t, exclusionMetalLayers.get(i), "150/" + (i + 1));
}
if (i > num_metal_layers - 2) continue;
Xml.Layer via = viaLayers.get(i);
makeLayerGDS(t, via, String.valueOf(gds_via_layer[i]));
}
// Writting Layer Rules
for (Xml.Layer l : diffLayers)
{
makeLayerRuleMinWid(t, l, diff_width);
makeLayersRule(t, l, DRCTemplate.DRCRuleType.SPACING, diff_spacing);
}
WizardField[] plus_diff = {pplus_overhang_diff, nplus_overhang_diff};
WizardField[] plus_width = {pplus_width, nplus_width};
WizardField[] plus_spacing = {pplus_spacing, nplus_spacing};
for (int i = 0; i < plusLayers.length; i++)
{
makeLayerRuleMinWid(t, plusLayers[i], plus_width[i]);
makeLayersRuleSurround(t, plusLayers[i], diffLayers[i], plus_diff[i]);
makeLayersRule(t, plusLayers[i], DRCTemplate.DRCRuleType.SPACING, plus_spacing[i]);
}
Xml.Layer[] wells = {pwellLayer, nwellLayer};
for (Xml.Layer w : wells)
{
makeLayerRuleMinWid(t, w, nwell_width);
makeLayersRuleSurround(t, w, diffPLayer, nwell_overhang_diff_p);
makeLayersRuleSurround(t, w, diffNLayer, nwell_overhang_diff_n);
makeLayersRule(t, w, DRCTemplate.DRCRuleType.SPACING, nwell_spacing);
}
Xml.Layer[] polys = {polyLayer, polyGateLayer};
for (Xml.Layer w : polys)
{
makeLayerRuleMinWid(t, w, poly_width);
makeLayersRule(t, w, DRCTemplate.DRCRuleType.SPACING, poly_spacing);
}
for (int i = 0; i < num_metal_layers; i++) {
Xml.Layer met = metalLayers.get(i);
makeLayerRuleMinWid(t, met, metal_width[i]);
if (i >= num_metal_layers - 1) continue;
Xml.Layer via = viaLayers.get(i);
makeLayerRuleMinWid(t, via, via_size[i]);
makeLayersRule(t, via, DRCTemplate.DRCRuleType.CONSPA, via_inline_spacing[i]);
makeLayersRule(t, via, DRCTemplate.DRCRuleType.UCONSPA2D, via_array_spacing[i]);
}
// Finish menu with Pure, Misc and Cell
List<Object> l = new ArrayList<Object>();
l.add(new String("Pure"));
t.menuPalette.menuBoxes.add(l);
l = new ArrayList<Object>();
l.add(new String("Misc."));
t.menuPalette.menuBoxes.add(l);
l = new ArrayList<Object>();
l.add(new String("Cell"));
t.menuPalette.menuBoxes.add(l);
// write finally the file
boolean includeDateAndVersion = User.isIncludeDateAndVersionInOutput();
String copyrightMessage = IOTool.isUseCopyrightMessage() ? IOTool.getCopyrightMessage() : null;
t.writeXml(fileName, includeDateAndVersion, copyrightMessage);
}
|
diff --git a/src/com/itmill/toolkit/terminal/gwt/client/ui/IButton.java b/src/com/itmill/toolkit/terminal/gwt/client/ui/IButton.java
index ce230247e..74b211bb0 100644
--- a/src/com/itmill/toolkit/terminal/gwt/client/ui/IButton.java
+++ b/src/com/itmill/toolkit/terminal/gwt/client/ui/IButton.java
@@ -1,136 +1,144 @@
package com.itmill.toolkit.terminal.gwt.client.ui;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;
import com.itmill.toolkit.terminal.gwt.client.ApplicationConnection;
import com.itmill.toolkit.terminal.gwt.client.ErrorMessage;
import com.itmill.toolkit.terminal.gwt.client.Paintable;
import com.itmill.toolkit.terminal.gwt.client.UIDL;
public class IButton extends Button implements Paintable {
public static final String CLASSNAME = "i-button";
String id;
ApplicationConnection client;
private Element errorIndicatorElement;
private Element captionElement = DOM.createSpan();
private ErrorMessage errorMessage;
private Icon icon;
public IButton() {
setStyleName(CLASSNAME);
DOM.appendChild(getElement(), captionElement);
addClickListener(new ClickListener() {
public void onClick(Widget sender) {
if (id == null || client == null) {
return;
}
/*
* TODO isolata workaround. Safari don't always seem to fire
* onblur previously focused component before button is clicked.
*/
IButton.this.setFocus(true);
client.updateVariable(id, "state", true, true);
}
});
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation,
// but don't let container manage caption etc.
if (client.updateComponent(this, uidl, false)) {
return;
}
// Save details
this.client = client;
id = uidl.getId();
// Set text
setText(uidl.getStringAttribute("caption"));
// handle error
if (uidl.hasAttribute("error")) {
UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
sinkEvents(Event.MOUSEEVENTS);
}
DOM.insertChild(getElement(), errorIndicatorElement, 0);
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
- DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
+ DOM.removeChild(getElement(), errorIndicatorElement);
+ errorIndicatorElement = null;
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.insertChild(getElement(), icon.getElement(), 0);
}
icon.setUri(uidl.getStringAttribute("icon"));
+ } else {
+ if (icon != null) {
+ DOM.removeChild(getElement(), icon.getElement());
+ icon = null;
+ }
}
// handle description
if (uidl.hasAttribute("description")) {
setTitle(uidl.getStringAttribute("description"));
+ } else {
+ setTitle(null);
}
}
public void setText(String text) {
DOM.setInnerText(captionElement, text);
}
public void onBrowserEvent(Event event) {
Element target = DOM.eventGetTarget(event);
if (errorIndicatorElement != null
&& DOM.compare(target, errorIndicatorElement)) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEOVER:
showErrorMessage();
break;
case Event.ONMOUSEOUT:
hideErrorMessage();
break;
case Event.ONCLICK:
ApplicationConnection.getConsole().log(
DOM.getInnerHTML(errorMessage.getElement()));
return;
default:
break;
}
}
super.onBrowserEvent(event);
}
private void hideErrorMessage() {
errorMessage.hide();
}
private void showErrorMessage() {
if (errorMessage != null) {
errorMessage.showAt(errorIndicatorElement);
}
}
}
| false | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation,
// but don't let container manage caption etc.
if (client.updateComponent(this, uidl, false)) {
return;
}
// Save details
this.client = client;
id = uidl.getId();
// Set text
setText(uidl.getStringAttribute("caption"));
// handle error
if (uidl.hasAttribute("error")) {
UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
sinkEvents(Event.MOUSEEVENTS);
}
DOM.insertChild(getElement(), errorIndicatorElement, 0);
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
DOM.setStyleAttribute(errorIndicatorElement, "display", "none");
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.insertChild(getElement(), icon.getElement(), 0);
}
icon.setUri(uidl.getStringAttribute("icon"));
}
// handle description
if (uidl.hasAttribute("description")) {
setTitle(uidl.getStringAttribute("description"));
}
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
// Ensure correct implementation,
// but don't let container manage caption etc.
if (client.updateComponent(this, uidl, false)) {
return;
}
// Save details
this.client = client;
id = uidl.getId();
// Set text
setText(uidl.getStringAttribute("caption"));
// handle error
if (uidl.hasAttribute("error")) {
UIDL errorUidl = uidl.getErrors();
if (errorIndicatorElement == null) {
errorIndicatorElement = DOM.createDiv();
DOM.setElementProperty(errorIndicatorElement, "className",
"i-errorindicator");
DOM.sinkEvents(errorIndicatorElement, Event.MOUSEEVENTS);
sinkEvents(Event.MOUSEEVENTS);
}
DOM.insertChild(getElement(), errorIndicatorElement, 0);
if (errorMessage == null) {
errorMessage = new ErrorMessage();
}
errorMessage.updateFromUIDL(errorUidl);
} else if (errorIndicatorElement != null) {
DOM.removeChild(getElement(), errorIndicatorElement);
errorIndicatorElement = null;
}
if (uidl.hasAttribute("icon")) {
if (icon == null) {
icon = new Icon(client);
DOM.insertChild(getElement(), icon.getElement(), 0);
}
icon.setUri(uidl.getStringAttribute("icon"));
} else {
if (icon != null) {
DOM.removeChild(getElement(), icon.getElement());
icon = null;
}
}
// handle description
if (uidl.hasAttribute("description")) {
setTitle(uidl.getStringAttribute("description"));
} else {
setTitle(null);
}
}
|
diff --git a/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/DataSourceSelectionPanel.java b/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/DataSourceSelectionPanel.java
index 4f22df108..32194e1b1 100644
--- a/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/DataSourceSelectionPanel.java
+++ b/obdalib/obdalib-core/src/main/java/it/unibz/krdb/obda/gui/swing/panel/DataSourceSelectionPanel.java
@@ -1,182 +1,183 @@
/*
* To change this template, choose Tools | Templates and open the template in
* the editor.
*/
package it.unibz.krdb.obda.gui.swing.panel;
import it.unibz.krdb.obda.model.DataSource;
import it.unibz.krdb.obda.model.DatasourcesController;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import javax.swing.JOptionPane;
/**
*
* @author obda
*/
public class DataSourceSelectionPanel extends javax.swing.JPanel {
/**
*
*/
private static final long serialVersionUID = -8124338850871507250L;
private DatasourcesController dscontroller = null;
private DatasourceSelector selector = null;
/** Creates new form DataSourceSelectionPanel */
public DataSourceSelectionPanel(DatasourcesController dscontroller) {
this.dscontroller = dscontroller;
initComponents();
init();
setDatasourcesController(dscontroller);
}
/***
* Changes the datasource controller associated to this selector. This will
* remove and update listeners and reset the content of the combo box.
*
* @param dsc
*/
public void setDatasourcesController(DatasourcesController dsc) {
/* removing listeners and references to the old */
dscontroller.removeDatasourceControllerListener(selector);
dscontroller = dsc;
selector.setDatasourceController(dsc);
/* setup the new listener */
dscontroller.addDatasourceControllerListener(selector);
}
public DatasourceSelector getDataSourceSelector() {
return selector;
}
private void init() {
selector = new DatasourceSelector(dscontroller);
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 0, 0);
add(selector, gridBagConstraints);
dscontroller.addDatasourceControllerListener(selector);
jButtonAdd.setText("Insert");
jButtonAdd.setMnemonic('i');
jButtonAdd.setToolTipText("Add a new datasource");
jButtonAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButtonAdd.setContentAreaFilled(false);
jButtonAdd.setIconTextGap(0);
- jButtonAdd.setMinimumSize(new java.awt.Dimension(50, 15));
+ jButtonAdd.setMaximumSize(new java.awt.Dimension(60, 30));
+ jButtonAdd.setMinimumSize(new java.awt.Dimension(50, 20));
jButtonAdd.setPreferredSize(new java.awt.Dimension(50, 20));
jButtonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
jButtonRemove.setText("Delete");
jButtonRemove.setMnemonic('d');
jButtonRemove.setToolTipText("Remove the selected datasource");
jButtonRemove.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButtonRemove.setContentAreaFilled(false);
jButtonRemove.setIconTextGap(0);
jButtonRemove.setMaximumSize(new java.awt.Dimension(60, 30));
- jButtonRemove.setMinimumSize(new java.awt.Dimension(50, 18));
+ jButtonRemove.setMinimumSize(new java.awt.Dimension(50, 20));
jButtonRemove.setPreferredSize(new java.awt.Dimension(50, 20));
jButtonRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
DataSource ds = selector.getSelectedDataSource();
if (ds != null) {
dscontroller.removeDataSource(ds.getSourceID());
}
}
});
jLabeltitle.setBackground(new java.awt.Color(153, 153, 153));
jLabeltitle.setFont(new java.awt.Font("Arial", 1, 11));
jLabeltitle.setForeground(new java.awt.Color(153, 153, 153));
jLabeltitle.setPreferredSize(new Dimension(119, 14));
}
private void addButtonActionPerformed(ActionEvent evt) {
String name = JOptionPane.showInputDialog(
"Insert the URI of the new data source.\n"
+ "The URI should be a unique idenfier for the data souce\n"
+ "not the connection url or the actual data source name.", null).trim();
if (!name.isEmpty()) {
URI uri = URI.create(name);
if (!dscontroller.isExisted(uri)) {
dscontroller.addDataSource(name);
}
else {
JOptionPane.showMessageDialog(this,
"The data source ID is already existed!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* 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() {
java.awt.GridBagConstraints gridBagConstraints;
jButtonAdd = new javax.swing.JButton();
jButtonRemove = new javax.swing.JButton();
jLabeltitle = new javax.swing.JLabel();
setBorder(javax.swing.BorderFactory.createTitledBorder("Datasource Selection"));
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jButtonAdd, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jButtonRemove, gridBagConstraints);
jLabeltitle.setText("Select datasource:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
add(jLabeltitle, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonAdd;
private javax.swing.JButton jButtonRemove;
private javax.swing.JLabel jLabeltitle;
// private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
| false | true | private void init() {
selector = new DatasourceSelector(dscontroller);
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 0, 0);
add(selector, gridBagConstraints);
dscontroller.addDatasourceControllerListener(selector);
jButtonAdd.setText("Insert");
jButtonAdd.setMnemonic('i');
jButtonAdd.setToolTipText("Add a new datasource");
jButtonAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButtonAdd.setContentAreaFilled(false);
jButtonAdd.setIconTextGap(0);
jButtonAdd.setMinimumSize(new java.awt.Dimension(50, 15));
jButtonAdd.setPreferredSize(new java.awt.Dimension(50, 20));
jButtonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
jButtonRemove.setText("Delete");
jButtonRemove.setMnemonic('d');
jButtonRemove.setToolTipText("Remove the selected datasource");
jButtonRemove.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButtonRemove.setContentAreaFilled(false);
jButtonRemove.setIconTextGap(0);
jButtonRemove.setMaximumSize(new java.awt.Dimension(60, 30));
jButtonRemove.setMinimumSize(new java.awt.Dimension(50, 18));
jButtonRemove.setPreferredSize(new java.awt.Dimension(50, 20));
jButtonRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
DataSource ds = selector.getSelectedDataSource();
if (ds != null) {
dscontroller.removeDataSource(ds.getSourceID());
}
}
});
jLabeltitle.setBackground(new java.awt.Color(153, 153, 153));
jLabeltitle.setFont(new java.awt.Font("Arial", 1, 11));
jLabeltitle.setForeground(new java.awt.Color(153, 153, 153));
jLabeltitle.setPreferredSize(new Dimension(119, 14));
}
| private void init() {
selector = new DatasourceSelector(dscontroller);
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(2, 5, 0, 0);
add(selector, gridBagConstraints);
dscontroller.addDatasourceControllerListener(selector);
jButtonAdd.setText("Insert");
jButtonAdd.setMnemonic('i');
jButtonAdd.setToolTipText("Add a new datasource");
jButtonAdd.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButtonAdd.setContentAreaFilled(false);
jButtonAdd.setIconTextGap(0);
jButtonAdd.setMaximumSize(new java.awt.Dimension(60, 30));
jButtonAdd.setMinimumSize(new java.awt.Dimension(50, 20));
jButtonAdd.setPreferredSize(new java.awt.Dimension(50, 20));
jButtonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
jButtonRemove.setText("Delete");
jButtonRemove.setMnemonic('d');
jButtonRemove.setToolTipText("Remove the selected datasource");
jButtonRemove.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButtonRemove.setContentAreaFilled(false);
jButtonRemove.setIconTextGap(0);
jButtonRemove.setMaximumSize(new java.awt.Dimension(60, 30));
jButtonRemove.setMinimumSize(new java.awt.Dimension(50, 20));
jButtonRemove.setPreferredSize(new java.awt.Dimension(50, 20));
jButtonRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
DataSource ds = selector.getSelectedDataSource();
if (ds != null) {
dscontroller.removeDataSource(ds.getSourceID());
}
}
});
jLabeltitle.setBackground(new java.awt.Color(153, 153, 153));
jLabeltitle.setFont(new java.awt.Font("Arial", 1, 11));
jLabeltitle.setForeground(new java.awt.Color(153, 153, 153));
jLabeltitle.setPreferredSize(new Dimension(119, 14));
}
|
diff --git a/demos/src/test/java/com/malhartech/demos/ads/ScaledApplicationTest.java b/demos/src/test/java/com/malhartech/demos/ads/ScaledApplicationTest.java
index 35e4d548c..523293013 100644
--- a/demos/src/test/java/com/malhartech/demos/ads/ScaledApplicationTest.java
+++ b/demos/src/test/java/com/malhartech/demos/ads/ScaledApplicationTest.java
@@ -1,27 +1,28 @@
/**
* Copyright (c) 2012-2012 Malhar, Inc.
* All rights reserved.
*/
package com.malhartech.demos.ads;
import com.malhartech.stram.StramLocalCluster;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.junit.Test;
/**
* Test the DAG declaration in local mode.
*/
public class ScaledApplicationTest {
@Test
public void testJavaConfig() throws IOException, Exception {
ScaledApplication app = new ScaledApplication();
app.setUnitTestMode(); // terminate quickly
//app.setLocalMode(); // terminate with a long run
StramLocalCluster lc = new StramLocalCluster(app.getApplication(new Configuration(false)));
lc.setHeartbeatMonitoringEnabled(false);
+ //lc.setPerContainerBufferServer(true);
lc.run();
}
}
| true | true | public void testJavaConfig() throws IOException, Exception {
ScaledApplication app = new ScaledApplication();
app.setUnitTestMode(); // terminate quickly
//app.setLocalMode(); // terminate with a long run
StramLocalCluster lc = new StramLocalCluster(app.getApplication(new Configuration(false)));
lc.setHeartbeatMonitoringEnabled(false);
lc.run();
}
| public void testJavaConfig() throws IOException, Exception {
ScaledApplication app = new ScaledApplication();
app.setUnitTestMode(); // terminate quickly
//app.setLocalMode(); // terminate with a long run
StramLocalCluster lc = new StramLocalCluster(app.getApplication(new Configuration(false)));
lc.setHeartbeatMonitoringEnabled(false);
//lc.setPerContainerBufferServer(true);
lc.run();
}
|
diff --git a/src/uk/co/timwise/sqlhawk/db/write/DbWriter.java b/src/uk/co/timwise/sqlhawk/db/write/DbWriter.java
index b7634ef..acdfd96 100644
--- a/src/uk/co/timwise/sqlhawk/db/write/DbWriter.java
+++ b/src/uk/co/timwise/sqlhawk/db/write/DbWriter.java
@@ -1,252 +1,252 @@
/* This file is a part of the sqlHawk project.
* http://timabell.github.com/sqlHawk/
*
* 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 uk.co.timwise.sqlhawk.db.write;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import uk.co.timwise.sqlhawk.config.Config;
import uk.co.timwise.sqlhawk.config.InvalidConfigurationException;
import uk.co.timwise.sqlhawk.db.SqlManagement;
import uk.co.timwise.sqlhawk.db.read.DbReader;
import uk.co.timwise.sqlhawk.db.read.TableReader;
import uk.co.timwise.sqlhawk.model.Database;
import uk.co.timwise.sqlhawk.model.ISqlObject;
import uk.co.timwise.sqlhawk.scm.read.UpgradeScriptReader;
import uk.co.timwise.sqlhawk.util.FileHandling;
public class DbWriter {
private final static Logger logger = Logger.getLogger(DbWriter.class.getName());
private String upgradeLogInsertSql;
private String upgradeLogFindSql;
public void write(Config config, Connection connection,
DatabaseMetaData meta, Database db) throws Exception {
logger.fine("Writing to database...");
boolean useTransactions = meta.supportsTransactions();
boolean savedTransactionsSetting = false;
if (useTransactions) {
logger.fine("Starting transaction for database write...");
savedTransactionsSetting = connection.getAutoCommit();
connection.setAutoCommit(false);
} else {
logger.fine("Transactions not supported by this db type. Transactions will not be used.");
}
try {
runUpgradeScripts(config, connection, meta);
logger.fine("Gathering update schema details before applying proc/view/function changes...");
DbReader reader = new DbReader();
Database existingDb = reader.Read(config, connection, meta, null);
createUpdateDrop(config, connection, db.getProcMap(), existingDb.getProcMap(), "procedure");
createUpdateDrop(config, connection, db.getViewMap(), existingDb.getViewMap(), "view");
createUpdateDrop(config, connection, db.getFunctionMap(), existingDb.getFunctionMap(), "function");
if (useTransactions) {
logger.fine("Committing database write transaction...");
connection.commit();
connection.setAutoCommit(savedTransactionsSetting);
}
} catch (Exception ex) {
if (useTransactions) {
logger.fine("Rolling back database write transaction...");
connection.rollback();
connection.setAutoCommit(savedTransactionsSetting);
}
throw ex;
}
}
/**
* Update views/functions/procs in target db to match contents of "updatedObjects".
* Note that exclusion patterns are expeccted to have already
* been applied to existingObjects data to avoid accidentally
* dropping excluded objects. */
private <TSqlObject extends ISqlObject> void createUpdateDrop(Config config, Connection connection,
Map<String, TSqlObject> updatedObjects, Map<String, TSqlObject> existingObjects, String typeName)
throws Exception, SQLException {
logger.fine("Synchronising " + typeName + "s...");
for (TSqlObject updatedObject : updatedObjects.values()){
String name = updatedObject.getName();
logger.finest("Processing " + typeName + " " + name);
String updatedDefinition = updatedObject.getDefinition();
if (existingObjects.containsKey(name)) {
//check if definitions match
if (updatedDefinition.equals(existingObjects.get(name).getDefinition())) {
if (!config.isForceEnabled()) {
logger.fine("Existing " + typeName + " " + name + " already up to date");
continue; //already up to date, move on to next object.
} else {
logger.fine("Forcing update of up to date " + typeName + " " + name);
}
}
logger.info("Updating existing " + typeName + " " + name);
if (config.getDbType().isAlterSupported()) {
//Change definition from CREATE to ALTER and run.
updatedDefinition = SqlManagement.ConvertCreateToAlter(updatedDefinition);
}
try {
if (!config.isDryRun()) {
if (!config.getDbType().isAlterSupported()) {
connection.prepareStatement("DROP " + typeName + " " + name).execute();
}
connection.prepareStatement(updatedDefinition).execute();
}
} catch (SQLException ex){
//rethrow with information on which object failed.
throw new Exception("Error updating " + typeName + " " + name, ex);
}
} else { //new object
logger.info("Adding new " + typeName + " " + name);
if (!config.getDbType().isAlterSupported()) {
updatedDefinition = SqlManagement.ConvertAlterToCreate(updatedDefinition);
}
try {
if (!config.isDryRun())
connection.prepareStatement(updatedDefinition).execute();
} catch (SQLException ex){
//rethrow with information on which object failed.
- throw new Exception("Error updating " + typeName + " " + name, ex);
+ throw new Exception("Error adding new " + typeName + " " + name, ex);
}
}
}
logger.fine("Deleting unwanted " + typeName + "s...");
for (TSqlObject existingView : existingObjects.values()){
String objectName = existingView.getName();
logger.finest("Checking if " + typeName + " " + objectName + " needs dropping...");
if (!updatedObjects.containsKey(objectName)){
logger.info("Dropping unwanted " + typeName + " " + objectName);
if (!config.isDryRun())
connection.prepareStatement("DROP " + typeName + " " + objectName).execute(); //TODO: move syntax to property files
}
}
}
public void initializeLog(Connection connection, Config config) throws SQLException, InvalidConfigurationException, IOException {
Properties properties = config.getDbType().getProps();
String upgradeLogTableSql = properties.getProperty("upgradeLogTable");
if (!config.isDryRun()) {
logger.info("Creating table SqlHawk_UpgradeLog...");
logger.finest("Running initialization sql:\n" + upgradeLogTableSql);
connection.prepareStatement(upgradeLogTableSql).execute();
}
}
/**
* Run upgrade scripts.
*
* @param config the config
* @param connection the connection
* @param meta the meta
* @return true, if any scripts were run, false if nothing was outstanding
* @throws Exception the exception
*/
public void runUpgradeScripts(Config config, Connection connection,
DatabaseMetaData meta) throws Exception {
logger.fine("Running upgrade scripts...");
File scriptFolder = new File(config.getTargetDir(), "UpgradeScripts");
if (!scriptFolder.isDirectory()) {
logger.warning("Upgrade script directory '" + scriptFolder + "' not found. Skipping upgrade scripts.");
return;
}
String upgradeBatch = config.getUpgradeBatch();
Properties properties = config.getDbType().getProps();
upgradeLogInsertSql = properties.getProperty("upgradeLogInsert");
upgradeLogFindSql = properties.getProperty("upgradeLogFind");
int strip = scriptFolder.toString().length() + 1; // remove base path + trailing slash
runScriptDirectory(config, connection, scriptFolder, upgradeBatch, strip);
}
/**
* Recursively run all the upgrade scripts in a directory.
*
* @param config the config
* @param connection the connection
* @param scriptFolder the script folder
* @param upgradeBatch string to tie all the scripts together with in the upgrade log table
* @param strip number of chars to remove from paths when logging
* @return whether any scripts were run
* @throws IOException Signals that an I/O exception has occurred.
* @throws Exception the exception
*/
private void runScriptDirectory(Config config, Connection connection, File scriptFolder, String upgradeBatch, int strip) throws IOException,
Exception {
List<String> scripts = UpgradeScriptReader.getUpgradeScripts(scriptFolder);
for(String script : scripts){
try {
PreparedStatement log = connection.prepareStatement(upgradeLogFindSql);
log.setString(1, script);
log.execute();
ResultSet resultSet = log.getResultSet();
if (resultSet.next()) { // existing record of this script found in log
int upgradeId = resultSet.getInt(1);
logger.fine("Script '" + script + "' already run. UpgradeId " + upgradeId);
continue;
}
} catch (Exception ex) {
throw new Exception("Reading table SqlHawk_UpgradeLog failed, use --initialize-tracking before first run.", ex);
}
runSqlScriptFile(connection, scriptFolder, script, config.isDryRun());
try {
PreparedStatement log = connection.prepareStatement(upgradeLogInsertSql);
log.setString(1, upgradeBatch);
log.setString(2, script);
log.execute();
} catch (Exception ex) {
throw new Exception("INSERT INTO SqlHawk_UpgradeLog failed.", ex);
}
}
}
/**
* Run a sql script file against the specified connection.
*
* @param connection the connection
* @param scriptFolder the root folder to find the script in
* @param script the relative path to the script file
* @param dryRun set to false to skip execution
*/
public static void runSqlScriptFile(Connection connection, File scriptFolder, String script, boolean dryRun)
throws Exception {
try {
logger.info("Running script '" + script + "'...");
String definition = FileHandling.readFile(new File(scriptFolder, script));
// Split into batches similar to the sql server tools,this makes
// management of scripts easier as you can include a reference to a
// new table in the same sql file as the create statement.
String[] splitSql = SqlManagement.SplitBatches(definition);
for (String sql : splitSql) {
logger.finest("Running script batch\n" + sql);
if (!dryRun) {
connection.prepareStatement(sql).execute();
}
}
} catch (Exception ex) {
throw new Exception("Failed to run script '" + script + "'.", ex);
}
}
}
| true | true | private <TSqlObject extends ISqlObject> void createUpdateDrop(Config config, Connection connection,
Map<String, TSqlObject> updatedObjects, Map<String, TSqlObject> existingObjects, String typeName)
throws Exception, SQLException {
logger.fine("Synchronising " + typeName + "s...");
for (TSqlObject updatedObject : updatedObjects.values()){
String name = updatedObject.getName();
logger.finest("Processing " + typeName + " " + name);
String updatedDefinition = updatedObject.getDefinition();
if (existingObjects.containsKey(name)) {
//check if definitions match
if (updatedDefinition.equals(existingObjects.get(name).getDefinition())) {
if (!config.isForceEnabled()) {
logger.fine("Existing " + typeName + " " + name + " already up to date");
continue; //already up to date, move on to next object.
} else {
logger.fine("Forcing update of up to date " + typeName + " " + name);
}
}
logger.info("Updating existing " + typeName + " " + name);
if (config.getDbType().isAlterSupported()) {
//Change definition from CREATE to ALTER and run.
updatedDefinition = SqlManagement.ConvertCreateToAlter(updatedDefinition);
}
try {
if (!config.isDryRun()) {
if (!config.getDbType().isAlterSupported()) {
connection.prepareStatement("DROP " + typeName + " " + name).execute();
}
connection.prepareStatement(updatedDefinition).execute();
}
} catch (SQLException ex){
//rethrow with information on which object failed.
throw new Exception("Error updating " + typeName + " " + name, ex);
}
} else { //new object
logger.info("Adding new " + typeName + " " + name);
if (!config.getDbType().isAlterSupported()) {
updatedDefinition = SqlManagement.ConvertAlterToCreate(updatedDefinition);
}
try {
if (!config.isDryRun())
connection.prepareStatement(updatedDefinition).execute();
} catch (SQLException ex){
//rethrow with information on which object failed.
throw new Exception("Error updating " + typeName + " " + name, ex);
}
}
}
logger.fine("Deleting unwanted " + typeName + "s...");
for (TSqlObject existingView : existingObjects.values()){
String objectName = existingView.getName();
logger.finest("Checking if " + typeName + " " + objectName + " needs dropping...");
if (!updatedObjects.containsKey(objectName)){
logger.info("Dropping unwanted " + typeName + " " + objectName);
if (!config.isDryRun())
connection.prepareStatement("DROP " + typeName + " " + objectName).execute(); //TODO: move syntax to property files
}
}
}
| private <TSqlObject extends ISqlObject> void createUpdateDrop(Config config, Connection connection,
Map<String, TSqlObject> updatedObjects, Map<String, TSqlObject> existingObjects, String typeName)
throws Exception, SQLException {
logger.fine("Synchronising " + typeName + "s...");
for (TSqlObject updatedObject : updatedObjects.values()){
String name = updatedObject.getName();
logger.finest("Processing " + typeName + " " + name);
String updatedDefinition = updatedObject.getDefinition();
if (existingObjects.containsKey(name)) {
//check if definitions match
if (updatedDefinition.equals(existingObjects.get(name).getDefinition())) {
if (!config.isForceEnabled()) {
logger.fine("Existing " + typeName + " " + name + " already up to date");
continue; //already up to date, move on to next object.
} else {
logger.fine("Forcing update of up to date " + typeName + " " + name);
}
}
logger.info("Updating existing " + typeName + " " + name);
if (config.getDbType().isAlterSupported()) {
//Change definition from CREATE to ALTER and run.
updatedDefinition = SqlManagement.ConvertCreateToAlter(updatedDefinition);
}
try {
if (!config.isDryRun()) {
if (!config.getDbType().isAlterSupported()) {
connection.prepareStatement("DROP " + typeName + " " + name).execute();
}
connection.prepareStatement(updatedDefinition).execute();
}
} catch (SQLException ex){
//rethrow with information on which object failed.
throw new Exception("Error updating " + typeName + " " + name, ex);
}
} else { //new object
logger.info("Adding new " + typeName + " " + name);
if (!config.getDbType().isAlterSupported()) {
updatedDefinition = SqlManagement.ConvertAlterToCreate(updatedDefinition);
}
try {
if (!config.isDryRun())
connection.prepareStatement(updatedDefinition).execute();
} catch (SQLException ex){
//rethrow with information on which object failed.
throw new Exception("Error adding new " + typeName + " " + name, ex);
}
}
}
logger.fine("Deleting unwanted " + typeName + "s...");
for (TSqlObject existingView : existingObjects.values()){
String objectName = existingView.getName();
logger.finest("Checking if " + typeName + " " + objectName + " needs dropping...");
if (!updatedObjects.containsKey(objectName)){
logger.info("Dropping unwanted " + typeName + " " + objectName);
if (!config.isDryRun())
connection.prepareStatement("DROP " + typeName + " " + objectName).execute(); //TODO: move syntax to property files
}
}
}
|
diff --git a/src/org/biojava/bio/seq/ragbag/RagbagParsedCachedSequence.java b/src/org/biojava/bio/seq/ragbag/RagbagParsedCachedSequence.java
index 52515def3..507fc776e 100644
--- a/src/org/biojava/bio/seq/ragbag/RagbagParsedCachedSequence.java
+++ b/src/org/biojava/bio/seq/ragbag/RagbagParsedCachedSequence.java
@@ -1,101 +1,101 @@
/**
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojava.bio.seq.ragbag;
import java.io.*;
import java.util.*;
import org.xml.sax.*;
import org.biojava.utils.stax.*;
import org.apache.xerces.parsers.*;
import org.biojava.bio.Annotation;
import org.biojava.bio.BioException;
import org.biojava.bio.BioError;
import org.biojava.bio.seq.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.symbol.*;
import org.biojava.bio.seq.io.game.*;
import org.biojava.utils.*;
import org.biojava.utils.cache.*;
/**
* A version of RagbagSequence that exhibits lazy instantiation
* and caching behaviour.
* It should reduce memory requirements when creating large
* assemblies.
* <p>
* It functionally proxies for RagbagSequence.
*/
class RagbagParsedCachedSequence extends RagbagCachedSequence
{
private RagbagFilterFactory filterFactory;
/**
* @param cache object that controls cache behaviour.
*/
public RagbagParsedCachedSequence(String name, String urn, Cache cache, RagbagFilterFactory filterFactory)
{
super(name, urn, cache);
this.filterFactory = filterFactory;
System.out.println("RagbagParsedCachedSequence constructor: " + name + " " + urn);
}
public void makeSequence()
throws BioException
{
// with lazy instantiation, there's little to do but validate
super.makeSequence();
// screen files without instantiating sequence object
try {
- RagbagSequenceItf seq = new RagbagSequence("", "", filterFactory.wrap(new IdleSequenceBuilder()));
+ RagbagSequenceItf seq = new RagbagSequence("", "", filterFactory.wrap(new RagbagIdleSequenceBuilder()));
seq.addSequenceFile(new File(seqFilename));
// now add any features if necessary
if (annotFilenames != null) {
// get iterator
Iterator ai = annotFilenames.iterator();
// add features
while (ai.hasNext()) {
// create file
File currAnnotFile = new File((String) ai.next());
// add its features
seq.addFeatureFile(currAnnotFile);
}
}
// create sequence
seq.makeSequence();
}
catch (BioException be) {
throw new BioError(be);
}
}
}
| true | true | public void makeSequence()
throws BioException
{
// with lazy instantiation, there's little to do but validate
super.makeSequence();
// screen files without instantiating sequence object
try {
RagbagSequenceItf seq = new RagbagSequence("", "", filterFactory.wrap(new IdleSequenceBuilder()));
seq.addSequenceFile(new File(seqFilename));
// now add any features if necessary
if (annotFilenames != null) {
// get iterator
Iterator ai = annotFilenames.iterator();
// add features
while (ai.hasNext()) {
// create file
File currAnnotFile = new File((String) ai.next());
// add its features
seq.addFeatureFile(currAnnotFile);
}
}
// create sequence
seq.makeSequence();
}
catch (BioException be) {
throw new BioError(be);
}
}
| public void makeSequence()
throws BioException
{
// with lazy instantiation, there's little to do but validate
super.makeSequence();
// screen files without instantiating sequence object
try {
RagbagSequenceItf seq = new RagbagSequence("", "", filterFactory.wrap(new RagbagIdleSequenceBuilder()));
seq.addSequenceFile(new File(seqFilename));
// now add any features if necessary
if (annotFilenames != null) {
// get iterator
Iterator ai = annotFilenames.iterator();
// add features
while (ai.hasNext()) {
// create file
File currAnnotFile = new File((String) ai.next());
// add its features
seq.addFeatureFile(currAnnotFile);
}
}
// create sequence
seq.makeSequence();
}
catch (BioException be) {
throw new BioError(be);
}
}
|
diff --git a/coastal-hazards-portal/src/main/java/gov/usgs/cida/coastalhazards/rest/data/ItemResource.java b/coastal-hazards-portal/src/main/java/gov/usgs/cida/coastalhazards/rest/data/ItemResource.java
index c5d00f1b6..128d534ca 100644
--- a/coastal-hazards-portal/src/main/java/gov/usgs/cida/coastalhazards/rest/data/ItemResource.java
+++ b/coastal-hazards-portal/src/main/java/gov/usgs/cida/coastalhazards/rest/data/ItemResource.java
@@ -1,232 +1,237 @@
package gov.usgs.cida.coastalhazards.rest.data;
import com.google.gson.Gson;
import gov.usgs.cida.coastalhazards.jpa.ItemManager;
import gov.usgs.cida.coastalhazards.model.Item;
import gov.usgs.cida.coastalhazards.model.summary.Summary;
import gov.usgs.cida.config.DynamicReadOnlyProperties;
import gov.usgs.cida.utilities.properties.JNDISingleton;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* Could also be called item or layer or some other way of describing a singular
* thing
*
* @author jordan
*/
@Path("item")
public class ItemResource {
@Context
private UriInfo context;
private Gson gson = new Gson();
private static ItemManager itemManager;
private static String cchn52Endpoint;
private static final DynamicReadOnlyProperties props;
static {
props = JNDISingleton.getInstance();
cchn52Endpoint = props.getProperty("coastal-hazards.n52.endpoint");
itemManager = new ItemManager();
}
/**
* Retrieves representation of an instance of
* gov.usgs.cida.coastalhazards.rest.TestResource
*
* @param id
* @return an instance of java.lang.String
*/
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getCard(@PathParam("id") String id) {
String jsonResult = itemManager.load(id);
Response response;
if (null == jsonResult) {
response = Response.status(Response.Status.NOT_FOUND).build();
} else {
response = Response.ok(jsonResult, MediaType.APPLICATION_JSON_TYPE).build();
}
return response;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response searchCards(
@DefaultValue("") @QueryParam("query") List<String> query,
@DefaultValue("") @QueryParam("type") List<String> type,
@DefaultValue("popularity") @QueryParam("sortBy") String sortBy,
@DefaultValue("-1") @QueryParam("count") int count,
@DefaultValue("") @QueryParam("bbox") String bbox) {
// need to figure out how to search popularity and bbox yet
String jsonResult = itemManager.query(query, type, sortBy, count, bbox);
return Response.ok(jsonResult, MediaType.APPLICATION_JSON_TYPE).build();
}
/**
* Only allows one card to be posted at a time for now
*
* @param content
* @return
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response postCard(String content, @Context HttpServletRequest request) {
Response response;
HttpSession session = request.getSession();
if (session == null) {
response = Response.status(Response.Status.BAD_REQUEST).build();
} else {
Boolean valid = (session.getAttribute("sessionValid") == null) ? false : (Boolean)session.getAttribute("sessionValid");
if (valid) {
final String id = itemManager.save(content);
if (null == id) {
response = Response.status(Response.Status.BAD_REQUEST).build();
} else {
Map<String, Object> ok = new HashMap<String, Object>() {
private static final long serialVersionUID = 2398472L;
{
put("id", id);
}
};
response = Response.ok(new Gson().toJson(ok, HashMap.class), MediaType.APPLICATION_JSON_TYPE).build();
}
} else {
response = Response.status(Response.Status.UNAUTHORIZED).build();
}
}
return response;
}
@POST
@Path("/preview")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response publishPreviewCard(String content) {
Response response = Response.serverError().build();
Item item = Item.fromJSON(content);
try {
String jsonSummary = getSummaryFromWPS(item.getMetadata(), item.getAttr());
// this is not actually summary json object, so we need to change that a bit
Summary summary = gson.fromJson(jsonSummary, Summary.class);
item.setSummary(summary);
} catch (Exception ex) {
Map<String,String> err = new HashMap<String, String>();
err.put("message", ex.getMessage());
response = Response.serverError().entity(new Gson().toJson(err, HashMap.class)).build();
}
if (item.getSummary() != null) {
final String id = itemManager.savePreview(item);
if (null == id) {
response = Response.status(Response.Status.BAD_REQUEST).build();
} else {
Map<String, String> ok = new HashMap<String, String>() {
private static final long serialVersionUID = 23918472L;
{
put("id", id);
}
};
response = Response.ok(new Gson().toJson(ok, HashMap.class), MediaType.APPLICATION_JSON_TYPE).build();
}
}
return response;
}
private String getSummaryFromWPS(String metadataId, String attr) throws IOException, ParserConfigurationException, SAXException {
MetadataResource metadata = new MetadataResource();
Response response = metadata.getFileById(metadataId);
String xmlWithoutHeader = response.getEntity().toString().replaceAll("<\\?xml[^>]*>", "");
String wpsRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<wps:Execute xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" service=\"WPS\" version=\"1.0.0\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
+ "<ows:Identifier>org.n52.wps.server.r.item.summary</ows:Identifier>"
+ "<wps:DataInputs>"
+ "<wps:Input>"
+ "<ows:Identifier>input</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:ComplexData mimeType=\"text/xml\">"
+ xmlWithoutHeader
+ "</wps:ComplexData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>attr</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + attr + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "</wps:DataInputs>"
+ "<wps:ResponseForm>"
+ "<wps:RawDataOutput>"
+ "<ows:Identifier>output</ows:Identifier>"
+ "</wps:RawDataOutput>"
+ "</wps:ResponseForm>"
+ "</wps:Execute>";
HttpUriRequest req = new HttpPost(cchn52Endpoint + "/WebProcessingService");
HttpClient client = new DefaultHttpClient();
req.addHeader("Content-Type", "text/xml");
if (!StringUtils.isBlank(wpsRequest) && req instanceof HttpEntityEnclosingRequestBase) {
StringEntity contentEntity = new StringEntity(wpsRequest);
((HttpEntityEnclosingRequestBase) req).setEntity(contentEntity);
}
HttpResponse resp = client.execute(req);
StatusLine statusLine = resp.getStatusLine();
if (statusLine.getStatusCode() != 200) {
throw new IOException("Error in response from wps");
}
String data = IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
if (data.contains("ExceptionReport")) {
String error = "Error in response from wps";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(data.getBytes()));
JXPathContext ctx = JXPathContext.newContext(doc.getDocumentElement());
- Node exText = (Node) ctx.selectSingleNode("//wps:ExceptionText/text()");
- if (exText != null) {
- error = exText.getTextContent();
+ ctx.registerNamespace("ows", "http://www.opengis.net/ows/1.1");
+ List<Node> nodes = ctx.selectNodes("ows:Exception/ows:ExceptionText/text()");
+ if (nodes != null && !nodes.isEmpty()) {
+ StringBuilder builder = new StringBuilder();
+ for (Node node : nodes) {
+ builder.append(node.getTextContent()).append(System.lineSeparator());
+ }
+ error = builder.toString();
}
throw new RuntimeException(error);
}
return data;
}
}
| true | true | private String getSummaryFromWPS(String metadataId, String attr) throws IOException, ParserConfigurationException, SAXException {
MetadataResource metadata = new MetadataResource();
Response response = metadata.getFileById(metadataId);
String xmlWithoutHeader = response.getEntity().toString().replaceAll("<\\?xml[^>]*>", "");
String wpsRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<wps:Execute xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" service=\"WPS\" version=\"1.0.0\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
+ "<ows:Identifier>org.n52.wps.server.r.item.summary</ows:Identifier>"
+ "<wps:DataInputs>"
+ "<wps:Input>"
+ "<ows:Identifier>input</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:ComplexData mimeType=\"text/xml\">"
+ xmlWithoutHeader
+ "</wps:ComplexData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>attr</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + attr + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "</wps:DataInputs>"
+ "<wps:ResponseForm>"
+ "<wps:RawDataOutput>"
+ "<ows:Identifier>output</ows:Identifier>"
+ "</wps:RawDataOutput>"
+ "</wps:ResponseForm>"
+ "</wps:Execute>";
HttpUriRequest req = new HttpPost(cchn52Endpoint + "/WebProcessingService");
HttpClient client = new DefaultHttpClient();
req.addHeader("Content-Type", "text/xml");
if (!StringUtils.isBlank(wpsRequest) && req instanceof HttpEntityEnclosingRequestBase) {
StringEntity contentEntity = new StringEntity(wpsRequest);
((HttpEntityEnclosingRequestBase) req).setEntity(contentEntity);
}
HttpResponse resp = client.execute(req);
StatusLine statusLine = resp.getStatusLine();
if (statusLine.getStatusCode() != 200) {
throw new IOException("Error in response from wps");
}
String data = IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
if (data.contains("ExceptionReport")) {
String error = "Error in response from wps";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(data.getBytes()));
JXPathContext ctx = JXPathContext.newContext(doc.getDocumentElement());
Node exText = (Node) ctx.selectSingleNode("//wps:ExceptionText/text()");
if (exText != null) {
error = exText.getTextContent();
}
throw new RuntimeException(error);
}
return data;
}
| private String getSummaryFromWPS(String metadataId, String attr) throws IOException, ParserConfigurationException, SAXException {
MetadataResource metadata = new MetadataResource();
Response response = metadata.getFileById(metadataId);
String xmlWithoutHeader = response.getEntity().toString().replaceAll("<\\?xml[^>]*>", "");
String wpsRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<wps:Execute xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ows=\"http://www.opengis.net/ows/1.1\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" service=\"WPS\" version=\"1.0.0\" xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
+ "<ows:Identifier>org.n52.wps.server.r.item.summary</ows:Identifier>"
+ "<wps:DataInputs>"
+ "<wps:Input>"
+ "<ows:Identifier>input</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:ComplexData mimeType=\"text/xml\">"
+ xmlWithoutHeader
+ "</wps:ComplexData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>attr</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + attr + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "</wps:DataInputs>"
+ "<wps:ResponseForm>"
+ "<wps:RawDataOutput>"
+ "<ows:Identifier>output</ows:Identifier>"
+ "</wps:RawDataOutput>"
+ "</wps:ResponseForm>"
+ "</wps:Execute>";
HttpUriRequest req = new HttpPost(cchn52Endpoint + "/WebProcessingService");
HttpClient client = new DefaultHttpClient();
req.addHeader("Content-Type", "text/xml");
if (!StringUtils.isBlank(wpsRequest) && req instanceof HttpEntityEnclosingRequestBase) {
StringEntity contentEntity = new StringEntity(wpsRequest);
((HttpEntityEnclosingRequestBase) req).setEntity(contentEntity);
}
HttpResponse resp = client.execute(req);
StatusLine statusLine = resp.getStatusLine();
if (statusLine.getStatusCode() != 200) {
throw new IOException("Error in response from wps");
}
String data = IOUtils.toString(resp.getEntity().getContent(), "UTF-8");
if (data.contains("ExceptionReport")) {
String error = "Error in response from wps";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(data.getBytes()));
JXPathContext ctx = JXPathContext.newContext(doc.getDocumentElement());
ctx.registerNamespace("ows", "http://www.opengis.net/ows/1.1");
List<Node> nodes = ctx.selectNodes("ows:Exception/ows:ExceptionText/text()");
if (nodes != null && !nodes.isEmpty()) {
StringBuilder builder = new StringBuilder();
for (Node node : nodes) {
builder.append(node.getTextContent()).append(System.lineSeparator());
}
error = builder.toString();
}
throw new RuntimeException(error);
}
return data;
}
|
diff --git a/jsf/plugins/org.jboss.tools.jsf.vpe.richfaces/src/org/jboss/tools/jsf/vpe/richfaces/template/RichFacesDataTableTemplate.java b/jsf/plugins/org.jboss.tools.jsf.vpe.richfaces/src/org/jboss/tools/jsf/vpe/richfaces/template/RichFacesDataTableTemplate.java
index 5c3540e25..7973c8ff9 100644
--- a/jsf/plugins/org.jboss.tools.jsf.vpe.richfaces/src/org/jboss/tools/jsf/vpe/richfaces/template/RichFacesDataTableTemplate.java
+++ b/jsf/plugins/org.jboss.tools.jsf.vpe.richfaces/src/org/jboss/tools/jsf/vpe/richfaces/template/RichFacesDataTableTemplate.java
@@ -1,339 +1,339 @@
/*******************************************************************************
* Copyright (c) 2007 Exadel, Inc. and Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Exadel, Inc. and Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.jsf.vpe.richfaces.template;
import java.util.ArrayList;
import org.jboss.tools.jsf.vpe.richfaces.ComponentUtil;
import org.jboss.tools.jsf.vpe.richfaces.template.util.RichFaces;
import org.jboss.tools.vpe.editor.context.VpePageContext;
import org.jboss.tools.vpe.editor.template.VpeAbstractTemplate;
import org.jboss.tools.vpe.editor.template.VpeChildrenInfo;
import org.jboss.tools.vpe.editor.template.VpeCreationData;
import org.jboss.tools.vpe.editor.util.Constants;
import org.jboss.tools.vpe.editor.util.HTML;
import org.jboss.tools.vpe.editor.util.VisualDomUtil;
import org.jboss.tools.vpe.editor.util.VpeStyleUtil;
import org.mozilla.interfaces.nsIDOMDocument;
import org.mozilla.interfaces.nsIDOMElement;
import org.mozilla.interfaces.nsIDOMNode;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class RichFacesDataTableTemplate extends VpeAbstractTemplate {
public VpeCreationData create(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument) {
Element sourceElement = (Element)sourceNode;
nsIDOMElement table = visualDocument.createElement(HTML.TAG_TABLE);
VisualDomUtil.copyAttributes(sourceNode, table);
VpeCreationData creationData = new VpeCreationData(table);
ComponentUtil.setCSSLink(pageContext, "dataTable/dataTable.css", "richFacesDataTable"); //$NON-NLS-1$ //$NON-NLS-2$
String tableClass = sourceElement.getAttribute(RichFaces.ATTR_STYLE_CLASS);
table.setAttribute(HTML.ATTR_CLASS, "dr-table rich-table " + (tableClass==null?Constants.EMPTY:tableClass)); //$NON-NLS-1$
// Encode colgroup definition.
ArrayList<Element> columns = getColumns(sourceElement);
int columnsLength = getColumnsCount(sourceElement, columns);
nsIDOMElement colgroup = visualDocument.createElement(HTML.TAG_COLGROUP);
colgroup.setAttribute(HTML.ATTR_SPAN, String.valueOf(columnsLength));
table.appendChild(colgroup);
String columnsWidth = sourceElement.getAttribute(RichFaces.ATTR_COLUMNS_WIDTH);
if (null != columnsWidth) {
String[] widths = columnsWidth.split(Constants.COMMA);
for (int i = 0; i < widths.length; i++) {
nsIDOMElement col = visualDocument.createElement(HTML.TAG_COL);
col.setAttribute(HTML.ATTR_WIDTH, widths[i]);
colgroup.appendChild(col);
}
}
//Encode Caption
encodeCaption(creationData, sourceElement, visualDocument, table);
// Encode Header
Node header = ComponentUtil.getFacet((Element)sourceElement, RichFaces.NAME_FACET_HEADER,true);
final boolean hasColumnWithHeader = hasColumnWithFacet(columns, RichFaces.NAME_FACET_HEADER);
if(header!=null || hasColumnWithHeader) {
nsIDOMElement thead = visualDocument.createElement(HTML.TAG_THEAD);
table.appendChild(thead);
String headerClass = (String) sourceElement.getAttribute(RichFaces.ATTR_HEADER_CLASS);
if(header != null) {
encodeTableHeaderOrFooterFacet(pageContext, creationData, thead, columnsLength, visualDocument, header,
"dr-table-header rich-table-header", //$NON-NLS-1$
"dr-table-header-continue rich-table-header-continue", //$NON-NLS-1$
"dr-table-headercell rich-table-headercell", //$NON-NLS-1$
headerClass, HTML.TAG_TD);
}
if(hasColumnWithHeader) {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
thead.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, "dr-table-subheader rich-table-subheader", null, headerClass); //$NON-NLS-1$
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
encodeHeaderOrFooterFacets(pageContext, creationData, tr, visualDocument, columns,
"dr-table-subheadercell rich-table-subheadercell", //$NON-NLS-1$
headerClass, RichFaces.NAME_FACET_HEADER, HTML.TAG_TD);
}
}
// Encode Footer
- Element footer = ComponentUtil.getFacet(sourceElement, RichFaces.NAME_FACET_FOOTER);
+ Node footer = ComponentUtil.getFacet((Element)sourceElement, RichFaces.NAME_FACET_FOOTER,true);
final boolean hasColumnWithFooter = hasColumnWithFacet(columns, RichFaces.NAME_FACET_FOOTER);
if (footer != null || hasColumnWithFooter) {
nsIDOMElement tfoot = visualDocument.createElement(HTML.TAG_TFOOT);
table.appendChild(tfoot);
String footerClass = (String) sourceElement.getAttribute(RichFaces.ATTR_FOOTER_CLASS);
if(hasColumnWithFooter) {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
tfoot.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, "dr-table-subfooter rich-table-subfooter", null, footerClass); //$NON-NLS-1$
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
encodeHeaderOrFooterFacets(pageContext, creationData, tr, visualDocument, columns,
"dr-table-subfootercell rich-table-subfootercell", //$NON-NLS-1$
footerClass, RichFaces.NAME_FACET_FOOTER, HTML.TAG_TD);
}
if (footer != null) {
encodeTableHeaderOrFooterFacet(pageContext, creationData, tfoot, columnsLength, visualDocument, footer,
"dr-table-footer rich-table-footer", //$NON-NLS-1$
"dr-table-footer-continue rich-table-footer-continue", //$NON-NLS-1$
"dr-table-footercell rich-table-footercell", //$NON-NLS-1$
footerClass,HTML.TAG_TD);
}
}
new RichFacesDataTableChildrenEncoder(creationData, visualDocument,
sourceElement, table).encodeChildren();
return creationData;
}
protected void encodeCaption(VpeCreationData creationData, Element sourceElement, nsIDOMDocument visualDocument, nsIDOMElement table) {
//Encode caption
Element captionFromFacet = ComponentUtil.getFacet(sourceElement, RichFaces.NAME_FACET_CAPTION);
if (captionFromFacet != null) {
String captionClass = (String) table.getAttribute(RichFaces.ATTR_CAPTION_CLASS);
String captionStyle = (String) table.getAttribute(RichFaces.ATTR_CAPTION_STYLE);
nsIDOMElement caption = visualDocument.createElement(HTML.TAG_CAPTION);
table.appendChild(caption);
if (captionClass != null && captionClass.length()>0) {
captionClass = "dr-table-caption rich-table-caption " + captionClass; //$NON-NLS-1$
} else {
captionClass = "dr-table-caption rich-table-caption"; //$NON-NLS-1$
}
caption.setAttribute(HTML.ATTR_CLASS, captionClass);
if (captionStyle != null && captionStyle.length()>0) {
caption.setAttribute(HTML.ATTR_STYLE, captionStyle);
}
VpeChildrenInfo cap = new VpeChildrenInfo(caption);
cap.addSourceChild(captionFromFacet);
creationData.addChildrenInfo(cap);
}
}
public static void encodeHeaderOrFooterFacets(VpePageContext pageContext, VpeCreationData creationData,
nsIDOMElement parentTr, nsIDOMDocument visualDocument, ArrayList<Element> headersOrFooters,
String skinCellClass, String headerClass, String facetName, String element) {
for (Element column : headersOrFooters) {
String classAttribute = facetName + "Class"; //$NON-NLS-1$
String columnHeaderClass = column.getAttribute(classAttribute);
nsIDOMElement td = visualDocument.createElement(element);
parentTr.appendChild(td);
String styleClass = ComponentUtil.encodeStyleClass(null, skinCellClass, headerClass, columnHeaderClass);
if (!RichFacesColumnTemplate.isVisible(column)) {
VisualDomUtil.setSubAttribute(td, HTML.ATTR_STYLE,
HTML.STYLE_PARAMETER_DISPLAY, HTML.STYLE_VALUE_NONE);
}
td.setAttribute(HTML.ATTR_CLASS, styleClass);
td.setAttribute(HTML.ATTR_SCOPE, "col"); //$NON-NLS-1$
String colspan = column.getAttribute("colspan"); //$NON-NLS-1$
if(colspan!=null && colspan.length()>0) {
td.setAttribute(HTML.ATTR_COLSPAN, colspan);
}
Node facetBody = ComponentUtil.getFacet(column, facetName,true);
nsIDOMElement span = visualDocument.createElement(HTML.TAG_SPAN);
td.appendChild(span);
if (RichFaces.NAME_FACET_HEADER.equals(facetName)) {
nsIDOMElement icon = RichFacesColumnTemplate.getHeaderIcon(pageContext, column, visualDocument);
if (icon != null) {
td.appendChild(icon);
}
}
VpeChildrenInfo childrenInfo = new VpeChildrenInfo(span);
childrenInfo.addSourceChild(facetBody);
creationData.addChildrenInfo(childrenInfo);
}
}
protected void encodeTableHeaderOrFooterFacet(final VpePageContext pageContext, VpeCreationData creationData,
nsIDOMElement parentTheadOrTfood, int columns, nsIDOMDocument visualDocument, Node facetBody,
String skinFirstRowClass, String skinRowClass, String skinCellClass, String facetBodyClass, String element) {
boolean isColumnGroup = facetBody.getNodeName().endsWith(RichFaces.TAG_COLUMN_GROUP);
boolean isSubTable = facetBody.getNodeName().endsWith(RichFaces.TAG_SUB_TABLE);
if(isColumnGroup) {
RichFacesColumnGroupTemplate.DEFAULT_INSTANCE.encode(pageContext, creationData, (Element)facetBody, visualDocument, parentTheadOrTfood);
} else if(isSubTable) {
RichFacesSubTableTemplate.DEFAULT_INSTANCE.encode(pageContext, creationData, (Element)facetBody, visualDocument, parentTheadOrTfood);
} else {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
parentTheadOrTfood.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, skinFirstRowClass, facetBodyClass, null);
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
String style = ComponentUtil.getHeaderBackgoundImgStyle();
tr.setAttribute(HTML.ATTR_STYLE, style);
nsIDOMElement td = visualDocument.createElement(element);
tr.appendChild(td);
styleClass = ComponentUtil.encodeStyleClass(null, skinCellClass, facetBodyClass, null);
if(styleClass!=null) {
td.setAttribute(HTML.ATTR_CLASS, styleClass);
}
// the cell spans the entire row
td.setAttribute(HTML.ATTR_COLSPAN, HTML.VALUE_COLSPAN_ALL);
td.setAttribute(HTML.ATTR_SCOPE, "colgroup"); //$NON-NLS-1$
VpeChildrenInfo child = new VpeChildrenInfo(td);
child.addSourceChild(facetBody);
creationData.addChildrenInfo(child);
}
}
public static ArrayList<Element> getColumns(Node parentSourceElement) {
ArrayList<Element> columns = new ArrayList<Element>();
NodeList children = parentSourceElement.getChildNodes();
for(int i=0; i<children.getLength(); i++) {
Node child = children.item(i);
String nodeName = child.getNodeName();
if((child instanceof Element) && (
nodeName.endsWith(RichFaces.TAG_COLUMN) ||
nodeName.endsWith(RichFaces.TAG_COLUMNS)
)) {
columns.add((Element)child);
}
}
return columns;
}
/**
* Returns true if and only if {@code columns} contains at least one column that have facet
* with given {@code facetName}.
*/
public static boolean hasColumnWithFacet(ArrayList<Element> columns, String facetName) {
for (Element column : columns) {
Node body = ComponentUtil.getFacet(column, facetName, true);
if(body!=null) {
return true;
}
}
return false;
}
protected int getColumnsCount(Element sourceElement, ArrayList<Element> columns) {
int count = 0;
// check for exact value in component
try {
count = Integer.parseInt(sourceElement.getAttribute(RichFaces.ATTR_COLUMNS));
} catch (NumberFormatException e) {
count = calculateRowColumns(sourceElement, columns);
}
return count;
}
/*
* Calculate max number of columns per row. For rows, recursive calculate
* max length.
*/
private int calculateRowColumns(Element sourceElement, ArrayList<Element> columns) {
int count = 0;
int currentLength = 0;
for (Element column : columns) {
if (ComponentUtil.isRendered(column)) {
String nodeName = column.getNodeName();
if (nodeName.endsWith(RichFaces.TAG_COLUMN_GROUP)) {
// Store max calculated value of previous rows.
count = Math.max(currentLength,count);
// Calculate number of columns in row.
currentLength = calculateRowColumns(sourceElement, getColumns(column));
// Store max calculated value
count = Math.max(currentLength,count);
currentLength = 0;
} else if (nodeName.equals(sourceElement.getPrefix() + Constants.COLON + RichFaces.TAG_COLUMN) ||
nodeName.equals(sourceElement.getPrefix() + Constants.COLON + RichFaces.TAG_COLUMNS)) {
// For new row, save length of previous.
if (Boolean.getBoolean(column.getAttribute(RichFaces.ATTR_BREAK_BEFORE))) {
count = Math.max(currentLength,count);
currentLength = 0;
}
String colspanStr = column.getAttribute("colspan"); //$NON-NLS-1$
Integer colspan = null;
try {
currentLength += Integer.parseInt(colspanStr);
} catch (NumberFormatException e) {
currentLength++;
}
} else if (nodeName.endsWith(RichFaces.TAG_COLUMN)) {
// UIColumn always have colspan == 1.
currentLength++;
}
}
}
return Math.max(currentLength,count);
}
/**
* @see org.jboss.tools.vpe.editor.template.VpeAbstractTemplate#validate(org.jboss.tools.vpe.editor.context.VpePageContext, org.w3c.dom.Node, org.mozilla.interfaces.nsIDOMDocument, org.jboss.tools.vpe.editor.template.VpeCreationData)
*/
@Override
public void validate(VpePageContext pageContext, Node sourceNode,
nsIDOMDocument visualDocument, VpeCreationData data) {
RichFacesDataTableChildrenEncoder.validateChildren(pageContext, sourceNode, visualDocument, data);
final RichFacesDataTableStyleClassesApplier styleClassesApplier =
new RichFacesDataTableStyleClassesApplier(visualDocument,
pageContext, sourceNode);
styleClassesApplier.applyClasses((nsIDOMElement) data.getNode());
}
@Override
public void removeAttribute(VpePageContext pageContext, Element sourceElement, nsIDOMDocument visualDocument, nsIDOMNode visualNode, Object data, String name) {
nsIDOMElement visualElement = (nsIDOMElement)visualNode.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
visualElement.removeAttribute(name);
}
@Override
public void setAttribute(VpePageContext pageContext, Element sourceElement, nsIDOMDocument visualDocument, nsIDOMNode visualNode, Object data, String name, String value) {
nsIDOMElement visualElement = (nsIDOMElement)visualNode.queryInterface(nsIDOMElement.NS_IDOMELEMENT_IID);
visualElement.setAttribute(name, value);
}
}
| true | true | public VpeCreationData create(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument) {
Element sourceElement = (Element)sourceNode;
nsIDOMElement table = visualDocument.createElement(HTML.TAG_TABLE);
VisualDomUtil.copyAttributes(sourceNode, table);
VpeCreationData creationData = new VpeCreationData(table);
ComponentUtil.setCSSLink(pageContext, "dataTable/dataTable.css", "richFacesDataTable"); //$NON-NLS-1$ //$NON-NLS-2$
String tableClass = sourceElement.getAttribute(RichFaces.ATTR_STYLE_CLASS);
table.setAttribute(HTML.ATTR_CLASS, "dr-table rich-table " + (tableClass==null?Constants.EMPTY:tableClass)); //$NON-NLS-1$
// Encode colgroup definition.
ArrayList<Element> columns = getColumns(sourceElement);
int columnsLength = getColumnsCount(sourceElement, columns);
nsIDOMElement colgroup = visualDocument.createElement(HTML.TAG_COLGROUP);
colgroup.setAttribute(HTML.ATTR_SPAN, String.valueOf(columnsLength));
table.appendChild(colgroup);
String columnsWidth = sourceElement.getAttribute(RichFaces.ATTR_COLUMNS_WIDTH);
if (null != columnsWidth) {
String[] widths = columnsWidth.split(Constants.COMMA);
for (int i = 0; i < widths.length; i++) {
nsIDOMElement col = visualDocument.createElement(HTML.TAG_COL);
col.setAttribute(HTML.ATTR_WIDTH, widths[i]);
colgroup.appendChild(col);
}
}
//Encode Caption
encodeCaption(creationData, sourceElement, visualDocument, table);
// Encode Header
Node header = ComponentUtil.getFacet((Element)sourceElement, RichFaces.NAME_FACET_HEADER,true);
final boolean hasColumnWithHeader = hasColumnWithFacet(columns, RichFaces.NAME_FACET_HEADER);
if(header!=null || hasColumnWithHeader) {
nsIDOMElement thead = visualDocument.createElement(HTML.TAG_THEAD);
table.appendChild(thead);
String headerClass = (String) sourceElement.getAttribute(RichFaces.ATTR_HEADER_CLASS);
if(header != null) {
encodeTableHeaderOrFooterFacet(pageContext, creationData, thead, columnsLength, visualDocument, header,
"dr-table-header rich-table-header", //$NON-NLS-1$
"dr-table-header-continue rich-table-header-continue", //$NON-NLS-1$
"dr-table-headercell rich-table-headercell", //$NON-NLS-1$
headerClass, HTML.TAG_TD);
}
if(hasColumnWithHeader) {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
thead.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, "dr-table-subheader rich-table-subheader", null, headerClass); //$NON-NLS-1$
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
encodeHeaderOrFooterFacets(pageContext, creationData, tr, visualDocument, columns,
"dr-table-subheadercell rich-table-subheadercell", //$NON-NLS-1$
headerClass, RichFaces.NAME_FACET_HEADER, HTML.TAG_TD);
}
}
// Encode Footer
Element footer = ComponentUtil.getFacet(sourceElement, RichFaces.NAME_FACET_FOOTER);
final boolean hasColumnWithFooter = hasColumnWithFacet(columns, RichFaces.NAME_FACET_FOOTER);
if (footer != null || hasColumnWithFooter) {
nsIDOMElement tfoot = visualDocument.createElement(HTML.TAG_TFOOT);
table.appendChild(tfoot);
String footerClass = (String) sourceElement.getAttribute(RichFaces.ATTR_FOOTER_CLASS);
if(hasColumnWithFooter) {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
tfoot.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, "dr-table-subfooter rich-table-subfooter", null, footerClass); //$NON-NLS-1$
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
encodeHeaderOrFooterFacets(pageContext, creationData, tr, visualDocument, columns,
"dr-table-subfootercell rich-table-subfootercell", //$NON-NLS-1$
footerClass, RichFaces.NAME_FACET_FOOTER, HTML.TAG_TD);
}
if (footer != null) {
encodeTableHeaderOrFooterFacet(pageContext, creationData, tfoot, columnsLength, visualDocument, footer,
"dr-table-footer rich-table-footer", //$NON-NLS-1$
"dr-table-footer-continue rich-table-footer-continue", //$NON-NLS-1$
"dr-table-footercell rich-table-footercell", //$NON-NLS-1$
footerClass,HTML.TAG_TD);
}
}
new RichFacesDataTableChildrenEncoder(creationData, visualDocument,
sourceElement, table).encodeChildren();
return creationData;
}
| public VpeCreationData create(VpePageContext pageContext, Node sourceNode, nsIDOMDocument visualDocument) {
Element sourceElement = (Element)sourceNode;
nsIDOMElement table = visualDocument.createElement(HTML.TAG_TABLE);
VisualDomUtil.copyAttributes(sourceNode, table);
VpeCreationData creationData = new VpeCreationData(table);
ComponentUtil.setCSSLink(pageContext, "dataTable/dataTable.css", "richFacesDataTable"); //$NON-NLS-1$ //$NON-NLS-2$
String tableClass = sourceElement.getAttribute(RichFaces.ATTR_STYLE_CLASS);
table.setAttribute(HTML.ATTR_CLASS, "dr-table rich-table " + (tableClass==null?Constants.EMPTY:tableClass)); //$NON-NLS-1$
// Encode colgroup definition.
ArrayList<Element> columns = getColumns(sourceElement);
int columnsLength = getColumnsCount(sourceElement, columns);
nsIDOMElement colgroup = visualDocument.createElement(HTML.TAG_COLGROUP);
colgroup.setAttribute(HTML.ATTR_SPAN, String.valueOf(columnsLength));
table.appendChild(colgroup);
String columnsWidth = sourceElement.getAttribute(RichFaces.ATTR_COLUMNS_WIDTH);
if (null != columnsWidth) {
String[] widths = columnsWidth.split(Constants.COMMA);
for (int i = 0; i < widths.length; i++) {
nsIDOMElement col = visualDocument.createElement(HTML.TAG_COL);
col.setAttribute(HTML.ATTR_WIDTH, widths[i]);
colgroup.appendChild(col);
}
}
//Encode Caption
encodeCaption(creationData, sourceElement, visualDocument, table);
// Encode Header
Node header = ComponentUtil.getFacet((Element)sourceElement, RichFaces.NAME_FACET_HEADER,true);
final boolean hasColumnWithHeader = hasColumnWithFacet(columns, RichFaces.NAME_FACET_HEADER);
if(header!=null || hasColumnWithHeader) {
nsIDOMElement thead = visualDocument.createElement(HTML.TAG_THEAD);
table.appendChild(thead);
String headerClass = (String) sourceElement.getAttribute(RichFaces.ATTR_HEADER_CLASS);
if(header != null) {
encodeTableHeaderOrFooterFacet(pageContext, creationData, thead, columnsLength, visualDocument, header,
"dr-table-header rich-table-header", //$NON-NLS-1$
"dr-table-header-continue rich-table-header-continue", //$NON-NLS-1$
"dr-table-headercell rich-table-headercell", //$NON-NLS-1$
headerClass, HTML.TAG_TD);
}
if(hasColumnWithHeader) {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
thead.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, "dr-table-subheader rich-table-subheader", null, headerClass); //$NON-NLS-1$
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
encodeHeaderOrFooterFacets(pageContext, creationData, tr, visualDocument, columns,
"dr-table-subheadercell rich-table-subheadercell", //$NON-NLS-1$
headerClass, RichFaces.NAME_FACET_HEADER, HTML.TAG_TD);
}
}
// Encode Footer
Node footer = ComponentUtil.getFacet((Element)sourceElement, RichFaces.NAME_FACET_FOOTER,true);
final boolean hasColumnWithFooter = hasColumnWithFacet(columns, RichFaces.NAME_FACET_FOOTER);
if (footer != null || hasColumnWithFooter) {
nsIDOMElement tfoot = visualDocument.createElement(HTML.TAG_TFOOT);
table.appendChild(tfoot);
String footerClass = (String) sourceElement.getAttribute(RichFaces.ATTR_FOOTER_CLASS);
if(hasColumnWithFooter) {
nsIDOMElement tr = visualDocument.createElement(HTML.TAG_TR);
tfoot.appendChild(tr);
String styleClass = ComponentUtil.encodeStyleClass(null, "dr-table-subfooter rich-table-subfooter", null, footerClass); //$NON-NLS-1$
if(styleClass!=null) {
tr.setAttribute(HTML.ATTR_CLASS, styleClass);
}
encodeHeaderOrFooterFacets(pageContext, creationData, tr, visualDocument, columns,
"dr-table-subfootercell rich-table-subfootercell", //$NON-NLS-1$
footerClass, RichFaces.NAME_FACET_FOOTER, HTML.TAG_TD);
}
if (footer != null) {
encodeTableHeaderOrFooterFacet(pageContext, creationData, tfoot, columnsLength, visualDocument, footer,
"dr-table-footer rich-table-footer", //$NON-NLS-1$
"dr-table-footer-continue rich-table-footer-continue", //$NON-NLS-1$
"dr-table-footercell rich-table-footercell", //$NON-NLS-1$
footerClass,HTML.TAG_TD);
}
}
new RichFacesDataTableChildrenEncoder(creationData, visualDocument,
sourceElement, table).encodeChildren();
return creationData;
}
|
diff --git a/Project_Files/GroupThread.java b/Project_Files/GroupThread.java
index b3b6252..fa4d5ab 100644
--- a/Project_Files/GroupThread.java
+++ b/Project_Files/GroupThread.java
@@ -1,454 +1,454 @@
/* This thread does all the work. It communicates with the client through Envelopes.
*
*/
import java.lang.Thread;
import java.net.Socket;
import java.io.*;
import java.util.*;
public class GroupThread extends Thread
{
private final Socket socket;
private GroupServer my_gs;
//These get spun off from GroupServer
public GroupThread(Socket _socket, GroupServer _gs)
{
socket = _socket;
my_gs = _gs;
}
public void run()
{
boolean proceed = true;
try
{
//Announces connection and opens object streams
System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***");
final ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
//handle messages from the input stream(ie. socket)
do
{
Envelope message = (Envelope)input.readObject();
System.out.println("Request received: " + message.getMessage());
Envelope response;
//--GET TOKEN---------------------------------------------------------------------------------------------------------
if(message.getMessage().equals("GET"))//Client wants a token
{
String username = (String)message.getObjContents().get(0); //Get the username
if(username == null || !my_gs.userList.checkUser(username))
{
response = new Envelope("FAIL");
response.addObject(null);
output.writeObject(response);
}
else
{
UserToken yourToken = createToken(username); //Create a token
//Respond to the client. On error, the client will receive a null token
response = new Envelope("OK");
response.addObject(yourToken);
output.writeObject(response);
}
}
//--CREATE USER-------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("CUSER")) //Client wants to create a user
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the user if the username/token allow it
if(createUser(username, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--DELETE USER---------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DUSER")) //Client wants to delete a user
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the user if the username/token allow it
if(deleteUser(username, yourToken))
{
response = new Envelope("OK"); //Success
}
else response = new Envelope("You could not delete the user");
}
}
}
output.writeObject(response);
}
//--CREATE GROUP---------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("CGROUP")) //Client wants to create a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the group if the it doesn't already exist
if(createGroup(groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
output.writeObject(response);
}
//--DELETE GROUP--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DGROUP")) //Client wants to delete a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the group if the it doesn't already exist
if(deleteGroup(groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
else response = new Envelope("You could not delete the group.");
}
}
output.writeObject(response);
}
//--LIST MEMBERS--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("LMEMBERS")) //Client wants a list of members in a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
ArrayList<String> users = listMembers(groupName, yourToken);
- if(users.size() > 0)
+ if(users != null && users.size() > 0)
{
response = new Envelope("OK");
response.addObject(users);
}
else//no files exist
{
response = new Envelope("FAIL-NOUSERS");
}
}
}
output.writeObject(response);
}
//--ADD TO GROUP--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("AUSERTOGROUP")) //Client wants to add user to a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 2)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0); //Extract the user name
String groupName = (String)message.getObjContents().get(1); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(2); //Extract the token
//verify the owner
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
//create the group if the it doesn't already exist
if(addToGroup(userName, groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--REMOVE FROM GROUP----------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("RUSERFROMGROUP")) //Client wants to remove user from a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0); //Extract the user name
String groupName = (String)message.getObjContents().get(1); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(2); //Extract the token
//verify the owner
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
//create the group if the it doesn't already exist
if(removeFromGroup(userName, groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--DISCONNECT----------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DISCONNECT")) //Client wants to disconnect
{
socket.close(); //Close the socket
proceed = false; //End this communication loop
}
else
{
response = new Envelope("FAIL"); //Server does not understand client request
output.writeObject(response);
}
}while(proceed);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
//Method to create tokens
private UserToken createToken(String username)
{
//Check that user exists
if(my_gs.userList.checkUser(username))
{
//Issue a new token with server's name, user's name, and user's groups
UserToken yourToken = new UserToken(my_gs.name, username, my_gs.userList.getUserGroups(username));
return yourToken;
}
else
{
return null;
}
}
//Method to create a user
private boolean createUser(String username, UserToken yourToken)
{
String requester = yourToken.getSubject();
//Check if requester exists
if(my_gs.userList.checkUser(requester))
{
//Get the user's groups
ArrayList<String> temp = my_gs.userList.getUserGroups(requester);
//requester needs to be an administrator
if(temp.contains("ADMIN"))
{
//Does user already exist?
if(my_gs.userList.checkUser(username))
{
return false; //User already exists
}
else
{
my_gs.userList.addUser(username);
return true;
}
}
else
{
return false; //requester not an administrator
}
}
else
{
return false; //requester does not exist
}
}
//Method to delete a user
private boolean deleteUser(String username, UserToken yourToken)
{
String requester = yourToken.getSubject();
//Does requester exist?
if(my_gs.userList.checkUser(requester))
{
ArrayList<String> temp = my_gs.userList.getUserGroups(requester);
//requester needs to be an administer
if(temp.contains("ADMIN"))
{
//Does user exist?
if(my_gs.userList.checkUser(username))
{
//User needs deleted from the groups they belong
ArrayList<String> deleteFromGroups = new ArrayList<String>();
//This will produce a hard copy of the list of groups this user belongs
for(int index = 0; index < my_gs.userList.getUserGroups(username).size(); index++)
{
deleteFromGroups.add(my_gs.userList.getUserGroups(username).get(index));
}
//Delete the user from the groups
//If user is the owner, removeMember will automatically delete group!
for(int index = 0; index < deleteFromGroups.size(); index++)
{
//NOTE: removed due to compiling error... waht happened to this function, should we add it? - jmh 2/10
my_gs.groupList.removeMember(deleteFromGroups.get(index), username);
}
//If groups are owned, they must be deleted
ArrayList<String> deleteOwnedGroup = new ArrayList<String>();
//Make a hard copy of the user's ownership list
for(int index = 0; index < my_gs.userList.getUserOwnership(username).size(); index++)
{
deleteOwnedGroup.add(my_gs.userList.getUserOwnership(username).get(index));
}
//Delete owned groups
for(int index = 0; index < deleteOwnedGroup.size(); index++)
{
//Use the delete group method. UserToken must be created for this action
deleteGroup(deleteOwnedGroup.get(index), new UserToken(my_gs.name, username, deleteOwnedGroup));
}
//Delete the user from the user list
my_gs.userList.deleteUser(username);
return true;
}
else
{
return false; //User does not exist
}
}
else
{
return false; //requester is not an administer
}
}
else
{
return false; //requester does not exist
}
}
//----------------------------------------------------------------------------------------------------------------------
//-- UTILITY FUNCITONS
//----------------------------------------------------------------------------------------------------------------------
private boolean createGroup(String groupName, UserToken yourToken)
{
//Check if group exists
if(!my_gs.groupList.checkGroup(groupName))
{
my_gs.createGroup(groupName, yourToken.getSubject());
return true;
}
return false; //requester does not exist
}
private boolean deleteGroup(String groupName, UserToken yourToken)
{
//verify that the group exists, and that the user is an owner
if(my_gs.groupList.checkGroup(groupName) && my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
my_gs.deleteGroup(groupName);
return true;
}
return false;
}
private ArrayList<String> listMembers(String groupName, UserToken yourToken)
{
ArrayList<String> members = null;
//verify that the group exists, and that the user is an owner
if(my_gs.groupList.checkGroup(groupName) && my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
members = my_gs.groupList.getGroupMembers(groupName);
}
return members;
}
private boolean addToGroup(String userName, String groupName, UserToken yourToken)
{
//verify that the group exists, that the user is an owner, and that the user isnt already a member
if(my_gs.groupList.checkGroup(groupName) && my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject())
&& !my_gs.groupList.getGroupMembers(groupName).contains(userName))
{
my_gs.addUserToGroup(groupName, userName);
}
return false;
}
private boolean removeFromGroup(String userName, String groupName, UserToken yourToken)
{
//verify that the group exists, and that the user is an owner
if(my_gs.groupList.checkGroup(groupName) && my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
my_gs.removeUserFromGroup(groupName, userName);
}
return false;
}
private boolean disconnect(String userName, UserToken yourToken)
{
return false;
}
}
| true | true | public void run()
{
boolean proceed = true;
try
{
//Announces connection and opens object streams
System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***");
final ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
//handle messages from the input stream(ie. socket)
do
{
Envelope message = (Envelope)input.readObject();
System.out.println("Request received: " + message.getMessage());
Envelope response;
//--GET TOKEN---------------------------------------------------------------------------------------------------------
if(message.getMessage().equals("GET"))//Client wants a token
{
String username = (String)message.getObjContents().get(0); //Get the username
if(username == null || !my_gs.userList.checkUser(username))
{
response = new Envelope("FAIL");
response.addObject(null);
output.writeObject(response);
}
else
{
UserToken yourToken = createToken(username); //Create a token
//Respond to the client. On error, the client will receive a null token
response = new Envelope("OK");
response.addObject(yourToken);
output.writeObject(response);
}
}
//--CREATE USER-------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("CUSER")) //Client wants to create a user
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the user if the username/token allow it
if(createUser(username, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--DELETE USER---------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DUSER")) //Client wants to delete a user
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the user if the username/token allow it
if(deleteUser(username, yourToken))
{
response = new Envelope("OK"); //Success
}
else response = new Envelope("You could not delete the user");
}
}
}
output.writeObject(response);
}
//--CREATE GROUP---------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("CGROUP")) //Client wants to create a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the group if the it doesn't already exist
if(createGroup(groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
output.writeObject(response);
}
//--DELETE GROUP--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DGROUP")) //Client wants to delete a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the group if the it doesn't already exist
if(deleteGroup(groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
else response = new Envelope("You could not delete the group.");
}
}
output.writeObject(response);
}
//--LIST MEMBERS--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("LMEMBERS")) //Client wants a list of members in a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
ArrayList<String> users = listMembers(groupName, yourToken);
if(users.size() > 0)
{
response = new Envelope("OK");
response.addObject(users);
}
else//no files exist
{
response = new Envelope("FAIL-NOUSERS");
}
}
}
output.writeObject(response);
}
//--ADD TO GROUP--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("AUSERTOGROUP")) //Client wants to add user to a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 2)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0); //Extract the user name
String groupName = (String)message.getObjContents().get(1); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(2); //Extract the token
//verify the owner
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
//create the group if the it doesn't already exist
if(addToGroup(userName, groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--REMOVE FROM GROUP----------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("RUSERFROMGROUP")) //Client wants to remove user from a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0); //Extract the user name
String groupName = (String)message.getObjContents().get(1); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(2); //Extract the token
//verify the owner
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
//create the group if the it doesn't already exist
if(removeFromGroup(userName, groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--DISCONNECT----------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DISCONNECT")) //Client wants to disconnect
{
socket.close(); //Close the socket
proceed = false; //End this communication loop
}
else
{
response = new Envelope("FAIL"); //Server does not understand client request
output.writeObject(response);
}
}while(proceed);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
| public void run()
{
boolean proceed = true;
try
{
//Announces connection and opens object streams
System.out.println("*** New connection from " + socket.getInetAddress() + ":" + socket.getPort() + "***");
final ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
final ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
//handle messages from the input stream(ie. socket)
do
{
Envelope message = (Envelope)input.readObject();
System.out.println("Request received: " + message.getMessage());
Envelope response;
//--GET TOKEN---------------------------------------------------------------------------------------------------------
if(message.getMessage().equals("GET"))//Client wants a token
{
String username = (String)message.getObjContents().get(0); //Get the username
if(username == null || !my_gs.userList.checkUser(username))
{
response = new Envelope("FAIL");
response.addObject(null);
output.writeObject(response);
}
else
{
UserToken yourToken = createToken(username); //Create a token
//Respond to the client. On error, the client will receive a null token
response = new Envelope("OK");
response.addObject(yourToken);
output.writeObject(response);
}
}
//--CREATE USER-------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("CUSER")) //Client wants to create a user
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the user if the username/token allow it
if(createUser(username, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--DELETE USER---------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DUSER")) //Client wants to delete a user
{
if(message.getObjContents().size() < 2)
{
response = new Envelope("FAIL");
}
else
{
response = new Envelope("FAIL");
if(message.getObjContents().get(0) != null)
{
if(message.getObjContents().get(1) != null)
{
String username = (String)message.getObjContents().get(0); //Extract the username
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the user if the username/token allow it
if(deleteUser(username, yourToken))
{
response = new Envelope("OK"); //Success
}
else response = new Envelope("You could not delete the user");
}
}
}
output.writeObject(response);
}
//--CREATE GROUP---------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("CGROUP")) //Client wants to create a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the group if the it doesn't already exist
if(createGroup(groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
output.writeObject(response);
}
//--DELETE GROUP--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DGROUP")) //Client wants to delete a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
//create the group if the it doesn't already exist
if(deleteGroup(groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
else response = new Envelope("You could not delete the group.");
}
}
output.writeObject(response);
}
//--LIST MEMBERS--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("LMEMBERS")) //Client wants a list of members in a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String groupName = (String)message.getObjContents().get(0); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(1); //Extract the token
ArrayList<String> users = listMembers(groupName, yourToken);
if(users != null && users.size() > 0)
{
response = new Envelope("OK");
response.addObject(users);
}
else//no files exist
{
response = new Envelope("FAIL-NOUSERS");
}
}
}
output.writeObject(response);
}
//--ADD TO GROUP--------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("AUSERTOGROUP")) //Client wants to add user to a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 2)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0); //Extract the user name
String groupName = (String)message.getObjContents().get(1); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(2); //Extract the token
//verify the owner
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
//create the group if the it doesn't already exist
if(addToGroup(userName, groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--REMOVE FROM GROUP----------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("RUSERFROMGROUP")) //Client wants to remove user from a group
{
//if the message is too short, return failure
response = new Envelope("FAIL");
if(message.getObjContents().size() > 1)
{
//get the elements of the message
if(message.getObjContents().get(0) != null && message.getObjContents().get(1) != null)
{
String userName = (String)message.getObjContents().get(0); //Extract the user name
String groupName = (String)message.getObjContents().get(1); //Extract the group name
UserToken yourToken = (UserToken)message.getObjContents().get(2); //Extract the token
//verify the owner
if(my_gs.groupList.getGroupOwners(groupName).contains(yourToken.getSubject()))
{
//create the group if the it doesn't already exist
if(removeFromGroup(userName, groupName, yourToken))
{
response = new Envelope("OK"); //Success
}
}
}
}
output.writeObject(response);
}
//--DISCONNECT----------------------------------------------------------------------------------------------------------
else if(message.getMessage().equals("DISCONNECT")) //Client wants to disconnect
{
socket.close(); //Close the socket
proceed = false; //End this communication loop
}
else
{
response = new Envelope("FAIL"); //Server does not understand client request
output.writeObject(response);
}
}while(proceed);
}
catch(Exception e)
{
System.err.println("Error: " + e.getMessage());
e.printStackTrace(System.err);
}
}
|
diff --git a/org.springsource.ide.eclipse.gradle.core.test/src/org/springsource/ide/eclipse/gradle/core/test/GradleImportTests.java b/org.springsource.ide.eclipse.gradle.core.test/src/org/springsource/ide/eclipse/gradle/core/test/GradleImportTests.java
index 755627c..a7ea01f 100644
--- a/org.springsource.ide.eclipse.gradle.core.test/src/org/springsource/ide/eclipse/gradle/core/test/GradleImportTests.java
+++ b/org.springsource.ide.eclipse.gradle.core.test/src/org/springsource/ide/eclipse/gradle/core/test/GradleImportTests.java
@@ -1,1192 +1,1193 @@
/*******************************************************************************
* Copyright (c) 2012 VMWare, 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:
* VMWare, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.gradle.core.test;
import static org.junit.Assert.assertArrayEquals;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.codehaus.groovy.eclipse.core.builder.GroovyClasspathContainer;
import org.codehaus.groovy.eclipse.dsl.GroovyDSLCoreActivator;
import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.springsource.ide.eclipse.gradle.core.ClassPath;
import org.springsource.ide.eclipse.gradle.core.GradleCore;
import org.springsource.ide.eclipse.gradle.core.GradleNature;
import org.springsource.ide.eclipse.gradle.core.GradleProject;
import org.springsource.ide.eclipse.gradle.core.actions.GradleRefreshPreferences;
import org.springsource.ide.eclipse.gradle.core.actions.RefreshAllActionCore;
import org.springsource.ide.eclipse.gradle.core.actions.RefreshDependenciesActionCore;
import org.springsource.ide.eclipse.gradle.core.classpathcontainer.GradleClassPathContainer;
import org.springsource.ide.eclipse.gradle.core.dsld.DSLDSupport;
import org.springsource.ide.eclipse.gradle.core.dsld.GradleDSLDClasspathContainer;
import org.springsource.ide.eclipse.gradle.core.launch.GradleLaunchConfigurationDelegate;
import org.springsource.ide.eclipse.gradle.core.launch.GradleProcess;
import org.springsource.ide.eclipse.gradle.core.launch.LaunchUtil;
import org.springsource.ide.eclipse.gradle.core.m2e.M2EUtils;
import org.springsource.ide.eclipse.gradle.core.preferences.GradleAPIProperties;
import org.springsource.ide.eclipse.gradle.core.preferences.GradleProjectPreferences;
import org.springsource.ide.eclipse.gradle.core.test.util.ACondition;
import org.springsource.ide.eclipse.gradle.core.test.util.ExternalCommand;
import org.springsource.ide.eclipse.gradle.core.test.util.GitProject;
import org.springsource.ide.eclipse.gradle.core.test.util.JUnitLaunchConfigUtil;
import org.springsource.ide.eclipse.gradle.core.test.util.JavaXXRuntime;
import org.springsource.ide.eclipse.gradle.core.test.util.MavenCommand;
import org.springsource.ide.eclipse.gradle.core.test.util.TestUtils;
import org.springsource.ide.eclipse.gradle.core.util.ErrorHandler;
import org.springsource.ide.eclipse.gradle.core.util.Joinable;
import org.springsource.ide.eclipse.gradle.core.util.NatureUtils;
import org.springsource.ide.eclipse.gradle.core.util.TimeUtils;
import org.springsource.ide.eclipse.gradle.core.wizards.GradleImportOperation;
import org.springsource.ide.eclipse.gradle.core.wtp.WTPUtil;
import org.springsource.ide.eclipse.gradle.ui.actions.EnableDisableDependencyManagementActionDelegate;
/**
* Basic tests for the GradleImport operation. Imports a project, all its subprojects using
* default settings.
*
* @author Kris De Volder
*/
public class GradleImportTests extends GradleTest {
public void testImportNoClasspathContainer() throws Exception {
String projectName = "quickstart";
File projectLoc = extractJavaSample(projectName);
GradleImportOperation importOp = importTestProjectOperation(projectLoc);
importOp.setEnableDependencyManagement(false); //use default values for everything else.
boolean expectDsld = importOp.getEnableDSLD();
performImport(importOp);
GradleProject project = getGradleProject(projectName);
assertProjects(projectName); //no compile errors?
assertFalse("Shouldn't have classpath container",
GradleClassPathContainer.isOnClassPath(project.getJavaProject()));
assertEquals("DSLD support enablement state", expectDsld, DSLDSupport.getInstance().isEnabled(project));
assertTrue("Gradle nature added?", GradleNature.hasNature(getProject(projectName)));
}
public void testImportNoDSLDSupport() throws Exception {
String projectName = "quickstart";
File projectLoc = extractJavaSample(projectName);
GradleImportOperation importOp = importTestProjectOperation(projectLoc);
importOp.setEnableDSLD(false); //use default values for everything else.
performImport(importOp);
GradleProject project = getGradleProject(projectName);
assertProjects(projectName); //no compile errors?
assertTrue("Should have classpath container", GradleClassPathContainer.isOnClassPath(project.getJavaProject()));
assertFalse("DSLD support added?", DSLDSupport.getInstance().isEnabled(project));
assertTrue("Gradle nature added?", GradleNature.hasNature(getProject(projectName)));
}
public void testImportNoClasspathContainerNoDSLDSupport() throws Exception {
String projectName = "quickstart";
File projectLoc = extractJavaSample(projectName);
GradleImportOperation importOp = importTestProjectOperation(projectLoc);
importOp.setEnableDependencyManagement(false);
importOp.setEnableDSLD(false);
performImport(importOp);
GradleProject project = getGradleProject(projectName);
assertProjects(projectName); //no compile errors?
assertFalse("Shouldn't have classpath container",
GradleClassPathContainer.isOnClassPath(project.getJavaProject()));
assertFalse("DSLD support should not have been added", DSLDSupport.getInstance().isEnabled(project));
assertTrue("Gradle nature added?", GradleNature.hasNature(getProject(projectName)));
}
public void testImportSpringFramework() throws Exception {
JavaXXRuntime.java7everyone();
String[] projectNames = {
"spring",
"spring-aop",
"spring-aspects",
"spring-beans",
"spring-build-src",
"spring-context",
"spring-context-support",
"spring-core",
"spring-expression",
"spring-instrument",
"spring-instrument-tomcat",
"spring-jdbc",
"spring-jms",
"spring-orm",
"spring-orm-hibernate4",
"spring-oxm",
"spring-test",
"spring-test-mvc",
"spring-tx",
"spring-web",
"spring-webmvc",
"spring-webmvc-portlet",
"spring-webmvc-tiles3"
};
// boolean good = false;
// while(!good) {
// try {
// Thread.sleep(20000); //Wait out the !@#$ interrupted exception that eclipse is sending.
// good = true;
// } catch (InterruptedException e) {
// }
// }
//
URI distro = new URI("http://services.gradle.org/distributions/gradle-1.3-bin.zip");
GradleCore.getInstance().getPreferences().setDistribution(distro);
final GradleImportOperation importOp = importGitProjectOperation(new GitProject("spring-framework",
new URI("git://github.com/SpringSource/spring-framework.git"),
"db3bbb5f8cb945b8f29fbd83aff9bbd2dbc70e1c"
)
);
String[] beforeTasks = {
//These tasks are set based on the shell script included with spring framework:
//https://github.com/SpringSource/spring-framework/blob/0ae973f995229bce0c5b9ffe25fe1f5340559656/import-into-eclipse.sh
"cleanEclipse",
":spring-oxm:compileTestJava",
"eclipse"
};
importOp.setEnableDSLD(false); // cause some compilation errors in this project so turn off
importOp.setEnableDependencyManagement(false);
importOp.setDoBeforeTasks(true);
importOp.setBeforeTasks(beforeTasks);
performImport(importOp,
//Ignore errors: (expected!)
"Project 'spring-aspects' is an AspectJ project"
);
// for (IProject p : ResourcesPlugin.getWorkspace().getRoot().getProjects()) {
// System.out.println(p.getName());
// }
//check that the refresh preferences got setup properly (only checking one property).
//the one that has a non-default value.
GradleProject project = getGradleProject("spring-aspects");
GradleRefreshPreferences prefs = project.getRefreshPreferences();
assertArrayEquals(beforeTasks, prefs.getBeforeTasks());
assertProjects(projectNames);
}
public void testSTS2407OutputFolderDependencyInNestedMultiproject() throws Exception {
String[] projectNames = {
"sts-2407",
"buildutilities",
"projectA",
"projectB",
"projectC",
"projectD",
};
importTestProject(projectNames[0]);
assertProjects(projectNames);
}
public void testSTS2276SetJavaHome() throws Exception {
//This test merely verifies whether nothing breaks when we set the JavaHome property.
//It doesn't actually test whether this setting actually makes Gradle use that JVM (how could we test that???)
IVMInstall defaultVM = JavaRuntime.getDefaultVMInstall();
try {
GradleCore.getInstance().getPreferences().setJavaHomeJREName(defaultVM.getName());
String projectName = "multiproject";
String subprojectName = "subproject";
importTestProject(projectName);
assertProjects(
projectName,
subprojectName);
} finally {
GradleCore.getInstance().getPreferences().unsetJavaHome(); //Reset to default
}
}
public void testImportSpringSecurity() throws Exception {
//TODO: test currently failing.
/// See http://forums.gradle.org/gradle/topics/tooling_api_1_2_model_build_fails_when_there_are_unresolved_dependencies
setSnapshotDistro();
GradleImportOperation importOp = importGitProjectOperation(new GitProject("spring-security",
new URI("git://github.com/SpringSource/spring-security.git"),
"66357a2077cb3d94657a5b759771572a341e55f4"
//"191fc9c8be80c7338ab8e183014de48f78fcffd1"
));
importOp.setDoBeforeTasks(true);
performImport(importOp,
//Ignore errors: (expected!)
"Project 'spring-security-aspects' is an AspectJ project",
"Project 'spring-security-samples-aspectj' is an AspectJ project"
);
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject proj : projects) {
System.out.println("\""+proj.getName()+"\","); //print out in a format convenient to copy paste below
}
assertProjects(
"docs-3.2.x",
"faq-3.2.x",
"itest-context-3.2.x",
"itest-web-3.2.x",
"manual-3.2.x",
"spring-security-3.2.x",
"spring-security-acl-3.2.x",
"spring-security-aspects-3.2.x",
"spring-security-cas-3.2.x",
"spring-security-config-3.2.x",
"spring-security-core-3.2.x",
"spring-security-crypto-3.2.x",
"spring-security-ldap-3.2.x",
"spring-security-openid-3.2.x",
"spring-security-remoting-3.2.x",
"spring-security-samples-aspectj-3.2.x",
"spring-security-samples-cassample-3.2.x",
"spring-security-samples-casserver-3.2.x",
"spring-security-samples-contacts-3.2.x",
"spring-security-samples-dms-3.2.x",
"spring-security-samples-gae-3.2.x",
"spring-security-samples-jaas-3.2.x",
"spring-security-samples-ldap-3.2.x",
"spring-security-samples-openid-3.2.x",
"spring-security-samples-preauth-3.2.x",
"spring-security-samples-servletapi-3.2.x",
"spring-security-samples-tutorial-3.2.x",
"spring-security-taglibs-3.2.x",
"spring-security-web-3.2.x"
);
assertTrue(WTPUtil.isWTPProject(getProject("spring-security-samples-jaas-3.2.x")));
}
public void testSTS2185AddWebAppLibrariesContainerToWTPProjects() throws Exception {
assertTrue("This test requires WTP functionality to be installed", WTPUtil.isInstalled());
String[] projectNames = {
"sts2185",
"A",
"B"
};
importTestProject(projectNames[0]);
assertProjects(projectNames);
new ACondition("testSTS2185AddWebAppLibrariesContainerToWTPProjects") {
@Override
public boolean test() throws Exception {
/////////////////////
//Check project A:
{
IJavaProject project = getJavaProject("A");
IClasspathEntry[] rawClasspath = project.getRawClasspath();
IClasspathEntry[] resolvedClasspath = project.getResolvedClasspath(false);
//Can we find the expected class path container?
assertClasspathContainer(rawClasspath, WTPUtil.JST_J2EE_WEB_CONTAINER);
//Can we find 'junk.jar' from the WEB-INF/lib directory of project A.
assertClasspathJarEntry("junk.jar", resolvedClasspath);
}
/////////////////////
//Check project B:
{
IJavaProject project = getJavaProject("B");
IClasspathEntry[] rawClasspath = project.getRawClasspath();
//It is a WTP project...
assertTrue(WTPUtil.isWTPProject(project.getProject()));
//... but shouldn't have libraries container because not a jst.web project.
assertNoClasspathContainer(rawClasspath, WTPUtil.JST_J2EE_WEB_CONTAINER);
}
return true;
}
}.waitFor(10000);
}
private void assertNoClasspathContainer(IClasspathEntry[] rawClasspath, String pathStr) {
IPath path = new Path(pathStr);
StringBuilder msg = new StringBuilder();
for (IClasspathEntry e : rawClasspath) {
if (e.getEntryKind()==IClasspathEntry.CPE_CONTAINER) {
if (path.equals(e.getPath())) {
fail("Found classpath container but shouldn't '"+pathStr+"':\n"+msg.toString());
}
}
msg.append(e+"\n");
}
}
public void testSTS1842SubProjectsWithSlashesInTheirName() throws Exception {
String[] projectNames = {
"sts1842",
"greeteds.world",
"hello"
};
importTestProject(projectNames[0]);
assertProjects(projectNames);
}
public void _testSTS1950RuntimeClasspathMergingFromSubprojectContainers() throws Exception {
//TODO: This test was disabled because test projects had a bunch of jars in it that
// we would have to raise IP log tickets for to put it on the open-sourced git repo.
// Should try to reinstate the test in future.
String[] projectNames = {
"sts1950",
"A", "B", "C"
};
importTestProject(projectNames[0]);
assertProjects(projectNames);
IJavaProject project = getJavaProject("B");
ILaunchConfigurationWorkingCopy launchConf = JUnitLaunchConfigUtil.createLaunchConfiguration(project);
IRuntimeClasspathEntry[] classpath = JavaRuntime.computeUnresolvedRuntimeClasspath(launchConf);
System.out.println(">>> Raw runtime classpath for B");
for (IRuntimeClasspathEntry e : classpath) {
System.out.println(e);
}
System.out.println("<<< Raw runtime classpath for B");
IRuntimeClasspathEntry[] runtimeClasspath = JavaRuntime.resolveRuntimeClasspath(classpath, launchConf);
System.out.println(">>> Runtime classpath for B");
for (IRuntimeClasspathEntry entry : runtimeClasspath) {
System.out.println(entry);
}
System.out.println("<<< Runtime classpath for B");
assertClasspathEntry("glazedlists-1.8.0-java15.jar", runtimeClasspath);
assertClasspathEntry("junit-4.4.jar", runtimeClasspath);
}
private void assertClasspathEntry(String jarFile, IRuntimeClasspathEntry[] runtimeClasspath) {
StringBuilder msg = new StringBuilder("Not found: "+jarFile+"\nFound:\n");
for (IRuntimeClasspathEntry e : runtimeClasspath) {
if (e.getType() == IRuntimeClasspathEntry.ARCHIVE) {
String path = e.getPath().toString();
if (path.endsWith(jarFile)) {
return; //OK
}
}
msg.append(e.toString()+"\n");
}
fail(msg.toString());
}
public void testSTS2202ImportFromSymlink() throws Exception {
//Reuse test project for sts2175
String[] projectNames = {
"sts2175",
"suba",
"subb",
"subc"
};
File testProj = getTestProjectCopy(projectNames[0]);
File tmpDir = TestUtils.createTempDirectory();
File link = new File(tmpDir, projectNames[0]);
Process process = Runtime.getRuntime().exec(new String[] {
"ln",
"-s",
testProj.toString(),
link.toString()
});
assertEquals(0, process.waitFor());
assertTrue(link.exists());
assertTrue(link.isDirectory());
importTestProject(link);
assertProjects(projectNames);
}
// /**
// * Projects that use version of wrapper generated pre 0.9 will have a wrapper properties file
// * that can't be read by 1.0-milestone-3, this causes a crash without a very good error message.
// * <p>
// * We attempt to recover from it by forcing a more recent version of Gradle, bypassing the wrapper
// * completely.
// *
// * @throws Exception
// */
// public void testImportOldWrapperFormat() throws Exception {
// String projectName = "oldWrapperFormat";
// GradleTest.MockFallBackDialog dialog = new GradleTest.MockFallBackDialog(true);
// FallBackDistributionCore.setTestDialogProvider(dialog);
//
// importTestProject(projectName);
// assertTrue(""+dialog.projectLoc, (""+dialog.projectLoc).endsWith(projectName)); //check if dialog called as expected
//
// assertProjects(projectName); //Check project imported and no errors.
// }
// /**
// * Different from earlier case: the wrapper format is readable by the tooling API, but it
// * specifies a version of Gradle that is too old.
// * <p>
// * Again, we should attempt to recover by trying to use more recent version.
// */
// public void testImportTooOldVersionInWrapper() throws Exception {
// String projectName = "oldWrapperVersion";
// GradleTest.MockFallBackDialog dialog = new GradleTest.MockFallBackDialog(true);
// FallBackDistributionCore.setTestDialogProvider(dialog);
//
// importTestProject(projectName);
// assertTrue(""+dialog.projectLoc, (""+dialog.projectLoc).endsWith(projectName)); //check if dialog called as expected
//
// assertProjects(projectName); //Check project imported and no errors.
// }
public void testSTS2058ImportProjectThatIsStoredInWorkspaceLocation() throws Exception {
IPath workspaceLoc = Platform.getLocation();
String[] projectNames = {
"multiproject",
"api",
"services",
"services-shared",
"webservice",
"shared"
};
String projectName = projectNames[0];
File orgTestProject = extractJavaSample(projectName);
File inWorkspaceCopy = new File(workspaceLoc.toFile(), projectName);
FileUtils.copyDirectory(orgTestProject, inWorkspaceCopy);
importTestProject(inWorkspaceCopy);
assertProjects(
projectNames
);
IJavaProject shared = getJavaProject("shared");
assertSourceFolder(shared, "src/main/java");
assertSourceFolder(shared, "src/main/resources");
assertSourceFolder(shared, "src/test/java");
assertSourceFolder(shared, "src/test/resources");
}
public void testImportSpringDataRedis() throws Exception {
GradleCore.getInstance().getPreferences().unsetJavaHome();
// JavaUtils.setJava15Compliance();
setSnapshotDistro();
importGitProject(new GitProject("spring-data-redis",
new URI("git://github.com/SpringSource/spring-data-redis.git"),
"9a31eb13")
);
// IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
// for (IProject proj : projects) {
// System.out.println(proj);
// }
assertProjects(
"spring-data-redis",
"docs"
);
}
/**
* Import preserves existing source folder exclusion filters?
*/
public void testSTS2205PreserveSourceFolderExclusions() throws Exception {
String projectName = "sts_2205";
File projectLoc = getTestProjectCopy(projectName);
GradleImportOperation importOp = importTestProjectOperation(projectLoc);
//Check that the import operation has the expected default options
assertTrue(importOp.getDoBeforeTasks());
assertTrue(importOp.getDoAfterTasks());
assertArrayEquals(new String[] { "cleanEclipse", "eclipse" },
importOp.getBeforeTasks());
assertArrayEquals(new String[] { "afterEclipseImport" },
importOp.getAfterTasks());
importOp.perform(defaultTestErrorHandler(), new NullProgressMonitor());
assertProjects(projectName);
//Check expected source folder has expected exclusions
GradleProject gp = getGradleProject(projectName);
ClassPath classpath = gp.getClassPath();
IClasspathEntry[] srcFolders = classpath.getSourceFolders();
assertEquals("Source folder count", 1, srcFolders.length);
IClasspathEntry entry = srcFolders[0];
IPath[] exclusions = entry.getExclusionPatterns();
assertArrayEquals(new IPath[] { new Path("testb2/**/*")},
exclusions);
}
public void testImportJavaQuickStart() throws Exception {
GradleClassPathContainer.DEBUG = true;
String name = "quickstart";
importSampleProject(name);
IJavaProject project = getJavaProject(name);
dumpJavaProjectInfo(project);
assertProjects(name);
assertJarEntry(project, "commons-collections-3.2.jar", true);
assertJarEntry(project, "junit-4.11.jar", true);
// assertJarEntry(project, "bogus-4.8.2.jar", true);
}
/**
* Test whether afterImportTasks are executed after an import
*/
public void testAfterImportTasksExecuted() throws Exception {
String projName = "afterImportTask";
//Create a simple test project with a simple tasks
GradleTaskRunTest.simpleProject(projName,
"apply plugin: 'java'\n" +
"task afterEclipseImport << {\n" +
" File f = new File(\"$projectDir/sub/test.txt\")\n" +
" f.getParentFile().mkdirs();\n" +
" f.write 'This is a test'\n"+
"}\n");
//simpl project creation actually uses 'import' to get project into workspace so...
//the afterEclipseImport task should have run.
IProject project = getProject(projName);
File location = project.getLocation().toFile();
IFile theFile = project.getFile("sub/test.txt");
assertTrue(theFile.exists());
//Now try again... reimport the project, but with the option to run the task disabled.
theFile.delete(true, new NullProgressMonitor());
project.delete(false, true, new NullProgressMonitor());
GradleImportOperation importOp = importTestProjectOperation(location);
importOp.setDoAfterTasks(false);
importOp.perform(new ErrorHandler.Test(), new NullProgressMonitor());
assertFalse(theFile.exists());
}
public void testImportAfterGradleEclipseTask() throws Exception {
String projectName = "quickstart";
File location = extractJavaSample(projectName);
GradleProject testProj = GradleCore.create(location);
generateEclipseFiles(testProj);
testProj.invalidateGradleModel(); // import must be as if model has not yet been built
importTestProject(testProj.getLocation());
IJavaProject project = getJavaProject(projectName);
dumpJavaProjectInfo(project);
assertProjects("quickstart");
assertJarEntry(project, "commons-collections-3.2.jar", true);
assertJarEntry(project, "junit-4.11.jar", true);
assertNoRawLibraryEntries(project);
// assertJarEntry(project, "bogus-4.8.2.jar", true);
}
/**
* Verify that project classpath does not have plain jar entries on it (all jars are managed in classpath containers).
* @throws JavaModelException
*/
public static void assertNoRawLibraryEntries(IJavaProject project) throws JavaModelException {
IClasspathEntry[] classpath = project.getRawClasspath();
for (IClasspathEntry entry : classpath) {
if (entry.getEntryKind()==IClasspathEntry.CPE_LIBRARY) {
fail("Raw classpath of project "+project.getElementName()+" has a library entry: "+entry);
}
}
}
/**
* Executes the gradle 'eclipse' task on project associated with given folder.
* @throws CoreException
* @throws OperationCanceledException
*/
private void generateEclipseFiles(GradleProject project) throws OperationCanceledException, CoreException {
String taskPath = ":eclipse";
Set<String> tasks = project.getAllTasks(new NullProgressMonitor());
assertTrue(tasks.contains(taskPath));
ILaunchConfigurationWorkingCopy launchConf = (ILaunchConfigurationWorkingCopy) GradleLaunchConfigurationDelegate.createDefault(project, false);
GradleLaunchConfigurationDelegate.setTasks(launchConf, Arrays.asList(taskPath));
GradleProcess process = LaunchUtil.synchLaunch(launchConf);
String output = process.getStreamsProxy().getOutputStreamMonitor().getContents();
assertContains("BUILD SUCCESSFUL", output);
}
public void testSts1907RemoveReferencedLibraries() throws Exception {
GradleClassPathContainer.DEBUG = true;
String name = "quickstart";
importSampleProject(name);
IJavaProject project = getJavaProject(name);
dumpJavaProjectInfo(project);
assertProjects(name);
assertJarEntry(project, "commons-collections-3.2.jar", true);
assertJarEntry(project, "junit-4.11.jar", true);
// assertJarEntry(project, "bogus-4.8.2.jar", true);
}
private void dumpJavaProjectInfo(IJavaProject project) throws CoreException {
System.out.println(">>>> JavaProject: "+project.getElementName());
String[] natures = project.getProject().getDescription().getNatureIds();
System.out.println("natures: ");
for (String nature : natures) {
System.out.println(" "+nature);
}
System.out.println("builders:");
for (ICommand cmd : project.getProject().getDescription().getBuildSpec()) {
System.out.println(" "+cmd);
}
System.out.println("Raw Class Path entries: ");
for (IClasspathEntry entry : project.getRawClasspath()) {
System.out.println(" "+entry);
}
System.out.println("<<<< JavaProject: "+project.getElementName());
}
public void testImportJavaMultiProject() throws Exception {
do_testImportJavaMultiProject("multiproject");
}
public void do_testImportJavaMultiProject(String rootProjName) throws Exception {
String[] projectNames = {
rootProjName,
"api",
"services",
"services-shared",
"webservice",
"shared"
};
IJavaProject rootProject = getJavaProject(projectNames[0]);
importSampleProject(projectNames[0]);
assertProjects(
projectNames
);
IJavaProject shared = getJavaProject("shared");
assertSourceFolder(shared, "src/main/java");
assertSourceFolder(shared, "src/main/resources");
assertSourceFolder(shared, "src/test/java");
assertSourceFolder(shared, "src/test/resources");
//Check that every eclipse project has been properly setup to have an association to
//a root project.
File rootLocation = GradleCore.create(rootProject).getLocation();
for (String projectName : projectNames) {
GradleProject project = getGradleProject(projectName);
File actualRootLocation = project.getProjectPreferences().getRootProjectLocation();
assertEquals("Root associated with "+project, rootLocation, actualRootLocation);
//Also check that we can still get it via getRootProject.
actualRootLocation = project.getRootProject().getLocation();
assertEquals("Root associated with "+project, rootLocation, actualRootLocation);
//Also check that we can still get it, even if preference is not set
project.getProjectPreferences().setRootProjectLocation(null);
actualRootLocation = project.getRootProject().getLocation();
assertEquals("Root associated with "+project, rootLocation, actualRootLocation);
//File actualRootLocation = project.getRootProject().getLocation();
}
}
public void testImportSpringIntegration() throws Exception {
GradleAPIProperties props = GradleCore.getInstance().getAPIProperties();
URI distro = null;
// if (!props.isSnapshot()) {
//We are running the 'regular' build!
//This test requires M8 (project's wrapper properties says so, but it is non-standar location so
// tooling API doesn't know.
// distro = new URI("http://repo.gradle.org/gradle/distributions/gradle-1.0-milestone-8-bin.zip");
// }
GradleCore.getInstance().getPreferences().setDistribution(distro);
GradleImportOperation op = importGitProjectOperation(
new GitProject(
"spring-integration",
new URI("git://github.com/kdvolder/spring-integration.git"),
"d4026bd63b43fdade2ed38a97bcdce89e6fab835"
).setRecursive(true)
);
+ op.setEnableDSLD(true);
op.perform(defaultTestErrorHandler(), new NullProgressMonitor());
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject proj : projects) {
System.out.println("\""+proj.getName()+"\",");
}
String[] projectNames = {
"spring-integration",
"spring-integration-amqp",
"spring-integration-core",
"spring-integration-event",
"spring-integration-feed",
"spring-integration-file",
"spring-integration-ftp",
"spring-integration-gemfire",
"spring-integration-groovy",
"spring-integration-http",
"spring-integration-ip",
"spring-integration-jdbc",
"spring-integration-jms",
"spring-integration-jmx",
"spring-integration-jpa",
"spring-integration-mail",
"spring-integration-mongodb",
"spring-integration-redis",
"spring-integration-rmi",
"spring-integration-scripting",
"spring-integration-security",
"spring-integration-sftp",
"spring-integration-stream",
"spring-integration-test",
"spring-integration-twitter",
"spring-integration-ws",
"spring-integration-xml",
"spring-integration-xmpp"
};
TestUtils.disableCompilerLevelCheck(getProject("spring-integration-groovy"));
TestUtils.disableCompilerLevelCheck(getProject("spring-integration-scripting"));
assertProjects(
projectNames
);
DSLDSupport dslSupport = DSLDSupport.getInstance();
for (IProject p : projects) {
GradleProject gp = GradleCore.create(p);
- //Iniatially dsl support is enabled.
- assertTrue(dslSupport.isEnabled(gp));
- assertTrue(p.hasNature(DSLDSupport.GROOVY_NATURE));
- //Disable dependency management on all the projects.
+ //Iniatially dsl support is ...
+ assertTrue("dslSupport enabled?", dslSupport.isEnabled(gp));
+ assertTrue("Groovy Nature", p.hasNature(DSLDSupport.GROOVY_NATURE));
+ //Disable dsl support
dslSupport.enableFor(gp, false, new NullProgressMonitor());
}
// Now do a basic refresh all test.
RefreshAllActionCore.callOn(Arrays.asList(projects)).join();
for (IProject p : projects) {
GradleProject gp = GradleCore.create(p);
assertFalse(dslSupport.isEnabled(gp));
if (p.getName().equals("spring-integration")) {
//The 'root' project keeps groovy nature because it doesn't apply the 'eclipse'
// plugin. Therefore it has no 'cleanEclipse' task and so the nature isn't erased.
// This is the expected behavior. (Or should we ourselves attempt to 'cleanEclipse'?).
assertTrue(p.hasNature(DSLDSupport.GROOVY_NATURE));
} else {
assertFalse("Project "+p.getName()+" still has Groovy nature",
p.hasNature(DSLDSupport.GROOVY_NATURE));
}
}
assertProjects(
projectNames
);
}
public void testSTS2094() throws Exception {
//This bug happens if one imports a set of projects then deletes them and then imports them all again.
testImportSpringIntegration();
GradleProject rootProject = getGradleProject("spring-integration");
File rootLocation = rootProject.getLocation();
for (IProject p : getProjects()) {
p.delete(false, true, new NullProgressMonitor());
}
GradleImportOperation importOp = GradleImportOperation.importAll(rootLocation);
importOp.verify();
importOp.perform(new ErrorHandler.Test(IStatus.ERROR), new NullProgressMonitor());
}
public void disabledTestTimedImport() throws Exception {
setSnapshotDistro();
final GradleImportOperation importOp = importGitProjectOperation(new GitProject("spring-security",
new URI("git://git.springsource.org/spring-security/spring-security.git"),
"359bd7c46")
);
importOp.excludeProjects(
"itest-context",
"itest-web",
"manual",
"docs",
"faq",
"spring-security"
);
List<Long> times = new ArrayList<Long>();
for (int i = 0; i < 3; i++) {
long startTime = System.currentTimeMillis();
performImport(importOp);
long endTime = System.currentTimeMillis();
times.add(endTime-startTime);
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject proj : projects) {
System.out.println(proj);
}
assertProjects(
"spring-security-acl",
"spring-security-aspects",
"spring-security-cas",
"spring-security-config",
"spring-security-core",
"spring-security-crypto",
"spring-security-ldap",
"spring-security-openid",
"spring-security-remoting",
"spring-security-samples-aspectj",
"spring-security-samples-cassample",
"spring-security-samples-casserver",
"spring-security-samples-contacts",
"spring-security-samples-dms",
"spring-security-samples-gae",
"spring-security-samples-jaas",
"spring-security-samples-ldap",
"spring-security-samples-openid",
"spring-security-samples-preauth",
"spring-security-samples-tutorial",
"spring-security-taglibs",
"spring-security-web"
);
assertTrue(WTPUtil.isWTPProject(getProject("spring-security-samples-jaas")));
getGradleProject("spring-security-acl").invalidateGradleModel();
ISchedulingRule buildRule = ResourcesPlugin.getWorkspace().getRuleFactory().buildRule();
Job.getJobManager().beginRule(buildRule, new NullProgressMonitor());
try {
for (IProject p : projects) {
p.delete(false, true, new NullProgressMonitor());
}
} finally {
Job.getJobManager().endRule(buildRule);
}
}
System.out.println(">>>> import times ====");
long sum = 0;
for (Long time : times) {
sum += time;
System.out.println(TimeUtils.minutusAndSecondsFromMillis(time));
}
System.out.println("----------------------");
System.out.println("Avg : "+TimeUtils.minutusAndSecondsFromMillis(sum/times.size()));
System.out.println("<<<< import times ====");
}
public void setSnapshotDistro() {
// Disabled for now... we won't be running 'integration' style tests anymore. The Gradle guys don't
// really seem to care about the test failures or bugs I've raised about them. We'll just run tests
// now with the versions that are supposed to be used with the various test projects.
// GradleProperties props = GradleCore.getInstance().getProperties();
// if (props.isSnapshot()) {
// URI distro = props.getDistribution();
// if (distro!=null) {
// GradleCore.getInstance().getPreferences().setDistribution(distro);
// }
// }
}
/**
* Gradle 1.0-M4 uses linked resources to deal with funny source folders like "../scripts" which
* are not legal in Eclipse since they don't lie within the project.
*/
public void testImportProjectWithLinkedResource() throws Exception {
String projectName = "multiproject";
String subprojectName = "subproject";
importTestProject(projectName);
assertProjects(
projectName,
subprojectName);
//Check whether the 'Main' type whose source code is actually inside of the parent project, but on the
//source path of the subproject is actually found in the subproject.
IJavaProject subproject = getJavaProject(subprojectName);
assertNotNull(subproject);
IType mainType = subproject.findType("Main");
assertNotNull(mainType);
mainType = subproject.findType("Spain");
assertNull(mainType);
//Next check whether after editing the build.gradle file the linked source folders
//are updated by a refresh source folders.
createFile(subproject.getProject(), "build.gradle",
"sourceSets {\n" +
" main {\n" +
" java {\n" +
" srcDir '../boink2'\n" +
" }\n" +
" }\n" +
"}");
GradleProject gSubproject = getGradleProject(subprojectName);
gSubproject.invalidateGradleModel();
gSubproject.refreshSourceFolders(new ErrorHandler.Test(), new NullProgressMonitor());
//Now 'main' should no longer exist, but spain should
mainType = subproject.findType("Main");
assertNull(mainType);
mainType = subproject.findType("Spain");
assertNotNull(mainType);
//Re-refreshing should not be a problem...
gSubproject.invalidateGradleModel();
gSubproject.refreshSourceFolders(new ErrorHandler.Test(), new NullProgressMonitor());
//Nothing changed, should still pass the same assertions
mainType = subproject.findType("Main");
assertNull(mainType);
mainType = subproject.findType("Spain");
assertNotNull(mainType);
}
/**
* Gradle 1.0-M4 uses linked resources to deal with funny source folders like "../scripts" which
* are not legal in Eclipse since they don't lie within the project.
*/
public void testWithMultipleLinkedResources() throws Exception {
String projectName = "multiproject";
String subprojectName = "subproject";
importTestProject(projectName);
assertProjects(
projectName,
subprojectName);
IJavaProject subproject = getJavaProject(subprojectName);
createFile(subproject.getProject(), "build.gradle",
"sourceSets {\n" +
" main {\n" +
" java {\n" +
" srcDir '../boink'\n" +
" srcDir '../boink2'\n" +
" }\n" +
" }\n" +
"}");
GradleProject gSubproject = getGradleProject(subprojectName);
gSubproject.invalidateGradleModel();
gSubproject.refreshSourceFolders(new ErrorHandler.Test(), new NullProgressMonitor());
//This time, both of the main types should be found since we added both source folders.
assertNotNull(subproject);
IType mainType = subproject.findType("Main");
assertNotNull(mainType);
mainType = subproject.findType("Spain");
assertNotNull(mainType);
}
public void testSTS2175ClassPathEntryOrder() throws Exception {
String[] projectNames = {
"sts2175",
"suba",
"subb",
"subc"
};
importTestProject(projectNames[0]);
assertProjects(projectNames);
assertTrue(GradleProjectPreferences.DEFAULT_ENABLE_CLASSPATH_SORTING);
for (String name : projectNames) {
GradleProject gp = getGradleProject(name);
assertEquals(GradleProjectPreferences.DEFAULT_ENABLE_CLASSPATH_SORTING, gp.getProjectPreferences().getEnableClasspatEntrySorting());
}
GradleProject gp = getGradleProject("suba");
IJavaProject jp = gp.getJavaProject();
String bThenC = "dependencies {\n" +
" compile project(':subb')\n" +
" compile project(':subc')\n" +
"}";
String cThenB = "dependencies {\n" +
" compile project(':subc')\n" +
" compile project(':subb')\n" +
"}";
dumpRawClasspath(jp);
createFile(getProject("suba"),"build.gradle", bThenC);
refreshDependencies();
dumpRawClasspath(jp);
assertArrayEquals(
sts2175ExpectedCP("subb", "subc"),
jp.getRawClasspath());
createFile(getProject("suba"),"build.gradle", cThenB); //Build script order changed!!
refreshDependencies();
assertArrayEquals(
sts2175ExpectedCP("subb", "subc"), //Classpath order same (is sorted!)
jp.getRawClasspath());
//Now disable sorting... the ordering should change
gp.getProjectPreferences().setEnableClasspatEntrySorting(false);
for (String name : projectNames) {
//Setting this should affect all projects in the hierarchy
GradleProject p = getGradleProject(name);
assertEquals(false, p.getProjectPreferences().getEnableClasspatEntrySorting());
}
refreshDependencies();
assertArrayEquals(
sts2175ExpectedCP("subc", "subb"), //Classpath order same (is sorted!)
jp.getRawClasspath());
createFile(getProject("suba"),"build.gradle", bThenC); //Order changed
refreshDependencies();
assertArrayEquals(
sts2175ExpectedCP("subb", "subc"), //Classpath order same (is sorted!)
jp.getRawClasspath());
}
public void testSTS2405RemapJarToMavenProject() throws Exception {
assertTrue("This test requires m2e", M2EUtils.isInstalled());
String userHome = System.getProperty("user.home");
String home = System.getenv("HOME");
System.out.println("HOME = "+home);
System.out.println("user.home = "+System.getProperty("user.home"));
System.out.println("maven.repo.local = "+System.getProperty("maven.repo.local"));
IProject mvnProject = importEclipseProject("sts2405/myLib");
String mvnLocalRepo = userHome +"/.m2/repository";
assertNoErrors(mvnProject, true);
new ExternalCommand(
"which", "mvn"
).exec(mvnProject.getLocation().toFile());
new ExternalCommand(
"env"
).exec(mvnProject.getLocation().toFile());
String mavenLocalProp = "-Dmaven.repo.local="+mvnLocalRepo;
new MavenCommand(
"mvn", mavenLocalProp, "install"
).exec(mvnProject.getLocation().toFile());
importTestProject("sts2405/main");
IProject gradleProject = getProject("main");
assertNoErrors(gradleProject, true);
IJavaProject jp = JavaCore.create(gradleProject);
assertNoClasspathJarEntry("myLib-0.0.1-SNAPSHOT.jar", jp);
assertClasspathProjectEntry(mvnProject, jp);
GradleCore.create(gradleProject).getProjectPreferences().setRemapJarsToMavenProjects(false);
RefreshDependenciesActionCore.synchCallOn(gradleProject);
assertNoClasspathProjectEntry(mvnProject, jp);
assertClasspathJarEntry("myLib-0.0.1-SNAPSHOT.jar", GradleCore.create(jp));
}
private void dumpRawClasspath(IJavaProject jp) throws JavaModelException {
System.out.println(">>> raw classpath for "+jp.getElementName());
for (IClasspathEntry e : jp.getRawClasspath()) {
System.out.println(e);
}
System.out.println("<<< raw classpath for "+jp.getElementName());
}
public void refreshDependencies() throws Exception {
Joinable<Void> j = RefreshDependenciesActionCore.callOn(Arrays.asList(getProjects()));
if (j!=null) {
j.join();
}
}
public IClasspathEntry[] sts2175ExpectedCP(String firstProj, String secondProj) {
IClasspathEntry[] expectedClasspath = {
JavaCore.newSourceEntry(new Path("/suba/src/main/java")),
JavaCore.newSourceEntry(new Path("/suba/src/test/java")),
JavaCore.newProjectEntry(new Path("/"+firstProj), true),
JavaCore.newProjectEntry(new Path("/"+secondProj), true),
//Order is alphapbetic:
JavaCore.newContainerEntry(GroovyDSLCoreActivator.CLASSPATH_CONTAINER_ID, false),
JavaCore.newContainerEntry(GroovyClasspathContainer.CONTAINER_ID, false),
//org.eclipse
JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER"), true),
//org.springsource
JavaCore.newContainerEntry(new Path(GradleClassPathContainer.ID), true),
JavaCore.newContainerEntry(new Path(GradleDSLDClasspathContainer.ID), false),
};
return expectedClasspath;
}
//TODO: under what circumstances will linked resources returned by gradle api refer to files (not folders)?
// We don't have a test for this situation so the code that supports it has never been run.
}
| false | true | public void testImportSpringIntegration() throws Exception {
GradleAPIProperties props = GradleCore.getInstance().getAPIProperties();
URI distro = null;
// if (!props.isSnapshot()) {
//We are running the 'regular' build!
//This test requires M8 (project's wrapper properties says so, but it is non-standar location so
// tooling API doesn't know.
// distro = new URI("http://repo.gradle.org/gradle/distributions/gradle-1.0-milestone-8-bin.zip");
// }
GradleCore.getInstance().getPreferences().setDistribution(distro);
GradleImportOperation op = importGitProjectOperation(
new GitProject(
"spring-integration",
new URI("git://github.com/kdvolder/spring-integration.git"),
"d4026bd63b43fdade2ed38a97bcdce89e6fab835"
).setRecursive(true)
);
op.perform(defaultTestErrorHandler(), new NullProgressMonitor());
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject proj : projects) {
System.out.println("\""+proj.getName()+"\",");
}
String[] projectNames = {
"spring-integration",
"spring-integration-amqp",
"spring-integration-core",
"spring-integration-event",
"spring-integration-feed",
"spring-integration-file",
"spring-integration-ftp",
"spring-integration-gemfire",
"spring-integration-groovy",
"spring-integration-http",
"spring-integration-ip",
"spring-integration-jdbc",
"spring-integration-jms",
"spring-integration-jmx",
"spring-integration-jpa",
"spring-integration-mail",
"spring-integration-mongodb",
"spring-integration-redis",
"spring-integration-rmi",
"spring-integration-scripting",
"spring-integration-security",
"spring-integration-sftp",
"spring-integration-stream",
"spring-integration-test",
"spring-integration-twitter",
"spring-integration-ws",
"spring-integration-xml",
"spring-integration-xmpp"
};
TestUtils.disableCompilerLevelCheck(getProject("spring-integration-groovy"));
TestUtils.disableCompilerLevelCheck(getProject("spring-integration-scripting"));
assertProjects(
projectNames
);
DSLDSupport dslSupport = DSLDSupport.getInstance();
for (IProject p : projects) {
GradleProject gp = GradleCore.create(p);
//Iniatially dsl support is enabled.
assertTrue(dslSupport.isEnabled(gp));
assertTrue(p.hasNature(DSLDSupport.GROOVY_NATURE));
//Disable dependency management on all the projects.
dslSupport.enableFor(gp, false, new NullProgressMonitor());
}
// Now do a basic refresh all test.
RefreshAllActionCore.callOn(Arrays.asList(projects)).join();
for (IProject p : projects) {
GradleProject gp = GradleCore.create(p);
assertFalse(dslSupport.isEnabled(gp));
if (p.getName().equals("spring-integration")) {
//The 'root' project keeps groovy nature because it doesn't apply the 'eclipse'
// plugin. Therefore it has no 'cleanEclipse' task and so the nature isn't erased.
// This is the expected behavior. (Or should we ourselves attempt to 'cleanEclipse'?).
assertTrue(p.hasNature(DSLDSupport.GROOVY_NATURE));
} else {
assertFalse("Project "+p.getName()+" still has Groovy nature",
p.hasNature(DSLDSupport.GROOVY_NATURE));
}
}
assertProjects(
projectNames
);
}
| public void testImportSpringIntegration() throws Exception {
GradleAPIProperties props = GradleCore.getInstance().getAPIProperties();
URI distro = null;
// if (!props.isSnapshot()) {
//We are running the 'regular' build!
//This test requires M8 (project's wrapper properties says so, but it is non-standar location so
// tooling API doesn't know.
// distro = new URI("http://repo.gradle.org/gradle/distributions/gradle-1.0-milestone-8-bin.zip");
// }
GradleCore.getInstance().getPreferences().setDistribution(distro);
GradleImportOperation op = importGitProjectOperation(
new GitProject(
"spring-integration",
new URI("git://github.com/kdvolder/spring-integration.git"),
"d4026bd63b43fdade2ed38a97bcdce89e6fab835"
).setRecursive(true)
);
op.setEnableDSLD(true);
op.perform(defaultTestErrorHandler(), new NullProgressMonitor());
IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
for (IProject proj : projects) {
System.out.println("\""+proj.getName()+"\",");
}
String[] projectNames = {
"spring-integration",
"spring-integration-amqp",
"spring-integration-core",
"spring-integration-event",
"spring-integration-feed",
"spring-integration-file",
"spring-integration-ftp",
"spring-integration-gemfire",
"spring-integration-groovy",
"spring-integration-http",
"spring-integration-ip",
"spring-integration-jdbc",
"spring-integration-jms",
"spring-integration-jmx",
"spring-integration-jpa",
"spring-integration-mail",
"spring-integration-mongodb",
"spring-integration-redis",
"spring-integration-rmi",
"spring-integration-scripting",
"spring-integration-security",
"spring-integration-sftp",
"spring-integration-stream",
"spring-integration-test",
"spring-integration-twitter",
"spring-integration-ws",
"spring-integration-xml",
"spring-integration-xmpp"
};
TestUtils.disableCompilerLevelCheck(getProject("spring-integration-groovy"));
TestUtils.disableCompilerLevelCheck(getProject("spring-integration-scripting"));
assertProjects(
projectNames
);
DSLDSupport dslSupport = DSLDSupport.getInstance();
for (IProject p : projects) {
GradleProject gp = GradleCore.create(p);
//Iniatially dsl support is ...
assertTrue("dslSupport enabled?", dslSupport.isEnabled(gp));
assertTrue("Groovy Nature", p.hasNature(DSLDSupport.GROOVY_NATURE));
//Disable dsl support
dslSupport.enableFor(gp, false, new NullProgressMonitor());
}
// Now do a basic refresh all test.
RefreshAllActionCore.callOn(Arrays.asList(projects)).join();
for (IProject p : projects) {
GradleProject gp = GradleCore.create(p);
assertFalse(dslSupport.isEnabled(gp));
if (p.getName().equals("spring-integration")) {
//The 'root' project keeps groovy nature because it doesn't apply the 'eclipse'
// plugin. Therefore it has no 'cleanEclipse' task and so the nature isn't erased.
// This is the expected behavior. (Or should we ourselves attempt to 'cleanEclipse'?).
assertTrue(p.hasNature(DSLDSupport.GROOVY_NATURE));
} else {
assertFalse("Project "+p.getName()+" still has Groovy nature",
p.hasNature(DSLDSupport.GROOVY_NATURE));
}
}
assertProjects(
projectNames
);
}
|
diff --git a/modules/resin/src/com/caucho/vfs/HttpPath.java b/modules/resin/src/com/caucho/vfs/HttpPath.java
index 7c45e71e3..4201dba25 100644
--- a/modules/resin/src/com/caucho/vfs/HttpPath.java
+++ b/modules/resin/src/com/caucho/vfs/HttpPath.java
@@ -1,547 +1,547 @@
/*
* Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.vfs;
import java.io.*;
import java.net.*;
import java.util.*;
import org.xml.sax.*;
import com.caucho.util.*;
import com.caucho.xml.*;
/**
* The HTTP scheme. Currently it supports GET and POST.
*
* <p>TODO: support WEBDAV, enabling the full Path API.
*/
public class HttpPath extends FilesystemPath {
protected static L10N L = new L10N(HttpPath.class);
protected static LruCache<String,CacheEntry> _cache =
new LruCache<String,CacheEntry>(1024);
protected String _host;
protected int _port;
protected String _query;
protected CacheEntry _cacheEntry;
/**
* Creates a new HTTP root path with a host and a port.
*
* @param host the target host
* @param port the target port, if zero, uses port 80.
*/
HttpPath(String host, int port)
{
super(null, "/", "/");
_root = this;
_host = host;
_port = port == 0 ? 80 : port;
}
/**
* Creates a new HTTP sub path.
*
* @param root the HTTP filesystem root
* @param userPath the argument to the calling lookup()
* @param newAttributes any attributes passed to http
* @param path the full normalized path
* @param query any query string
*/
HttpPath(FilesystemPath root,
String userPath, Map<String,Object> newAttributes,
String path, String query)
{
super(root, userPath, path);
_host = ((HttpPath) root)._host;
_port = ((HttpPath) root)._port;
_query = query;
}
/**
* Overrides the default lookup to parse the host and port
* before parsing the path.
*
* @param userPath the path passed in by the user
* @param newAttributes attributes passed by the user
*
* @return the final path.
*/
public Path lookupImpl(String userPath, Map<String,Object> newAttributes)
{
String newPath;
if (userPath == null)
return _root.fsWalk(getPath(), newAttributes, "/");
int length = userPath.length();
int colon = userPath.indexOf(':');
int slash = userPath.indexOf('/');
// parent handles scheme:xxx
if (colon != -1 && (colon < slash || slash == -1))
return super.lookupImpl(userPath, newAttributes);
// //hostname
if (slash == 0 && length > 1 && userPath.charAt(1) == '/')
return schemeWalk(userPath, newAttributes, userPath, 0);
// /path
else if (slash == 0)
newPath = normalizePath("/", userPath, 0, '/');
// path
else
newPath = normalizePath(_pathname, userPath, 0, '/');
// XXX: does missing root here cause problems with restrictions?
return _root.fsWalk(userPath, newAttributes, newPath);
}
/**
* Walk down the path starting from the portion immediately following
* the scheme. i.e. schemeWalk is responsible for parsing the host and
* port from the URL.
*
* @param userPath the user's passed in path
* @param attributes the attributes for the new path
* @param uri the normalized full uri
* @param offset offset into the uri to start processing, i.e. after the
* scheme.
*
* @return the looked-up path.
*/
protected Path schemeWalk(String userPath,
Map<String,Object> attributes,
String uri,
int offset)
{
int length = uri.length();
if (length < 2 + offset ||
uri.charAt(offset) != '/' ||
uri.charAt(offset + 1) != '/')
throw new RuntimeException(L.l("bad scheme in `{0}'", uri));
CharBuffer buf = CharBuffer.allocate();
int i = 2 + offset;
int ch = 0;
for (; i < length && (ch = uri.charAt(i)) != ':' && ch != '/' && ch != '?';
i++) {
buf.append((char) ch);
}
String host = buf.close();
if (host.length() == 0)
throw new RuntimeException(L.l("bad host in `{0}'", uri));
int port = 0;
if (ch == ':') {
for (i++; i < length && (ch = uri.charAt(i)) >= '0' && ch <= '9'; i++) {
port = 10 * port + uri.charAt(i) - '0';
}
}
if (port == 0)
port = 80;
HttpPath root = create(host, port);
return root.fsWalk(userPath, attributes, uri.substring(i));
}
/**
* Scans the path portion of the URI, i.e. everything after the
* host and port.
*
* @param userPath the user's supplied path
* @param attributes the attributes for the new path
* @param uri the full uri for the new path.
*
* @return the found path.
*/
protected Path fsWalk(String userPath,
Map<String,Object> attributes,
String uri)
{
String path;
String query = null;
int queryIndex = uri.indexOf('?');
if (queryIndex >= 0) {
path = uri.substring(0, queryIndex);
query = uri.substring(queryIndex + 1);
} else
path = uri;
if (path.length() == 0)
path = "/";
return create(_root, userPath, attributes, path, query);
}
protected HttpPath create(String host, int port)
{
return new HttpPath(host, port);
}
protected HttpPath create(FilesystemPath root,
String userPath,
Map<String,Object> newAttributes,
String path, String query)
{
return new HttpPath(root, userPath, newAttributes, path, query);
}
/**
* Returns the scheme, http.
*/
public String getScheme()
{
return "http";
}
/**
* Returns a full URL for the path.
*/
public String getURL()
{
int port = getPort();
return (getScheme() + "://" + getHost() +
(port == 80 ? "" : ":" + getPort()) +
getPath() +
(_query == null ? "" : "?" + _query));
}
/**
* Returns the host part of the url.
*/
public String getHost()
{
return _host;
}
/**
* Returns the port part of the url.
*/
public int getPort()
{
return _port;
}
/**
* Returns the user's path.
*/
public String getUserPath()
{
return _userPath;
}
/**
* Returns the query string.
*/
public String getQuery()
{
return _query;
}
/**
* Returns the last modified time.
*/
public long getLastModified()
{
return getCache().lastModified;
}
/**
* Returns the file's length
*/
public long getLength()
{
return getCache().length;
}
/**
* Returns true if the file exists.
*/
public boolean exists()
{
return getCache().lastModified >= 0;
}
/**
* Returns true if the file exists.
*/
public boolean isFile()
{
return ! getPath().endsWith("/") && getCache().lastModified >= 0;
}
/**
* Returns true if the file is readable.
*/
public boolean canRead()
{
return isFile();
}
/**
* Returns the last modified time.
*/
public boolean isDirectory()
{
return getPath().endsWith("/") && getCache().lastModified >= 0;
}
/**
* @return The contents of this directory or null if the path does not
* refer to a directory.
*/
public String []list() throws IOException
{
try {
HttpStream stream = (HttpStream) openReadWriteImpl();
stream.setMethod("PROPFIND");
stream.setAttribute("Depth", "1");
WriteStream os = new WriteStream(stream);
os.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
os.println("<propfind xmlns=\"DAV:\"><prop>");
os.println("<resourcetype/>");
os.println("</prop></propfind>");
os.flush();
ReadStream is = new ReadStream(stream);
ListHandler handler = new ListHandler(getPath());
XmlParser parser = new XmlParser();
parser.setContentHandler(handler);
parser.parse(is);
is.close();
os.close();
stream.close();
ArrayList<String> names = handler.getNames();
String []list = new String[names.size()];
names.toArray(list);
return list;
} catch (Exception e) {
throw new IOException(L.l("list() is not supported by this server"));
}
}
protected CacheEntry getCache()
{
if (_cacheEntry == null) {
synchronized (_cache) {
_cacheEntry = _cache.get(getPath());
if (_cacheEntry == null) {
_cacheEntry = new CacheEntry();
_cache.put(getPath(), _cacheEntry);
}
}
}
long now = Alarm.getCurrentTime();
synchronized (_cacheEntry) {
try {
if (_cacheEntry.expires > now)
return _cacheEntry;
- HttpStream stream = (HttpStream) openReadImpl();
+ HttpStreamWrapper stream = (HttpStreamWrapper) openReadImpl();
stream.setHead(true);
stream.setSocketTimeout(120000);
String status = (String) stream.getAttribute("status");
if (status.equals("200")) {
String lastModified = (String) stream.getAttribute("last-modified");
_cacheEntry.lastModified = 0;
if (lastModified != null) {
QDate date = QDate.getGlobalDate();
synchronized (date) {
_cacheEntry.lastModified = date.parseDate(lastModified);
}
}
String length = (String) stream.getAttribute("content-length");
_cacheEntry.length = 0;
if (length != null) {
_cacheEntry.length = Integer.parseInt(length);
}
}
else
_cacheEntry.lastModified = -1;
_cacheEntry.expires = now + 5000;
stream.close();
return _cacheEntry;
} catch (Exception e) {
_cacheEntry.lastModified = -1;
_cacheEntry.expires = now + 5000;
return _cacheEntry;
}
}
}
/**
* Returns a read stream for a GET request.
*/
public StreamImpl openReadImpl() throws IOException
{
return HttpStream.openRead(this);
}
/**
* Returns a read/write pair for a POST request.
*/
public StreamImpl openReadWriteImpl() throws IOException
{
return HttpStream.openReadWrite(this);
}
@Override
protected Path cacheCopy()
{
return new HttpPath(getRoot(), getUserPath(),
null,
getPath(), _query);
}
/**
* Returns the string form of the http path.
*/
public String toString()
{
return getURL();
}
/**
* Returns a hashCode for the path.
*/
public int hashCode()
{
return 65537 * super.hashCode() + 37 * _host.hashCode() + _port;
}
/**
* Overrides equals to test for equality with an HTTP path.
*/
public boolean equals(Object o)
{
if (! (o instanceof HttpPath))
return false;
HttpPath test = (HttpPath) o;
if (! _host.equals(test._host))
return false;
else if (_port != test._port)
return false;
else if (_query != null && ! _query.equals(test._query))
return false;
else if (_query == null && test._query != null)
return false;
else
return true;
}
static class CacheEntry {
long lastModified;
long length;
boolean canRead;
long expires;
}
static class ListHandler extends org.xml.sax.helpers.DefaultHandler {
String _prefix;
ArrayList<String> _names = new ArrayList<String>();
boolean _inHref;
ListHandler(String prefix)
{
_prefix = prefix;
}
ArrayList<String> getNames()
{
return _names;
}
public void startElement (String uri, String localName,
String qName, Attributes attributes)
{
if (localName.equals("href"))
_inHref = true;
}
public void characters(char []data, int offset, int length)
throws SAXException
{
if (! _inHref)
return;
String href = new String(data, offset, length).trim();
if (! href.startsWith(_prefix))
return;
href = href.substring(_prefix.length());
if (href.startsWith("/"))
href = href.substring(1);
int p = href.indexOf('/');
if (href.equals("") || p == 0)
return;
if (p < 0)
_names.add(href);
else
_names.add(href.substring(0, p));
}
public void endElement (String uri, String localName, String qName)
throws SAXException
{
if (localName.equals("href"))
_inHref = false;
}
}
}
| true | true | protected CacheEntry getCache()
{
if (_cacheEntry == null) {
synchronized (_cache) {
_cacheEntry = _cache.get(getPath());
if (_cacheEntry == null) {
_cacheEntry = new CacheEntry();
_cache.put(getPath(), _cacheEntry);
}
}
}
long now = Alarm.getCurrentTime();
synchronized (_cacheEntry) {
try {
if (_cacheEntry.expires > now)
return _cacheEntry;
HttpStream stream = (HttpStream) openReadImpl();
stream.setHead(true);
stream.setSocketTimeout(120000);
String status = (String) stream.getAttribute("status");
if (status.equals("200")) {
String lastModified = (String) stream.getAttribute("last-modified");
_cacheEntry.lastModified = 0;
if (lastModified != null) {
QDate date = QDate.getGlobalDate();
synchronized (date) {
_cacheEntry.lastModified = date.parseDate(lastModified);
}
}
String length = (String) stream.getAttribute("content-length");
_cacheEntry.length = 0;
if (length != null) {
_cacheEntry.length = Integer.parseInt(length);
}
}
else
_cacheEntry.lastModified = -1;
_cacheEntry.expires = now + 5000;
stream.close();
return _cacheEntry;
} catch (Exception e) {
_cacheEntry.lastModified = -1;
_cacheEntry.expires = now + 5000;
return _cacheEntry;
}
}
}
| protected CacheEntry getCache()
{
if (_cacheEntry == null) {
synchronized (_cache) {
_cacheEntry = _cache.get(getPath());
if (_cacheEntry == null) {
_cacheEntry = new CacheEntry();
_cache.put(getPath(), _cacheEntry);
}
}
}
long now = Alarm.getCurrentTime();
synchronized (_cacheEntry) {
try {
if (_cacheEntry.expires > now)
return _cacheEntry;
HttpStreamWrapper stream = (HttpStreamWrapper) openReadImpl();
stream.setHead(true);
stream.setSocketTimeout(120000);
String status = (String) stream.getAttribute("status");
if (status.equals("200")) {
String lastModified = (String) stream.getAttribute("last-modified");
_cacheEntry.lastModified = 0;
if (lastModified != null) {
QDate date = QDate.getGlobalDate();
synchronized (date) {
_cacheEntry.lastModified = date.parseDate(lastModified);
}
}
String length = (String) stream.getAttribute("content-length");
_cacheEntry.length = 0;
if (length != null) {
_cacheEntry.length = Integer.parseInt(length);
}
}
else
_cacheEntry.lastModified = -1;
_cacheEntry.expires = now + 5000;
stream.close();
return _cacheEntry;
} catch (Exception e) {
_cacheEntry.lastModified = -1;
_cacheEntry.expires = now + 5000;
return _cacheEntry;
}
}
}
|
diff --git a/AMBroSIA/src/gui/EndGamePanel.java b/AMBroSIA/src/gui/EndGamePanel.java
index fbd95ee..d98349c 100644
--- a/AMBroSIA/src/gui/EndGamePanel.java
+++ b/AMBroSIA/src/gui/EndGamePanel.java
@@ -1,126 +1,126 @@
package gui;
import game.GameState;
import highscoreData.highScoreWriter;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/**
* The
* <code>EndGamePanel</code> class displays game over screen.
*
* @author Haisin Yip
*
*/
public class EndGamePanel extends JPanel {
// private properties
private GameState gamestate;
private JTable StatisticsTable;
private JScrollPane scrollPane;
private Image img;
// initialize size, layout and informative display
/**
* Creates EndGamePanel using given parameters. It initializes size, layout
* and informative display.
*
* @param img image for EndGamePanel
* @param gs current game state
* @param singleP boolean value representing single player mode or 2 player
* mode.
*/
public EndGamePanel(Image img, GameState gs, boolean singleP) {
this.gamestate = gs;
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
makeComponents(getWidth(), getHeight(), singleP);
makeLayout();
}
// construct the main components and informative content
private void makeComponents(int w, int h, boolean singleP) {
// informative content will be displayed at end game
String player, highscore, asteroidsDestroyed, aliensDestroyed, killDeathRatio, level, bombs, shootingAccuracy;
//when single player, display player's information
if (singleP) {
player = "p1";
highscore = String.valueOf(gamestate.getCurrentScore());
asteroidsDestroyed = String.valueOf(gamestate.getP1asteroidDestroyed());
aliensDestroyed = String.valueOf(gamestate.getP1alienDestroyed());;
killDeathRatio = "";
level = String.valueOf(gamestate.getLevel());
bombs = String.valueOf(gamestate.getP1BombUsed());
shootingAccuracy = "";
//Total Shot used
System.out.println(gamestate.getP1shootCounter());
} //two player
else {
//player 1, player 2 scores
int highscoreP1 = gamestate.getPlayer1Score();
String levelP1 = String.valueOf(gamestate.getPlayer1Level());
int highscoreP2 = gamestate.getPlayer2Score();
String levelP2 = String.valueOf(gamestate.getPlayer2Level());
//display winner's score
if (highscoreP1 >= highscoreP2) {
player = "p1";
highscore = String.valueOf(highscoreP1);
bombs = String.valueOf(gamestate.getP1BombUsed());
aliensDestroyed = String.valueOf(gamestate.getP1alienDestroyed());
asteroidsDestroyed = String.valueOf(gamestate.getP1asteroidDestroyed());
level = levelP1;
} else {
player = "p2";
highscore = String.valueOf(highscoreP2);
bombs = String.valueOf(gamestate.getP2BombUsed());
aliensDestroyed = String.valueOf(gamestate.getP2alienDestroyed());
asteroidsDestroyed = String.valueOf(gamestate.getP2asteroidDestroyed());
level = levelP2;
}
}
//fill in table info
String[] columnData = {"", ""};
String[][] rowData = {{"Player name", player}, {"Highscore", highscore}, {"Asteroids Destroyed", asteroidsDestroyed}, {"Aliens Destroyed", aliensDestroyed}, {"Kill-Death ratio", "killDeathRatio"}, {"Last level", level}, {"Bombs used", bombs}, {"Shooting Accuracy", "shootingAccuracy"}};
StatisticsTable = new JTable(rowData, columnData);
StatisticsTable.setPreferredScrollableViewportSize(new Dimension(w / 2, h / 6));
StatisticsTable.setFillsViewportHeight(true);
- String[] scoreData = {player + " ", highscore + " ", asteroidsDestroyed + "", "aliensdestroyed ", "Kill-Deathratio ", level + " ", bombs + " ", "shootingaccuracy"};
+ String[] scoreData = {player + " ", highscore + " ", asteroidsDestroyed + " ", "aliensdestroyed ", "Kill-Deathratio ", level + " ", bombs + " ", "shootingaccuracy"};
highScoreWriter writer = new highScoreWriter(scoreData, "./src/highscoreData/scoreInfo.txt");
writer.writeToFile();
}
// set the layout with a scrollable table
private void makeLayout() {
setLayout(new FlowLayout());
add(StatisticsTable);
add(new JScrollPane(StatisticsTable));
}
// set endgame background image
/**
* Sets endgame background image.
*
* @param g image for background
*/
@Override
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
}
}
| true | true | private void makeComponents(int w, int h, boolean singleP) {
// informative content will be displayed at end game
String player, highscore, asteroidsDestroyed, aliensDestroyed, killDeathRatio, level, bombs, shootingAccuracy;
//when single player, display player's information
if (singleP) {
player = "p1";
highscore = String.valueOf(gamestate.getCurrentScore());
asteroidsDestroyed = String.valueOf(gamestate.getP1asteroidDestroyed());
aliensDestroyed = String.valueOf(gamestate.getP1alienDestroyed());;
killDeathRatio = "";
level = String.valueOf(gamestate.getLevel());
bombs = String.valueOf(gamestate.getP1BombUsed());
shootingAccuracy = "";
//Total Shot used
System.out.println(gamestate.getP1shootCounter());
} //two player
else {
//player 1, player 2 scores
int highscoreP1 = gamestate.getPlayer1Score();
String levelP1 = String.valueOf(gamestate.getPlayer1Level());
int highscoreP2 = gamestate.getPlayer2Score();
String levelP2 = String.valueOf(gamestate.getPlayer2Level());
//display winner's score
if (highscoreP1 >= highscoreP2) {
player = "p1";
highscore = String.valueOf(highscoreP1);
bombs = String.valueOf(gamestate.getP1BombUsed());
aliensDestroyed = String.valueOf(gamestate.getP1alienDestroyed());
asteroidsDestroyed = String.valueOf(gamestate.getP1asteroidDestroyed());
level = levelP1;
} else {
player = "p2";
highscore = String.valueOf(highscoreP2);
bombs = String.valueOf(gamestate.getP2BombUsed());
aliensDestroyed = String.valueOf(gamestate.getP2alienDestroyed());
asteroidsDestroyed = String.valueOf(gamestate.getP2asteroidDestroyed());
level = levelP2;
}
}
//fill in table info
String[] columnData = {"", ""};
String[][] rowData = {{"Player name", player}, {"Highscore", highscore}, {"Asteroids Destroyed", asteroidsDestroyed}, {"Aliens Destroyed", aliensDestroyed}, {"Kill-Death ratio", "killDeathRatio"}, {"Last level", level}, {"Bombs used", bombs}, {"Shooting Accuracy", "shootingAccuracy"}};
StatisticsTable = new JTable(rowData, columnData);
StatisticsTable.setPreferredScrollableViewportSize(new Dimension(w / 2, h / 6));
StatisticsTable.setFillsViewportHeight(true);
String[] scoreData = {player + " ", highscore + " ", asteroidsDestroyed + "", "aliensdestroyed ", "Kill-Deathratio ", level + " ", bombs + " ", "shootingaccuracy"};
highScoreWriter writer = new highScoreWriter(scoreData, "./src/highscoreData/scoreInfo.txt");
writer.writeToFile();
}
| private void makeComponents(int w, int h, boolean singleP) {
// informative content will be displayed at end game
String player, highscore, asteroidsDestroyed, aliensDestroyed, killDeathRatio, level, bombs, shootingAccuracy;
//when single player, display player's information
if (singleP) {
player = "p1";
highscore = String.valueOf(gamestate.getCurrentScore());
asteroidsDestroyed = String.valueOf(gamestate.getP1asteroidDestroyed());
aliensDestroyed = String.valueOf(gamestate.getP1alienDestroyed());;
killDeathRatio = "";
level = String.valueOf(gamestate.getLevel());
bombs = String.valueOf(gamestate.getP1BombUsed());
shootingAccuracy = "";
//Total Shot used
System.out.println(gamestate.getP1shootCounter());
} //two player
else {
//player 1, player 2 scores
int highscoreP1 = gamestate.getPlayer1Score();
String levelP1 = String.valueOf(gamestate.getPlayer1Level());
int highscoreP2 = gamestate.getPlayer2Score();
String levelP2 = String.valueOf(gamestate.getPlayer2Level());
//display winner's score
if (highscoreP1 >= highscoreP2) {
player = "p1";
highscore = String.valueOf(highscoreP1);
bombs = String.valueOf(gamestate.getP1BombUsed());
aliensDestroyed = String.valueOf(gamestate.getP1alienDestroyed());
asteroidsDestroyed = String.valueOf(gamestate.getP1asteroidDestroyed());
level = levelP1;
} else {
player = "p2";
highscore = String.valueOf(highscoreP2);
bombs = String.valueOf(gamestate.getP2BombUsed());
aliensDestroyed = String.valueOf(gamestate.getP2alienDestroyed());
asteroidsDestroyed = String.valueOf(gamestate.getP2asteroidDestroyed());
level = levelP2;
}
}
//fill in table info
String[] columnData = {"", ""};
String[][] rowData = {{"Player name", player}, {"Highscore", highscore}, {"Asteroids Destroyed", asteroidsDestroyed}, {"Aliens Destroyed", aliensDestroyed}, {"Kill-Death ratio", "killDeathRatio"}, {"Last level", level}, {"Bombs used", bombs}, {"Shooting Accuracy", "shootingAccuracy"}};
StatisticsTable = new JTable(rowData, columnData);
StatisticsTable.setPreferredScrollableViewportSize(new Dimension(w / 2, h / 6));
StatisticsTable.setFillsViewportHeight(true);
String[] scoreData = {player + " ", highscore + " ", asteroidsDestroyed + " ", "aliensdestroyed ", "Kill-Deathratio ", level + " ", bombs + " ", "shootingaccuracy"};
highScoreWriter writer = new highScoreWriter(scoreData, "./src/highscoreData/scoreInfo.txt");
writer.writeToFile();
}
|
diff --git a/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java b/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java
index 73d6ffdf3..df4208c24 100644
--- a/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java
+++ b/applications/exo.jcr.applications.backupconsole/src/main/java/org/exoplatform/jcr/backupconsole/BackupConsole.java
@@ -1,696 +1,696 @@
/*
* Copyright (C) 2009 eXo Platform SAS.
*
* 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.exoplatform.jcr.backupconsole;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
/**
* Created by The eXo Platform SAS. <br/>Date:
*
* @author <a href="[email protected]">Karpenko Sergiy</a>
* @version $Id: BackupConsole.java 111 2008-11-11 11:11:11Z serg $
*/
public class BackupConsole
{
/**
* Incorrect parameter string.
*/
private static final String INCORRECT_PARAM = "Incorrect parameter: ";
/**
* Too many parameters string.
*/
private static final String TOO_MANY_PARAMS = "Too many parameters.";
/**
* Login password string.
*/
private static final String LOGIN_PASS_SPLITTER = ":";
/**
* Force close session parameter string.
*/
private static final String FORCE_CLOSE = "force-close-session";
/**
* Help string.
*/
private static final String HELP_INFO =
"Help info:\n"
+ " <url_basic_authentication>|<url form authentication> <cmd> \n"
+ " <url_basic_authentication> : http(s)//login:password@host:port/<context> \n\n"
+ " <url form authentication> : http(s)//host:port/<context> \"<form auth parm>\" \n"
+ " <form auth parm> : form <method> <form path>\n"
+ " <method> : POST or GET\n"
+ " <form path> : /path/path?<paramName1>=<paramValue1>&<paramName2>=<paramValue2>...\n"
+ " Example to <url form authentication> : http://127.0.0.1:8080/portal/rest form POST \"/portal/login?initialURI=/portal/private&username=root&password=gtn\"\n\n"
+ " <cmd> : start <repo[/ws]> <backup_dir> [<incr>] \n"
+ " stop <backup_id> \n"
+ " status <backup_id> \n"
+ " restores <repo[/ws]> \n"
+ " restore [remove-exists] [<repo[/ws]>] {<backup_id>|<backup_set_path>} [<pathToConfigFile>] \n"
+ " list [completed] \n"
+ " info \n"
+ " drop [force-close-session] <repo[/ws]> \n"
+ " help \n\n"
+ " start - start backup of repositpry or workspace \n"
+ " stop - stop backup \n"
+ " status - information about the current or completed backup by 'backup_id' \n"
+ " restores - information about the last restore on specific repository or workspace \n"
+ " restore - restore the repository or workspace from specific backup \n"
+ " list - information about the current backups (in progress) \n"
+ " list completed - information about the completed (ready to restore) backups \n"
+ " info - information about the service backup \n"
+ " drop - delete the repository or workspace \n"
+ " help - print help information about backup console \n\n"
+ " <repo[/ws]> - /<reponsitory-name>[/<workspace-name>] the repository or workspace \n"
+ " <backup_dir> - path to folder for backup on remote server \n"
+ " <backup_id> - the identifier for backup \n"
+ " <backup_set_dir> - path to folder with backup set on remote server\n"
+ " <incr> - incemental job period \n"
+ " <pathToConfigFile> - path (local) to repository or workspace configuration \n"
+ " remove-exists - remove fully (db, value storage, index) exists repository/workspace \n"
+ " force-close-session - close opened sessions on repositpry or workspace. \n\n";
/**
* Main.
*
* @param args -
* arguments used as parameters for execute backup server commands.
*/
public static void main(String[] args)
{
int curArg = 0;
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no any parameters."); //NOSONAR
return;
}
// help
if (args[curArg].equalsIgnoreCase("help"))
{
System.out.println(HELP_INFO); //NOSONAR
return;
}
// url
String sUrl = args[curArg];
curArg++;
URL url;
try
{
url = new URL(sUrl);
}
catch (MalformedURLException e)
{
System.out.println(INCORRECT_PARAM + "There is no url parameter."); //NOSONAR
return;
}
String urlPath = null;
if (!("".equals(url.getPath())))
urlPath = url.getPath();
// try form
String form = null;
if (curArg < args.length)
{
if (args[curArg].equals("form"))
{
form = args[curArg++];
if (url.getUserInfo() != null)
{
- System.out
- .println(INCORRECT_PARAM
- + "Parameters Login:Password should not be specified in url parameter to form authentication - "
- + sUrl); //NOSONAR
+ System.out //NOSONAR
+ .println(INCORRECT_PARAM
+ + "Parameters Login:Password should not be specified in url parameter to form authentication - "
+ + sUrl);
return;
}
}
}
// login:password
String login = url.getUserInfo();
FormAuthentication formAuthentication = null;
if (form != null && form.equals("form"))
{
//check POST or GET
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "No specified POST or GET parameter to form parameter."); //NOSONAR
return;
}
String method = args[curArg++];
if (!method.equalsIgnoreCase("GET") && !method.equalsIgnoreCase("POST"))
{
- System.out.println(INCORRECT_PARAM
- + "Method to form authentication shulde be GET or POST to form parameter - " + method); //NOSONAR
+ System.out.println(INCORRECT_PARAM //NOSONAR
+ + "Method to form authentication shulde be GET or POST to form parameter - " + method);
return;
}
//url to form authentication
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "No specified url and form properties to form parameter."); //NOSONAR
return;
}
String[] params = args[curArg++].split("[?]");
if (params.length != 2)
{
- System.out
- .println(INCORRECT_PARAM + "From parameters is not spacified to form parameter - " + args[curArg]); //NOSONAR
+ System.out //NOSONAR
+ .println(INCORRECT_PARAM + "From parameters is not spacified to form parameter - " + args[curArg]);
return;
}
String formUrl = params[0];
// parameters to form
String[] formParams = params[1].split("&");
if (formParams.length < 2)
{
System.out.println(INCORRECT_PARAM //NOSONAR
+ "From parameters shoulde be conatains at least two (for login and for pasword) parameters - " //NOSONAR
+ params[1]); //NOSONAR
return;
}
HashMap<String, String> mapFormParams = new HashMap<String, String>();
for (String fParam : formParams)
{
String[] para = fParam.split("=");
if (para.length != 2)
{
- System.out.println(INCORRECT_PARAM + "From parameters is incorect, shoulde be as \"name=value\" - "
- + fParam); //NOSONAR
+ System.out.println(INCORRECT_PARAM + "From parameters is incorect, shoulde be as \"name=value\" - " //NOSONAR
+ + fParam);
return;
}
mapFormParams.put(para[0], para[1]);
}
formAuthentication = new FormAuthentication(method, formUrl, mapFormParams);
}
else
{
if (login == null)
{
System.out.println(INCORRECT_PARAM + "There is no specific Login:Password in url parameter - " + sUrl); //NOSONAR
return;
}
else if (!login.matches("[^:]+:[^:]+"))
{
System.out.println(INCORRECT_PARAM + "There is incorrect Login:Password parameter - " + login); //NOSONAR
return;
}
}
String host = url.getHost() + ":" + url.getPort();
// initialize transport and backup client
ClientTransport transport;
BackupClient client;
if (formAuthentication != null)
{
transport = new ClientTransportImpl(formAuthentication, host, url.getProtocol());
client = new BackupClientImpl(transport, formAuthentication, urlPath);
}
else
{
String[] lp = login.split(LOGIN_PASS_SPLITTER);
transport = new ClientTransportImpl(lp[0], lp[1], host, url.getProtocol());
client = new BackupClientImpl(transport, urlPath);
}
// commands
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no command parameter."); //NOSONAR
return;
}
String command = args[curArg++];
try
{
if (command.equalsIgnoreCase("start"))
{
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
String backupDir;
if (curArg == args.length)
{
backupDir = null;
}
else
{
//check is incremental job period
if (args[curArg].matches("[0-9]+"))
{
backupDir = null;
}
else
{
backupDir = args[curArg++];
}
}
if (curArg == args.length)
{
System.out.println(client.startBackUp(repositoryName, workspaceName, backupDir)); //NOSONAR
}
else
{
// incremental job period
String incr = args[curArg++];
long inc = 0;
try
{
inc = Long.parseLong(incr);
}
catch (NumberFormatException e)
{
System.out.println(INCORRECT_PARAM + "Incemental job period is not didgit - " + e.getMessage()); //NOSONAR
return;
}
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.startIncrementalBackUp(repositoryName, workspaceName, backupDir, inc)); //NOSONAR
}
}
else if (command.equalsIgnoreCase("stop"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier parameter."); //NOSONAR
return;
}
String backupId = args[curArg++];
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.stop(backupId)); //NOSONAR
}
else if (command.equalsIgnoreCase("drop"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to workspace or force-session-close parameter."); //NOSONAR
return;
}
String param = args[curArg++];
boolean isForce = true;
if (!param.equalsIgnoreCase(FORCE_CLOSE))
{
curArg--;
isForce = false;
}
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.drop(isForce, repositoryName, workspaceName)); //NOSONAR
}
else if (command.equalsIgnoreCase("status"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier parameter."); //NOSONAR
return;
}
String backupId = args[curArg++];
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.status(backupId)); //NOSONAR
}
else if (command.equalsIgnoreCase("info"))
{
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.info()); //NOSONAR
}
else if (command.equalsIgnoreCase("restores"))
{
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);;
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.restores(repositoryName, workspaceName)); //NOSONAR
}
else if (command.equalsIgnoreCase("list"))
{
if (curArg == args.length)
{
System.out.println(client.list()); //NOSONAR
}
else
{
String complated = args[curArg++];
if (complated.equalsIgnoreCase("completed"))
{
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.listCompleted()); //NOSONAR
}
else
{
System.out.println(INCORRECT_PARAM + "There is no 'completed' parameter - " + complated); //NOSONAR
return;
}
}
}
else if (command.equalsIgnoreCase("restore"))
{
/*
All valid combination of paramter.
1. restore remove-exists <repo/ws> <backup_id> <pathToConfigFile>
2. restore remove-exists <repo> <backup_id> <pathToConfigFile>
3. restore remove-exists <repo/ws> <backup_set_path> <pathToConfigFile>
4. restore remove-exists <repo> <backup_set_path> <pathToConfigFile>
5. restore remove-exists <backup_id>
6. restore remove-exists <backup_set_path>
7. restore <repo/ws> <backup_id> <pathToConfigFile>
8. restore <repo> <backup_id> <pathToConfigFile>
9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
10. restore <repo> <backup_set_path> <pathToConfigFile>
11. restore <backup_id>
12. restore <backup_set_path>
*/
boolean removeExists = false;
String backupSetPath = null;
String backupId = null;
String pathToWS = null;
String repositoryName = null;
String workspaceName = null;
String parameter = args[curArg++];
//check remove-exists
if (parameter.equals("remove-exists"))
{
removeExists = true;
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "Should be more parameters."); //NOSONAR
return;
}
}
if (removeExists)
{
parameter = args[curArg++];
}
//check backup_id
if (isBackupId(parameter))
{
backupId = parameter;
curArg++;
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
//5. restore remove-exists <backup_id>
//11. restore <backup_id>
- System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath,
- removeExists)); //NOSONAR
+ System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath, //NOSONAR
+ removeExists));
return;
}
//check /repo/ws or /repo
else if (isRepoWS(parameter))
{
pathToWS = getRepoWS(args, curArg - 1);
if (pathToWS == null)
return;
repositoryName = getRepositoryName(pathToWS);
workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
}
// this is backup_set_path
else
{
backupSetPath = parameter;
if (curArg < args.length)
{
System.out.println(INCORRECT_PARAM + "Should be less parameters : " + parameter); //NOSONAR
return;
}
//6. restore remove-exists <backup_set_path>
//12. restore <backup_set_path>
- System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath,
- removeExists)); //NOSONAR
+ System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath, //NOSONAR
+ removeExists));
return;
}
// check backup_id or backup_set_path
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier or backup set path parameter."); //NOSONAR
return;
}
parameter = args[curArg++];
if (isBackupId(parameter))
{
backupId = parameter;
}
else
{
backupSetPath = parameter;
}
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to config file parameter."); //NOSONAR
return;
}
String pathToConf = args[curArg++];
File conf = new File(pathToConf);
if (!conf.exists())
{
System.out.println(" File " + pathToConf + " do not exist. Check the path."); //NOSONAR
return;
}
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
/*
1. restore remove-exists <repo/ws> <backup_id> <pathToConfigFile>
2. restore remove-exists <repo> <backup_id> <pathToConfigFile>
3. restore remove-exists <repo/ws> <backup_set_path> <pathToConfigFile>
4. restore remove-exists <repo> <backup_set_path> <pathToConfigFile>
7. restore <repo/ws> <backup_id> <pathToConfigFile>
8. restore <repo> <backup_id> <pathToConfigFile>
9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
10. restore <repo> <backup_set_path> <pathToConfigFile>
*/
System.out.println(client.restore(repositoryName, workspaceName, backupId, new FileInputStream(conf), //NOSONAR
backupSetPath, removeExists));
}
else
{
System.out.println("Unknown command <" + command + ">"); //NOSONAR
}
}
catch (IOException e)
{
System.out.println("ERROR: " + e.getMessage()); //NOSONAR
- e.printStackTrace();
+ e.printStackTrace(); //NOSONAR
}
catch (BackupExecuteException e)
{
System.out.println("ERROR: " + e.getMessage()); //NOSONAR
- e.printStackTrace();
+ e.printStackTrace(); //NOSONAR
}
System.exit(0);
}
/**
* Check is "/repo" or "/repo/ws" parameter.
*
* @param parameter
* String, parameter.
* @return Boolean
* return "true" if it "/repo" or "/repo/ws" parameter
*/
private static boolean isRepoWS(String parameter)
{
String repWS = parameter;
repWS = repWS.replaceAll("\\\\", "/");
if ( !repWS.matches("[/][^/]+") && !repWS.matches("[/][^/]+[/][^/]+"))
{
return false;
}
else
{
return true;
}
}
/**
* Check is backip_id parameter.
*
* @param firstParameter
* String, parameter.
* @return Boolean
* return "true" if it backup identifier parameter
*/
private static boolean isBackupId(String parameter)
{
return parameter.matches("[0-9abcdef]+") && parameter.length() == 32;
}
/**
* getWorkspaceName.
*
* @param pathToWS
* the /<repository-name>/<workspace name>
* @return String return the workspace name
*/
private static String getWorkspaceName(String pathToWS)
{
return pathToWS.split("/")[2];
}
/**
* getRepositoryName.
*
* @param pathToWS
* the /<repository-name>/<workspace name>
* @return String return the repository name
*/
private static String getRepositoryName(String pathToWS)
{
return pathToWS.split("/")[1];
}
/**
* Get parameter from argument list, check it and return as valid path to repository and
* workspace.
*
* @param args
* list of arguments.
* @param curArg
* argument index.
* @return String valid path.
*/
private static String getRepoWS(String[] args, int curArg)
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to workspace parameter."); //NOSONAR
return null;
}
// make correct path
String repWS = args[curArg];
repWS = repWS.replaceAll("\\\\", "/");
if ( !repWS.matches("[/][^/]+") && !repWS.matches("[/][^/]+[/][^/]+"))
{
System.out.println(INCORRECT_PARAM + "There is incorrect path to workspace parameter: " + repWS); //NOSONAR
return null;
}
else
{
return repWS;
}
}
}
| false | true | public static void main(String[] args)
{
int curArg = 0;
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no any parameters."); //NOSONAR
return;
}
// help
if (args[curArg].equalsIgnoreCase("help"))
{
System.out.println(HELP_INFO); //NOSONAR
return;
}
// url
String sUrl = args[curArg];
curArg++;
URL url;
try
{
url = new URL(sUrl);
}
catch (MalformedURLException e)
{
System.out.println(INCORRECT_PARAM + "There is no url parameter."); //NOSONAR
return;
}
String urlPath = null;
if (!("".equals(url.getPath())))
urlPath = url.getPath();
// try form
String form = null;
if (curArg < args.length)
{
if (args[curArg].equals("form"))
{
form = args[curArg++];
if (url.getUserInfo() != null)
{
System.out
.println(INCORRECT_PARAM
+ "Parameters Login:Password should not be specified in url parameter to form authentication - "
+ sUrl); //NOSONAR
return;
}
}
}
// login:password
String login = url.getUserInfo();
FormAuthentication formAuthentication = null;
if (form != null && form.equals("form"))
{
//check POST or GET
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "No specified POST or GET parameter to form parameter."); //NOSONAR
return;
}
String method = args[curArg++];
if (!method.equalsIgnoreCase("GET") && !method.equalsIgnoreCase("POST"))
{
System.out.println(INCORRECT_PARAM
+ "Method to form authentication shulde be GET or POST to form parameter - " + method); //NOSONAR
return;
}
//url to form authentication
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "No specified url and form properties to form parameter."); //NOSONAR
return;
}
String[] params = args[curArg++].split("[?]");
if (params.length != 2)
{
System.out
.println(INCORRECT_PARAM + "From parameters is not spacified to form parameter - " + args[curArg]); //NOSONAR
return;
}
String formUrl = params[0];
// parameters to form
String[] formParams = params[1].split("&");
if (formParams.length < 2)
{
System.out.println(INCORRECT_PARAM //NOSONAR
+ "From parameters shoulde be conatains at least two (for login and for pasword) parameters - " //NOSONAR
+ params[1]); //NOSONAR
return;
}
HashMap<String, String> mapFormParams = new HashMap<String, String>();
for (String fParam : formParams)
{
String[] para = fParam.split("=");
if (para.length != 2)
{
System.out.println(INCORRECT_PARAM + "From parameters is incorect, shoulde be as \"name=value\" - "
+ fParam); //NOSONAR
return;
}
mapFormParams.put(para[0], para[1]);
}
formAuthentication = new FormAuthentication(method, formUrl, mapFormParams);
}
else
{
if (login == null)
{
System.out.println(INCORRECT_PARAM + "There is no specific Login:Password in url parameter - " + sUrl); //NOSONAR
return;
}
else if (!login.matches("[^:]+:[^:]+"))
{
System.out.println(INCORRECT_PARAM + "There is incorrect Login:Password parameter - " + login); //NOSONAR
return;
}
}
String host = url.getHost() + ":" + url.getPort();
// initialize transport and backup client
ClientTransport transport;
BackupClient client;
if (formAuthentication != null)
{
transport = new ClientTransportImpl(formAuthentication, host, url.getProtocol());
client = new BackupClientImpl(transport, formAuthentication, urlPath);
}
else
{
String[] lp = login.split(LOGIN_PASS_SPLITTER);
transport = new ClientTransportImpl(lp[0], lp[1], host, url.getProtocol());
client = new BackupClientImpl(transport, urlPath);
}
// commands
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no command parameter."); //NOSONAR
return;
}
String command = args[curArg++];
try
{
if (command.equalsIgnoreCase("start"))
{
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
String backupDir;
if (curArg == args.length)
{
backupDir = null;
}
else
{
//check is incremental job period
if (args[curArg].matches("[0-9]+"))
{
backupDir = null;
}
else
{
backupDir = args[curArg++];
}
}
if (curArg == args.length)
{
System.out.println(client.startBackUp(repositoryName, workspaceName, backupDir)); //NOSONAR
}
else
{
// incremental job period
String incr = args[curArg++];
long inc = 0;
try
{
inc = Long.parseLong(incr);
}
catch (NumberFormatException e)
{
System.out.println(INCORRECT_PARAM + "Incemental job period is not didgit - " + e.getMessage()); //NOSONAR
return;
}
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.startIncrementalBackUp(repositoryName, workspaceName, backupDir, inc)); //NOSONAR
}
}
else if (command.equalsIgnoreCase("stop"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier parameter."); //NOSONAR
return;
}
String backupId = args[curArg++];
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.stop(backupId)); //NOSONAR
}
else if (command.equalsIgnoreCase("drop"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to workspace or force-session-close parameter."); //NOSONAR
return;
}
String param = args[curArg++];
boolean isForce = true;
if (!param.equalsIgnoreCase(FORCE_CLOSE))
{
curArg--;
isForce = false;
}
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.drop(isForce, repositoryName, workspaceName)); //NOSONAR
}
else if (command.equalsIgnoreCase("status"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier parameter."); //NOSONAR
return;
}
String backupId = args[curArg++];
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.status(backupId)); //NOSONAR
}
else if (command.equalsIgnoreCase("info"))
{
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.info()); //NOSONAR
}
else if (command.equalsIgnoreCase("restores"))
{
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);;
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.restores(repositoryName, workspaceName)); //NOSONAR
}
else if (command.equalsIgnoreCase("list"))
{
if (curArg == args.length)
{
System.out.println(client.list()); //NOSONAR
}
else
{
String complated = args[curArg++];
if (complated.equalsIgnoreCase("completed"))
{
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.listCompleted()); //NOSONAR
}
else
{
System.out.println(INCORRECT_PARAM + "There is no 'completed' parameter - " + complated); //NOSONAR
return;
}
}
}
else if (command.equalsIgnoreCase("restore"))
{
/*
All valid combination of paramter.
1. restore remove-exists <repo/ws> <backup_id> <pathToConfigFile>
2. restore remove-exists <repo> <backup_id> <pathToConfigFile>
3. restore remove-exists <repo/ws> <backup_set_path> <pathToConfigFile>
4. restore remove-exists <repo> <backup_set_path> <pathToConfigFile>
5. restore remove-exists <backup_id>
6. restore remove-exists <backup_set_path>
7. restore <repo/ws> <backup_id> <pathToConfigFile>
8. restore <repo> <backup_id> <pathToConfigFile>
9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
10. restore <repo> <backup_set_path> <pathToConfigFile>
11. restore <backup_id>
12. restore <backup_set_path>
*/
boolean removeExists = false;
String backupSetPath = null;
String backupId = null;
String pathToWS = null;
String repositoryName = null;
String workspaceName = null;
String parameter = args[curArg++];
//check remove-exists
if (parameter.equals("remove-exists"))
{
removeExists = true;
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "Should be more parameters."); //NOSONAR
return;
}
}
if (removeExists)
{
parameter = args[curArg++];
}
//check backup_id
if (isBackupId(parameter))
{
backupId = parameter;
curArg++;
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
//5. restore remove-exists <backup_id>
//11. restore <backup_id>
System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath,
removeExists)); //NOSONAR
return;
}
//check /repo/ws or /repo
else if (isRepoWS(parameter))
{
pathToWS = getRepoWS(args, curArg - 1);
if (pathToWS == null)
return;
repositoryName = getRepositoryName(pathToWS);
workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
}
// this is backup_set_path
else
{
backupSetPath = parameter;
if (curArg < args.length)
{
System.out.println(INCORRECT_PARAM + "Should be less parameters : " + parameter); //NOSONAR
return;
}
//6. restore remove-exists <backup_set_path>
//12. restore <backup_set_path>
System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath,
removeExists)); //NOSONAR
return;
}
// check backup_id or backup_set_path
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier or backup set path parameter."); //NOSONAR
return;
}
parameter = args[curArg++];
if (isBackupId(parameter))
{
backupId = parameter;
}
else
{
backupSetPath = parameter;
}
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to config file parameter."); //NOSONAR
return;
}
String pathToConf = args[curArg++];
File conf = new File(pathToConf);
if (!conf.exists())
{
System.out.println(" File " + pathToConf + " do not exist. Check the path."); //NOSONAR
return;
}
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
/*
1. restore remove-exists <repo/ws> <backup_id> <pathToConfigFile>
2. restore remove-exists <repo> <backup_id> <pathToConfigFile>
3. restore remove-exists <repo/ws> <backup_set_path> <pathToConfigFile>
4. restore remove-exists <repo> <backup_set_path> <pathToConfigFile>
7. restore <repo/ws> <backup_id> <pathToConfigFile>
8. restore <repo> <backup_id> <pathToConfigFile>
9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
10. restore <repo> <backup_set_path> <pathToConfigFile>
*/
System.out.println(client.restore(repositoryName, workspaceName, backupId, new FileInputStream(conf), //NOSONAR
backupSetPath, removeExists));
}
else
{
System.out.println("Unknown command <" + command + ">"); //NOSONAR
}
}
catch (IOException e)
{
System.out.println("ERROR: " + e.getMessage()); //NOSONAR
e.printStackTrace();
}
catch (BackupExecuteException e)
{
System.out.println("ERROR: " + e.getMessage()); //NOSONAR
e.printStackTrace();
}
System.exit(0);
}
| public static void main(String[] args)
{
int curArg = 0;
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no any parameters."); //NOSONAR
return;
}
// help
if (args[curArg].equalsIgnoreCase("help"))
{
System.out.println(HELP_INFO); //NOSONAR
return;
}
// url
String sUrl = args[curArg];
curArg++;
URL url;
try
{
url = new URL(sUrl);
}
catch (MalformedURLException e)
{
System.out.println(INCORRECT_PARAM + "There is no url parameter."); //NOSONAR
return;
}
String urlPath = null;
if (!("".equals(url.getPath())))
urlPath = url.getPath();
// try form
String form = null;
if (curArg < args.length)
{
if (args[curArg].equals("form"))
{
form = args[curArg++];
if (url.getUserInfo() != null)
{
System.out //NOSONAR
.println(INCORRECT_PARAM
+ "Parameters Login:Password should not be specified in url parameter to form authentication - "
+ sUrl);
return;
}
}
}
// login:password
String login = url.getUserInfo();
FormAuthentication formAuthentication = null;
if (form != null && form.equals("form"))
{
//check POST or GET
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "No specified POST or GET parameter to form parameter."); //NOSONAR
return;
}
String method = args[curArg++];
if (!method.equalsIgnoreCase("GET") && !method.equalsIgnoreCase("POST"))
{
System.out.println(INCORRECT_PARAM //NOSONAR
+ "Method to form authentication shulde be GET or POST to form parameter - " + method);
return;
}
//url to form authentication
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "No specified url and form properties to form parameter."); //NOSONAR
return;
}
String[] params = args[curArg++].split("[?]");
if (params.length != 2)
{
System.out //NOSONAR
.println(INCORRECT_PARAM + "From parameters is not spacified to form parameter - " + args[curArg]);
return;
}
String formUrl = params[0];
// parameters to form
String[] formParams = params[1].split("&");
if (formParams.length < 2)
{
System.out.println(INCORRECT_PARAM //NOSONAR
+ "From parameters shoulde be conatains at least two (for login and for pasword) parameters - " //NOSONAR
+ params[1]); //NOSONAR
return;
}
HashMap<String, String> mapFormParams = new HashMap<String, String>();
for (String fParam : formParams)
{
String[] para = fParam.split("=");
if (para.length != 2)
{
System.out.println(INCORRECT_PARAM + "From parameters is incorect, shoulde be as \"name=value\" - " //NOSONAR
+ fParam);
return;
}
mapFormParams.put(para[0], para[1]);
}
formAuthentication = new FormAuthentication(method, formUrl, mapFormParams);
}
else
{
if (login == null)
{
System.out.println(INCORRECT_PARAM + "There is no specific Login:Password in url parameter - " + sUrl); //NOSONAR
return;
}
else if (!login.matches("[^:]+:[^:]+"))
{
System.out.println(INCORRECT_PARAM + "There is incorrect Login:Password parameter - " + login); //NOSONAR
return;
}
}
String host = url.getHost() + ":" + url.getPort();
// initialize transport and backup client
ClientTransport transport;
BackupClient client;
if (formAuthentication != null)
{
transport = new ClientTransportImpl(formAuthentication, host, url.getProtocol());
client = new BackupClientImpl(transport, formAuthentication, urlPath);
}
else
{
String[] lp = login.split(LOGIN_PASS_SPLITTER);
transport = new ClientTransportImpl(lp[0], lp[1], host, url.getProtocol());
client = new BackupClientImpl(transport, urlPath);
}
// commands
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no command parameter."); //NOSONAR
return;
}
String command = args[curArg++];
try
{
if (command.equalsIgnoreCase("start"))
{
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
String backupDir;
if (curArg == args.length)
{
backupDir = null;
}
else
{
//check is incremental job period
if (args[curArg].matches("[0-9]+"))
{
backupDir = null;
}
else
{
backupDir = args[curArg++];
}
}
if (curArg == args.length)
{
System.out.println(client.startBackUp(repositoryName, workspaceName, backupDir)); //NOSONAR
}
else
{
// incremental job period
String incr = args[curArg++];
long inc = 0;
try
{
inc = Long.parseLong(incr);
}
catch (NumberFormatException e)
{
System.out.println(INCORRECT_PARAM + "Incemental job period is not didgit - " + e.getMessage()); //NOSONAR
return;
}
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.startIncrementalBackUp(repositoryName, workspaceName, backupDir, inc)); //NOSONAR
}
}
else if (command.equalsIgnoreCase("stop"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier parameter."); //NOSONAR
return;
}
String backupId = args[curArg++];
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.stop(backupId)); //NOSONAR
}
else if (command.equalsIgnoreCase("drop"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to workspace or force-session-close parameter."); //NOSONAR
return;
}
String param = args[curArg++];
boolean isForce = true;
if (!param.equalsIgnoreCase(FORCE_CLOSE))
{
curArg--;
isForce = false;
}
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.drop(isForce, repositoryName, workspaceName)); //NOSONAR
}
else if (command.equalsIgnoreCase("status"))
{
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier parameter."); //NOSONAR
return;
}
String backupId = args[curArg++];
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.status(backupId)); //NOSONAR
}
else if (command.equalsIgnoreCase("info"))
{
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.info()); //NOSONAR
}
else if (command.equalsIgnoreCase("restores"))
{
String pathToWS = getRepoWS(args, curArg++);
if (pathToWS == null)
return;
String repositoryName = getRepositoryName(pathToWS);
String workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);;
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.restores(repositoryName, workspaceName)); //NOSONAR
}
else if (command.equalsIgnoreCase("list"))
{
if (curArg == args.length)
{
System.out.println(client.list()); //NOSONAR
}
else
{
String complated = args[curArg++];
if (complated.equalsIgnoreCase("completed"))
{
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
System.out.println(client.listCompleted()); //NOSONAR
}
else
{
System.out.println(INCORRECT_PARAM + "There is no 'completed' parameter - " + complated); //NOSONAR
return;
}
}
}
else if (command.equalsIgnoreCase("restore"))
{
/*
All valid combination of paramter.
1. restore remove-exists <repo/ws> <backup_id> <pathToConfigFile>
2. restore remove-exists <repo> <backup_id> <pathToConfigFile>
3. restore remove-exists <repo/ws> <backup_set_path> <pathToConfigFile>
4. restore remove-exists <repo> <backup_set_path> <pathToConfigFile>
5. restore remove-exists <backup_id>
6. restore remove-exists <backup_set_path>
7. restore <repo/ws> <backup_id> <pathToConfigFile>
8. restore <repo> <backup_id> <pathToConfigFile>
9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
10. restore <repo> <backup_set_path> <pathToConfigFile>
11. restore <backup_id>
12. restore <backup_set_path>
*/
boolean removeExists = false;
String backupSetPath = null;
String backupId = null;
String pathToWS = null;
String repositoryName = null;
String workspaceName = null;
String parameter = args[curArg++];
//check remove-exists
if (parameter.equals("remove-exists"))
{
removeExists = true;
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "Should be more parameters."); //NOSONAR
return;
}
}
if (removeExists)
{
parameter = args[curArg++];
}
//check backup_id
if (isBackupId(parameter))
{
backupId = parameter;
curArg++;
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
//5. restore remove-exists <backup_id>
//11. restore <backup_id>
System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath, //NOSONAR
removeExists));
return;
}
//check /repo/ws or /repo
else if (isRepoWS(parameter))
{
pathToWS = getRepoWS(args, curArg - 1);
if (pathToWS == null)
return;
repositoryName = getRepositoryName(pathToWS);
workspaceName = (pathToWS.split("/").length == 3 ? getWorkspaceName(pathToWS) : null);
}
// this is backup_set_path
else
{
backupSetPath = parameter;
if (curArg < args.length)
{
System.out.println(INCORRECT_PARAM + "Should be less parameters : " + parameter); //NOSONAR
return;
}
//6. restore remove-exists <backup_set_path>
//12. restore <backup_set_path>
System.out.println(client.restore(repositoryName, workspaceName, backupId, null, backupSetPath, //NOSONAR
removeExists));
return;
}
// check backup_id or backup_set_path
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no backup identifier or backup set path parameter."); //NOSONAR
return;
}
parameter = args[curArg++];
if (isBackupId(parameter))
{
backupId = parameter;
}
else
{
backupSetPath = parameter;
}
if (curArg == args.length)
{
System.out.println(INCORRECT_PARAM + "There is no path to config file parameter."); //NOSONAR
return;
}
String pathToConf = args[curArg++];
File conf = new File(pathToConf);
if (!conf.exists())
{
System.out.println(" File " + pathToConf + " do not exist. Check the path."); //NOSONAR
return;
}
if (curArg < args.length)
{
System.out.println(TOO_MANY_PARAMS); //NOSONAR
return;
}
/*
1. restore remove-exists <repo/ws> <backup_id> <pathToConfigFile>
2. restore remove-exists <repo> <backup_id> <pathToConfigFile>
3. restore remove-exists <repo/ws> <backup_set_path> <pathToConfigFile>
4. restore remove-exists <repo> <backup_set_path> <pathToConfigFile>
7. restore <repo/ws> <backup_id> <pathToConfigFile>
8. restore <repo> <backup_id> <pathToConfigFile>
9. restore <repo/ws> <backup_set_path> <pathToConfigFile>
10. restore <repo> <backup_set_path> <pathToConfigFile>
*/
System.out.println(client.restore(repositoryName, workspaceName, backupId, new FileInputStream(conf), //NOSONAR
backupSetPath, removeExists));
}
else
{
System.out.println("Unknown command <" + command + ">"); //NOSONAR
}
}
catch (IOException e)
{
System.out.println("ERROR: " + e.getMessage()); //NOSONAR
e.printStackTrace(); //NOSONAR
}
catch (BackupExecuteException e)
{
System.out.println("ERROR: " + e.getMessage()); //NOSONAR
e.printStackTrace(); //NOSONAR
}
System.exit(0);
}
|
diff --git a/src/org/rascalmpl/interpreter/TraversalEvaluator.java b/src/org/rascalmpl/interpreter/TraversalEvaluator.java
index 7b7f1d29f0..15345937ab 100644
--- a/src/org/rascalmpl/interpreter/TraversalEvaluator.java
+++ b/src/org/rascalmpl/interpreter/TraversalEvaluator.java
@@ -1,555 +1,555 @@
/*******************************************************************************
* Copyright (c) 2009-2013 CWI
* 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:
* * Jurgen J. Vinju - [email protected] - CWI
* * Tijs van der Storm - [email protected]
* * Emilie Balland - (CWI)
* * Paul Klint - [email protected] - CWI
* * Mark Hills - [email protected] (CWI)
* * Arnold Lankamp - [email protected]
*******************************************************************************/
package org.rascalmpl.interpreter;
import static org.rascalmpl.interpreter.result.ResultFactory.makeResult;
import java.util.Iterator;
import java.util.Map.Entry;
import org.eclipse.imp.pdb.facts.IConstructor;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IListWriter;
import org.eclipse.imp.pdb.facts.IMap;
import org.eclipse.imp.pdb.facts.IMapWriter;
import org.eclipse.imp.pdb.facts.INode;
import org.eclipse.imp.pdb.facts.ISet;
import org.eclipse.imp.pdb.facts.ISetWriter;
import org.eclipse.imp.pdb.facts.IString;
import org.eclipse.imp.pdb.facts.ITuple;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.type.Type;
import org.eclipse.imp.pdb.facts.type.TypeFactory;
import org.rascalmpl.ast.AbstractAST;
import org.rascalmpl.interpreter.asserts.ImplementationError;
import org.rascalmpl.interpreter.control_exceptions.Failure;
import org.rascalmpl.interpreter.env.Environment;
import org.rascalmpl.interpreter.matching.IBooleanResult;
import org.rascalmpl.interpreter.matching.LiteralPattern;
import org.rascalmpl.interpreter.matching.RegExpPatternValue;
import org.rascalmpl.interpreter.matching.TypedVariablePattern;
import org.rascalmpl.interpreter.result.Result;
import org.rascalmpl.interpreter.staticErrors.SyntaxError;
import org.rascalmpl.interpreter.staticErrors.UnexpectedType;
import org.rascalmpl.interpreter.utils.Cases.CaseBlock;
import org.rascalmpl.values.uptr.TreeAdapter;
// TODO: this class is still too tightly coupled with evaluator
public class TraversalEvaluator {
public enum DIRECTION {BottomUp, TopDown} // Parameters for traversing trees
public enum FIXEDPOINT {Yes, No}
public enum PROGRESS {Continuing, Breaking}
private final IEvaluator<Result<IValue>> eval;
private static final TypeFactory tf = TypeFactory.getInstance();
public TraversalEvaluator(IEvaluator<Result<IValue>> eval) {
this.eval = eval;
}
public static class CaseBlockList {
private java.util.List<CaseBlock> cases;
private boolean allConcretePatternCases = true;
private boolean hasRegexp = false;
public CaseBlockList(java.util.List<CaseBlock> cases){
this.cases = cases;
for (CaseBlock c : cases) {
allConcretePatternCases &= c.allConcrete;
hasRegexp |= c.hasRegExp;
}
}
public boolean hasRegexp() {
return hasRegexp;
}
public int length(){
return cases.size();
}
public boolean hasAllConcretePatternCases(){
return allConcretePatternCases;
}
public java.util.List<CaseBlock> getCases(){
return cases;
}
}
public IValue traverse(IValue subject, CaseBlockList casesOrRules, DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint) {
return traverseOnce(subject, casesOrRules, direction, progress, fixedpoint, new TraverseResult());
}
private IValue traverseOnce(IValue subject, CaseBlockList casesOrRules, DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr){
Type subjectType = subject.getType();
IValue result = subject;
if (/* casesOrRules.hasRegexp() && */ subjectType.isStringType()) {
return traverseStringOnce(subject, casesOrRules, tr);
}
boolean hasMatched = false;
boolean hasChanged = false;
if (direction == DIRECTION.TopDown){
IValue newTop = traverseTop(subject, casesOrRules, tr);
if ((progress == PROGRESS.Breaking) && tr.matched) {
return newTop;
}
else if (fixedpoint == FIXEDPOINT.Yes && tr.changed) {
do {
tr.changed = false;
newTop = traverseTop(newTop, casesOrRules, tr);
} while (tr.changed);
tr.changed = true;
subject = newTop;
}
else {
subject = newTop;
}
hasMatched = tr.matched;
hasChanged = tr.changed;
}
if (subjectType.isAbstractDataType()){
result = traverseADTOnce(subject, casesOrRules, direction, progress, fixedpoint, tr);
} else if (subjectType.isNodeType()){
result = traverseNodeOnce(subject, casesOrRules, direction, progress, fixedpoint, tr);
} else if(subjectType.isListType()){
result = traverseListOnce(subject, casesOrRules, direction, progress, fixedpoint, tr);
} else if(subjectType.isSetType()){
result = traverseSetOnce(subject, casesOrRules, direction, progress, fixedpoint, tr);
} else if (subjectType.isMapType()) {
result = traverseMapOnce(subject, casesOrRules, direction, progress, fixedpoint, tr);
} else if(subjectType.isTupleType()){
result = traverseTupleOnce(subject, casesOrRules, direction, progress, fixedpoint, tr);
} else {
result = subject;
}
if (direction == DIRECTION.TopDown) {
tr.matched |= hasMatched;
tr.changed |= hasChanged;
}
if (direction == DIRECTION.BottomUp) {
if ((progress == PROGRESS.Breaking) && tr.changed) {
return result;
}
hasMatched = tr.matched;
hasChanged = tr.changed;
tr.matched = false;
tr.changed = false;
result = traverseTop(result, casesOrRules, tr);
if (tr.changed && fixedpoint == FIXEDPOINT.Yes) {
do {
tr.changed = false;
tr.matched = false;
result = traverseTop(result, casesOrRules, tr);
} while (tr.changed);
tr.changed = true;
tr.matched = true;
}
tr.changed |= hasChanged;
tr.matched |= hasMatched;
}
return result;
}
private IValue traverseStringOnce(IValue subject,
CaseBlockList casesOrRules, TraverseResult tr) {
boolean hasMatched = tr.matched;
boolean hasChanged = tr.changed;
tr.matched = false;
tr.changed = false;
IValue res = traverseString(subject, casesOrRules, tr);
tr.matched |= hasMatched;
tr.changed |= hasChanged;
return res;
}
private IValue traverseTupleOnce(IValue subject, CaseBlockList casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr) {
IValue result;
ITuple tuple = (ITuple) subject;
int arity = tuple.arity();
IValue args[] = new IValue[arity];
boolean hasMatched = false;
boolean hasChanged = false;
for (int i = 0; i < arity; i++){
tr.changed = false;
tr.matched = false;
args[i] = traverseOnce(tuple.get(i), casesOrRules, direction, progress, fixedpoint, tr);
hasMatched |= tr.matched;
hasChanged |= tr.changed;
}
result = eval.getValueFactory().tuple(args);
tr.changed = hasChanged;
tr.matched = hasMatched;
return result;
}
private IValue traverseADTOnce(IValue subject, CaseBlockList casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr) {
IConstructor cons = (IConstructor)subject;
if (cons.arity() == 0) {
return subject; // constants have no children to traverse into
}
if (casesOrRules.hasAllConcretePatternCases() && TreeAdapter.isChar(cons)) {
return subject; // we dont traverse into the structure of literals and characters
}
IValue args[] = new IValue[cons.arity()];
if (casesOrRules.hasAllConcretePatternCases() && TreeAdapter.isAppl(cons)){
// Constructor is "appl": we are dealing with a syntax tree
// - Lexical or literal are returned immediately
if (TreeAdapter.isLexical(cons)|| TreeAdapter.isLiteral(cons)){
return subject; // we dont traverse into the structure of literals, lexicals, and characters
}
// Otherwise:
// - Copy prod node verbatim to result
// - Only visit non-layout nodes in argument list
args[0] = cons.get(0);
IList list = (IList) cons.get(1);
int len = list.length();
if (len > 0) {
IListWriter w = list.getType().writer(eval.getValueFactory());
boolean hasChanged = false;
boolean hasMatched = false;
for (int i = 0; i < len; i++){
IValue elem = list.get(i);
if (i % 2 == 0) { // Recursion to all non-layout elements
tr.changed = false;
tr.matched = false;
w.append(traverseOnce(elem, casesOrRules, direction, progress, fixedpoint, tr));
hasChanged |= tr.changed;
hasMatched |= tr.matched;
} else { // Just copy layout elements
w.append(list.get(i));
}
}
tr.changed = hasChanged;
tr.matched = hasMatched;
args[1] = w.done();
} else {
args[1] = list;
}
} else {
// Constructor is not "appl", or at least one of the patterns is not a concrete pattern
boolean hasChanged = false;
boolean hasMatched = false;
for (int i = 0; i < cons.arity(); i++){
IValue child = cons.get(i);
tr.matched = false;
tr.changed = false;
args[i] = traverseOnce(child, casesOrRules, direction, progress, fixedpoint, tr);
hasChanged |= tr.changed;
hasMatched |= tr.matched;
}
tr.matched = hasMatched;
tr.changed = hasChanged;
}
if (tr.changed) {
IConstructor rcons = (IConstructor) eval.call(cons.getName(), args);
if (cons.hasAnnotations()) {
rcons = rcons.setAnnotations(cons.getAnnotations());
}
return rcons;
}
else {
return subject;
}
}
private IValue traverseMapOnce(IValue subject, CaseBlockList casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr) {
IMap map = (IMap) subject;
if(!map.isEmpty()){
IMapWriter w = map.getType().writer(eval.getValueFactory());
Iterator<Entry<IValue,IValue>> iter = map.entryIterator();
boolean hasChanged = false;
boolean hasMatched = false;
while (iter.hasNext()) {
Entry<IValue,IValue> entry = iter.next();
tr.changed = false;
tr.matched = false;
IValue newKey = traverseOnce(entry.getKey(), casesOrRules, direction, progress, fixedpoint, tr);
hasChanged |= tr.changed;
hasMatched |= tr.matched;
tr.changed = false;
tr.matched = false;
IValue newValue = traverseOnce(entry.getValue(), casesOrRules, direction, progress, fixedpoint, tr);
hasChanged |= tr.changed;
hasMatched |= tr.matched;
w.put(newKey, newValue);
}
tr.changed = hasChanged;
tr.matched = hasMatched;
return w.done();
} else {
return subject;
}
}
private IValue traverseSetOnce(IValue subject, CaseBlockList casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr) {
ISet set = (ISet) subject;
if(!set.isEmpty()){
ISetWriter w = set.getType().writer(eval.getValueFactory());
boolean hasChanged = false;
boolean hasMatched = false;
for (IValue v : set) {
tr.changed = false;
tr.matched = false;
w.insert(traverseOnce(v, casesOrRules, direction, progress, fixedpoint, tr));
hasChanged |= tr.changed;
hasMatched |= tr.matched;
}
tr.changed = hasChanged;
tr.matched = hasMatched;
return w.done();
} else {
return subject;
}
}
private IValue traverseListOnce(IValue subject, CaseBlockList casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr) {
IList list = (IList) subject;
int len = list.length();
if (len > 0){
IListWriter w = list.getType().writer(eval.getValueFactory());
boolean hasChanged = false;
boolean hasMatched = false;
for (int i = 0; i < len; i++){
IValue elem = list.get(i);
tr.changed = false;
tr.matched = false;
w.append(traverseOnce(elem, casesOrRules, direction, progress, fixedpoint, tr));
hasChanged |= tr.changed;
hasMatched |= tr.matched;
}
tr.changed = hasChanged;
tr.matched = hasMatched;
return w.done();
} else {
return subject;
}
}
private IValue traverseNodeOnce(IValue subject, CaseBlockList casesOrRules,
DIRECTION direction, PROGRESS progress, FIXEDPOINT fixedpoint, TraverseResult tr) {
IValue result;
INode node = (INode)subject;
if (node.arity() == 0){
result = subject;
}
else {
IValue args[] = new IValue[node.arity()];
boolean hasChanged = false;
boolean hasMatched = false;
for (int i = 0; i < node.arity(); i++){
IValue child = node.get(i);
tr.changed = false;
tr.matched = false;
args[i] = traverseOnce(child, casesOrRules, direction, progress, fixedpoint, tr);
hasChanged |= tr.changed;
hasMatched |= tr.matched;
}
tr.changed = hasChanged;
tr.matched = hasMatched;
INode n = eval.getValueFactory().node(node.getName(), args);
if (node.hasAnnotations()) {
n = n.setAnnotations(node.getAnnotations());
}
result = n;
}
return result;
}
private IValue applyCases(IValue subject, CaseBlockList casesOrRules, TraverseResult tr) {
for (CaseBlock cs : casesOrRules.getCases()) {
Environment old = eval.getCurrentEnvt();
AbstractAST prevAst = eval.getCurrentAST();
try {
eval.pushEnv();
tr.matched = cs.matchAndEval(eval, makeResult(subject.getType(), subject, eval));
if (tr.matched) {
return subject;
}
}
catch (Failure e) {
// just continue with the next case
continue;
}
finally {
eval.unwind(old);
eval.setCurrentAST(prevAst);
}
}
return subject;
}
/*
* traverseTop: traverse the outermost symbol of the subject.
*/
public IValue traverseTop(IValue subject, CaseBlockList casesOrRules, TraverseResult tr) {
try {
return applyCases(subject, casesOrRules, tr);
}
catch (org.rascalmpl.interpreter.control_exceptions.Insert e) {
tr.changed = true;
tr.matched = true;
Result<IValue> toBeInserted = e.getValue();
if (!toBeInserted.getType().equivalent(subject.getType())) {
throw new UnexpectedType(subject.getType(), toBeInserted.getType(), eval.getCurrentAST());
}
return e.getValue().getValue();
}
}
/*
* traverseString implements a visit of a string subject by visiting subsequent substrings
* subject[0,len], subject[1,len] ...and trying to match the cases. If a case matches
* the subject cursor is advanced by the length of the match and the matched substring may be replaced.
* At the end, the subject string including all replacements is returned.
*
* Performance issue: we create a lot of garbage by producing all these substrings.
*/
public IValue traverseString(IValue subject, CaseBlockList casesOrRules, TraverseResult tr){
String subjectString = ((IString) subject).getValue();
int len = subjectString.length();
int subjectCursor = 0;
int subjectCursorForResult = 0;
StringBuffer replacementString = null;
boolean hasMatched = false;
boolean hasChanged = false;
while (subjectCursor < len){
//System.err.println("cursor = " + cursor);
try {
IString substring = eval.getValueFactory().string(subjectString.substring(subjectCursor, len));
IValue subresult = substring;
tr.matched = false;
tr.changed = false;
// will throw insert or fail
applyCases(subresult, casesOrRules, tr);
hasMatched |= tr.matched;
hasChanged |= tr.changed;
subjectCursor++;
} catch (org.rascalmpl.interpreter.control_exceptions.Insert e) {
IValue repl = e.getValue().getValue();
hasChanged = true;
hasMatched = true;
if (repl.getType().isStringType()){
int start;
int end;
IBooleanResult lastPattern = e.getMatchPattern();
if (lastPattern == null) {
throw new ImplementationError("No last pattern known");
}
if (lastPattern instanceof RegExpPatternValue){
start = ((RegExpPatternValue)lastPattern).getStart();
end = ((RegExpPatternValue)lastPattern).getEnd();
}
else if (lastPattern instanceof LiteralPattern || lastPattern instanceof TypedVariablePattern){
start = 0;
- end = ((IString)repl).getValue().length();
+ end = subjectString.length();
}
else {
throw new SyntaxError("Illegal pattern " + lastPattern + " in string visit", eval.getCurrentAST().getLocation());
}
// Create replacementString when this is the first replacement
if (replacementString == null) {
replacementString = new StringBuffer();
}
// Copy string before the match to the replacement string
for (; subjectCursorForResult < subjectCursor + start; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
subjectCursorForResult = subjectCursor + end;
// Copy replacement into replacement string
replacementString.append(((IString)repl).getValue());
tr.matched = true;
tr.changed = true;
subjectCursor += end;
} else {
throw new UnexpectedType(tf.stringType(),repl.getType(), eval.getCurrentAST());
}
}
}
tr.changed |= hasChanged;
tr.matched |= hasMatched;
if (!tr.changed) {
return subject;
}
// Copy remaining characters of subject string into replacement string
for (; subjectCursorForResult < len; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
return eval.getValueFactory().string(replacementString.toString());
}
}
| true | true | public IValue traverseString(IValue subject, CaseBlockList casesOrRules, TraverseResult tr){
String subjectString = ((IString) subject).getValue();
int len = subjectString.length();
int subjectCursor = 0;
int subjectCursorForResult = 0;
StringBuffer replacementString = null;
boolean hasMatched = false;
boolean hasChanged = false;
while (subjectCursor < len){
//System.err.println("cursor = " + cursor);
try {
IString substring = eval.getValueFactory().string(subjectString.substring(subjectCursor, len));
IValue subresult = substring;
tr.matched = false;
tr.changed = false;
// will throw insert or fail
applyCases(subresult, casesOrRules, tr);
hasMatched |= tr.matched;
hasChanged |= tr.changed;
subjectCursor++;
} catch (org.rascalmpl.interpreter.control_exceptions.Insert e) {
IValue repl = e.getValue().getValue();
hasChanged = true;
hasMatched = true;
if (repl.getType().isStringType()){
int start;
int end;
IBooleanResult lastPattern = e.getMatchPattern();
if (lastPattern == null) {
throw new ImplementationError("No last pattern known");
}
if (lastPattern instanceof RegExpPatternValue){
start = ((RegExpPatternValue)lastPattern).getStart();
end = ((RegExpPatternValue)lastPattern).getEnd();
}
else if (lastPattern instanceof LiteralPattern || lastPattern instanceof TypedVariablePattern){
start = 0;
end = ((IString)repl).getValue().length();
}
else {
throw new SyntaxError("Illegal pattern " + lastPattern + " in string visit", eval.getCurrentAST().getLocation());
}
// Create replacementString when this is the first replacement
if (replacementString == null) {
replacementString = new StringBuffer();
}
// Copy string before the match to the replacement string
for (; subjectCursorForResult < subjectCursor + start; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
subjectCursorForResult = subjectCursor + end;
// Copy replacement into replacement string
replacementString.append(((IString)repl).getValue());
tr.matched = true;
tr.changed = true;
subjectCursor += end;
} else {
throw new UnexpectedType(tf.stringType(),repl.getType(), eval.getCurrentAST());
}
}
}
tr.changed |= hasChanged;
tr.matched |= hasMatched;
if (!tr.changed) {
return subject;
}
// Copy remaining characters of subject string into replacement string
for (; subjectCursorForResult < len; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
return eval.getValueFactory().string(replacementString.toString());
}
| public IValue traverseString(IValue subject, CaseBlockList casesOrRules, TraverseResult tr){
String subjectString = ((IString) subject).getValue();
int len = subjectString.length();
int subjectCursor = 0;
int subjectCursorForResult = 0;
StringBuffer replacementString = null;
boolean hasMatched = false;
boolean hasChanged = false;
while (subjectCursor < len){
//System.err.println("cursor = " + cursor);
try {
IString substring = eval.getValueFactory().string(subjectString.substring(subjectCursor, len));
IValue subresult = substring;
tr.matched = false;
tr.changed = false;
// will throw insert or fail
applyCases(subresult, casesOrRules, tr);
hasMatched |= tr.matched;
hasChanged |= tr.changed;
subjectCursor++;
} catch (org.rascalmpl.interpreter.control_exceptions.Insert e) {
IValue repl = e.getValue().getValue();
hasChanged = true;
hasMatched = true;
if (repl.getType().isStringType()){
int start;
int end;
IBooleanResult lastPattern = e.getMatchPattern();
if (lastPattern == null) {
throw new ImplementationError("No last pattern known");
}
if (lastPattern instanceof RegExpPatternValue){
start = ((RegExpPatternValue)lastPattern).getStart();
end = ((RegExpPatternValue)lastPattern).getEnd();
}
else if (lastPattern instanceof LiteralPattern || lastPattern instanceof TypedVariablePattern){
start = 0;
end = subjectString.length();
}
else {
throw new SyntaxError("Illegal pattern " + lastPattern + " in string visit", eval.getCurrentAST().getLocation());
}
// Create replacementString when this is the first replacement
if (replacementString == null) {
replacementString = new StringBuffer();
}
// Copy string before the match to the replacement string
for (; subjectCursorForResult < subjectCursor + start; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
subjectCursorForResult = subjectCursor + end;
// Copy replacement into replacement string
replacementString.append(((IString)repl).getValue());
tr.matched = true;
tr.changed = true;
subjectCursor += end;
} else {
throw new UnexpectedType(tf.stringType(),repl.getType(), eval.getCurrentAST());
}
}
}
tr.changed |= hasChanged;
tr.matched |= hasMatched;
if (!tr.changed) {
return subject;
}
// Copy remaining characters of subject string into replacement string
for (; subjectCursorForResult < len; subjectCursorForResult++){
replacementString.append(subjectString.charAt(subjectCursorForResult));
}
return eval.getValueFactory().string(replacementString.toString());
}
|
diff --git a/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java b/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java
index 08622af0..222946b6 100644
--- a/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java
+++ b/src/org/intellij/erlang/formatter/ErlangIndentProcessor.java
@@ -1,125 +1,125 @@
/*
* Copyright 2012 Sergey Ignatov
*
* 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.intellij.erlang.formatter;
import com.intellij.formatting.Indent;
import com.intellij.lang.ASTNode;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.erlang.psi.ErlangArgumentDefinition;
import org.intellij.erlang.psi.ErlangExpression;
import org.intellij.erlang.psi.ErlangParenthesizedExpression;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
import static org.intellij.erlang.ErlangParserDefinition.COMMENTS;
import static org.intellij.erlang.ErlangTypes.*;
/**
* @author ignatov
*/
public class ErlangIndentProcessor {
private static final Set<IElementType> BIN_OPERATORS = ContainerUtil.set(
ERL_OP_PLUS, ERL_OP_MINUS, ERL_OP_AR_MUL, ERL_OP_AR_DIV, ERL_REM,
ERL_OR, ERL_XOR, ERL_BOR, ERL_BXOR, ERL_BSL, ERL_BSR, ERL_AND,
ERL_BAND, ERL_OP_EQ_EQ, ERL_OP_DIV_EQ, ERL_OP_EQ_COL_EQ, ERL_OP_EQ_DIV_EQ,
ERL_OP_LT, ERL_OP_EQ_LT, ERL_OP_GT, ERL_OP_GT_EQ, ERL_OP_LT_EQ, ERL_OP_PLUS_PLUS,
ERL_OP_MINUS_MINUS, ERL_OP_EQ, ERL_OP_EXL, ERL_OP_LT_MINUS, ERL_ANDALSO, ERL_ORELSE
);
private final CommonCodeStyleSettings settings;
public ErlangIndentProcessor(CommonCodeStyleSettings settings) {
this.settings = settings;
}
public Indent getChildIndent(ASTNode node) {
IElementType elementType = node.getElementType();
ASTNode parent = node.getTreeParent();
IElementType parentType = parent != null ? parent.getElementType() : null;
ASTNode grandfather = parent != null ? parent.getTreeParent() : null;
IElementType grandfatherType = grandfather != null ? grandfather.getElementType() : null;
ASTNode prevSibling = FormatterUtil.getPreviousNonWhitespaceSibling(node);
IElementType prevSiblingElementType = prevSibling != null ? prevSibling.getElementType() : null;
if (parent == null || parent.getTreeParent() == null) {
return Indent.getNoneIndent();
}
if (COMMENTS.contains(elementType) && settings.KEEP_FIRST_COLUMN_COMMENT) {
return Indent.getAbsoluteNoneIndent();
}
if (elementType == ERL_CATCH) {
return Indent.getNoneIndent();
}
if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_DEFINITION_LIST
|| parentType == ERL_FUN_TYPE || parentType == ERL_FUN_TYPE_ARGUMENTS) {
if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getContinuationIndent();
}
if (parentType == ERL_ARGUMENT_LIST) {
if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS) {
if (elementType == ERL_CURLY_LEFT || elementType == ERL_CURLY_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS || parentType == ERL_EXPORT_TYPES) {
if (elementType == ERL_BRACKET_LEFT || elementType == ERL_BRACKET_RIGHT || elementType == ERL_BIN_START || elementType == ERL_BIN_END || elementType == ERL_LC_EXPRS) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if ((parentType == ERL_GUARD || (parentType == ERL_CLAUSE_GUARD && elementType == ERL_WHEN)) && grandfatherType != ERL_IF_CLAUSE) {
return Indent.getNormalIndent();
}
if (parentType == ERL_LC_EXPRS) {
return Indent.getNormalIndent();
}
if (parentType == ERL_RECORD_FIELDS) {
// todo: not a smart solution
//noinspection unchecked
boolean insideCall = PsiTreeUtil.getParentOfType(node.getPsi(), ErlangArgumentDefinition.class, ErlangParenthesizedExpression.class) != null;
- return insideCall ? Indent.getContinuationIndent() : Indent.getNormalIndent();
+ return insideCall ? Indent.getNormalIndent() : Indent.getNoneIndent();
}
if (needIndent(parentType)) {
return Indent.getNormalIndent();
}
if (parent.getPsi() instanceof ErlangExpression && (BIN_OPERATORS.contains(elementType) || BIN_OPERATORS.contains(prevSiblingElementType))) {
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
private static boolean needIndent(@Nullable IElementType type) {
if (type == null) {
return false;
}
return ErlangFormattingBlock.BLOCKS_TOKEN_SET.contains(type);
}
}
| true | true | public Indent getChildIndent(ASTNode node) {
IElementType elementType = node.getElementType();
ASTNode parent = node.getTreeParent();
IElementType parentType = parent != null ? parent.getElementType() : null;
ASTNode grandfather = parent != null ? parent.getTreeParent() : null;
IElementType grandfatherType = grandfather != null ? grandfather.getElementType() : null;
ASTNode prevSibling = FormatterUtil.getPreviousNonWhitespaceSibling(node);
IElementType prevSiblingElementType = prevSibling != null ? prevSibling.getElementType() : null;
if (parent == null || parent.getTreeParent() == null) {
return Indent.getNoneIndent();
}
if (COMMENTS.contains(elementType) && settings.KEEP_FIRST_COLUMN_COMMENT) {
return Indent.getAbsoluteNoneIndent();
}
if (elementType == ERL_CATCH) {
return Indent.getNoneIndent();
}
if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_DEFINITION_LIST
|| parentType == ERL_FUN_TYPE || parentType == ERL_FUN_TYPE_ARGUMENTS) {
if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getContinuationIndent();
}
if (parentType == ERL_ARGUMENT_LIST) {
if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS) {
if (elementType == ERL_CURLY_LEFT || elementType == ERL_CURLY_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS || parentType == ERL_EXPORT_TYPES) {
if (elementType == ERL_BRACKET_LEFT || elementType == ERL_BRACKET_RIGHT || elementType == ERL_BIN_START || elementType == ERL_BIN_END || elementType == ERL_LC_EXPRS) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if ((parentType == ERL_GUARD || (parentType == ERL_CLAUSE_GUARD && elementType == ERL_WHEN)) && grandfatherType != ERL_IF_CLAUSE) {
return Indent.getNormalIndent();
}
if (parentType == ERL_LC_EXPRS) {
return Indent.getNormalIndent();
}
if (parentType == ERL_RECORD_FIELDS) {
// todo: not a smart solution
//noinspection unchecked
boolean insideCall = PsiTreeUtil.getParentOfType(node.getPsi(), ErlangArgumentDefinition.class, ErlangParenthesizedExpression.class) != null;
return insideCall ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
if (needIndent(parentType)) {
return Indent.getNormalIndent();
}
if (parent.getPsi() instanceof ErlangExpression && (BIN_OPERATORS.contains(elementType) || BIN_OPERATORS.contains(prevSiblingElementType))) {
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
| public Indent getChildIndent(ASTNode node) {
IElementType elementType = node.getElementType();
ASTNode parent = node.getTreeParent();
IElementType parentType = parent != null ? parent.getElementType() : null;
ASTNode grandfather = parent != null ? parent.getTreeParent() : null;
IElementType grandfatherType = grandfather != null ? grandfather.getElementType() : null;
ASTNode prevSibling = FormatterUtil.getPreviousNonWhitespaceSibling(node);
IElementType prevSiblingElementType = prevSibling != null ? prevSibling.getElementType() : null;
if (parent == null || parent.getTreeParent() == null) {
return Indent.getNoneIndent();
}
if (COMMENTS.contains(elementType) && settings.KEEP_FIRST_COLUMN_COMMENT) {
return Indent.getAbsoluteNoneIndent();
}
if (elementType == ERL_CATCH) {
return Indent.getNoneIndent();
}
if (parentType == ERL_PARENTHESIZED_EXPRESSION || parentType == ERL_ARGUMENT_DEFINITION_LIST
|| parentType == ERL_FUN_TYPE || parentType == ERL_FUN_TYPE_ARGUMENTS) {
if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getContinuationIndent();
}
if (parentType == ERL_ARGUMENT_LIST) {
if (elementType == ERL_PAR_LEFT || elementType == ERL_PAR_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if (parentType == ERL_TUPLE_EXPRESSION || parentType == ERL_RECORD_TUPLE || parentType == ERL_TYPED_RECORD_FIELDS) {
if (elementType == ERL_CURLY_LEFT || elementType == ERL_CURLY_RIGHT) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if (parentType == ERL_LIST_EXPRESSION || parentType == ERL_LIST_COMPREHENSION || parentType == ERL_EXPORT_FUNCTIONS || parentType == ERL_EXPORT_TYPES) {
if (elementType == ERL_BRACKET_LEFT || elementType == ERL_BRACKET_RIGHT || elementType == ERL_BIN_START || elementType == ERL_BIN_END || elementType == ERL_LC_EXPRS) {
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
if ((parentType == ERL_GUARD || (parentType == ERL_CLAUSE_GUARD && elementType == ERL_WHEN)) && grandfatherType != ERL_IF_CLAUSE) {
return Indent.getNormalIndent();
}
if (parentType == ERL_LC_EXPRS) {
return Indent.getNormalIndent();
}
if (parentType == ERL_RECORD_FIELDS) {
// todo: not a smart solution
//noinspection unchecked
boolean insideCall = PsiTreeUtil.getParentOfType(node.getPsi(), ErlangArgumentDefinition.class, ErlangParenthesizedExpression.class) != null;
return insideCall ? Indent.getNormalIndent() : Indent.getNoneIndent();
}
if (needIndent(parentType)) {
return Indent.getNormalIndent();
}
if (parent.getPsi() instanceof ErlangExpression && (BIN_OPERATORS.contains(elementType) || BIN_OPERATORS.contains(prevSiblingElementType))) {
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
|
diff --git a/src/com/csipsimple/pjsip/PjSipService.java b/src/com/csipsimple/pjsip/PjSipService.java
index 53f31393..f32e2fcb 100644
--- a/src/com/csipsimple/pjsip/PjSipService.java
+++ b/src/com/csipsimple/pjsip/PjSipService.java
@@ -1,1821 +1,1821 @@
/**
* Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
* This file is part of CSipSimple.
*
* CSipSimple 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.
* If you own a pjsip commercial license you can also redistribute it
* and/or modify it under the terms of the GNU Lesser General Public License
* as an android library.
*
* CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>.
*/
package com.csipsimple.pjsip;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import com.csipsimple.R;
import com.csipsimple.api.SipCallSession;
import com.csipsimple.api.SipConfigManager;
import com.csipsimple.api.SipManager;
import com.csipsimple.api.SipManager.PresenceStatus;
import com.csipsimple.api.SipProfile;
import com.csipsimple.api.SipProfileState;
import com.csipsimple.service.MediaManager;
import com.csipsimple.service.SipService;
import com.csipsimple.service.SipService.SameThreadException;
import com.csipsimple.service.SipService.ToCall;
import com.csipsimple.utils.ExtraPlugins;
import com.csipsimple.utils.ExtraPlugins.DynCodecInfos;
import com.csipsimple.utils.Log;
import com.csipsimple.utils.PreferencesProviderWrapper;
import com.csipsimple.utils.PreferencesWrapper;
import com.csipsimple.utils.TimerWrapper;
import com.csipsimple.wizards.WizardUtils;
import org.pjsip.pjsua.csipsimple_config;
import org.pjsip.pjsua.dynamic_factory;
import org.pjsip.pjsua.pj_qos_params;
import org.pjsip.pjsua.pj_str_t;
import org.pjsip.pjsua.pjmedia_srtp_use;
import org.pjsip.pjsua.pjsip_timer_setting;
import org.pjsip.pjsua.pjsip_tls_setting;
import org.pjsip.pjsua.pjsip_transport_type_e;
import org.pjsip.pjsua.pjsua;
import org.pjsip.pjsua.pjsuaConstants;
import org.pjsip.pjsua.pjsua_acc_config;
import org.pjsip.pjsua.pjsua_acc_info;
import org.pjsip.pjsua.pjsua_buddy_config;
import org.pjsip.pjsua.pjsua_call_flag;
import org.pjsip.pjsua.pjsua_call_setting;
import org.pjsip.pjsua.pjsua_config;
import org.pjsip.pjsua.pjsua_logging_config;
import org.pjsip.pjsua.pjsua_media_config;
import org.pjsip.pjsua.pjsua_msg_data;
import org.pjsip.pjsua.pjsua_transport_config;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PjSipService {
private static final String THIS_FILE = "PjService";
public SipService service;
private boolean created = false;
private boolean hasSipStack = false;
private boolean sipStackIsCorrupted = false;
private Integer udpTranportId, tcpTranportId, tlsTransportId;
private Integer localUdpAccPjId, localTcpAccPjId, localTlsAccPjId;
public PreferencesProviderWrapper prefsWrapper;
private PjStreamDialtoneGenerator dialtoneGenerator;
private Integer hasBeenHoldByGSM = null;
public UAStateReceiver userAgentReceiver;
public MediaManager mediaManager;
// -------
// Locks
// -------
public PjSipService() {
}
public void setService(SipService aService) {
service = aService;
prefsWrapper = service.getPrefs();
}
public boolean isCreated() {
return created;
}
public boolean tryToLoadStack() {
if (hasSipStack) {
return true;
}
// File stackFile = NativeLibManager.getStackLibFile(service);
if (!sipStackIsCorrupted) {
try {
// Try to load the stack
// System.load(NativeLibManager.getBundledStackLibFile(service,
// "libcrypto.so").getAbsolutePath());
// System.load(NativeLibManager.getBundledStackLibFile(service,
// "libssl.so").getAbsolutePath());
// System.loadLibrary("crypto");
// System.loadLibrary("ssl");
System.loadLibrary(NativeLibManager.STACK_NAME);
hasSipStack = true;
return true;
} catch (UnsatisfiedLinkError e) {
// If it fails we probably are running on a special hardware,
// redirect to support webpage
Log.e(THIS_FILE,
"We have a problem with the current stack.... NOT YET Implemented", e);
hasSipStack = false;
sipStackIsCorrupted = true;
/*
* //Obsolete Intent it = new Intent(Intent.ACTION_VIEW);
* it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
* it.setData(Uri.parse(
* "http://code.google.com/p/csipsimple/wiki/NewHardwareSupportRequest"
* )); startActivity(it);
*/
// service.stopSelf();
return false;
} catch (Exception e) {
Log.e(THIS_FILE, "We have a problem with the current stack....", e);
}
}
return false;
}
// Start the sip stack according to current settings
/**
* Start the sip stack Thread safing of this method must be ensured by upper
* layer Every calls from pjsip that require start/stop/getInfos from the
* underlying stack must be done on the same thread
*/
public boolean sipStart() throws SameThreadException {
Log.setLogLevel(prefsWrapper.getLogLevel());
if (!hasSipStack) {
Log.e(THIS_FILE, "We have no sip stack, we can't start");
return false;
}
// Ensure the stack is not already created or is being created
if (!created) {
Log.d(THIS_FILE, "Starting sip stack");
udpTranportId = null;
tcpTranportId = null;
tlsTransportId = null;
// Pj timer
TimerWrapper.create(service);
int status;
status = pjsua.create();
Log.i(THIS_FILE, "Created " + status);
// General config
{
pj_str_t[] stunServers = null;
int stunServersCount = 0;
pjsua_config cfg = new pjsua_config();
pjsua_logging_config logCfg = new pjsua_logging_config();
pjsua_media_config mediaCfg = new pjsua_media_config();
csipsimple_config cssCfg = new csipsimple_config();
// SERVICE CONFIG
if (userAgentReceiver == null) {
Log.d(THIS_FILE, "create receiver....");
userAgentReceiver = new UAStateReceiver();
userAgentReceiver.initService(this);
}
if (mediaManager == null) {
mediaManager = new MediaManager(service);
}
mediaManager.startService();
pjsua.setCallbackObject(userAgentReceiver);
Log.d(THIS_FILE, "Attach is done to callback");
int isTurnEnabled = prefsWrapper.getTurnEnabled();
// CSS CONFIG
pjsua.csipsimple_config_default(cssCfg);
cssCfg.setUse_compact_form_headers(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.USE_COMPACT_FORM) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setUse_compact_form_sdp(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.USE_COMPACT_FORM) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setUse_no_update(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.FORCE_NO_UPDATE) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setTcp_keep_alive_interval(prefsWrapper.getTcpKeepAliveInterval());
cssCfg.setTls_keep_alive_interval(prefsWrapper.getTlsKeepAliveInterval());
// Transaction timeouts
int tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T1_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t1_timeout(tsx_to);
}
tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T2_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t2_timeout(tsx_to);
}
tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T4_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t4_timeout(tsx_to);
}
// TURN
if (isTurnEnabled == 1) {
cssCfg.setTurn_username(pjsua.pj_str_copy(prefsWrapper
.getPreferenceStringValue(SipConfigManager.TURN_USERNAME)));
cssCfg.setTurn_password(pjsua.pj_str_copy(prefsWrapper
.getPreferenceStringValue(SipConfigManager.TURN_PASSWORD)));
}
// -- USE_ZRTP 1 is no_zrtp, 2 is create_zrtp
File zrtpFolder = PreferencesWrapper.getZrtpFolder(service);
if (zrtpFolder != null) {
cssCfg.setUse_zrtp((prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.USE_ZRTP) > 1) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setStorage_folder(pjsua.pj_str_copy(zrtpFolder.getAbsolutePath()));
} else {
cssCfg.setUse_zrtp(pjsua.PJ_FALSE);
cssCfg.setStorage_folder(pjsua.pj_str_copy(""));
}
Map<String, DynCodecInfos> availableCodecs = ExtraPlugins.getDynPlugins(service, SipManager.ACTION_GET_EXTRA_CODECS);
dynamic_factory[] cssCodecs = cssCfg.getExtra_aud_codecs();
int i = 0;
for (Entry<String, DynCodecInfos> availableCodec : availableCodecs.entrySet()) {
DynCodecInfos dyn = availableCodec.getValue();
if (!TextUtils.isEmpty(dyn.libraryPath)) {
cssCodecs[i].setShared_lib_path(pjsua.pj_str_copy(dyn.libraryPath));
cssCodecs[i++].setInit_factory_name(pjsua
.pj_str_copy(dyn.factoryInitFunction));
}
}
cssCfg.setExtra_aud_codecs_cnt(i);
// Audio implementation
int implementation = prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.AUDIO_IMPLEMENTATION);
if (implementation == SipConfigManager.AUDIO_IMPLEMENTATION_OPENSLES) {
dynamic_factory audImp = cssCfg.getAudio_implementation();
audImp.setInit_factory_name(pjsua.pj_str_copy("pjmedia_opensl_factory"));
File openslLib = NativeLibManager.getBundledStackLibFile(service,
"libpj_opensl_dev.so");
audImp.setShared_lib_path(pjsua.pj_str_copy(openslLib.getAbsolutePath()));
cssCfg.setAudio_implementation(audImp);
Log.d(THIS_FILE, "Use OpenSL-ES implementation");
}
// Video implementation
if(prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_VIDEO)){
// TODO :: Have plugins per capture / render / video codec / converter
Map<String, DynCodecInfos> videoPlugins = ExtraPlugins.getDynPlugins(service, SipManager.ACTION_GET_VIDEO_PLUGIN);
if(videoPlugins.size() > 0) {
DynCodecInfos videoPlugin = videoPlugins.values().iterator().next();
pj_str_t pjVideoFile = pjsua.pj_str_copy(videoPlugin.libraryPath);
Log.d(THIS_FILE, "Load video plugin at " + videoPlugin.libraryPath );
// Render
{
dynamic_factory vidImpl = cssCfg.getVideo_render_implementation();
vidImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_webrtc_vid_render_factory"));
vidImpl.setShared_lib_path(pjVideoFile);
}
// Capture
{
dynamic_factory vidImpl = cssCfg.getVideo_capture_implementation();
vidImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_webrtc_vid_capture_factory"));
vidImpl.setShared_lib_path(pjVideoFile);
/* -- For testing video screen -- Not yet released
try {
ComponentName cmp = new ComponentName("com.csipsimple.plugins.video", "com.csipsimple.plugins.video.CaptureReceiver");
DynCodecInfos screenCapt = new ExtraPlugins.DynCodecInfos(service, cmp);
vidImpl.setInit_factory_name(pjsua
.pj_str_copy(screenCapt.factoryInitFunction));
vidImpl.setShared_lib_path(pjsua
.pj_str_copy(screenCapt.libraryPath));
} catch (NameNotFoundException e) {
Log.e(THIS_FILE, "Not found capture plugin");
}
*/
}
// Codecs
cssCodecs = cssCfg.getExtra_vid_codecs();
cssCodecs[0].setShared_lib_path(pjVideoFile);
cssCodecs[0].setInit_factory_name(pjsua
- .pj_str_copy("pjmedia_codec_ffmpeg_init"));
+ .pj_str_copy("pjmedia_codec_ffmpeg_vid_init"));
cssCodecs = cssCfg.getExtra_vid_codecs_destroy();
cssCodecs[0].setShared_lib_path(pjVideoFile);
cssCodecs[0].setInit_factory_name(pjsua
- .pj_str_copy("pjmedia_codec_ffmpeg_deinit"));
+ .pj_str_copy("pjmedia_codec_ffmpeg_vid_deinit"));
cssCfg.setExtra_vid_codecs_cnt(1);
// Converter
dynamic_factory convertImpl = cssCfg.getVid_converter();
convertImpl.setShared_lib_path(pjVideoFile);
convertImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_libswscale_converter_init"));
}
}
// MAIN CONFIG
pjsua.config_default(cfg);
cfg.setCb(pjsuaConstants.WRAPPER_CALLBACK_STRUCT);
cfg.setUser_agent(pjsua.pj_str_copy(prefsWrapper.getUserAgent(service)));
// With new timer implementation, thread count of pjsip can be 0
// it will use less CPU since now thread are launched by
// alarmManager
cfg.setThread_cnt(0);
cfg.setUse_srtp(getUseSrtp());
cfg.setSrtp_secure_signaling(0);
pjsip_timer_setting timerSetting = cfg.getTimer_setting();
int minSe = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TIMER_MIN_SE);
int sessExp = prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.TIMER_SESS_EXPIRES);
if (minSe <= sessExp && minSe >= 90) {
timerSetting.setMin_se(minSe);
timerSetting.setSess_expires(sessExp);
cfg.setTimer_setting(timerSetting);
}
// DNS
if (prefsWrapper.enableDNSSRV() && !prefsWrapper.useIPv6()) {
pj_str_t[] nameservers = getNameservers();
if (nameservers != null) {
cfg.setNameserver_count(nameservers.length);
cfg.setNameserver(nameservers);
} else {
cfg.setNameserver_count(0);
}
}
// STUN
int isStunEnabled = prefsWrapper.getStunEnabled();
if (isStunEnabled == 1) {
String[] servers = prefsWrapper.getPreferenceStringValue(
SipConfigManager.STUN_SERVER).split(",");
cfg.setStun_srv_cnt(servers.length);
stunServers = cfg.getStun_srv();
for (String server : servers) {
Log.d(THIS_FILE, "add server " + server.trim());
stunServers[stunServersCount] = pjsua.pj_str_copy(server.trim());
stunServersCount++;
}
cfg.setStun_srv(stunServers);
}
// LOGGING CONFIG
pjsua.logging_config_default(logCfg);
logCfg.setConsole_level(prefsWrapper.getLogLevel());
logCfg.setLevel(prefsWrapper.getLogLevel());
logCfg.setMsg_logging(pjsuaConstants.PJ_TRUE);
// MEDIA CONFIG
pjsua.media_config_default(mediaCfg);
// For now only this cfg is supported
mediaCfg.setChannel_count(1);
mediaCfg.setSnd_auto_close_time(prefsWrapper.getAutoCloseTime());
// Echo cancellation
mediaCfg.setEc_tail_len(prefsWrapper.getEchoCancellationTail());
int echoMode = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.ECHO_MODE);
long clockRate = prefsWrapper.getClockRate();
if (clockRate > 16000 && echoMode == SipConfigManager.ECHO_MODE_WEBRTC_M) {
// WebRTC mobile does not allow higher that 16kHz for now
// TODO : warn user about this point
echoMode = SipConfigManager.ECHO_MODE_SIMPLE;
}
mediaCfg.setEc_options(echoMode);
mediaCfg.setNo_vad(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.ENABLE_VAD) ? 0 : 1);
mediaCfg.setQuality(prefsWrapper.getMediaQuality());
mediaCfg.setClock_rate(clockRate);
mediaCfg.setAudio_frame_ptime(prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.SND_PTIME));
// Disabled because only one thread enabled now for battery perfs on normal state
mediaCfg.setHas_ioqueue(/*prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.HAS_IO_QUEUE) ? 1 :*/ 0);
// ICE
mediaCfg.setEnable_ice(prefsWrapper.getIceEnabled());
// TURN
if (isTurnEnabled == 1) {
mediaCfg.setEnable_turn(isTurnEnabled);
mediaCfg.setTurn_server(pjsua.pj_str_copy(prefsWrapper.getTurnServer()));
}
// INITIALIZE
status = pjsua.csipsimple_init(cfg, logCfg, mediaCfg, cssCfg, service);
if (status != pjsuaConstants.PJ_SUCCESS) {
String msg = "Fail to init pjsua "
+ pjStrToString(pjsua.get_error_message(status));
Log.e(THIS_FILE, msg);
service.notifyUserOfMessage(msg);
cleanPjsua();
return false;
}
/*
* if (stunServersCount > 0) { int s = pjsua.detect_nat_type();
* Log.d(THIS_FILE, ">>> NAT TYPE is "+s); }
*/
}
// Add transports
{
// UDP
if (prefsWrapper.isUDPEnabled()) {
pjsip_transport_type_e t = pjsip_transport_type_e.PJSIP_TRANSPORT_UDP;
if (prefsWrapper.useIPv6()) {
t = pjsip_transport_type_e.PJSIP_TRANSPORT_UDP6;
}
udpTranportId = createTransport(t, prefsWrapper.getUDPTransportPort());
if (udpTranportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
// TODO : allow to configure this account
int[] p_acc_id = new int[1];
pjsua.acc_add_local(udpTranportId, pjsua.PJ_FALSE, p_acc_id);
localUdpAccPjId = p_acc_id[0];
// Log.d(THIS_FILE, "Udp account "+p_acc_id);
}
// TCP
if (prefsWrapper.isTCPEnabled() && !prefsWrapper.useIPv6()) {
pjsip_transport_type_e t = pjsip_transport_type_e.PJSIP_TRANSPORT_TCP;
if (prefsWrapper.useIPv6()) {
t = pjsip_transport_type_e.PJSIP_TRANSPORT_TCP6;
}
tcpTranportId = createTransport(t, prefsWrapper.getTCPTransportPort());
if (tcpTranportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
int[] p_acc_id = new int[1];
pjsua.acc_add_local(tcpTranportId, pjsua.PJ_FALSE, p_acc_id);
localTcpAccPjId = p_acc_id[0];
}
// TLS
if (prefsWrapper.isTLSEnabled() && !prefsWrapper.useIPv6()) {
tlsTransportId = createTransport(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS,
prefsWrapper.getTLSTransportPort());
if (tlsTransportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
int[] p_acc_id = new int[1];
pjsua.acc_add_local(tlsTransportId, pjsua.PJ_FALSE, p_acc_id);
localTlsAccPjId = p_acc_id[0];
}
// RTP transport
/*
* { pjsua_transport_config cfg = new pjsua_transport_config();
* pjsua.transport_config_default(cfg);
* cfg.setPort(prefsWrapper.getRTPPort()); if
* (prefsWrapper.getPreferenceBooleanValue
* (SipConfigManager.ENABLE_QOS)) { Log.d(THIS_FILE,
* "Activate qos for voice packets");
* cfg.setQos_type(pj_qos_type.PJ_QOS_TYPE_VOICE); } if
* (prefsWrapper.useIPv6()) { status =
* pjsua.media_transports_create_ipv6(cfg); } else { status =
* pjsua.media_transports_create(cfg); } if (status !=
* pjsuaConstants.PJ_SUCCESS) { String msg =
* "Fail to add media transport " +
* pjStrToString(pjsua.get_error_message(status));
* Log.e(THIS_FILE, msg); service.notifyUserOfMessage(msg);
* cleanPjsua(); return false; } }
*/
}
// Initialization is done, now start pjsua
status = pjsua.start();
if (status != pjsua.PJ_SUCCESS) {
String msg = "Fail to start pjsip "
+ pjStrToString(pjsua.get_error_message(status));
Log.e(THIS_FILE, msg);
service.notifyUserOfMessage(msg);
cleanPjsua();
return false;
}
// Init media codecs
initCodecs();
setCodecsPriorities();
created = true;
return true;
}
return false;
}
/**
* Stop sip service
*
* @return true if stop has been performed
*/
public boolean sipStop() throws SameThreadException {
Log.d(THIS_FILE, ">> SIP STOP <<");
if (getActiveCallInProgress() != null) {
Log.e(THIS_FILE, "We have a call in progress... DO NOT STOP !!!");
// TODO : queue quit on end call;
return false;
}
if (service.notificationManager != null) {
service.notificationManager.cancelRegisters();
}
if (created) {
cleanPjsua();
TimerWrapper.destroy();
}
Log.i(THIS_FILE, ">> Media m " + mediaManager);
return true;
}
private void cleanPjsua() throws SameThreadException {
Log.d(THIS_FILE, "Detroying...");
// This will destroy all accounts so synchronize with accounts
// management lock
pjsua.csipsimple_destroy();
service.getContentResolver().delete(SipProfile.ACCOUNT_STATUS_URI, null, null);
if (userAgentReceiver != null) {
userAgentReceiver.stopService();
userAgentReceiver = null;
}
if (mediaManager != null) {
mediaManager.stopService();
mediaManager = null;
}
created = false;
}
/**
* Utility to create a transport
*
* @return transport id or -1 if failed
*/
private Integer createTransport(pjsip_transport_type_e type, int port)
throws SameThreadException {
pjsua_transport_config cfg = new pjsua_transport_config();
int[] tId = new int[1];
int status;
pjsua.transport_config_default(cfg);
cfg.setPort(port);
if (type.equals(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS)) {
pjsip_tls_setting tlsSetting = cfg.getTls_setting();
/* TODO : THIS IS OBSOLETE -- remove from UI
String serverName = prefsWrapper
.getPreferenceStringValue(SipConfigManager.TLS_SERVER_NAME);
if (!TextUtils.isEmpty(serverName)) {
tlsSetting.setServer_name(pjsua.pj_str_copy(serverName));
}
*/
String caListFile = prefsWrapper
.getPreferenceStringValue(SipConfigManager.CA_LIST_FILE);
if (!TextUtils.isEmpty(caListFile)) {
tlsSetting.setCa_list_file(pjsua.pj_str_copy(caListFile));
}
String certFile = prefsWrapper.getPreferenceStringValue(SipConfigManager.CERT_FILE);
if (!TextUtils.isEmpty(certFile)) {
tlsSetting.setCert_file(pjsua.pj_str_copy(certFile));
}
String privKey = prefsWrapper.getPreferenceStringValue(SipConfigManager.PRIVKEY_FILE);
if (!TextUtils.isEmpty(privKey)) {
tlsSetting.setPrivkey_file(pjsua.pj_str_copy(privKey));
}
String tlsPwd = prefsWrapper.getPreferenceStringValue(SipConfigManager.TLS_PASSWORD);
if (!TextUtils.isEmpty(tlsPwd)) {
tlsSetting.setPassword(pjsua.pj_str_copy(tlsPwd));
}
boolean checkClient = prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.TLS_VERIFY_CLIENT);
tlsSetting.setVerify_client(checkClient ? 1 : 0);
tlsSetting.setMethod(prefsWrapper.getTLSMethod());
boolean checkServer = prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.TLS_VERIFY_SERVER);
tlsSetting.setVerify_server(checkServer ? 1 : 0);
cfg.setTls_setting(tlsSetting);
}
// else?
if (prefsWrapper.getPreferenceBooleanValue(SipConfigManager.ENABLE_QOS)) {
Log.d(THIS_FILE, "Activate qos for this transport");
pj_qos_params qosParam = cfg.getQos_params();
qosParam.setDscp_val((short) prefsWrapper.getDSCPVal());
qosParam.setFlags((short) 1); // DSCP
cfg.setQos_params(qosParam);
}
status = pjsua.transport_create(type, cfg, tId);
if (status != pjsuaConstants.PJ_SUCCESS) {
String errorMsg = pjStrToString(pjsua.get_error_message(status));
String msg = "Fail to create transport " + errorMsg + " (" + status + ")";
Log.e(THIS_FILE, msg);
if (status == 120098) { /* Already binded */
msg = service.getString(R.string.another_application_use_sip_port);
}
service.notifyUserOfMessage(msg);
return null;
}
return tId[0];
}
public boolean addAccount(SipProfile profile) throws SameThreadException {
int status = pjsuaConstants.PJ_FALSE;
if (!created) {
Log.e(THIS_FILE, "PJSIP is not started here, nothing can be done");
return status == pjsuaConstants.PJ_SUCCESS;
}
PjSipAccount account = new PjSipAccount(profile);
account.applyExtraParams(service);
// Force the use of a transport
switch (account.transport) {
case SipProfile.TRANSPORT_UDP:
if (udpTranportId != null) {
account.cfg.setTransport_id(udpTranportId);
}
break;
case SipProfile.TRANSPORT_TCP:
if (tcpTranportId != null) {
// account.cfg.setTransport_id(tcpTranportId);
}
break;
case SipProfile.TRANSPORT_TLS:
if (tlsTransportId != null) {
// account.cfg.setTransport_id(tlsTransportId);
}
break;
default:
break;
}
SipProfileState currentAccountStatus = getProfileState(profile);
if (currentAccountStatus.isAddedToStack()) {
pjsua.csipsimple_set_acc_user_data(account.cfg, account.css_cfg);
status = pjsua.acc_modify(currentAccountStatus.getPjsuaId(), account.cfg);
ContentValues cv = new ContentValues();
cv.put(SipProfileState.ADDED_STATUS, status);
service.getContentResolver().update(
ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, profile.id),
cv, null, null);
if (!account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) {
// Re register
if (status == pjsuaConstants.PJ_SUCCESS) {
status = pjsua.acc_set_registration(currentAccountStatus.getPjsuaId(), 1);
if (status == pjsuaConstants.PJ_SUCCESS) {
pjsua.acc_set_online_status(currentAccountStatus.getPjsuaId(), 1);
}
}
}
} else {
int[] accId = new int[1];
if (account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) {
// We already have local account by default
// For now consider we are talking about UDP one
// In the future local account should be set per transport
switch(account.transport) {
case SipProfile.TRANSPORT_UDP:
accId[0] = localUdpAccPjId;
break;
case SipProfile.TRANSPORT_TCP:
accId[0] = localTcpAccPjId;
break;
case SipProfile.TRANSPORT_TLS:
accId[0] = localTlsAccPjId;
break;
default:
// By default use UDP
accId[0] = localUdpAccPjId;
break;
}
pjsua_acc_config nCfg = new pjsua_acc_config();
pjsua.acc_get_config(accId[0], nCfg);
pjsua.csipsimple_set_acc_user_data(nCfg, account.css_cfg);
nCfg.setVid_in_auto_show(pjsuaConstants.PJ_TRUE);
nCfg.setVid_out_auto_transmit(pjsuaConstants.PJ_TRUE);
status = pjsua.acc_modify(accId[0], nCfg);
} else {
// Cause of standard account different from local account :)
pjsua.csipsimple_set_acc_user_data(account.cfg, account.css_cfg);
status = pjsua.acc_add(account.cfg, pjsuaConstants.PJ_FALSE, accId);
}
if (status == pjsuaConstants.PJ_SUCCESS) {
SipProfileState ps = new SipProfileState(profile);
ps.setAddedStatus(status);
ps.setPjsuaId(accId[0]);
service.getContentResolver().insert(
ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE,
account.id), ps.getAsContentValue());
pjsua.acc_set_online_status(accId[0], 1);
}
}
return status == pjsuaConstants.PJ_SUCCESS;
}
/**
* Synchronize content provider backend from pjsip stack
* @param pjsuaId the pjsua id of the account to synchronize
* @throws SameThreadException
*/
public void updateProfileStateFromService(int pjsuaId) throws SameThreadException {
if (!created) {
return;
}
long accId = getAccountIdForPjsipId(pjsuaId);
Log.d(THIS_FILE, "Update profile from service for " + pjsuaId + " aka in db " + accId);
if (accId != SipProfile.INVALID_ID) {
int success = pjsuaConstants.PJ_FALSE;
pjsua_acc_info pjAccountInfo;
pjAccountInfo = new pjsua_acc_info();
success = pjsua.acc_get_info(pjsuaId, pjAccountInfo);
if (success == pjsuaConstants.PJ_SUCCESS && pjAccountInfo != null) {
ContentValues cv = new ContentValues();
try {
// Should be fine : status code are coherent with RFC
// status codes
cv.put(SipProfileState.STATUS_CODE, pjAccountInfo.getStatus().swigValue());
} catch (IllegalArgumentException e) {
cv.put(SipProfileState.STATUS_CODE,
SipCallSession.StatusCode.INTERNAL_SERVER_ERROR);
}
cv.put(SipProfileState.STATUS_TEXT, pjStrToString(pjAccountInfo.getStatus_text()));
cv.put(SipProfileState.EXPIRES, pjAccountInfo.getExpires());
service.getContentResolver().update(
ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, accId),
cv, null, null);
Log.d(THIS_FILE, "Profile state UP : " + cv);
}
}
}
/**
* Get the dynamic state of the profile
* @param account the sip profile from database. Important field is id.
* @return the dynamic sip profile state
*/
public SipProfileState getProfileState(SipProfile account) {
if (!created || account == null) {
return null;
}
if(account.id == SipProfile.INVALID_ID) {
return null;
}
SipProfileState accountInfo = new SipProfileState(account);
Cursor c = service.getContentResolver().query(
ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_ID_URI_BASE, account.id),
null, null, null, null);
if (c != null) {
try {
if (c.getCount() > 0) {
c.moveToFirst();
accountInfo.createFromDb(c);
}
} catch (Exception e) {
Log.e(THIS_FILE, "Error on looping over sip profiles states", e);
} finally {
c.close();
}
}
return accountInfo;
}
private static ArrayList<String> codecs = new ArrayList<String>();
private static ArrayList<String> video_codecs = new ArrayList<String>();
private static boolean codecs_initialized = false;
/**
* Reset the list of codecs stored
*/
public static void resetCodecs() {
synchronized (codecs) {
if (codecs_initialized) {
codecs.clear();
video_codecs.clear();
codecs_initialized = false;
}
}
}
/**
* Retrieve codecs from pjsip stack and store it inside preference storage
* so that it can be retrieved in the interface view
* @throws SameThreadException
*/
private void initCodecs() throws SameThreadException {
synchronized (codecs) {
if (!codecs_initialized) {
int nbrCodecs, i;
// Audio codecs
nbrCodecs = pjsua.codecs_get_nbr();
for (i = 0; i < nbrCodecs; i++) {
String codecId = pjStrToString(pjsua.codecs_get_id(i));
codecs.add(codecId);
// Log.d(THIS_FILE, "Added codec " + codecId);
}
// Set it in prefs if not already set correctly
prefsWrapper.setCodecList(codecs);
// Video codecs
nbrCodecs = pjsua.codecs_vid_get_nbr();
for (i = 0; i < nbrCodecs; i++) {
String codecId = pjStrToString(pjsua.codecs_vid_get_id(i));
video_codecs.add(codecId);
Log.d(THIS_FILE, "Added video codec " + codecId);
}
// Set it in prefs if not already set correctly
prefsWrapper.setVideoCodecList(video_codecs);
codecs_initialized = true;
// We are now always capable of tls and srtp !
prefsWrapper.setLibCapability(PreferencesProviderWrapper.LIB_CAP_TLS, true);
prefsWrapper.setLibCapability(PreferencesProviderWrapper.LIB_CAP_SRTP, true);
}
}
}
/**
* Append log for the codec in String builder
* @param sb the buffer to be appended with the codec info
* @param codec the codec name
* @param prio the priority of the codec
*/
private void buffCodecLog(StringBuilder sb, String codec, short prio) {
if (prio > 0 && Log.getLogLevel() >= 4) {
sb.append(codec);
sb.append(" (");
sb.append(prio);
sb.append(") - ");
}
}
/**
* Set the codec priority in pjsip stack layer based on preference store
* @throws SameThreadException
*/
private void setCodecsPriorities() throws SameThreadException {
ConnectivityManager cm = ((ConnectivityManager) service
.getSystemService(Context.CONNECTIVITY_SERVICE));
synchronized (codecs) {
if (codecs_initialized) {
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null) {
StringBuilder audioSb = new StringBuilder();
StringBuilder videoSb = new StringBuilder();
audioSb.append("Audio codecs : ");
videoSb.append("Video codecs : ");
String currentBandType = prefsWrapper.getPreferenceStringValue(
SipConfigManager.getBandTypeKey(ni.getType(), ni.getSubtype()),
SipConfigManager.CODEC_WB);
synchronized (codecs) {
for (String codec : codecs) {
short aPrio = prefsWrapper.getCodecPriority(codec, currentBandType,
"-1");
buffCodecLog(audioSb, codec, aPrio);
if (aPrio >= 0) {
pjsua.codec_set_priority(pjsua.pj_str_copy(codec), aPrio);
}
}
for(String codec : video_codecs) {
short aPrio = prefsWrapper.getCodecPriority(codec, currentBandType,
"-1");
buffCodecLog(videoSb, codec, aPrio);
if (aPrio >= 0) {
pjsua.codec_set_priority(pjsua.pj_str_copy(codec), aPrio);
}
}
}
Log.d(THIS_FILE, audioSb.toString());
Log.d(THIS_FILE, videoSb.toString());
}
}
}
}
// Call related
/**
* Answer a call
*
* @param callId the id of the call to answer to
* @param code the status code to send in the response
* @return
*/
public int callAnswer(int callId, int code) throws SameThreadException {
if (created) {
pjsua_call_setting cs = new pjsua_call_setting();
pjsua.call_setting_default(cs);
cs.setAud_cnt(1);
cs.setVid_cnt(prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_VIDEO) ? 1 : 0);
cs.setFlag(0);
return pjsua.call_answer2(callId, cs, code, null, null);
//return pjsua.call_answer(callId, code, null, null);
}
return -1;
}
/**
* Hangup a call
*
* @param callId the id of the call to hangup
* @param code the status code to send in the response
* @return
*/
public int callHangup(int callId, int code) throws SameThreadException {
if (created) {
return pjsua.call_hangup(callId, code, null, null);
}
return -1;
}
public int callXfer(int callId, String callee) throws SameThreadException {
if (created) {
return pjsua.call_xfer(callId, pjsua.pj_str_copy(callee), null);
}
return -1;
}
public int callXferReplace(int callId, int otherCallId, int options) throws SameThreadException {
if (created) {
return pjsua.call_xfer_replaces(callId, otherCallId, options, null);
}
return -1;
}
/**
* Make a call
*
* @param callee remote contact ot call If not well formated we try to add
* domain name of the default account
*/
public int makeCall(String callee, int accountId) throws SameThreadException {
if (!created) {
return -1;
}
final ToCall toCall = sanitizeSipUri(callee, accountId);
if (toCall != null) {
pj_str_t uri = pjsua.pj_str_copy(toCall.getCallee());
// Nothing to do with this values
byte[] userData = new byte[1];
int[] callId = new int[1];
pjsua_call_setting cs = new pjsua_call_setting();
pjsua_msg_data msgData = new pjsua_msg_data();
int pjsuaAccId = toCall.getPjsipAccountId();
// Call settings to add video
pjsua.call_setting_default(cs);
cs.setAud_cnt(1);
cs.setVid_cnt(prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_VIDEO) ? 1 : 0);
cs.setFlag(0);
// Msg data to add headers
pjsua.msg_data_init(msgData);
pjsua.csipsimple_init_acc_msg_data(pjsuaAccId, msgData);
return pjsua.call_make_call(pjsuaAccId, uri, cs, userData, msgData, callId);
} else {
service.notifyUserOfMessage(service.getString(R.string.invalid_sip_uri) + " : "
+ callee);
}
return -1;
}
/**
* Send a dtmf signal to a call
*
* @param callId the call to send the signal
* @param keyCode the keyCode to send (android style)
* @return
*/
public int sendDtmf(int callId, int keyCode) throws SameThreadException {
if (!created) {
return -1;
}
int res = -1;
String keyPressed = "";
// Since some device (xoom...) are apparently buggy with key character map loading...
// we have to do crappy thing here
if(keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9 ) {
keyPressed = Integer.toString(keyCode - KeyEvent.KEYCODE_0);
} else if (keyCode == KeyEvent.KEYCODE_POUND){
keyPressed = "#";
} else if (keyCode == KeyEvent.KEYCODE_STAR){
keyPressed = "*";
} else {
// Fallback... should never be there if using visible dialpad, but possible using keyboard
KeyCharacterMap km = KeyCharacterMap.load(KeyCharacterMap.NUMERIC);
keyPressed = Integer.toString(km.getNumber(keyCode));
}
pj_str_t pjKeyPressed = pjsua.pj_str_copy(keyPressed);
if (prefsWrapper.useSipInfoDtmf()) {
res = pjsua.send_dtmf_info(callId, pjKeyPressed);
Log.d(THIS_FILE, "Has been sent DTMF INFO : " + res);
} else {
if (!prefsWrapper.forceDtmfInBand()) {
// Generate using RTP
res = pjsua.call_dial_dtmf(callId, pjKeyPressed);
Log.d(THIS_FILE, "Has been sent in RTP DTMF : " + res);
}
if (res != pjsua.PJ_SUCCESS && !prefsWrapper.forceDtmfRTP()) {
// Generate using analogic inband
if (dialtoneGenerator == null) {
dialtoneGenerator = new PjStreamDialtoneGenerator();
}
res = dialtoneGenerator.sendPjMediaDialTone(callId, keyPressed);
Log.d(THIS_FILE, "Has been sent DTMF analogic : " + res);
}
}
return res;
}
/**
* Send sms/message using SIP server
*/
public ToCall sendMessage(String callee, String message, long accountId)
throws SameThreadException {
if (!created) {
return null;
}
ToCall toCall = sanitizeSipUri(callee, accountId);
if (toCall != null) {
pj_str_t uri = pjsua.pj_str_copy(toCall.getCallee());
pj_str_t text = pjsua.pj_str_copy(message);
/*
* Log.d(THIS_FILE, "get for outgoing"); int finalAccountId =
* accountId; if (accountId == -1) { finalAccountId =
* pjsua.acc_find_for_outgoing(uri); }
*/
// Nothing to do with this values
byte[] userData = new byte[1];
int status = pjsua.im_send(toCall.getPjsipAccountId(), uri, null, text, null, userData);
return (status == pjsuaConstants.PJ_SUCCESS) ? toCall : null;
}
return toCall;
}
/**
* Add a buddy to buddies list
* @param buddyUri the uri to register to
* @throws SameThreadException
*/
public int addBuddy(String buddyUri) throws SameThreadException {
if (!created) {
return -1;
}
int[] p_buddy_id = new int[1];
pjsua_buddy_config buddy_cfg = new pjsua_buddy_config();
pjsua.buddy_config_default(buddy_cfg);
buddy_cfg.setSubscribe(1);
buddy_cfg.setUri(pjsua.pj_str_copy(buddyUri));
pjsua.buddy_add(buddy_cfg , p_buddy_id);
return p_buddy_id[0];
}
/**
* Remove one buddy from the buddy list managed by pjsip
* @param buddyUri he uri to unregister
* @throws SameThreadException
*/
public void removeBuddy(String buddyUri) throws SameThreadException {
if (!created) {
return;
}
int buddyId = pjsua.buddy_find(pjsua.pj_str_copy(buddyUri));
if(buddyId >= 0) {
pjsua.buddy_del(buddyId);
}
}
public void stopDialtoneGenerator() {
if (dialtoneGenerator != null) {
dialtoneGenerator.stopDialtoneGenerator();
dialtoneGenerator = null;
}
}
public int callHold(int callId) throws SameThreadException {
if (created) {
return pjsua.call_set_hold(callId, null);
}
return -1;
}
public int callReinvite(int callId, boolean unhold) throws SameThreadException {
if (created) {
return pjsua.call_reinvite(callId,
unhold ? pjsua_call_flag.PJSUA_CALL_UNHOLD.swigValue() : 0, null);
}
return -1;
}
public SipCallSession getCallInfo(int callId) {
if (created/* && !creating */&& userAgentReceiver != null) {
SipCallSession callInfo = userAgentReceiver.getCallInfo(callId);
return callInfo;
}
return null;
}
public void setBluetoothOn(boolean on) throws SameThreadException {
if (created && mediaManager != null) {
mediaManager.setBluetoothOn(on);
}
}
/**
* Mute microphone
* @param on true if microphone has to be muted
* @throws SameThreadException
*/
public void setMicrophoneMute(boolean on) throws SameThreadException {
if (created && mediaManager != null) {
mediaManager.setMicrophoneMute(on);
}
}
/**
* Change speaker phone mode
* @param on true if the speaker mode has to be on.
* @throws SameThreadException
*/
public void setSpeakerphoneOn(boolean on) throws SameThreadException {
if (created && mediaManager != null) {
mediaManager.setSpeakerphoneOn(on);
}
}
public SipCallSession[] getCalls() {
if (created && userAgentReceiver != null) {
SipCallSession[] callsInfo = userAgentReceiver.getCalls();
return callsInfo;
}
return new SipCallSession[0];
}
public void confAdjustTxLevel(int port, float value) throws SameThreadException {
if (created && userAgentReceiver != null) {
pjsua.conf_adjust_tx_level(port, value);
}
}
public void confAdjustRxLevel(int port, float value) throws SameThreadException {
if (created && userAgentReceiver != null) {
pjsua.conf_adjust_rx_level(port, value);
}
}
public void setEchoCancellation(boolean on) throws SameThreadException {
if (created && userAgentReceiver != null) {
Log.d(THIS_FILE, "set echo cancelation " + on);
pjsua.set_ec(on ? prefsWrapper.getEchoCancellationTail() : 0,
prefsWrapper.getPreferenceIntegerValue(SipConfigManager.ECHO_MODE));
}
}
public void adjustStreamVolume(int stream, int direction, int flags) {
if (mediaManager != null) {
mediaManager.adjustStreamVolume(stream, direction, AudioManager.FLAG_SHOW_UI);
}
}
public void silenceRinger() {
if (mediaManager != null) {
mediaManager.stopRingAndUnfocus();
}
}
/**
* Change account registration / adding state
* @param account The account to modify registration
* @param renew if 0 we ask for deletion of this account; if 1 we ask for registration of this account (and add if necessary)
* @param forceReAdd if true, we will first remove the account and then re-add it
* @return true if the operation get completed without problem
* @throws SameThreadException
*/
public boolean setAccountRegistration(SipProfile account, int renew, boolean forceReAdd)
throws SameThreadException {
int status = -1;
if (!created || account == null) {
Log.e(THIS_FILE, "PJSIP is not started here, nothing can be done");
return false;
}
if(account.id == SipProfile.INVALID_ID) {
Log.w(THIS_FILE, "Trying to set registration on a deleted account");
return false;
}
// If local account -- Ensure we are not deleting, because this would be invalid
if(account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) {
if(renew == 0) {
return false;
}
}
SipProfileState profileState = getProfileState(account);
// In case of already added, we have to act finely
// If it's local we can just consider that we have to re-add account
// since it will actually just touch the account with a modify
if (profileState != null && profileState.isAddedToStack() && !account.wizard.equalsIgnoreCase(WizardUtils.LOCAL_WIZARD_TAG)) {
// The account is already there in accounts list
service.getContentResolver().delete(
ContentUris.withAppendedId(SipProfile.ACCOUNT_STATUS_URI, account.id), null,
null);
Log.d(THIS_FILE, "Account already added to stack, remove and re-load or delete");
if (renew == 1) {
if (forceReAdd) {
status = pjsua.acc_del(profileState.getPjsuaId());
addAccount(account);
} else {
pjsua.acc_set_online_status(profileState.getPjsuaId(), getOnlineForStatus(service.getPresence()));
status = pjsua.acc_set_registration(profileState.getPjsuaId(), renew);
}
} else {
// if(status == pjsuaConstants.PJ_SUCCESS && renew == 0) {
Log.d(THIS_FILE, "Delete account !!");
status = pjsua.acc_del(profileState.getPjsuaId());
}
} else {
if (renew == 1) {
addAccount(account);
} else {
Log.w(THIS_FILE, "Ask to unregister an unexisting account !!" + account.id);
}
}
// PJ_SUCCESS = 0
return status == 0;
}
/**
* Set self presence
* @param presence the SipManager.SipPresence
* @param statusText the text of the presence
* @throws SameThreadException
*/
public void setPresence(PresenceStatus presence, String statusText, long accountId) throws SameThreadException {
if (!created) {
Log.e(THIS_FILE, "PJSIP is not started here, nothing can be done");
return;
}
SipProfile account = new SipProfile();
account.id = accountId;
SipProfileState profileState = getProfileState(account);
// In case of already added, we have to act finely
// If it's local we can just consider that we have to re-add account
// since it will actually just touch the account with a modify
if (profileState != null && profileState.isAddedToStack()) {
// The account is already there in accounts list
pjsua.acc_set_online_status(profileState.getPjsuaId(), getOnlineForStatus(presence));
}
}
private int getOnlineForStatus(PresenceStatus presence) {
return presence == PresenceStatus.ONLINE ? 1 : 0;
}
public long getAccountIdForPjsipId(int pjId) {
long accId = SipProfile.INVALID_ID;
Cursor c = service.getContentResolver().query(SipProfile.ACCOUNT_STATUS_URI, null, null,
null, null);
if (c != null) {
try {
c.moveToFirst();
do {
int pjsuaId = c.getInt(c.getColumnIndex(SipProfileState.PJSUA_ID));
Log.d(THIS_FILE, "Found pjsua " + pjsuaId + " searching " + pjId);
if (pjsuaId == pjId) {
accId = c.getInt(c.getColumnIndex(SipProfileState.ACCOUNT_ID));
break;
}
} while (c.moveToNext());
} catch (Exception e) {
Log.e(THIS_FILE, "Error on looping over sip profiles", e);
} finally {
c.close();
}
}
return accId;
}
public SipProfile getAccountForPjsipId(int pjId) {
long accId = getAccountIdForPjsipId(pjId);
if (accId == SipProfile.INVALID_ID) {
return null;
} else {
return service.getAccount(accId);
}
}
public int setAudioInCall(int clockRate) {
if (mediaManager != null) {
return mediaManager.setAudioInCall(clockRate);
} else {
Log.e(THIS_FILE, "WARNING !!! WE HAVE NO MEDIA MANAGER AT THIS POINT");
}
return -1;
}
public void unsetAudioInCall() {
if (mediaManager != null) {
mediaManager.unsetAudioInCall();
}
}
public SipCallSession getActiveCallInProgress() {
if (created && userAgentReceiver != null) {
return userAgentReceiver.getActiveCallInProgress();
}
return null;
}
// TO call utils
/**
* Transform a string callee into a valid sip uri in the context of an
* account
*
* @param callee the callee string to call
* @param accountId the context account
* @return ToCall object representing what to call and using which account
*/
private ToCall sanitizeSipUri(String callee, long accountId) throws SameThreadException {
// accountId is the id in term of csipsimple database
// pjsipAccountId is the account id in term of pjsip adding
int pjsipAccountId = (int) SipProfile.INVALID_ID;
// Fake a sip profile empty to get it's profile state
// Real get from db will be done later
SipProfile account = new SipProfile();
account.id = accountId;
SipProfileState profileState = getProfileState(account);
long finalAccountId = accountId;
// If this is an invalid account id
if (accountId == SipProfile.INVALID_ID || !profileState.isAddedToStack()) {
int defaultPjsipAccount = pjsua.acc_get_default();
boolean valid = false;
account = getAccountForPjsipId(defaultPjsipAccount);
if (account != null) {
profileState = getProfileState(account);
valid = profileState.isAddedToStack();
}
// If default account is not active
if (!valid) {
Cursor c = service.getContentResolver().query(SipProfile.ACCOUNT_STATUS_URI, null,
null, null, null);
if (c != null) {
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
SipProfileState ps = new SipProfileState(c);
if (ps.isValidForCall()) {
finalAccountId = ps.getDatabaseId();
pjsipAccountId = ps.getPjsuaId();
break;
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.e(THIS_FILE, "Error on looping over sip profiles state", e);
} finally {
c.close();
}
}
} else {
// Use the default account
finalAccountId = profileState.getDatabaseId();
pjsipAccountId = profileState.getPjsuaId();
}
} else {
// If the account is valid
pjsipAccountId = profileState.getPjsuaId();
}
if (pjsipAccountId == SipProfile.INVALID_ID) {
Log.e(THIS_FILE, "Unable to find a valid account for this call");
return null;
}
// Check integrity of callee field
Pattern p = Pattern.compile("^.*(?:<)?(sip(?:s)?):([^@]*@[^>]*)(?:>)?$",
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(callee);
String finalCallee = callee;
if (!m.matches()) {
// Assume this is a direct call using digit dialer
Log.d(THIS_FILE, "default acc : " + finalAccountId);
account = service.getAccount((int) finalAccountId);
String defaultDomain = account.getDefaultDomain();
Log.d(THIS_FILE, "default domain : " + defaultDomain);
p = Pattern.compile("^sip(s)?:[^@]*$", Pattern.CASE_INSENSITIVE);
if (p.matcher(callee).matches()) {
finalCallee = "<" + callee;
} else {
String scheme = "sip";
if(account.transport == SipProfile.TRANSPORT_TLS) {
scheme = "sips";
}
// Should it be encoded?
finalCallee = "<"+scheme+":" + /* Uri.encode( */callee/* ) */;
}
// Add domain if needed
if(TextUtils.isEmpty(defaultDomain)) {
finalCallee += ">";
}else {
finalCallee += "@"+defaultDomain+">";
}
} else {
finalCallee = "<" + m.group(1) + ":" + m.group(2) + ">";
}
Log.d(THIS_FILE, "will call " + finalCallee);
if (pjsua.verify_sip_url(finalCallee) == 0) {
// In worse worse case, find back the account id for uri.. but
// probably useless case
if (pjsipAccountId == SipProfile.INVALID_ID) {
pjsipAccountId = pjsua.acc_find_for_outgoing(pjsua.pj_str_copy(finalCallee));
}
return new ToCall(pjsipAccountId, finalCallee);
}
return null;
}
public void onGSMStateChanged(int state, String incomingNumber) throws SameThreadException {
// Avoid ringing if new GSM state is not idle
if (state != TelephonyManager.CALL_STATE_IDLE && mediaManager != null) {
mediaManager.stopRingAndUnfocus();
}
// If new call state is not idle
if (state != TelephonyManager.CALL_STATE_IDLE && userAgentReceiver != null) {
SipCallSession currentActiveCall = userAgentReceiver.getActiveCallInProgress();
if (currentActiveCall != null) {
AudioManager am = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE);
if (state != TelephonyManager.CALL_STATE_RINGING) {
// New state is not ringing nor idle... so off hook, hold
// current sip call
hasBeenHoldByGSM = currentActiveCall.getCallId();
callHold(hasBeenHoldByGSM);
pjsua.set_no_snd_dev();
am.setMode(AudioManager.MODE_IN_CALL);
} else {
// We have a ringing incoming call.
// Avoid vibration
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
} else {
// GSM is now back to an IDLE state, resume previously stopped SIP
// calls
if (hasBeenHoldByGSM != null && isCreated()) {
pjsua.set_snd_dev(0, 0);
callReinvite(hasBeenHoldByGSM, true);
hasBeenHoldByGSM = null;
}
}
}
/*
* public void sendKeepAlivePackets() throws SameThreadException {
* ArrayList<SipProfileState> accounts = getActiveProfilesState(); for
* (SipProfileState acc : accounts) {
* pjsua.send_keep_alive(acc.getPjsuaId()); } }
*/
public void zrtpSASVerified(int dataPtr) throws SameThreadException {
if (!created) {
return;
}
pjsua.jzrtp_SASVerified(dataPtr);
}
// Config subwrapper
private pj_str_t[] getNameservers() {
pj_str_t[] nameservers = null;
if (prefsWrapper.enableDNSSRV()) {
String prefsDNS = prefsWrapper
.getPreferenceStringValue(SipConfigManager.OVERRIDE_NAMESERVER);
if (TextUtils.isEmpty(prefsDNS)) {
String dnsName1 = prefsWrapper.getSystemProp("net.dns1");
String dnsName2 = prefsWrapper.getSystemProp("net.dns2");
Log.d(THIS_FILE, "DNS server will be set to : " + dnsName1 + " / " + dnsName2);
if (dnsName1 == null && dnsName2 == null) {
// TODO : WARNING : In this case....we have probably a
// problem !
nameservers = new pj_str_t[] {};
} else if (dnsName1 == null) {
nameservers = new pj_str_t[] {
pjsua.pj_str_copy(dnsName2)
};
} else if (dnsName2 == null) {
nameservers = new pj_str_t[] {
pjsua.pj_str_copy(dnsName1)
};
} else {
nameservers = new pj_str_t[] {
pjsua.pj_str_copy(dnsName1), pjsua.pj_str_copy(dnsName2)
};
}
} else {
nameservers = new pj_str_t[] {
pjsua.pj_str_copy(prefsDNS)
};
}
}
return nameservers;
}
private pjmedia_srtp_use getUseSrtp() {
try {
int use_srtp = Integer.parseInt(prefsWrapper
.getPreferenceStringValue(SipConfigManager.USE_SRTP));
if(use_srtp >= 0) {
return pjmedia_srtp_use.swigToEnum(use_srtp);
}
} catch (NumberFormatException e) {
Log.e(THIS_FILE, "Transport port not well formated");
}
return pjmedia_srtp_use.PJMEDIA_SRTP_DISABLED;
}
public void setNoSnd() throws SameThreadException {
if (!created) {
return;
}
pjsua.set_no_snd_dev();
}
public void setSnd() throws SameThreadException {
if (!created) {
return;
}
pjsua.set_snd_dev(0, 0);
}
// About recording things
// Recorder
public final static int INVALID_RECORD = -1;
public int recordedCall = INVALID_RECORD;
private int recorderId = INVALID_RECORD;
public void startRecording(int callId) {
if(!created) {
return;
}
// Make sure we are in a valid state for recording
SipCallSession callInfo = getCallInfo(callId);
if (callInfo == null ||
(callInfo.getMediaStatus() != SipCallSession.MediaState.ACTIVE && callInfo.getMediaStatus() != SipCallSession.MediaState.REMOTE_HOLD) ) {
return;
}
// If nothing is recording currently, create recorder
if (recordedCall == INVALID_RECORD) {
File wavFile = getRecordFile(callInfo.getRemoteContact());
if (wavFile != null) {
int[] recId = new int[1];
pj_str_t filename = pjsua.pj_str_copy(wavFile.getAbsolutePath());
int status = pjsua.recorder_create(filename, 0, (byte[]) null, 0, 0, recId);
if (status == pjsuaConstants.PJ_SUCCESS) {
recorderId = recId[0];
Log.d(THIS_FILE, "Record started : " + recorderId + " for " + recordedCall);
recordedCall = callId;
}
} else {
// TODO: toaster
Log.w(THIS_FILE, "Impossible to write file");
}
}
if(recorderId != INVALID_RECORD) {
int recPort = pjsua.recorder_get_conf_port(recorderId);
pjsua.conf_connect(callInfo.getConfPort(), recPort);
pjsua.conf_connect(0, recPort);
}
}
public void stopRecording() {
if (!created) {
recorderId = INVALID_RECORD;
recordedCall = INVALID_RECORD;
return;
}
Log.d(THIS_FILE, "Stop recording call " + recordedCall);
if (recorderId != INVALID_RECORD) {
pjsua.conf_remove_port(recorderId);
pjsua.recorder_destroy(recorderId);
}
recorderId = INVALID_RECORD;
recordedCall = INVALID_RECORD;
}
public boolean canRecord(int callId) {
if (created && recordedCall == INVALID_RECORD) {
SipCallSession callInfo = getCallInfo(callId);
if (callInfo == null || callInfo.getMediaStatus() != SipCallSession.MediaState.ACTIVE) {
return false;
}
return true;
}
return false;
}
public int getRecordedCall() {
return recordedCall;
}
private File getRecordFile(String remoteContact) {
File dir = PreferencesProviderWrapper.getRecordsFolder(service);
if (dir != null) {
Date d = new Date();
File file = new File(dir.getAbsoluteFile() + File.separator
+ sanitizeForFile(remoteContact) + "_"
+ DateFormat.format("MM-dd-yy_kkmmss", d) + ".wav");
Log.d(THIS_FILE, "Out dir " + file.getAbsolutePath());
return file;
}
return null;
}
private String sanitizeForFile(String remoteContact) {
String fileName = remoteContact;
fileName = fileName.replaceAll("[\\.\\\\<>:; \"\'\\*]", "_");
return fileName;
}
// Wave player
int[] plId = null;
public final static int BITMASK_OUT = 1 << 0;
public final static int BITMASK_IN = 1 << 1;
public void playWaveFile(String filePath, int callId, int way) {
if (!created) {
return;
}
// Create new player int holder or destroy existing one if any
if (plId == null) {
plId = new int[1];
} else {
pjsua.player_destroy(plId[0]);
}
// Anyway we create a new player conf port.
pj_str_t filename = pjsua.pj_str_copy(filePath);
int status = pjsua.player_create(filename, 1 /* PJMEDIA_FILE_NO_LOOP */, plId);
if (status == pjsuaConstants.PJ_SUCCESS) {
SipCallSession callInfo = getCallInfo(callId);
int wavConfPort = callInfo.getConfPort();
int wavPort = pjsua.player_get_conf_port(plId[0]);
if ((way & BITMASK_OUT) == BITMASK_OUT) {
pjsua.conf_connect(wavPort, wavConfPort);
}
if ((way & BITMASK_IN) == BITMASK_IN) {
pjsua.conf_connect(wavPort, 0);
}
// Once connected, start to play
pjsua.player_set_pos(plId[0], 0);
}
}
public void updateTransportIp(String oldIPAddress) throws SameThreadException {
if (!created) {
return;
}
Log.d(THIS_FILE, "Trying to update my address in the current call to " + oldIPAddress);
pjsua.update_transport(pjsua.pj_str_copy(oldIPAddress));
}
public static String pjStrToString(pj_str_t pjStr) {
try {
if (pjStr != null) {
// If there's utf-8 ptr length is possibly lower than slen
int len = pjStr.getSlen();
if(pjStr.getPtr() != null) {
if(pjStr.getPtr().length() < len) {
len = pjStr.getPtr().length();
}
if (len > 0) {
return pjStr.getPtr().substring(0, len);
}
}
}
} catch (StringIndexOutOfBoundsException e) {
Log.e(THIS_FILE, "Impossible to retrieve string from pjsip ", e);
}
return "";
}
}
| false | true | public boolean sipStart() throws SameThreadException {
Log.setLogLevel(prefsWrapper.getLogLevel());
if (!hasSipStack) {
Log.e(THIS_FILE, "We have no sip stack, we can't start");
return false;
}
// Ensure the stack is not already created or is being created
if (!created) {
Log.d(THIS_FILE, "Starting sip stack");
udpTranportId = null;
tcpTranportId = null;
tlsTransportId = null;
// Pj timer
TimerWrapper.create(service);
int status;
status = pjsua.create();
Log.i(THIS_FILE, "Created " + status);
// General config
{
pj_str_t[] stunServers = null;
int stunServersCount = 0;
pjsua_config cfg = new pjsua_config();
pjsua_logging_config logCfg = new pjsua_logging_config();
pjsua_media_config mediaCfg = new pjsua_media_config();
csipsimple_config cssCfg = new csipsimple_config();
// SERVICE CONFIG
if (userAgentReceiver == null) {
Log.d(THIS_FILE, "create receiver....");
userAgentReceiver = new UAStateReceiver();
userAgentReceiver.initService(this);
}
if (mediaManager == null) {
mediaManager = new MediaManager(service);
}
mediaManager.startService();
pjsua.setCallbackObject(userAgentReceiver);
Log.d(THIS_FILE, "Attach is done to callback");
int isTurnEnabled = prefsWrapper.getTurnEnabled();
// CSS CONFIG
pjsua.csipsimple_config_default(cssCfg);
cssCfg.setUse_compact_form_headers(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.USE_COMPACT_FORM) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setUse_compact_form_sdp(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.USE_COMPACT_FORM) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setUse_no_update(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.FORCE_NO_UPDATE) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setTcp_keep_alive_interval(prefsWrapper.getTcpKeepAliveInterval());
cssCfg.setTls_keep_alive_interval(prefsWrapper.getTlsKeepAliveInterval());
// Transaction timeouts
int tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T1_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t1_timeout(tsx_to);
}
tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T2_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t2_timeout(tsx_to);
}
tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T4_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t4_timeout(tsx_to);
}
// TURN
if (isTurnEnabled == 1) {
cssCfg.setTurn_username(pjsua.pj_str_copy(prefsWrapper
.getPreferenceStringValue(SipConfigManager.TURN_USERNAME)));
cssCfg.setTurn_password(pjsua.pj_str_copy(prefsWrapper
.getPreferenceStringValue(SipConfigManager.TURN_PASSWORD)));
}
// -- USE_ZRTP 1 is no_zrtp, 2 is create_zrtp
File zrtpFolder = PreferencesWrapper.getZrtpFolder(service);
if (zrtpFolder != null) {
cssCfg.setUse_zrtp((prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.USE_ZRTP) > 1) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setStorage_folder(pjsua.pj_str_copy(zrtpFolder.getAbsolutePath()));
} else {
cssCfg.setUse_zrtp(pjsua.PJ_FALSE);
cssCfg.setStorage_folder(pjsua.pj_str_copy(""));
}
Map<String, DynCodecInfos> availableCodecs = ExtraPlugins.getDynPlugins(service, SipManager.ACTION_GET_EXTRA_CODECS);
dynamic_factory[] cssCodecs = cssCfg.getExtra_aud_codecs();
int i = 0;
for (Entry<String, DynCodecInfos> availableCodec : availableCodecs.entrySet()) {
DynCodecInfos dyn = availableCodec.getValue();
if (!TextUtils.isEmpty(dyn.libraryPath)) {
cssCodecs[i].setShared_lib_path(pjsua.pj_str_copy(dyn.libraryPath));
cssCodecs[i++].setInit_factory_name(pjsua
.pj_str_copy(dyn.factoryInitFunction));
}
}
cssCfg.setExtra_aud_codecs_cnt(i);
// Audio implementation
int implementation = prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.AUDIO_IMPLEMENTATION);
if (implementation == SipConfigManager.AUDIO_IMPLEMENTATION_OPENSLES) {
dynamic_factory audImp = cssCfg.getAudio_implementation();
audImp.setInit_factory_name(pjsua.pj_str_copy("pjmedia_opensl_factory"));
File openslLib = NativeLibManager.getBundledStackLibFile(service,
"libpj_opensl_dev.so");
audImp.setShared_lib_path(pjsua.pj_str_copy(openslLib.getAbsolutePath()));
cssCfg.setAudio_implementation(audImp);
Log.d(THIS_FILE, "Use OpenSL-ES implementation");
}
// Video implementation
if(prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_VIDEO)){
// TODO :: Have plugins per capture / render / video codec / converter
Map<String, DynCodecInfos> videoPlugins = ExtraPlugins.getDynPlugins(service, SipManager.ACTION_GET_VIDEO_PLUGIN);
if(videoPlugins.size() > 0) {
DynCodecInfos videoPlugin = videoPlugins.values().iterator().next();
pj_str_t pjVideoFile = pjsua.pj_str_copy(videoPlugin.libraryPath);
Log.d(THIS_FILE, "Load video plugin at " + videoPlugin.libraryPath );
// Render
{
dynamic_factory vidImpl = cssCfg.getVideo_render_implementation();
vidImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_webrtc_vid_render_factory"));
vidImpl.setShared_lib_path(pjVideoFile);
}
// Capture
{
dynamic_factory vidImpl = cssCfg.getVideo_capture_implementation();
vidImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_webrtc_vid_capture_factory"));
vidImpl.setShared_lib_path(pjVideoFile);
/* -- For testing video screen -- Not yet released
try {
ComponentName cmp = new ComponentName("com.csipsimple.plugins.video", "com.csipsimple.plugins.video.CaptureReceiver");
DynCodecInfos screenCapt = new ExtraPlugins.DynCodecInfos(service, cmp);
vidImpl.setInit_factory_name(pjsua
.pj_str_copy(screenCapt.factoryInitFunction));
vidImpl.setShared_lib_path(pjsua
.pj_str_copy(screenCapt.libraryPath));
} catch (NameNotFoundException e) {
Log.e(THIS_FILE, "Not found capture plugin");
}
*/
}
// Codecs
cssCodecs = cssCfg.getExtra_vid_codecs();
cssCodecs[0].setShared_lib_path(pjVideoFile);
cssCodecs[0].setInit_factory_name(pjsua
.pj_str_copy("pjmedia_codec_ffmpeg_init"));
cssCodecs = cssCfg.getExtra_vid_codecs_destroy();
cssCodecs[0].setShared_lib_path(pjVideoFile);
cssCodecs[0].setInit_factory_name(pjsua
.pj_str_copy("pjmedia_codec_ffmpeg_deinit"));
cssCfg.setExtra_vid_codecs_cnt(1);
// Converter
dynamic_factory convertImpl = cssCfg.getVid_converter();
convertImpl.setShared_lib_path(pjVideoFile);
convertImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_libswscale_converter_init"));
}
}
// MAIN CONFIG
pjsua.config_default(cfg);
cfg.setCb(pjsuaConstants.WRAPPER_CALLBACK_STRUCT);
cfg.setUser_agent(pjsua.pj_str_copy(prefsWrapper.getUserAgent(service)));
// With new timer implementation, thread count of pjsip can be 0
// it will use less CPU since now thread are launched by
// alarmManager
cfg.setThread_cnt(0);
cfg.setUse_srtp(getUseSrtp());
cfg.setSrtp_secure_signaling(0);
pjsip_timer_setting timerSetting = cfg.getTimer_setting();
int minSe = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TIMER_MIN_SE);
int sessExp = prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.TIMER_SESS_EXPIRES);
if (minSe <= sessExp && minSe >= 90) {
timerSetting.setMin_se(minSe);
timerSetting.setSess_expires(sessExp);
cfg.setTimer_setting(timerSetting);
}
// DNS
if (prefsWrapper.enableDNSSRV() && !prefsWrapper.useIPv6()) {
pj_str_t[] nameservers = getNameservers();
if (nameservers != null) {
cfg.setNameserver_count(nameservers.length);
cfg.setNameserver(nameservers);
} else {
cfg.setNameserver_count(0);
}
}
// STUN
int isStunEnabled = prefsWrapper.getStunEnabled();
if (isStunEnabled == 1) {
String[] servers = prefsWrapper.getPreferenceStringValue(
SipConfigManager.STUN_SERVER).split(",");
cfg.setStun_srv_cnt(servers.length);
stunServers = cfg.getStun_srv();
for (String server : servers) {
Log.d(THIS_FILE, "add server " + server.trim());
stunServers[stunServersCount] = pjsua.pj_str_copy(server.trim());
stunServersCount++;
}
cfg.setStun_srv(stunServers);
}
// LOGGING CONFIG
pjsua.logging_config_default(logCfg);
logCfg.setConsole_level(prefsWrapper.getLogLevel());
logCfg.setLevel(prefsWrapper.getLogLevel());
logCfg.setMsg_logging(pjsuaConstants.PJ_TRUE);
// MEDIA CONFIG
pjsua.media_config_default(mediaCfg);
// For now only this cfg is supported
mediaCfg.setChannel_count(1);
mediaCfg.setSnd_auto_close_time(prefsWrapper.getAutoCloseTime());
// Echo cancellation
mediaCfg.setEc_tail_len(prefsWrapper.getEchoCancellationTail());
int echoMode = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.ECHO_MODE);
long clockRate = prefsWrapper.getClockRate();
if (clockRate > 16000 && echoMode == SipConfigManager.ECHO_MODE_WEBRTC_M) {
// WebRTC mobile does not allow higher that 16kHz for now
// TODO : warn user about this point
echoMode = SipConfigManager.ECHO_MODE_SIMPLE;
}
mediaCfg.setEc_options(echoMode);
mediaCfg.setNo_vad(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.ENABLE_VAD) ? 0 : 1);
mediaCfg.setQuality(prefsWrapper.getMediaQuality());
mediaCfg.setClock_rate(clockRate);
mediaCfg.setAudio_frame_ptime(prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.SND_PTIME));
// Disabled because only one thread enabled now for battery perfs on normal state
mediaCfg.setHas_ioqueue(/*prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.HAS_IO_QUEUE) ? 1 :*/ 0);
// ICE
mediaCfg.setEnable_ice(prefsWrapper.getIceEnabled());
// TURN
if (isTurnEnabled == 1) {
mediaCfg.setEnable_turn(isTurnEnabled);
mediaCfg.setTurn_server(pjsua.pj_str_copy(prefsWrapper.getTurnServer()));
}
// INITIALIZE
status = pjsua.csipsimple_init(cfg, logCfg, mediaCfg, cssCfg, service);
if (status != pjsuaConstants.PJ_SUCCESS) {
String msg = "Fail to init pjsua "
+ pjStrToString(pjsua.get_error_message(status));
Log.e(THIS_FILE, msg);
service.notifyUserOfMessage(msg);
cleanPjsua();
return false;
}
/*
* if (stunServersCount > 0) { int s = pjsua.detect_nat_type();
* Log.d(THIS_FILE, ">>> NAT TYPE is "+s); }
*/
}
// Add transports
{
// UDP
if (prefsWrapper.isUDPEnabled()) {
pjsip_transport_type_e t = pjsip_transport_type_e.PJSIP_TRANSPORT_UDP;
if (prefsWrapper.useIPv6()) {
t = pjsip_transport_type_e.PJSIP_TRANSPORT_UDP6;
}
udpTranportId = createTransport(t, prefsWrapper.getUDPTransportPort());
if (udpTranportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
// TODO : allow to configure this account
int[] p_acc_id = new int[1];
pjsua.acc_add_local(udpTranportId, pjsua.PJ_FALSE, p_acc_id);
localUdpAccPjId = p_acc_id[0];
// Log.d(THIS_FILE, "Udp account "+p_acc_id);
}
// TCP
if (prefsWrapper.isTCPEnabled() && !prefsWrapper.useIPv6()) {
pjsip_transport_type_e t = pjsip_transport_type_e.PJSIP_TRANSPORT_TCP;
if (prefsWrapper.useIPv6()) {
t = pjsip_transport_type_e.PJSIP_TRANSPORT_TCP6;
}
tcpTranportId = createTransport(t, prefsWrapper.getTCPTransportPort());
if (tcpTranportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
int[] p_acc_id = new int[1];
pjsua.acc_add_local(tcpTranportId, pjsua.PJ_FALSE, p_acc_id);
localTcpAccPjId = p_acc_id[0];
}
// TLS
if (prefsWrapper.isTLSEnabled() && !prefsWrapper.useIPv6()) {
tlsTransportId = createTransport(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS,
prefsWrapper.getTLSTransportPort());
if (tlsTransportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
int[] p_acc_id = new int[1];
pjsua.acc_add_local(tlsTransportId, pjsua.PJ_FALSE, p_acc_id);
localTlsAccPjId = p_acc_id[0];
}
// RTP transport
/*
* { pjsua_transport_config cfg = new pjsua_transport_config();
* pjsua.transport_config_default(cfg);
* cfg.setPort(prefsWrapper.getRTPPort()); if
* (prefsWrapper.getPreferenceBooleanValue
* (SipConfigManager.ENABLE_QOS)) { Log.d(THIS_FILE,
* "Activate qos for voice packets");
* cfg.setQos_type(pj_qos_type.PJ_QOS_TYPE_VOICE); } if
* (prefsWrapper.useIPv6()) { status =
* pjsua.media_transports_create_ipv6(cfg); } else { status =
* pjsua.media_transports_create(cfg); } if (status !=
* pjsuaConstants.PJ_SUCCESS) { String msg =
* "Fail to add media transport " +
* pjStrToString(pjsua.get_error_message(status));
* Log.e(THIS_FILE, msg); service.notifyUserOfMessage(msg);
* cleanPjsua(); return false; } }
*/
}
// Initialization is done, now start pjsua
status = pjsua.start();
if (status != pjsua.PJ_SUCCESS) {
String msg = "Fail to start pjsip "
+ pjStrToString(pjsua.get_error_message(status));
Log.e(THIS_FILE, msg);
service.notifyUserOfMessage(msg);
cleanPjsua();
return false;
}
// Init media codecs
initCodecs();
setCodecsPriorities();
created = true;
return true;
}
return false;
}
| public boolean sipStart() throws SameThreadException {
Log.setLogLevel(prefsWrapper.getLogLevel());
if (!hasSipStack) {
Log.e(THIS_FILE, "We have no sip stack, we can't start");
return false;
}
// Ensure the stack is not already created or is being created
if (!created) {
Log.d(THIS_FILE, "Starting sip stack");
udpTranportId = null;
tcpTranportId = null;
tlsTransportId = null;
// Pj timer
TimerWrapper.create(service);
int status;
status = pjsua.create();
Log.i(THIS_FILE, "Created " + status);
// General config
{
pj_str_t[] stunServers = null;
int stunServersCount = 0;
pjsua_config cfg = new pjsua_config();
pjsua_logging_config logCfg = new pjsua_logging_config();
pjsua_media_config mediaCfg = new pjsua_media_config();
csipsimple_config cssCfg = new csipsimple_config();
// SERVICE CONFIG
if (userAgentReceiver == null) {
Log.d(THIS_FILE, "create receiver....");
userAgentReceiver = new UAStateReceiver();
userAgentReceiver.initService(this);
}
if (mediaManager == null) {
mediaManager = new MediaManager(service);
}
mediaManager.startService();
pjsua.setCallbackObject(userAgentReceiver);
Log.d(THIS_FILE, "Attach is done to callback");
int isTurnEnabled = prefsWrapper.getTurnEnabled();
// CSS CONFIG
pjsua.csipsimple_config_default(cssCfg);
cssCfg.setUse_compact_form_headers(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.USE_COMPACT_FORM) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setUse_compact_form_sdp(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.USE_COMPACT_FORM) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setUse_no_update(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.FORCE_NO_UPDATE) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setTcp_keep_alive_interval(prefsWrapper.getTcpKeepAliveInterval());
cssCfg.setTls_keep_alive_interval(prefsWrapper.getTlsKeepAliveInterval());
// Transaction timeouts
int tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T1_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t1_timeout(tsx_to);
}
tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T2_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t2_timeout(tsx_to);
}
tsx_to = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TSX_T4_TIMEOUT);
if(tsx_to > 0) {
cssCfg.setTsx_t4_timeout(tsx_to);
}
// TURN
if (isTurnEnabled == 1) {
cssCfg.setTurn_username(pjsua.pj_str_copy(prefsWrapper
.getPreferenceStringValue(SipConfigManager.TURN_USERNAME)));
cssCfg.setTurn_password(pjsua.pj_str_copy(prefsWrapper
.getPreferenceStringValue(SipConfigManager.TURN_PASSWORD)));
}
// -- USE_ZRTP 1 is no_zrtp, 2 is create_zrtp
File zrtpFolder = PreferencesWrapper.getZrtpFolder(service);
if (zrtpFolder != null) {
cssCfg.setUse_zrtp((prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.USE_ZRTP) > 1) ? pjsua.PJ_TRUE
: pjsua.PJ_FALSE);
cssCfg.setStorage_folder(pjsua.pj_str_copy(zrtpFolder.getAbsolutePath()));
} else {
cssCfg.setUse_zrtp(pjsua.PJ_FALSE);
cssCfg.setStorage_folder(pjsua.pj_str_copy(""));
}
Map<String, DynCodecInfos> availableCodecs = ExtraPlugins.getDynPlugins(service, SipManager.ACTION_GET_EXTRA_CODECS);
dynamic_factory[] cssCodecs = cssCfg.getExtra_aud_codecs();
int i = 0;
for (Entry<String, DynCodecInfos> availableCodec : availableCodecs.entrySet()) {
DynCodecInfos dyn = availableCodec.getValue();
if (!TextUtils.isEmpty(dyn.libraryPath)) {
cssCodecs[i].setShared_lib_path(pjsua.pj_str_copy(dyn.libraryPath));
cssCodecs[i++].setInit_factory_name(pjsua
.pj_str_copy(dyn.factoryInitFunction));
}
}
cssCfg.setExtra_aud_codecs_cnt(i);
// Audio implementation
int implementation = prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.AUDIO_IMPLEMENTATION);
if (implementation == SipConfigManager.AUDIO_IMPLEMENTATION_OPENSLES) {
dynamic_factory audImp = cssCfg.getAudio_implementation();
audImp.setInit_factory_name(pjsua.pj_str_copy("pjmedia_opensl_factory"));
File openslLib = NativeLibManager.getBundledStackLibFile(service,
"libpj_opensl_dev.so");
audImp.setShared_lib_path(pjsua.pj_str_copy(openslLib.getAbsolutePath()));
cssCfg.setAudio_implementation(audImp);
Log.d(THIS_FILE, "Use OpenSL-ES implementation");
}
// Video implementation
if(prefsWrapper.getPreferenceBooleanValue(SipConfigManager.USE_VIDEO)){
// TODO :: Have plugins per capture / render / video codec / converter
Map<String, DynCodecInfos> videoPlugins = ExtraPlugins.getDynPlugins(service, SipManager.ACTION_GET_VIDEO_PLUGIN);
if(videoPlugins.size() > 0) {
DynCodecInfos videoPlugin = videoPlugins.values().iterator().next();
pj_str_t pjVideoFile = pjsua.pj_str_copy(videoPlugin.libraryPath);
Log.d(THIS_FILE, "Load video plugin at " + videoPlugin.libraryPath );
// Render
{
dynamic_factory vidImpl = cssCfg.getVideo_render_implementation();
vidImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_webrtc_vid_render_factory"));
vidImpl.setShared_lib_path(pjVideoFile);
}
// Capture
{
dynamic_factory vidImpl = cssCfg.getVideo_capture_implementation();
vidImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_webrtc_vid_capture_factory"));
vidImpl.setShared_lib_path(pjVideoFile);
/* -- For testing video screen -- Not yet released
try {
ComponentName cmp = new ComponentName("com.csipsimple.plugins.video", "com.csipsimple.plugins.video.CaptureReceiver");
DynCodecInfos screenCapt = new ExtraPlugins.DynCodecInfos(service, cmp);
vidImpl.setInit_factory_name(pjsua
.pj_str_copy(screenCapt.factoryInitFunction));
vidImpl.setShared_lib_path(pjsua
.pj_str_copy(screenCapt.libraryPath));
} catch (NameNotFoundException e) {
Log.e(THIS_FILE, "Not found capture plugin");
}
*/
}
// Codecs
cssCodecs = cssCfg.getExtra_vid_codecs();
cssCodecs[0].setShared_lib_path(pjVideoFile);
cssCodecs[0].setInit_factory_name(pjsua
.pj_str_copy("pjmedia_codec_ffmpeg_vid_init"));
cssCodecs = cssCfg.getExtra_vid_codecs_destroy();
cssCodecs[0].setShared_lib_path(pjVideoFile);
cssCodecs[0].setInit_factory_name(pjsua
.pj_str_copy("pjmedia_codec_ffmpeg_vid_deinit"));
cssCfg.setExtra_vid_codecs_cnt(1);
// Converter
dynamic_factory convertImpl = cssCfg.getVid_converter();
convertImpl.setShared_lib_path(pjVideoFile);
convertImpl.setInit_factory_name(pjsua
.pj_str_copy("pjmedia_libswscale_converter_init"));
}
}
// MAIN CONFIG
pjsua.config_default(cfg);
cfg.setCb(pjsuaConstants.WRAPPER_CALLBACK_STRUCT);
cfg.setUser_agent(pjsua.pj_str_copy(prefsWrapper.getUserAgent(service)));
// With new timer implementation, thread count of pjsip can be 0
// it will use less CPU since now thread are launched by
// alarmManager
cfg.setThread_cnt(0);
cfg.setUse_srtp(getUseSrtp());
cfg.setSrtp_secure_signaling(0);
pjsip_timer_setting timerSetting = cfg.getTimer_setting();
int minSe = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.TIMER_MIN_SE);
int sessExp = prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.TIMER_SESS_EXPIRES);
if (minSe <= sessExp && minSe >= 90) {
timerSetting.setMin_se(minSe);
timerSetting.setSess_expires(sessExp);
cfg.setTimer_setting(timerSetting);
}
// DNS
if (prefsWrapper.enableDNSSRV() && !prefsWrapper.useIPv6()) {
pj_str_t[] nameservers = getNameservers();
if (nameservers != null) {
cfg.setNameserver_count(nameservers.length);
cfg.setNameserver(nameservers);
} else {
cfg.setNameserver_count(0);
}
}
// STUN
int isStunEnabled = prefsWrapper.getStunEnabled();
if (isStunEnabled == 1) {
String[] servers = prefsWrapper.getPreferenceStringValue(
SipConfigManager.STUN_SERVER).split(",");
cfg.setStun_srv_cnt(servers.length);
stunServers = cfg.getStun_srv();
for (String server : servers) {
Log.d(THIS_FILE, "add server " + server.trim());
stunServers[stunServersCount] = pjsua.pj_str_copy(server.trim());
stunServersCount++;
}
cfg.setStun_srv(stunServers);
}
// LOGGING CONFIG
pjsua.logging_config_default(logCfg);
logCfg.setConsole_level(prefsWrapper.getLogLevel());
logCfg.setLevel(prefsWrapper.getLogLevel());
logCfg.setMsg_logging(pjsuaConstants.PJ_TRUE);
// MEDIA CONFIG
pjsua.media_config_default(mediaCfg);
// For now only this cfg is supported
mediaCfg.setChannel_count(1);
mediaCfg.setSnd_auto_close_time(prefsWrapper.getAutoCloseTime());
// Echo cancellation
mediaCfg.setEc_tail_len(prefsWrapper.getEchoCancellationTail());
int echoMode = prefsWrapper.getPreferenceIntegerValue(SipConfigManager.ECHO_MODE);
long clockRate = prefsWrapper.getClockRate();
if (clockRate > 16000 && echoMode == SipConfigManager.ECHO_MODE_WEBRTC_M) {
// WebRTC mobile does not allow higher that 16kHz for now
// TODO : warn user about this point
echoMode = SipConfigManager.ECHO_MODE_SIMPLE;
}
mediaCfg.setEc_options(echoMode);
mediaCfg.setNo_vad(prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.ENABLE_VAD) ? 0 : 1);
mediaCfg.setQuality(prefsWrapper.getMediaQuality());
mediaCfg.setClock_rate(clockRate);
mediaCfg.setAudio_frame_ptime(prefsWrapper
.getPreferenceIntegerValue(SipConfigManager.SND_PTIME));
// Disabled because only one thread enabled now for battery perfs on normal state
mediaCfg.setHas_ioqueue(/*prefsWrapper
.getPreferenceBooleanValue(SipConfigManager.HAS_IO_QUEUE) ? 1 :*/ 0);
// ICE
mediaCfg.setEnable_ice(prefsWrapper.getIceEnabled());
// TURN
if (isTurnEnabled == 1) {
mediaCfg.setEnable_turn(isTurnEnabled);
mediaCfg.setTurn_server(pjsua.pj_str_copy(prefsWrapper.getTurnServer()));
}
// INITIALIZE
status = pjsua.csipsimple_init(cfg, logCfg, mediaCfg, cssCfg, service);
if (status != pjsuaConstants.PJ_SUCCESS) {
String msg = "Fail to init pjsua "
+ pjStrToString(pjsua.get_error_message(status));
Log.e(THIS_FILE, msg);
service.notifyUserOfMessage(msg);
cleanPjsua();
return false;
}
/*
* if (stunServersCount > 0) { int s = pjsua.detect_nat_type();
* Log.d(THIS_FILE, ">>> NAT TYPE is "+s); }
*/
}
// Add transports
{
// UDP
if (prefsWrapper.isUDPEnabled()) {
pjsip_transport_type_e t = pjsip_transport_type_e.PJSIP_TRANSPORT_UDP;
if (prefsWrapper.useIPv6()) {
t = pjsip_transport_type_e.PJSIP_TRANSPORT_UDP6;
}
udpTranportId = createTransport(t, prefsWrapper.getUDPTransportPort());
if (udpTranportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
// TODO : allow to configure this account
int[] p_acc_id = new int[1];
pjsua.acc_add_local(udpTranportId, pjsua.PJ_FALSE, p_acc_id);
localUdpAccPjId = p_acc_id[0];
// Log.d(THIS_FILE, "Udp account "+p_acc_id);
}
// TCP
if (prefsWrapper.isTCPEnabled() && !prefsWrapper.useIPv6()) {
pjsip_transport_type_e t = pjsip_transport_type_e.PJSIP_TRANSPORT_TCP;
if (prefsWrapper.useIPv6()) {
t = pjsip_transport_type_e.PJSIP_TRANSPORT_TCP6;
}
tcpTranportId = createTransport(t, prefsWrapper.getTCPTransportPort());
if (tcpTranportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
int[] p_acc_id = new int[1];
pjsua.acc_add_local(tcpTranportId, pjsua.PJ_FALSE, p_acc_id);
localTcpAccPjId = p_acc_id[0];
}
// TLS
if (prefsWrapper.isTLSEnabled() && !prefsWrapper.useIPv6()) {
tlsTransportId = createTransport(pjsip_transport_type_e.PJSIP_TRANSPORT_TLS,
prefsWrapper.getTLSTransportPort());
if (tlsTransportId == null) {
cleanPjsua();
return false;
}
// We need a local account to not have the
// application lost when direct call to the IP
int[] p_acc_id = new int[1];
pjsua.acc_add_local(tlsTransportId, pjsua.PJ_FALSE, p_acc_id);
localTlsAccPjId = p_acc_id[0];
}
// RTP transport
/*
* { pjsua_transport_config cfg = new pjsua_transport_config();
* pjsua.transport_config_default(cfg);
* cfg.setPort(prefsWrapper.getRTPPort()); if
* (prefsWrapper.getPreferenceBooleanValue
* (SipConfigManager.ENABLE_QOS)) { Log.d(THIS_FILE,
* "Activate qos for voice packets");
* cfg.setQos_type(pj_qos_type.PJ_QOS_TYPE_VOICE); } if
* (prefsWrapper.useIPv6()) { status =
* pjsua.media_transports_create_ipv6(cfg); } else { status =
* pjsua.media_transports_create(cfg); } if (status !=
* pjsuaConstants.PJ_SUCCESS) { String msg =
* "Fail to add media transport " +
* pjStrToString(pjsua.get_error_message(status));
* Log.e(THIS_FILE, msg); service.notifyUserOfMessage(msg);
* cleanPjsua(); return false; } }
*/
}
// Initialization is done, now start pjsua
status = pjsua.start();
if (status != pjsua.PJ_SUCCESS) {
String msg = "Fail to start pjsip "
+ pjStrToString(pjsua.get_error_message(status));
Log.e(THIS_FILE, msg);
service.notifyUserOfMessage(msg);
cleanPjsua();
return false;
}
// Init media codecs
initCodecs();
setCodecsPriorities();
created = true;
return true;
}
return false;
}
|
diff --git a/src/net/colar/netbeans/fan/wizard/FanProjectPropertiesPanel.java b/src/net/colar/netbeans/fan/wizard/FanProjectPropertiesPanel.java
index a3062e5..72403ea 100644
--- a/src/net/colar/netbeans/fan/wizard/FanProjectPropertiesPanel.java
+++ b/src/net/colar/netbeans/fan/wizard/FanProjectPropertiesPanel.java
@@ -1,276 +1,276 @@
/*
* Thibaut Colar Aug 13, 2009
*/
/*
* FanProjectPropertiesPanel.java
*
* Created on Aug 13, 2009, 2:21:31 PM
*/
package net.colar.netbeans.fan.wizard;
/**
* Main UI panel for project/pod properties
* @author thibautc
*/
public class FanProjectPropertiesPanel extends javax.swing.JPanel
{
/** Creates new form FanProjectPropertiesPanel */
public FanProjectPropertiesPanel()
{
initComponents();
}
/** 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() {
mainMethodLbl = new javax.swing.JLabel();
buildTargetLbl = new javax.swing.JLabel();
mainMethod = new javax.swing.JTextField();
buildTarget = new javax.swing.JTextField();
dependenciesLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
dependenciesTable = new javax.swing.JTable();
dependenciesEditButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
metasList = new javax.swing.JList();
metasEditButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
indexesList = new javax.swing.JList();
indexesEditButton = new javax.swing.JButton();
metasLabel = new javax.swing.JLabel();
indexesLabel = new javax.swing.JLabel();
outputDirectoryLabel = new javax.swing.JLabel();
outputDirectoryField = new javax.swing.JTextField();
outputDirectoryEditButton = new javax.swing.JButton();
mainMethodLbl.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.mainMethodLbl.text")); // NOI18N
buildTargetLbl.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.buildTargetLbl.text")); // NOI18N
mainMethod.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.mainMethod.text")); // NOI18N
buildTarget.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.buildTarget.text")); // NOI18N
buildTarget.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildTargetActionPerformed(evt);
}
});
dependenciesLabel.setLabelFor(dependenciesTable);
dependenciesLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.dependenciesLabel.text")); // NOI18N
dependenciesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(dependenciesTable);
dependenciesEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.dependenciesEditButton.text")); // NOI18N
dependenciesEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dependenciesEditButtonActionPerformed(evt);
}
});
metasList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(metasList);
metasEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.metasEditButton.text")); // NOI18N
metasEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
metasEditButtonActionPerformed(evt);
}
});
indexesList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane3.setViewportView(indexesList);
indexesEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.indexesEditButton.text")); // NOI18N
indexesEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
indexesEditButtonActionPerformed(evt);
}
});
metasLabel.setLabelFor(metasList);
metasLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.metasLabel.text")); // NOI18N
indexesLabel.setLabelFor(indexesList);
indexesLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.indexesLabel.text")); // NOI18N
outputDirectoryLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryLabel.text")); // NOI18N
outputDirectoryField.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryField.text")); // NOI18N
- outputDirectoryEditButton.setLabel(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryEditButton.label")); // NOI18N
+ outputDirectoryEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryEditButton.label")); // NOI18N
outputDirectoryEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
outputDirectoryEditButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainMethodLbl)
.add(buildTargetLbl)
.add(dependenciesLabel)
.add(metasLabel)
.add(indexesLabel)
.add(outputDirectoryLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainMethod, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, buildTarget, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, outputDirectoryField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(indexesEditButton)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(dependenciesEditButton)
.add(metasEditButton)))
.add(outputDirectoryEditButton))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(mainMethodLbl)
.add(mainMethod, 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(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(buildTargetLbl)
.add(buildTarget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(dependenciesLabel)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 86, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.add(40, 40, 40)
.add(dependenciesEditButton)))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(27, 27, 27)
.add(metasEditButton))
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(metasLabel)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(indexesLabel)
.add(5, 5, 5)
.add(indexesEditButton))
.add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(outputDirectoryField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(outputDirectoryEditButton)
.add(outputDirectoryLabel))
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void dependenciesEditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dependenciesEditButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_dependenciesEditButtonActionPerformed
private void metasEditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_metasEditButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_metasEditButtonActionPerformed
private void indexesEditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_indexesEditButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_indexesEditButtonActionPerformed
private void outputDirectoryEditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputDirectoryEditButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_outputDirectoryEditButtonActionPerformed
private void buildTargetActionPerformed(java.awt.event.ActionEvent evt)
{
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField buildTarget;
private javax.swing.JLabel buildTargetLbl;
private javax.swing.JButton dependenciesEditButton;
private javax.swing.JLabel dependenciesLabel;
private javax.swing.JTable dependenciesTable;
private javax.swing.JButton indexesEditButton;
private javax.swing.JLabel indexesLabel;
private javax.swing.JList indexesList;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField mainMethod;
private javax.swing.JLabel mainMethodLbl;
private javax.swing.JButton metasEditButton;
private javax.swing.JLabel metasLabel;
private javax.swing.JList metasList;
private javax.swing.JButton outputDirectoryEditButton;
private javax.swing.JTextField outputDirectoryField;
private javax.swing.JLabel outputDirectoryLabel;
// End of variables declaration//GEN-END:variables
public void setBuildTarget(String target)
{
if(target==null)
target="";
buildTarget.setText(target);
}
public String getMainMethod()
{
return mainMethod.getText();
}
public String getBuildTarget()
{
return buildTarget.getText();
}
public void setMainMethod(String method)
{
if(method==null || method.length()==0)
method="Main.main";
mainMethod.setText(method);
}
}
| true | true | private void initComponents() {
mainMethodLbl = new javax.swing.JLabel();
buildTargetLbl = new javax.swing.JLabel();
mainMethod = new javax.swing.JTextField();
buildTarget = new javax.swing.JTextField();
dependenciesLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
dependenciesTable = new javax.swing.JTable();
dependenciesEditButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
metasList = new javax.swing.JList();
metasEditButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
indexesList = new javax.swing.JList();
indexesEditButton = new javax.swing.JButton();
metasLabel = new javax.swing.JLabel();
indexesLabel = new javax.swing.JLabel();
outputDirectoryLabel = new javax.swing.JLabel();
outputDirectoryField = new javax.swing.JTextField();
outputDirectoryEditButton = new javax.swing.JButton();
mainMethodLbl.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.mainMethodLbl.text")); // NOI18N
buildTargetLbl.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.buildTargetLbl.text")); // NOI18N
mainMethod.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.mainMethod.text")); // NOI18N
buildTarget.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.buildTarget.text")); // NOI18N
buildTarget.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildTargetActionPerformed(evt);
}
});
dependenciesLabel.setLabelFor(dependenciesTable);
dependenciesLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.dependenciesLabel.text")); // NOI18N
dependenciesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(dependenciesTable);
dependenciesEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.dependenciesEditButton.text")); // NOI18N
dependenciesEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dependenciesEditButtonActionPerformed(evt);
}
});
metasList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(metasList);
metasEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.metasEditButton.text")); // NOI18N
metasEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
metasEditButtonActionPerformed(evt);
}
});
indexesList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane3.setViewportView(indexesList);
indexesEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.indexesEditButton.text")); // NOI18N
indexesEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
indexesEditButtonActionPerformed(evt);
}
});
metasLabel.setLabelFor(metasList);
metasLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.metasLabel.text")); // NOI18N
indexesLabel.setLabelFor(indexesList);
indexesLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.indexesLabel.text")); // NOI18N
outputDirectoryLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryLabel.text")); // NOI18N
outputDirectoryField.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryField.text")); // NOI18N
outputDirectoryEditButton.setLabel(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryEditButton.label")); // NOI18N
outputDirectoryEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
outputDirectoryEditButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainMethodLbl)
.add(buildTargetLbl)
.add(dependenciesLabel)
.add(metasLabel)
.add(indexesLabel)
.add(outputDirectoryLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainMethod, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, buildTarget, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, outputDirectoryField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(indexesEditButton)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(dependenciesEditButton)
.add(metasEditButton)))
.add(outputDirectoryEditButton))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(mainMethodLbl)
.add(mainMethod, 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(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(buildTargetLbl)
.add(buildTarget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(dependenciesLabel)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 86, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.add(40, 40, 40)
.add(dependenciesEditButton)))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(27, 27, 27)
.add(metasEditButton))
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(metasLabel)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(indexesLabel)
.add(5, 5, 5)
.add(indexesEditButton))
.add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(outputDirectoryField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(outputDirectoryEditButton)
.add(outputDirectoryLabel))
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
mainMethodLbl = new javax.swing.JLabel();
buildTargetLbl = new javax.swing.JLabel();
mainMethod = new javax.swing.JTextField();
buildTarget = new javax.swing.JTextField();
dependenciesLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
dependenciesTable = new javax.swing.JTable();
dependenciesEditButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
metasList = new javax.swing.JList();
metasEditButton = new javax.swing.JButton();
jScrollPane3 = new javax.swing.JScrollPane();
indexesList = new javax.swing.JList();
indexesEditButton = new javax.swing.JButton();
metasLabel = new javax.swing.JLabel();
indexesLabel = new javax.swing.JLabel();
outputDirectoryLabel = new javax.swing.JLabel();
outputDirectoryField = new javax.swing.JTextField();
outputDirectoryEditButton = new javax.swing.JButton();
mainMethodLbl.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.mainMethodLbl.text")); // NOI18N
buildTargetLbl.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.buildTargetLbl.text")); // NOI18N
mainMethod.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.mainMethod.text")); // NOI18N
buildTarget.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.buildTarget.text")); // NOI18N
buildTarget.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildTargetActionPerformed(evt);
}
});
dependenciesLabel.setLabelFor(dependenciesTable);
dependenciesLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.dependenciesLabel.text")); // NOI18N
dependenciesTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(dependenciesTable);
dependenciesEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.dependenciesEditButton.text")); // NOI18N
dependenciesEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dependenciesEditButtonActionPerformed(evt);
}
});
metasList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(metasList);
metasEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.metasEditButton.text")); // NOI18N
metasEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
metasEditButtonActionPerformed(evt);
}
});
indexesList.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane3.setViewportView(indexesList);
indexesEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.indexesEditButton.text")); // NOI18N
indexesEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
indexesEditButtonActionPerformed(evt);
}
});
metasLabel.setLabelFor(metasList);
metasLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.metasLabel.text")); // NOI18N
indexesLabel.setLabelFor(indexesList);
indexesLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.indexesLabel.text")); // NOI18N
outputDirectoryLabel.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryLabel.text")); // NOI18N
outputDirectoryField.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryField.text")); // NOI18N
outputDirectoryEditButton.setText(org.openide.util.NbBundle.getMessage(FanProjectPropertiesPanel.class, "FanProjectPropertiesPanel.outputDirectoryEditButton.label")); // NOI18N
outputDirectoryEditButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
outputDirectoryEditButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainMethodLbl)
.add(buildTargetLbl)
.add(dependenciesLabel)
.add(metasLabel)
.add(indexesLabel)
.add(outputDirectoryLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(mainMethod, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, buildTarget, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 372, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, outputDirectoryField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
.add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(indexesEditButton)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(dependenciesEditButton)
.add(metasEditButton)))
.add(outputDirectoryEditButton))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(mainMethodLbl)
.add(mainMethod, 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(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(buildTargetLbl)
.add(buildTarget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(dependenciesLabel)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 86, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.add(40, 40, 40)
.add(dependenciesEditButton)))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(27, 27, 27)
.add(metasEditButton))
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(metasLabel)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 79, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(indexesLabel)
.add(5, 5, 5)
.add(indexesEditButton))
.add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 80, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(outputDirectoryField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(outputDirectoryEditButton)
.add(outputDirectoryLabel))
.addContainerGap(20, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/ac/robinson/util/BitmapUtilities.java b/src/ac/robinson/util/BitmapUtilities.java
index 6cb8dd3..0f663e8 100644
--- a/src/ac/robinson/util/BitmapUtilities.java
+++ b/src/ac/robinson/util/BitmapUtilities.java
@@ -1,663 +1,663 @@
/*
* Copyright (C) 2012 Simon Robinson
*
* This file is part of Com-Me.
*
* Com-Me is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* Com-Me 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 Com-Me.
* If not, see <http://www.gnu.org/licenses/>.
*/
package ac.robinson.util;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.YuvImage;
import android.media.ExifInterface;
import android.text.TextUtils;
/**
* Class containing static utility methods for bitmap decoding and scaling
*
* @author Andreas Agvard ([email protected])
*/
public class BitmapUtilities {
// if a bitmap's width (height) is more than this many times its height (width) then the ScalingLogic.CROP option
// will be ignored and the bitmap will scaled to fit into the destination box to save memory
public static final int MAX_SAMPLE_WIDTH_HEIGHT_RATIO = 12;
public static class CacheTypeContainer {
public Bitmap.CompressFormat type;
public CacheTypeContainer(Bitmap.CompressFormat type) {
this.type = type;
}
}
// get screen size by: Display display =
// ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
// if using an ImageView etc, remember that the size is zero initially before inflation
public static Bitmap loadAndCreateScaledBitmap(String imagePath, int dstWidth, int dstHeight,
ScalingLogic scalingLogic, boolean rotateImage) {
Matrix imageMatrix = new Matrix();
if (rotateImage) {
int rotationNeeded = getImageRotationDegrees(imagePath);
if (rotationNeeded != 0) {
imageMatrix.postRotate(rotationNeeded);
}
}
Bitmap unscaledBitmap = decodeFile(imagePath, dstWidth, dstHeight, scalingLogic);
return createScaledBitmap(unscaledBitmap, dstWidth, dstHeight, scalingLogic, imageMatrix);
}
public static Bitmap loadAndCreateScaledResource(Resources res, int resId, int dstWidth, int dstHeight,
ScalingLogic scalingLogic) {
Bitmap unscaledBitmap = decodeResource(res, resId, dstWidth, dstHeight, scalingLogic);
return createScaledBitmap(unscaledBitmap, dstWidth, dstHeight, scalingLogic, new Matrix());
}
public static Bitmap loadAndCreateScaledStream(String streamPath, int dstWidth, int dstHeight,
ScalingLogic scalingLogic) {
Bitmap unscaledBitmap = decodeStream(streamPath, dstWidth, dstHeight, scalingLogic);
return createScaledBitmap(unscaledBitmap, dstWidth, dstHeight, scalingLogic, new Matrix());
}
public static Bitmap scaleBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
return createScaledBitmap(unscaledBitmap, dstWidth, dstHeight, scalingLogic, new Matrix());
}
public static int getImageOrientation(String imagePath) {
ExifInterface exifInterface;
try {
exifInterface = new ExifInterface(imagePath);
} catch (IOException err) {
return ExifInterface.ORIENTATION_UNDEFINED;
}
return exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
}
public static int getImageRotationDegrees(String imagePath) {
int currentRotation = getImageOrientation(imagePath);
switch (currentRotation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
}
return 0;
}
public static Options getImageDimensions(String imagePath) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
return options;
}
/**
* Utility function for decoding an image resource. The decoded bitmap will be optimized for further scaling to the
* requested destination dimensions and scaling logic.
*
* @param res The resources object containing the image data
* @param resId The resource id of the image data
* @param dstWidth Width of destination area
* @param dstHeight Height of destination area
* @param scalingLogic Logic to use to avoid image stretching
* @return Decoded bitmap
*/
public static Bitmap decodeResource(Resources res, int resId, int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
if (dstWidth <= 0 || dstHeight <= 0)
return null;
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inJustDecodeBounds = false;
// options.inPurgeable = true; // ignored for resources: http://stackoverflow.com/a/7068403
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight,
scalingLogic);
Bitmap unscaledBitmap = BitmapFactory.decodeResource(res, resId, options);
return unscaledBitmap;
}
/**
* Utility function for decoding an image file. The decoded bitmap will be optimized for further scaling to the
* requested destination dimensions and scaling logic.
*
* @param imagePath the file path of the image
* @param dstWidth Width of destination area
* @param dstHeight Height of destination area
* @param scalingLogic Logic to use to avoid image stretching
* @return Decoded bitmap
*/
public static Bitmap decodeFile(String imagePath, int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
if (dstWidth <= 0 || dstHeight <= 0)
return null;
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
options.inJustDecodeBounds = false;
// options.inPurgeable = true; // not appropriate for image cache; to be enabled later
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight,
scalingLogic);
Bitmap unscaledBitmap = BitmapFactory.decodeFile(imagePath, options);
return unscaledBitmap;
}
/**
* Utility function for decoding an image stream. The decoded bitmap will be optimized for further scaling to the
* requested destination dimensions and scaling logic.
*
* @param streamPath The path of the image stream to decode
* @param dstWidth Width of destination area
* @param dstHeight Height of destination area
* @param scalingLogic Logic to use to avoid image stretching
* @return Decoded bitmap, or null on error
*/
public static Bitmap decodeStream(String streamPath, int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
try {
if (dstWidth <= 0 || dstHeight <= 0)
return null;
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(streamPath), null, options);
options.inJustDecodeBounds = false;
// options.inPurgeable = true; // not appropriate for image cache; to be enabled later
options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight,
scalingLogic);
Bitmap unscaledBitmap = BitmapFactory.decodeStream(new FileInputStream(streamPath), null, options);
return unscaledBitmap;
} catch (FileNotFoundException e) {
return null;
}
}
/**
* Utility function for creating a scaled version of an existing bitmap
*
* @param unscaledBitmap Bitmap to scale
* @param dstWidth Wanted width of destination bitmap
* @param dstHeight Wanted height of destination bitmap
* @param scalingLogic Logic to use to avoid image stretching
* @return New scaled bitmap object
*/
public static Bitmap createScaledBitmap(Bitmap unscaledBitmap, int dstWidth, int dstHeight,
ScalingLogic scalingLogic, Matrix imageMatrix) {
if (unscaledBitmap == null)
return null;
unscaledBitmap = Bitmap.createBitmap(unscaledBitmap, 0, 0, unscaledBitmap.getWidth(),
unscaledBitmap.getHeight(), imageMatrix, true);
Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight,
scalingLogic);
Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight,
scalingLogic);
Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(),
ImageCacheUtilities.mBitmapFactoryOptions.inPreferredConfig);
Canvas canvas = new Canvas(scaledBitmap);
canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));
return scaledBitmap;
}
/**
* ScalingLogic defines how scaling should be carried out if source and destination image has different aspect
* ratio.
*
* CROP: Scales the image the minimum amount while making sure that at least one of the two dimensions fit inside
* the requested destination area. Parts of the source image will be cropped to realize this.
*
* FIT: Scales the image the minimum amount while making sure both dimensions fit inside the requested destination
* area. The resulting destination dimensions might be adjusted to a smaller size than requested.
*/
public static enum ScalingLogic {
CROP, FIT
}
/**
* Calculate optimal down-sampling factor given the dimensions of a source image, the dimensions of a destination
* area and a scaling logic.
*
* @param srcWidth Width of source image
* @param srcHeight Height of source image
* @param dstWidth Width of destination area
* @param dstHeight Height of destination area
* @param scalingLogic Logic to use to avoid image stretching
* @return Optimal down scaling sample size for decoding
*/
private static int calculateSampleSize(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
ScalingLogic scalingLogic) {
final float srcAspect = (float) srcWidth / (float) srcHeight;
if (scalingLogic == ScalingLogic.FIT) {
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
return Math.round((float) srcWidth / (float) dstWidth);
} else {
return Math.round((float) srcHeight / (float) dstHeight);
}
} else {
boolean tooTall = (float) srcHeight / (float) srcWidth > MAX_SAMPLE_WIDTH_HEIGHT_RATIO;
if ((srcWidth > srcHeight && srcAspect < MAX_SAMPLE_WIDTH_HEIGHT_RATIO) || tooTall) {
return Math.round((float) srcHeight / (float) dstHeight);
} else {
return Math.round((float) srcWidth / (float) dstWidth);
}
}
}
/**
* Calculates source rectangle for scaling bitmap
*
* @param srcWidth Width of source image
* @param srcHeight Height of source image
* @param dstWidth Width of destination area
* @param dstHeight Height of destination area
* @param scalingLogic Logic to use to avoid image stretching
* @return Optimal source rectangle
*/
private static Rect calculateSrcRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.CROP) {
final float srcAspect = (float) srcWidth / (float) srcHeight;
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
final int srcRectWidth = (int) (srcHeight * dstAspect);
final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth, srcHeight);
} else {
final int srcRectHeight = (int) (srcWidth / dstAspect);
final int scrRectTop = (int) (srcHeight - srcRectHeight) / 2;
return new Rect(0, scrRectTop, srcWidth, scrRectTop + srcRectHeight);
}
} else {
return new Rect(0, 0, srcWidth, srcHeight);
}
}
/**
* Calculates destination rectangle for scaling bitmap
*
* @param srcWidth Width of source image
* @param srcHeight Height of source image
* @param dstWidth Width of destination area
* @param dstHeight Height of destination area
* @param scalingLogic Logic to use to avoid image stretching
* @return Optimal destination rectangle
*/
private static Rect calculateDstRect(int srcWidth, int srcHeight, int dstWidth, int dstHeight,
ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.FIT) {
final float srcAspect = (float) srcWidth / (float) srcHeight;
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
return new Rect(0, 0, dstWidth, (int) (dstWidth / srcAspect));
} else {
return new Rect(0, 0, (int) (dstHeight * srcAspect), dstHeight);
}
} else {
return new Rect(0, 0, dstWidth, dstHeight);
}
}
public static Bitmap getMutableBitmap(Bitmap bitmap) {
if (bitmap.isMutable()) {
return bitmap;
}
Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
ImageCacheUtilities.mBitmapFactoryOptions.inPreferredConfig);
Canvas canvas = new Canvas(newBitmap);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas = null;
return newBitmap;
}
public static Bitmap rotate(Bitmap bitmap, int orientationDegrees, float xPosition, float yPosition) {
Bitmap rotated = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
ImageCacheUtilities.mBitmapFactoryOptions.inPreferredConfig);
Canvas canvas = new Canvas(rotated);
canvas.rotate(orientationDegrees, xPosition, yPosition);
canvas.drawBitmap(bitmap, 0, 0, null);
canvas = null;
return rotated;
}
public static boolean saveByteImage(byte[] imageData, File saveTo, int quality, boolean flipHorizontally) {
FileOutputStream fileOutputStream = null;
BufferedOutputStream byteOutputStream = null;
try {
fileOutputStream = new FileOutputStream(saveTo);
boolean imageSaved = false;
if (flipHorizontally) { // need to flip front camera images horizontally; only done for front as we'd be out
// of memory for back camera
try {
Bitmap newImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
Matrix flipMatrix = new Matrix();
flipMatrix.postScale(-1.0f, 1.0f);
newImage = Bitmap.createBitmap(newImage, 0, 0, newImage.getWidth(), newImage.getHeight(),
flipMatrix, true);
byteOutputStream = new BufferedOutputStream(fileOutputStream);
newImage.compress(CompressFormat.JPEG, quality, byteOutputStream);
byteOutputStream.flush();
byteOutputStream.close();
imageSaved = true;
} catch (OutOfMemoryError e) {
} // probably doesn't actually catch...
}
if (!flipHorizontally || !imageSaved) {
fileOutputStream.write(imageData);
}
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} finally {
IOUtilities.closeStream(byteOutputStream);
}
return true;
}
/**
* Save YUV image data (NV21 or YUV420sp) as JPEG to a FileOutputStream.
*/
public static boolean saveYUYToJPEG(byte[] imageData, File saveTo, int format, int quality, int width, int height,
int rotation, boolean flipHorizontally) {
FileOutputStream fileOutputStream = null;
YuvImage yuvImg = null;
try {
fileOutputStream = new FileOutputStream(saveTo);
yuvImg = new YuvImage(imageData, format, width, height, null);
ByteArrayOutputStream jpegOutput = new ByteArrayOutputStream(imageData.length);
yuvImg.compressToJpeg(new Rect(0, 0, width - 1, height - 1), 90, jpegOutput);
Bitmap yuvBitmap = BitmapFactory.decodeByteArray(jpegOutput.toByteArray(), 0, jpegOutput.size());
Matrix imageMatrix = new Matrix();
if (rotation != 0) {
imageMatrix.postRotate(rotation);
}
if (flipHorizontally) {
// imageMatrix.postScale(-1.0f, 1.0f);
}
yuvBitmap = Bitmap.createBitmap(yuvBitmap, 0, 0, yuvBitmap.getWidth(), yuvBitmap.getHeight(), imageMatrix,
true);
yuvBitmap.compress(CompressFormat.JPEG, quality, fileOutputStream);
} catch (FileNotFoundException e) {
return false;
}
return true;
}
/**
* Save YUV image data (NV21 or YUV420sp) as JPEG to a FileOutputStream.
*/
public static boolean saveJPEGToJPEG(byte[] imageData, File saveTo, boolean flipHorizontally) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(saveTo);
fileOutputStream.write(imageData);
IOUtilities.closeStream(fileOutputStream);
} catch (FileNotFoundException e) {
} catch (IOException e) {
return false;
}
// try {
if (flipHorizontally) {
// ExifInterface exif = new ExifInterface(saveTo.getAbsolutePath());
// int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
// ExifInterface.ORIENTATION_UNDEFINED);
// exifOrientation |= ExifInterface.ORIENTATION_FLIP_HORIZONTAL;
// exif.setAttribute(ExifInterface.TAG_ORIENTATION, Integer.toString(exifOrientation));
// exif.saveAttributes();
}
// } catch (IOException e) {
// // don't return false - we saved fine, but just couldn't set the exif attributes
// }
return true;
}
public static boolean saveBitmap(Bitmap bitmap, CompressFormat format, int quality, File saveTo) {
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
fileOutputStream = new FileOutputStream(saveTo);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bitmap.compress(format, quality, bufferedOutputStream);
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
} finally {
IOUtilities.closeStream(bufferedOutputStream);
}
return true;
}
/**
* Note: the paint's textSize and alignment will be changed...
*
* @param textString
* @param textCanvas
* @param textPaint
* @param textColour
* @param backgroundColour
* @param backgroundPadding
* @param backgroundRadius
* @param alignBottom
* @param leftOffset
* @param backgroundSpanWidth
* @param maxHeight
* @param maxTextSize
* @param maxCharactersPerLine
* @return The height of the drawn text, including padding
*/
public static int drawScaledText(String textString, Canvas textCanvas, Paint textPaint, int textColour,
int backgroundColour, int backgroundPadding, int backgroundRadius, boolean alignBottom, float leftOffset,
boolean backgroundSpanWidth, float maxHeight, int maxTextSize, int maxCharactersPerLine) {
if (TextUtils.isEmpty(textString) || "".equals(textString.trim())) {
return 0;
}
float maxWidth = (int) Math.floor(textCanvas.getWidth() - leftOffset);
// split the text into lines
// TODO: respect user-created formatting more closely? (e.g., linebreaks and spaces)
int textLength = textString.length();
StringBuilder formattedString = new StringBuilder(textLength);
+ String[] stringLines = textString.split("\n");
int numLines = Integer.MAX_VALUE;
- int maxLines = (int) Math.ceil(Math.sqrt(textLength / maxCharactersPerLine)) + 1;
+ int maxLines = Math.max((int) Math.ceil(Math.sqrt(textLength / maxCharactersPerLine)) + 1, stringLines.length);
int maxLineLength = 0;
while (numLines > maxLines) {
formattedString.setLength(0); // clears
numLines = 0;
maxLineLength = 0;
int lineLength = 0;
- String[] stringLines = textString.split("\n");
for (String line : stringLines) {
String[] lineFragments = line.split(" ");
for (String fragment : lineFragments) {
if (lineLength + fragment.length() > maxCharactersPerLine) {
formattedString.append("\n");
numLines += 1;
lineLength = 0;
}
formattedString.append(fragment);
lineLength += fragment.length();
if (lineLength > maxLineLength) {
maxLineLength = lineLength;
}
formattedString.append(" ");
lineLength += 1;
}
formattedString.append("\n");
numLines += 1;
lineLength = 0;
}
if (numLines > maxLines) {
// so we *always* increase the character count (and don't get stuck)
maxCharactersPerLine = (int) (maxCharactersPerLine * 1.05) + 1;
}
}
textString = formattedString.toString().replace(" \n", "\n"); // remove extra spaces
String[] textsToDraw = textString.split("\n");
// scale the text size appropriately (padding intentionally ignored here)
textPaint = adjustTextSize(textPaint, maxLineLength, textsToDraw.length, maxWidth, maxHeight, maxTextSize);
backgroundPadding = (int) Math.ceil(backgroundPadding / (maxTextSize / textPaint.getTextSize())) + 1;
// set up location for drawing
int lineHeight = (int) Math.ceil(Math.abs(textPaint.ascent()) + textPaint.descent());
float drawingX = 0;
float drawingY;
if (alignBottom) {
drawingY = textCanvas.getHeight() - getActualDescentSize(textsToDraw[textsToDraw.length - 1], textPaint)
- backgroundPadding;
} else {
drawingY = ((textCanvas.getHeight() + (lineHeight * (textsToDraw.length - 1))) / 2) + textPaint.descent();
}
float initialX = (maxWidth / 2) + leftOffset;
float initialY = drawingY;
float finalHeight = 0;
// draw the background box
if (backgroundColour != 0) {
String firstText = textsToDraw[0].trim();
Rect textBounds = new Rect();
textPaint.getTextBounds(firstText, 0, firstText.length(), textBounds);
float boxTop = drawingY - (lineHeight * (textsToDraw.length - 1)) - textBounds.height()
+ getActualDescentSize(firstText, textPaint) - backgroundPadding;
float boxLeft = backgroundSpanWidth ? 0 : initialX;
float boxRight = backgroundSpanWidth ? textCanvas.getWidth() : initialX;
int totalPadding = 2 * backgroundPadding;
RectF outerTextBounds = new RectF(boxLeft, boxTop, boxRight, textCanvas.getHeight());
for (String text : textsToDraw) {
float newWidth = textPaint.measureText(text.trim()) + totalPadding;
float currentWidth = outerTextBounds.width();
if (newWidth > currentWidth) {
outerTextBounds.inset(-(newWidth - currentWidth) / 2, 0);
}
}
finalHeight = outerTextBounds.height();
textPaint.setColor(backgroundColour);
textCanvas.drawRoundRect(outerTextBounds, backgroundRadius, backgroundRadius, textPaint);
} else {
finalHeight = lineHeight * (textsToDraw.length);
}
// draw the text
drawingX = initialX;
drawingY = initialY;
textPaint.setTextAlign(Align.CENTER);
textPaint.setColor(textColour);
for (int i = textsToDraw.length - 1; i >= 0; i--) {
textCanvas.drawText(textsToDraw[i].trim(), drawingX, drawingY, textPaint);
drawingY -= lineHeight;
}
return (int) Math.round(finalHeight);
}
public static float getActualDescentSize(String text, Paint textPaint) {
// find the text baseline (there seems to be no proper way to calculate *actual* (not general) descent height)
Rect descentBounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), descentBounds);
int textHeightNormal = descentBounds.height();
textPaint.getTextBounds("," + text, 0, text.length() + 1, descentBounds);
return (textHeightNormal < descentBounds.height()) ? 0 : textPaint.descent();
}
public static Paint adjustTextSize(Paint paint, int maxCharactersPerLine, int numLines, float maxWidth,
float maxHeight, int maxTextSize) {
// make sure text is small enough for its width (most common scenario)
String exampleText = "WM�1by}.acI"; // for measuring width - hacky!
float width = paint.measureText(exampleText) * maxCharactersPerLine / exampleText.length();
float newTextSize = Math.round((maxWidth / width) * paint.getTextSize());
paint.setTextSize(newTextSize);
// do the same for height
float textHeight = Math.abs(paint.ascent() - paint.descent()) * numLines;
if (textHeight > maxHeight) {
newTextSize = Math.round(newTextSize * (maxHeight / textHeight));
paint.setTextSize(newTextSize);
}
if (newTextSize > maxTextSize) {
paint.setTextSize(maxTextSize);
}
return paint;
}
public static void addBorder(Canvas borderCanvas, Paint borderPaint, int borderWidth, int borderColor) {
borderPaint.setColor(borderColor);
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setStrokeWidth(borderWidth);
borderWidth /= 2;
Rect iconBorder = new Rect(borderWidth, borderWidth, borderCanvas.getWidth() - borderWidth,
borderCanvas.getWidth() - borderWidth);
borderCanvas.drawRect(iconBorder, borderPaint);
}
public static Paint getPaint(int color, int strokeWidth) {
Paint bitmapPaint = new Paint(Paint.DEV_KERN_TEXT_FLAG);
bitmapPaint.setDither(true);
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
bitmapPaint.setSubpixelText(true);
bitmapPaint.setStrokeCap(Paint.Cap.ROUND);
bitmapPaint.setStrokeJoin(Paint.Join.ROUND);
bitmapPaint.setStrokeMiter(1);
bitmapPaint.setColor(color);
bitmapPaint.setStrokeWidth(strokeWidth);
return bitmapPaint;
}
}
| false | true | public static int drawScaledText(String textString, Canvas textCanvas, Paint textPaint, int textColour,
int backgroundColour, int backgroundPadding, int backgroundRadius, boolean alignBottom, float leftOffset,
boolean backgroundSpanWidth, float maxHeight, int maxTextSize, int maxCharactersPerLine) {
if (TextUtils.isEmpty(textString) || "".equals(textString.trim())) {
return 0;
}
float maxWidth = (int) Math.floor(textCanvas.getWidth() - leftOffset);
// split the text into lines
// TODO: respect user-created formatting more closely? (e.g., linebreaks and spaces)
int textLength = textString.length();
StringBuilder formattedString = new StringBuilder(textLength);
int numLines = Integer.MAX_VALUE;
int maxLines = (int) Math.ceil(Math.sqrt(textLength / maxCharactersPerLine)) + 1;
int maxLineLength = 0;
while (numLines > maxLines) {
formattedString.setLength(0); // clears
numLines = 0;
maxLineLength = 0;
int lineLength = 0;
String[] stringLines = textString.split("\n");
for (String line : stringLines) {
String[] lineFragments = line.split(" ");
for (String fragment : lineFragments) {
if (lineLength + fragment.length() > maxCharactersPerLine) {
formattedString.append("\n");
numLines += 1;
lineLength = 0;
}
formattedString.append(fragment);
lineLength += fragment.length();
if (lineLength > maxLineLength) {
maxLineLength = lineLength;
}
formattedString.append(" ");
lineLength += 1;
}
formattedString.append("\n");
numLines += 1;
lineLength = 0;
}
if (numLines > maxLines) {
// so we *always* increase the character count (and don't get stuck)
maxCharactersPerLine = (int) (maxCharactersPerLine * 1.05) + 1;
}
}
textString = formattedString.toString().replace(" \n", "\n"); // remove extra spaces
String[] textsToDraw = textString.split("\n");
// scale the text size appropriately (padding intentionally ignored here)
textPaint = adjustTextSize(textPaint, maxLineLength, textsToDraw.length, maxWidth, maxHeight, maxTextSize);
backgroundPadding = (int) Math.ceil(backgroundPadding / (maxTextSize / textPaint.getTextSize())) + 1;
// set up location for drawing
int lineHeight = (int) Math.ceil(Math.abs(textPaint.ascent()) + textPaint.descent());
float drawingX = 0;
float drawingY;
if (alignBottom) {
drawingY = textCanvas.getHeight() - getActualDescentSize(textsToDraw[textsToDraw.length - 1], textPaint)
- backgroundPadding;
} else {
drawingY = ((textCanvas.getHeight() + (lineHeight * (textsToDraw.length - 1))) / 2) + textPaint.descent();
}
float initialX = (maxWidth / 2) + leftOffset;
float initialY = drawingY;
float finalHeight = 0;
// draw the background box
if (backgroundColour != 0) {
String firstText = textsToDraw[0].trim();
Rect textBounds = new Rect();
textPaint.getTextBounds(firstText, 0, firstText.length(), textBounds);
float boxTop = drawingY - (lineHeight * (textsToDraw.length - 1)) - textBounds.height()
+ getActualDescentSize(firstText, textPaint) - backgroundPadding;
float boxLeft = backgroundSpanWidth ? 0 : initialX;
float boxRight = backgroundSpanWidth ? textCanvas.getWidth() : initialX;
int totalPadding = 2 * backgroundPadding;
RectF outerTextBounds = new RectF(boxLeft, boxTop, boxRight, textCanvas.getHeight());
for (String text : textsToDraw) {
float newWidth = textPaint.measureText(text.trim()) + totalPadding;
float currentWidth = outerTextBounds.width();
if (newWidth > currentWidth) {
outerTextBounds.inset(-(newWidth - currentWidth) / 2, 0);
}
}
finalHeight = outerTextBounds.height();
textPaint.setColor(backgroundColour);
textCanvas.drawRoundRect(outerTextBounds, backgroundRadius, backgroundRadius, textPaint);
} else {
finalHeight = lineHeight * (textsToDraw.length);
}
// draw the text
drawingX = initialX;
drawingY = initialY;
textPaint.setTextAlign(Align.CENTER);
textPaint.setColor(textColour);
for (int i = textsToDraw.length - 1; i >= 0; i--) {
textCanvas.drawText(textsToDraw[i].trim(), drawingX, drawingY, textPaint);
drawingY -= lineHeight;
}
return (int) Math.round(finalHeight);
}
| public static int drawScaledText(String textString, Canvas textCanvas, Paint textPaint, int textColour,
int backgroundColour, int backgroundPadding, int backgroundRadius, boolean alignBottom, float leftOffset,
boolean backgroundSpanWidth, float maxHeight, int maxTextSize, int maxCharactersPerLine) {
if (TextUtils.isEmpty(textString) || "".equals(textString.trim())) {
return 0;
}
float maxWidth = (int) Math.floor(textCanvas.getWidth() - leftOffset);
// split the text into lines
// TODO: respect user-created formatting more closely? (e.g., linebreaks and spaces)
int textLength = textString.length();
StringBuilder formattedString = new StringBuilder(textLength);
String[] stringLines = textString.split("\n");
int numLines = Integer.MAX_VALUE;
int maxLines = Math.max((int) Math.ceil(Math.sqrt(textLength / maxCharactersPerLine)) + 1, stringLines.length);
int maxLineLength = 0;
while (numLines > maxLines) {
formattedString.setLength(0); // clears
numLines = 0;
maxLineLength = 0;
int lineLength = 0;
for (String line : stringLines) {
String[] lineFragments = line.split(" ");
for (String fragment : lineFragments) {
if (lineLength + fragment.length() > maxCharactersPerLine) {
formattedString.append("\n");
numLines += 1;
lineLength = 0;
}
formattedString.append(fragment);
lineLength += fragment.length();
if (lineLength > maxLineLength) {
maxLineLength = lineLength;
}
formattedString.append(" ");
lineLength += 1;
}
formattedString.append("\n");
numLines += 1;
lineLength = 0;
}
if (numLines > maxLines) {
// so we *always* increase the character count (and don't get stuck)
maxCharactersPerLine = (int) (maxCharactersPerLine * 1.05) + 1;
}
}
textString = formattedString.toString().replace(" \n", "\n"); // remove extra spaces
String[] textsToDraw = textString.split("\n");
// scale the text size appropriately (padding intentionally ignored here)
textPaint = adjustTextSize(textPaint, maxLineLength, textsToDraw.length, maxWidth, maxHeight, maxTextSize);
backgroundPadding = (int) Math.ceil(backgroundPadding / (maxTextSize / textPaint.getTextSize())) + 1;
// set up location for drawing
int lineHeight = (int) Math.ceil(Math.abs(textPaint.ascent()) + textPaint.descent());
float drawingX = 0;
float drawingY;
if (alignBottom) {
drawingY = textCanvas.getHeight() - getActualDescentSize(textsToDraw[textsToDraw.length - 1], textPaint)
- backgroundPadding;
} else {
drawingY = ((textCanvas.getHeight() + (lineHeight * (textsToDraw.length - 1))) / 2) + textPaint.descent();
}
float initialX = (maxWidth / 2) + leftOffset;
float initialY = drawingY;
float finalHeight = 0;
// draw the background box
if (backgroundColour != 0) {
String firstText = textsToDraw[0].trim();
Rect textBounds = new Rect();
textPaint.getTextBounds(firstText, 0, firstText.length(), textBounds);
float boxTop = drawingY - (lineHeight * (textsToDraw.length - 1)) - textBounds.height()
+ getActualDescentSize(firstText, textPaint) - backgroundPadding;
float boxLeft = backgroundSpanWidth ? 0 : initialX;
float boxRight = backgroundSpanWidth ? textCanvas.getWidth() : initialX;
int totalPadding = 2 * backgroundPadding;
RectF outerTextBounds = new RectF(boxLeft, boxTop, boxRight, textCanvas.getHeight());
for (String text : textsToDraw) {
float newWidth = textPaint.measureText(text.trim()) + totalPadding;
float currentWidth = outerTextBounds.width();
if (newWidth > currentWidth) {
outerTextBounds.inset(-(newWidth - currentWidth) / 2, 0);
}
}
finalHeight = outerTextBounds.height();
textPaint.setColor(backgroundColour);
textCanvas.drawRoundRect(outerTextBounds, backgroundRadius, backgroundRadius, textPaint);
} else {
finalHeight = lineHeight * (textsToDraw.length);
}
// draw the text
drawingX = initialX;
drawingY = initialY;
textPaint.setTextAlign(Align.CENTER);
textPaint.setColor(textColour);
for (int i = textsToDraw.length - 1; i >= 0; i--) {
textCanvas.drawText(textsToDraw[i].trim(), drawingX, drawingY, textPaint);
drawingY -= lineHeight;
}
return (int) Math.round(finalHeight);
}
|
diff --git a/Request/src/edu/purdue/cs/cs180/safewalk/RequestActivity.java b/Request/src/edu/purdue/cs/cs180/safewalk/RequestActivity.java
index d866cae..4dc6d92 100644
--- a/Request/src/edu/purdue/cs/cs180/safewalk/RequestActivity.java
+++ b/Request/src/edu/purdue/cs/cs180/safewalk/RequestActivity.java
@@ -1,98 +1,98 @@
package edu.purdue.cs.cs180.safewalk;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import edu.purdue.cs.cs180.channel.ChannelException;
import edu.purdue.cs.cs180.channel.FailedToCreateChannelException;
import edu.purdue.cs.cs180.channel.MessageListener;
import edu.purdue.cs.cs180.channel.TCPChannel;
public class RequestActivity extends Activity implements MessageListener {
TCPChannel channel = null;
Handler mHandler = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
// the submit button.
final Button button = (Button) findViewById(R.id.submit_button);
final Spinner locations = (Spinner) findViewById(R.id.locations_spinner);
final TextView status = (TextView) findViewById(R.id.status_textview);
try {
channel = new Channel(getString(R.string.host_name),
Integer.parseInt(getString(R.string.port_number)));
} catch (FailedToCreateChannelException e) {
System.exit(1);
}
// A handler is needed since the message received is called from a
// different Thread, and only the main thread can update the UI.
// As a workaround, we create a handler in the main thread that displays
// whatever it receives from the message received.
mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
Message safeWalkMessage = (Message) msg.obj;
switch (safeWalkMessage.getType()) {
case Searching:
status.setText("Searching");
break;
case Assigned:
status.setText("Assigned: "+safeWalkMessage.getInfo());
- location.setEnabled(true);
- submit.setEnabled(true);
+ locations.setEnabled(true);
+ button.setEnabled(true);
break;
default:
System.err.println("Unexpected message type: "+safeWalkMessage.getType());
break;
}
}
};
// The on click event.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner locations = (Spinner) findViewById(R.id.locations_spinner);
String selectedItem = (String) locations.getSelectedItem();
locations.setEnabled(false);
button.setEnabled(false);
Message msg = new Message(Message.Type.Request,
selectedItem,
channel.getID());
try {
channel.sendMessage(msg.toString());
} catch (ChannelException e) {
System.exit(1);
}
}
});
}
@Override
public void messageReceived(String message, int clientID) {
// Create a handler message, and send it to the Main Thread.
Message safeWalkMessage = new Message(message, clientID);
android.os.Message msg = new android.os.Message();
msg.obj = safeWalkMessage;
mHandler.sendMessage(msg);
}
/**
* Close the application if sent to the background.
*/
@Override
protected void onPause() {
super.onPause();
System.exit(0);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
// the submit button.
final Button button = (Button) findViewById(R.id.submit_button);
final Spinner locations = (Spinner) findViewById(R.id.locations_spinner);
final TextView status = (TextView) findViewById(R.id.status_textview);
try {
channel = new Channel(getString(R.string.host_name),
Integer.parseInt(getString(R.string.port_number)));
} catch (FailedToCreateChannelException e) {
System.exit(1);
}
// A handler is needed since the message received is called from a
// different Thread, and only the main thread can update the UI.
// As a workaround, we create a handler in the main thread that displays
// whatever it receives from the message received.
mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
Message safeWalkMessage = (Message) msg.obj;
switch (safeWalkMessage.getType()) {
case Searching:
status.setText("Searching");
break;
case Assigned:
status.setText("Assigned: "+safeWalkMessage.getInfo());
location.setEnabled(true);
submit.setEnabled(true);
break;
default:
System.err.println("Unexpected message type: "+safeWalkMessage.getType());
break;
}
}
};
// The on click event.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner locations = (Spinner) findViewById(R.id.locations_spinner);
String selectedItem = (String) locations.getSelectedItem();
locations.setEnabled(false);
button.setEnabled(false);
Message msg = new Message(Message.Type.Request,
selectedItem,
channel.getID());
try {
channel.sendMessage(msg.toString());
} catch (ChannelException e) {
System.exit(1);
}
}
});
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
// the submit button.
final Button button = (Button) findViewById(R.id.submit_button);
final Spinner locations = (Spinner) findViewById(R.id.locations_spinner);
final TextView status = (TextView) findViewById(R.id.status_textview);
try {
channel = new Channel(getString(R.string.host_name),
Integer.parseInt(getString(R.string.port_number)));
} catch (FailedToCreateChannelException e) {
System.exit(1);
}
// A handler is needed since the message received is called from a
// different Thread, and only the main thread can update the UI.
// As a workaround, we create a handler in the main thread that displays
// whatever it receives from the message received.
mHandler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
Message safeWalkMessage = (Message) msg.obj;
switch (safeWalkMessage.getType()) {
case Searching:
status.setText("Searching");
break;
case Assigned:
status.setText("Assigned: "+safeWalkMessage.getInfo());
locations.setEnabled(true);
button.setEnabled(true);
break;
default:
System.err.println("Unexpected message type: "+safeWalkMessage.getType());
break;
}
}
};
// The on click event.
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner locations = (Spinner) findViewById(R.id.locations_spinner);
String selectedItem = (String) locations.getSelectedItem();
locations.setEnabled(false);
button.setEnabled(false);
Message msg = new Message(Message.Type.Request,
selectedItem,
channel.getID());
try {
channel.sendMessage(msg.toString());
} catch (ChannelException e) {
System.exit(1);
}
}
});
}
|
diff --git a/src/com/redhat/qe/xmlrpc/Session.java b/src/com/redhat/qe/xmlrpc/Session.java
index ffdc7fa..e405e50 100644
--- a/src/com/redhat/qe/xmlrpc/Session.java
+++ b/src/com/redhat/qe/xmlrpc/Session.java
@@ -1,101 +1,102 @@
package com.redhat.qe.xmlrpc;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.contrib.auth.NegotiateScheme;
import org.apache.commons.httpclient.params.DefaultHttpParams;
import org.apache.commons.httpclient.params.HttpParams;
import org.apache.ws.commons.util.NamespaceContextImpl;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
import org.apache.xmlrpc.common.TypeFactoryImpl;
import org.apache.xmlrpc.common.XmlRpcController;
import org.apache.xmlrpc.common.XmlRpcStreamConfig;
import org.apache.xmlrpc.parser.NullParser;
import org.apache.xmlrpc.parser.TypeParser;
import org.apache.xmlrpc.serializer.NullSerializer;
import com.redhat.qe.tools.SSLCertificateTruster;
public class Session {
protected String userName;
protected String password;
protected URL url;
protected XmlRpcClient client;
public Session(String userName, String password, URL url) {
this.userName = userName;
this.password = password;
this.url = url;
}
public void init() throws XmlRpcException, GeneralSecurityException,
IOException {
SSLCertificateTruster.trustAllCertsForApacheXMLRPC();
// setup client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(url);
client = new XmlRpcClient();
client.setConfig(config);
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);
client.setTransportFactory(factory);
factory.setHttpClient(new HttpClient());
client.setTypeFactory(new MyTypeFactory(client));
factory.getHttpClient().getState().setCredentials(
new AuthScope(url.getHost(), 443, null), new UsernamePasswordCredentials(userName, password));
// register the auth scheme
AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference
List<String> schemes = new ArrayList<String>();
+ schemes.add(AuthPolicy.BASIC);
schemes.add("Negotiate");
HttpParams params = DefaultHttpParams.getDefaultParams();
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
- Credentials use_jaas_creds = new Credentials() {};
+ Credentials use_jaas_creds = new UsernamePasswordCredentials(userName, password);
factory.getHttpClient().getState().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
}
public XmlRpcClient getClient() {
return client;
}
public class MyTypeFactory extends TypeFactoryImpl {
public MyTypeFactory(XmlRpcController pController) {
super(pController);
}
@Override
public TypeParser getParser(XmlRpcStreamConfig pConfig,
NamespaceContextImpl pContext, String pURI, String pLocalName) {
if ("".equals(pURI) && NullSerializer.NIL_TAG.equals(pLocalName)) {
return new NullParser();
} else {
return super.getParser(pConfig, pContext, pURI, pLocalName);
}
}
}
}
| false | true | public void init() throws XmlRpcException, GeneralSecurityException,
IOException {
SSLCertificateTruster.trustAllCertsForApacheXMLRPC();
// setup client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(url);
client = new XmlRpcClient();
client.setConfig(config);
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);
client.setTransportFactory(factory);
factory.setHttpClient(new HttpClient());
client.setTypeFactory(new MyTypeFactory(client));
factory.getHttpClient().getState().setCredentials(
new AuthScope(url.getHost(), 443, null), new UsernamePasswordCredentials(userName, password));
// register the auth scheme
AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference
List<String> schemes = new ArrayList<String>();
schemes.add("Negotiate");
HttpParams params = DefaultHttpParams.getDefaultParams();
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
Credentials use_jaas_creds = new Credentials() {};
factory.getHttpClient().getState().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
}
| public void init() throws XmlRpcException, GeneralSecurityException,
IOException {
SSLCertificateTruster.trustAllCertsForApacheXMLRPC();
// setup client
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
config.setServerURL(url);
client = new XmlRpcClient();
client.setConfig(config);
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(client);
client.setTransportFactory(factory);
factory.setHttpClient(new HttpClient());
client.setTypeFactory(new MyTypeFactory(client));
factory.getHttpClient().getState().setCredentials(
new AuthScope(url.getHost(), 443, null), new UsernamePasswordCredentials(userName, password));
// register the auth scheme
AuthPolicy.registerAuthScheme("Negotiate", NegotiateScheme.class);
// include the scheme in the AuthPolicy.AUTH_SCHEME_PRIORITY preference
List<String> schemes = new ArrayList<String>();
schemes.add(AuthPolicy.BASIC);
schemes.add("Negotiate");
HttpParams params = DefaultHttpParams.getDefaultParams();
params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
Credentials use_jaas_creds = new UsernamePasswordCredentials(userName, password);
factory.getHttpClient().getState().setCredentials(
new AuthScope(null, -1, null),
use_jaas_creds);
}
|
diff --git a/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/wizards/clone/GitCloneWizardTest.java b/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/wizards/clone/GitCloneWizardTest.java
index 516218da..5928e6c1 100644
--- a/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/wizards/clone/GitCloneWizardTest.java
+++ b/org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/wizards/clone/GitCloneWizardTest.java
@@ -1,278 +1,277 @@
/*******************************************************************************
* Copyright (C) 2009, Robin Rosenberg <[email protected]>
* Copyright (C) 2010, Ketan Padegaonkar <[email protected]>
* Copyright (C) 2010, Matthias Sohn <[email protected]>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.egit.ui.wizards.clone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Platform;
import org.eclipse.egit.ui.common.RepoPropertiesPage;
import org.eclipse.egit.ui.common.RepoRemoteBranchesPage;
import org.eclipse.egit.ui.common.WorkingCopyPage;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepository;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class GitCloneWizardTest extends GitCloneWizardTestBase {
@BeforeClass
public static void setup() throws Exception {
r = new SampleTestRepository(NUMBER_RANDOM_COMMITS, false);
}
@Test
public void updatesParameterFieldsInImportDialogWhenURIIsUpdated()
throws Exception {
importWizard.openWizard();
RepoPropertiesPage propertiesPage = importWizard.openCloneWizard();
propertiesPage.setURI("git://www.jgit.org/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT", "git",
"", true, "", "", false, false);
propertiesPage.appendToURI("X");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGITX",
"git", "", true, "", "", false, false);
propertiesPage.setURI("git://www.jgit.org/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT", "git",
"", true, "", "", false, false);
propertiesPage.setURI("git://user:[email protected]/EGIT");
propertiesPage.assertSourceParams(
" User not supported on git protocol.", "www.jgit.org",
"/EGIT", "git", "", true, "user", "hi", false, false);
// UI doesn't change URI even when password is entered in clear text as
// part of URI. Opinions on this may vary.
propertiesPage.assertURI("git://user:[email protected]/EGIT");
propertiesPage.setURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "", true, "user", "", true, true);
propertiesPage.setURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "", true, "user", "", true, true);
propertiesPage.setURI("ssh://user:[email protected]:33/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "33", true, "user", "hi", true, true);
propertiesPage.setURI("ssh:///EGIT");
propertiesPage.assertSourceParams(" Host required for ssh protocol.",
"", "/EGIT", "ssh", "", true, "", "", true, true);
propertiesPage.setURI("file:///some/place");
if (Platform.getOS().equals(Platform.OS_WIN32))
propertiesPage.assertSourceParams(" "
+ System.getProperty("user.dir")
+ "\\.\\some\\place does not exist.", "", "/some/place",
"file", "", false, "", "", false, false);
else
propertiesPage.assertSourceParams(" /some/place does not exist.",
"", "/some/place", "file", "", false, "", "", false, false);
// Now try changing some fields other than URI and see how the URI field
// gets changed
propertiesPage.setURI("ssh://[email protected]/EGIT");
// ..change host
bot.textWithLabel("Host:").setText("example.com");
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "user", "", true, true);
// ..change user
bot.textWithLabel("User:").setText("gitney");
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "gitney", "", true, true);
// ..change password
bot.textWithLabel("Password:").setText("fsck");
// Password is not written into the URL here!
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "gitney", "fsck", true, true);
// change port number
bot.textWithLabel("Port:").setText("99");
propertiesPage.assertURI("ssh://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "99", true, "gitney", "fsck", true, true);
// change protocol to another with user/password capability
bot.comboBoxWithLabel("Protocol:").setSelection("ftp");
propertiesPage.assertURI("ftp://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT", "ftp",
"99", true, "gitney", "fsck", true, true);
// change protocol to one without user/password capability
bot.comboBoxWithLabel("Protocol:").setSelection("git");
propertiesPage.assertURI("git://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(
" User not supported on git protocol.", "example.com", "/EGIT",
"git", "99", true, "gitney", "fsck", false, false);
// change protocol to one without host capability
bot.comboBoxWithLabel("Protocol:").setSelection("file");
propertiesPage.assertURI("file://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(
" Host not supported on file protocol.", "example.com",
"/EGIT", "file", "99", false, "gitney", "fsck", false, false);
// Local protocol with file: prefix. We need to make sure the
// local path exists as a directory so we choose user.home as
// that one should exist.
if (Platform.getOS().equals(Platform.OS_WIN32))
propertiesPage.setURI("file:///" + System.getProperty("user.home"));
else
propertiesPage.setURI("file://" + System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
- "user.home").replace('\\', '/'), "file", "", false, "", "",
+ "user.home"), "file", "", false, "", "",
false, false);
// Local protocol without file: prefix
propertiesPage.setURI(System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
- "user.home").replace('\\', '/'), "file", "", false, "", "",
+ "user.home"), "file", "", false, "", "",
false, false);
// On windows the use can choose forward or backward slashes, so add
// a case for forward slashes using the non prefixed local protocol.
if (Platform.getOS().equals(Platform.OS_WIN32)) {
- propertiesPage.setURI(System.getProperty("user.home").replace('\\',
- '/'));
+ propertiesPage.setURI(System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
- "user.home").replace('\\', '/'), "file", "", false, "", "",
+ "user.home"), "file", "", false, "", "",
false, false);
}
bot.button("Cancel").click();
}
@Test
public void canCloneARemoteRepo() throws Exception {
destRepo = new File(ResourcesPlugin.getWorkspace()
.getRoot().getLocation().toFile(), "test1");
importWizard.openWizard();
RepoPropertiesPage propertiesPage = importWizard.openCloneWizard();
RepoRemoteBranchesPage remoteBranches = propertiesPage
.nextToRemoteBranches(r.getUri());
cloneRepo(destRepo, remoteBranches);
}
@Test
public void clonedRepositoryShouldExistOnFileSystem() {
importWizard.openWizard();
RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
RepoRemoteBranchesPage remoteBranches = repoProperties
.nextToRemoteBranches(r.getUri());
remoteBranches.assertRemoteBranches(SampleTestRepository.FIX, Constants.MASTER);
WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
workingCopy.assertWorkingCopyExists();
}
@Test
public void alteringSomeParametersDuringClone() throws Exception {
destRepo = new File(ResourcesPlugin.getWorkspace()
.getRoot().getLocation().toFile(), "test2");
importWizard.openWizard();
RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
RepoRemoteBranchesPage remoteBranches = repoProperties
.nextToRemoteBranches(r.getUri());
remoteBranches.deselectAllBranches();
remoteBranches
.assertErrorMessage("At least one branch must be selected.");
remoteBranches.assertNextIsDisabled();
remoteBranches.selectBranches(SampleTestRepository.FIX);
remoteBranches.assertNextIsEnabled();
WorkingCopyPage workingCopy = remoteBranches.nextToWorkingCopy();
workingCopy.setDirectory(destRepo.toString());
workingCopy.assertBranch(SampleTestRepository.FIX);
workingCopy.setRemoteName("src");
workingCopy.waitForCreate();
// Some random sampling to see we got something. We do not test
// the integrity of the repository here. Only a few basic properties
// we'd expect from a clone made this way, that would possibly
// not hold true given other parameters in the GUI.
Repository repository = new FileRepository(new File(destRepo, Constants.DOT_GIT));
assertNotNull(repository.resolve("src/" + SampleTestRepository.FIX));
// we didn't clone that one
assertNull(repository.resolve("src/master"));
// and a local master initialized from origin/master (default!)
assertEquals(repository.resolve("stable"), repository
.resolve("src/stable"));
// A well known tag
assertNotNull(repository.resolve(Constants.R_TAGS + SampleTestRepository.v2_0_name).name());
// lots of refs
assertTrue(repository.getAllRefs().size() >= 4);
}
@Test
public void invalidHostnameFreezesDialog() throws Exception {
importWizard.openWizard();
RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
RepoRemoteBranchesPage remoteBranches = repoProperties
.nextToRemoteBranches("git://no.example.com/EGIT");
remoteBranches
.assertErrorMessage("git://no.example.com/EGIT: unknown host");
remoteBranches.assertCannotProceed();
remoteBranches.cancel();
}
// TODO: Broken, seems that this takes forever and does not come back with
// an error. Perhaps set a higher timeout for this test ?
@Ignore
public void invalidPortFreezesDialog() throws Exception {
importWizard.openWizard();
RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
RepoRemoteBranchesPage remoteBranches = repoProperties
.nextToRemoteBranches("git://localhost:80/EGIT");
remoteBranches
.assertErrorMessage("git://localhost:80/EGIT: not found.");
remoteBranches.assertCannotProceed();
remoteBranches.cancel();
}
// TODO: Broken, seems that this takes forever and does not come back with
// an error. Perhaps set a higher timeout for this test ?
@Ignore
public void timeoutToASocketFreezesDialog() throws Exception {
importWizard.openWizard();
RepoPropertiesPage repoProperties = importWizard.openCloneWizard();
RepoRemoteBranchesPage remoteBranches = repoProperties
.nextToRemoteBranches("git://www.example.com/EGIT");
remoteBranches
.assertErrorMessage("git://www.example.com/EGIT: Connection timed out");
remoteBranches.assertCannotProceed();
remoteBranches.cancel();
}
}
| false | true | public void updatesParameterFieldsInImportDialogWhenURIIsUpdated()
throws Exception {
importWizard.openWizard();
RepoPropertiesPage propertiesPage = importWizard.openCloneWizard();
propertiesPage.setURI("git://www.jgit.org/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT", "git",
"", true, "", "", false, false);
propertiesPage.appendToURI("X");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGITX",
"git", "", true, "", "", false, false);
propertiesPage.setURI("git://www.jgit.org/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT", "git",
"", true, "", "", false, false);
propertiesPage.setURI("git://user:[email protected]/EGIT");
propertiesPage.assertSourceParams(
" User not supported on git protocol.", "www.jgit.org",
"/EGIT", "git", "", true, "user", "hi", false, false);
// UI doesn't change URI even when password is entered in clear text as
// part of URI. Opinions on this may vary.
propertiesPage.assertURI("git://user:[email protected]/EGIT");
propertiesPage.setURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "", true, "user", "", true, true);
propertiesPage.setURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "", true, "user", "", true, true);
propertiesPage.setURI("ssh://user:[email protected]:33/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "33", true, "user", "hi", true, true);
propertiesPage.setURI("ssh:///EGIT");
propertiesPage.assertSourceParams(" Host required for ssh protocol.",
"", "/EGIT", "ssh", "", true, "", "", true, true);
propertiesPage.setURI("file:///some/place");
if (Platform.getOS().equals(Platform.OS_WIN32))
propertiesPage.assertSourceParams(" "
+ System.getProperty("user.dir")
+ "\\.\\some\\place does not exist.", "", "/some/place",
"file", "", false, "", "", false, false);
else
propertiesPage.assertSourceParams(" /some/place does not exist.",
"", "/some/place", "file", "", false, "", "", false, false);
// Now try changing some fields other than URI and see how the URI field
// gets changed
propertiesPage.setURI("ssh://[email protected]/EGIT");
// ..change host
bot.textWithLabel("Host:").setText("example.com");
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "user", "", true, true);
// ..change user
bot.textWithLabel("User:").setText("gitney");
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "gitney", "", true, true);
// ..change password
bot.textWithLabel("Password:").setText("fsck");
// Password is not written into the URL here!
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "gitney", "fsck", true, true);
// change port number
bot.textWithLabel("Port:").setText("99");
propertiesPage.assertURI("ssh://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "99", true, "gitney", "fsck", true, true);
// change protocol to another with user/password capability
bot.comboBoxWithLabel("Protocol:").setSelection("ftp");
propertiesPage.assertURI("ftp://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT", "ftp",
"99", true, "gitney", "fsck", true, true);
// change protocol to one without user/password capability
bot.comboBoxWithLabel("Protocol:").setSelection("git");
propertiesPage.assertURI("git://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(
" User not supported on git protocol.", "example.com", "/EGIT",
"git", "99", true, "gitney", "fsck", false, false);
// change protocol to one without host capability
bot.comboBoxWithLabel("Protocol:").setSelection("file");
propertiesPage.assertURI("file://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(
" Host not supported on file protocol.", "example.com",
"/EGIT", "file", "99", false, "gitney", "fsck", false, false);
// Local protocol with file: prefix. We need to make sure the
// local path exists as a directory so we choose user.home as
// that one should exist.
if (Platform.getOS().equals(Platform.OS_WIN32))
propertiesPage.setURI("file:///" + System.getProperty("user.home"));
else
propertiesPage.setURI("file://" + System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
"user.home").replace('\\', '/'), "file", "", false, "", "",
false, false);
// Local protocol without file: prefix
propertiesPage.setURI(System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
"user.home").replace('\\', '/'), "file", "", false, "", "",
false, false);
// On windows the use can choose forward or backward slashes, so add
// a case for forward slashes using the non prefixed local protocol.
if (Platform.getOS().equals(Platform.OS_WIN32)) {
propertiesPage.setURI(System.getProperty("user.home").replace('\\',
'/'));
propertiesPage.assertSourceParams(null, "", System.getProperty(
"user.home").replace('\\', '/'), "file", "", false, "", "",
false, false);
}
bot.button("Cancel").click();
}
| public void updatesParameterFieldsInImportDialogWhenURIIsUpdated()
throws Exception {
importWizard.openWizard();
RepoPropertiesPage propertiesPage = importWizard.openCloneWizard();
propertiesPage.setURI("git://www.jgit.org/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT", "git",
"", true, "", "", false, false);
propertiesPage.appendToURI("X");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGITX",
"git", "", true, "", "", false, false);
propertiesPage.setURI("git://www.jgit.org/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT", "git",
"", true, "", "", false, false);
propertiesPage.setURI("git://user:[email protected]/EGIT");
propertiesPage.assertSourceParams(
" User not supported on git protocol.", "www.jgit.org",
"/EGIT", "git", "", true, "user", "hi", false, false);
// UI doesn't change URI even when password is entered in clear text as
// part of URI. Opinions on this may vary.
propertiesPage.assertURI("git://user:[email protected]/EGIT");
propertiesPage.setURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "", true, "user", "", true, true);
propertiesPage.setURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "", true, "user", "", true, true);
propertiesPage.setURI("ssh://user:[email protected]:33/EGIT");
propertiesPage.assertSourceParams(null, "www.jgit.org", "/EGIT",
"ssh", "33", true, "user", "hi", true, true);
propertiesPage.setURI("ssh:///EGIT");
propertiesPage.assertSourceParams(" Host required for ssh protocol.",
"", "/EGIT", "ssh", "", true, "", "", true, true);
propertiesPage.setURI("file:///some/place");
if (Platform.getOS().equals(Platform.OS_WIN32))
propertiesPage.assertSourceParams(" "
+ System.getProperty("user.dir")
+ "\\.\\some\\place does not exist.", "", "/some/place",
"file", "", false, "", "", false, false);
else
propertiesPage.assertSourceParams(" /some/place does not exist.",
"", "/some/place", "file", "", false, "", "", false, false);
// Now try changing some fields other than URI and see how the URI field
// gets changed
propertiesPage.setURI("ssh://[email protected]/EGIT");
// ..change host
bot.textWithLabel("Host:").setText("example.com");
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "user", "", true, true);
// ..change user
bot.textWithLabel("User:").setText("gitney");
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "gitney", "", true, true);
// ..change password
bot.textWithLabel("Password:").setText("fsck");
// Password is not written into the URL here!
propertiesPage.assertURI("ssh://[email protected]/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "", true, "gitney", "fsck", true, true);
// change port number
bot.textWithLabel("Port:").setText("99");
propertiesPage.assertURI("ssh://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT",
"ssh", "99", true, "gitney", "fsck", true, true);
// change protocol to another with user/password capability
bot.comboBoxWithLabel("Protocol:").setSelection("ftp");
propertiesPage.assertURI("ftp://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(null, "example.com", "/EGIT", "ftp",
"99", true, "gitney", "fsck", true, true);
// change protocol to one without user/password capability
bot.comboBoxWithLabel("Protocol:").setSelection("git");
propertiesPage.assertURI("git://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(
" User not supported on git protocol.", "example.com", "/EGIT",
"git", "99", true, "gitney", "fsck", false, false);
// change protocol to one without host capability
bot.comboBoxWithLabel("Protocol:").setSelection("file");
propertiesPage.assertURI("file://[email protected]:99/EGIT");
propertiesPage.assertSourceParams(
" Host not supported on file protocol.", "example.com",
"/EGIT", "file", "99", false, "gitney", "fsck", false, false);
// Local protocol with file: prefix. We need to make sure the
// local path exists as a directory so we choose user.home as
// that one should exist.
if (Platform.getOS().equals(Platform.OS_WIN32))
propertiesPage.setURI("file:///" + System.getProperty("user.home"));
else
propertiesPage.setURI("file://" + System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
"user.home"), "file", "", false, "", "",
false, false);
// Local protocol without file: prefix
propertiesPage.setURI(System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
"user.home"), "file", "", false, "", "",
false, false);
// On windows the use can choose forward or backward slashes, so add
// a case for forward slashes using the non prefixed local protocol.
if (Platform.getOS().equals(Platform.OS_WIN32)) {
propertiesPage.setURI(System.getProperty("user.home"));
propertiesPage.assertSourceParams(null, "", System.getProperty(
"user.home"), "file", "", false, "", "",
false, false);
}
bot.button("Cancel").click();
}
|
diff --git a/srcj/com/sun/electric/technology/technologies/MoCMOS.java b/srcj/com/sun/electric/technology/technologies/MoCMOS.java
index 1d9e221c6..14d520014 100644
--- a/srcj/com/sun/electric/technology/technologies/MoCMOS.java
+++ b/srcj/com/sun/electric/technology/technologies/MoCMOS.java
@@ -1,1208 +1,1214 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: MoCMOS.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.technology.technologies;
import com.sun.electric.database.ImmutableNodeInst;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.text.Setting;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.AbstractShapeBuilder;
import com.sun.electric.technology.DRCRules;
import com.sun.electric.technology.DRCTemplate;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitivePort;
import com.sun.electric.technology.TechFactory;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.XMLRules;
import com.sun.electric.technology.Xml;
import com.sun.electric.tool.drc.DRC;
import com.sun.electric.tool.user.User;
import java.io.PrintWriter;
import java.util.*;
/**
* This is the MOSIS CMOS technology.
*/
public class MoCMOS extends Technology
{
/** Value for standard SCMOS rules. */ public static final int SCMOSRULES = 0;
/** Value for submicron rules. */ public static final int SUBMRULES = 1;
/** Value for deep rules. */ public static final int DEEPRULES = 2;
/** key of Variable for saving technology state. */
public static final Variable.Key TECH_LAST_STATE = Variable.newKey("TECH_last_state");
public static final Version changeOfMetal6 = Version.parseVersion("8.02o"); // Fix of bug #357
private static final String TECH_NAME = "mocmos";
private static final String XML_PREFIX = TECH_NAME + ".";
private static final String PREF_PREFIX = "technology/technologies/";
private static final TechFactory.Param techParamRuleSet =
new TechFactory.Param(XML_PREFIX + "MOCMOS Rule Set", PREF_PREFIX + "MoCMOSRuleSet", Integer.valueOf(1));
private static final TechFactory.Param techParamNumMetalLayers =
new TechFactory.Param(XML_PREFIX + "NumMetalLayers", PREF_PREFIX + TECH_NAME + "NumberOfMetalLayers", Integer.valueOf(6));
private static final TechFactory.Param techParamUseSecondPolysilicon =
new TechFactory.Param(XML_PREFIX +"UseSecondPolysilicon", PREF_PREFIX + TECH_NAME + "SecondPolysilicon", Boolean.TRUE);
private static final TechFactory.Param techParamDisallowStackedVias =
new TechFactory.Param(XML_PREFIX + "DisallowStackedVias", PREF_PREFIX + "MoCMOSDisallowStackedVias", Boolean.FALSE);
private static final TechFactory.Param techParamUseAlternativeActivePolyRules =
new TechFactory.Param(XML_PREFIX + "UseAlternativeActivePolyRules", PREF_PREFIX + "MoCMOSAlternateActivePolyRules", Boolean.FALSE);
private static final TechFactory.Param techParamAnalog =
new TechFactory.Param(XML_PREFIX + "Analog", PREF_PREFIX + TECH_NAME + "Analog", Boolean.FALSE);
// Tech params
private Integer paramRuleSet;
private Boolean paramUseSecondPolysilicon;
private Boolean paramDisallowStackedVias;
private Boolean paramUseAlternativeActivePolyRules;
private Boolean paramAnalog;
// nodes. Storing nodes only whe they are need in outside the constructor
/** metal-1-P/N-active-contacts */ private PrimitiveNode[] metalActiveContactNodes = new PrimitiveNode[2];
/** Scalable Transistors */ private PrimitiveNode[] scalableTransistorNodes = new PrimitiveNode[2];
// -------------------- private and protected methods ------------------------
public MoCMOS(Generic generic, TechFactory techFactory, Map<TechFactory.Param,Object> techParams, Xml.Technology t) {
super(generic, techFactory, techParams, t);
paramRuleSet = (Integer)techParams.get(techParamRuleSet);
paramNumMetalLayers = (Integer)techParams.get(techParamNumMetalLayers);
paramUseSecondPolysilicon = (Boolean)techParams.get(techParamUseSecondPolysilicon);
paramDisallowStackedVias = (Boolean)techParams.get(techParamDisallowStackedVias);
paramUseAlternativeActivePolyRules = (Boolean)techParams.get(techParamUseAlternativeActivePolyRules);
paramAnalog = (Boolean)techParams.get(techParamAnalog);
setStaticTechnology();
//setFactoryResolution(0.01); // value in lambdas 0.005um -> 0.05 lambdas
//**************************************** NODES ****************************************
metalActiveContactNodes[P_TYPE] = findNodeProto("Metal-1-P-Active-Con");
metalActiveContactNodes[N_TYPE] = findNodeProto("Metal-1-N-Active-Con");
scalableTransistorNodes[P_TYPE] = findNodeProto("P-Transistor-Scalable");
scalableTransistorNodes[N_TYPE] = findNodeProto("N-Transistor-Scalable");
for (Iterator<Layer> it = getLayers(); it.hasNext(); ) {
Layer layer = it.next();
if (!layer.getFunction().isUsed(getNumMetals(), isSecondPolysilicon() ? 2 : 1))
layer.getPureLayerNode().setNotUsed(true);
}
PrimitiveNode np = findNodeProto("P-Transistor-Scalable");
if (np != null) np.setCanShrink();
np = findNodeProto("N-Transistor-Scalable");
if (np != null) np.setCanShrink();
np = findNodeProto("NPN-Transistor");
if (np != null) np.setCanShrink();
}
/******************** SUPPORT METHODS ********************/
@Override
protected void copyState(Technology that) {
super.copyState(that);
MoCMOS mocmos = (MoCMOS)that;
paramRuleSet = mocmos.paramRuleSet;
paramNumMetalLayers = mocmos.paramNumMetalLayers;
paramUseSecondPolysilicon = mocmos.paramUseSecondPolysilicon;
paramDisallowStackedVias = mocmos.paramDisallowStackedVias;
paramUseAlternativeActivePolyRules = mocmos.paramUseAlternativeActivePolyRules;
paramAnalog = mocmos.paramAnalog;
}
@Override
protected void dumpExtraProjectSettings(PrintWriter out, Map<Setting,Object> settings) {
printlnSetting(out, settings, getRuleSetSetting());
printlnSetting(out, settings, getSecondPolysiliconSetting());
printlnSetting(out, settings, getDisallowStackedViasSetting());
printlnSetting(out, settings, getAlternateActivePolyRulesSetting());
printlnSetting(out, settings, getAnalogSetting());
}
/******************** SCALABLE TRANSISTOR DESCRIPTION ********************/
private static final int SCALABLE_ACTIVE_TOP = 0;
private static final int SCALABLE_METAL_TOP = 1;
private static final int SCALABLE_CUT_TOP = 2;
private static final int SCALABLE_ACTIVE_BOT = 3;
private static final int SCALABLE_METAL_BOT = 4;
private static final int SCALABLE_CUT_BOT = 5;
private static final int SCALABLE_ACTIVE_CTR = 6;
private static final int SCALABLE_POLY = 7;
private static final int SCALABLE_WELL = 8;
private static final int SCALABLE_SUBSTRATE = 9;
private static final int SCALABLE_TOTAL = 10;
/**
* Puts into shape builder s the polygons that describe node "n", given a set of
* NodeLayer objects to use.
* This method is overridden by specific Technologys.
* @param b shape builder where to put polygons
* @param n the ImmutableNodeInst that is being described.
* @param pn proto of the ImmutableNodeInst in this Technology
* @param primLayers an array of NodeLayer objects to convert to Poly objects.
* The prototype of this NodeInst must be a PrimitiveNode and not a Cell.
*/
@Override
protected void genShapeOfNode(AbstractShapeBuilder b, ImmutableNodeInst n, PrimitiveNode pn, Technology.NodeLayer[] primLayers) {
if (pn != scalableTransistorNodes[P_TYPE] && pn != scalableTransistorNodes[N_TYPE]) {
b.genShapeOfNode(n, pn, primLayers, null);
return;
}
genShapeOfNodeScalable(b, n, pn, null, b.isReasonable());
}
/**
* Special getShapeOfNode function for scalable transistors
* @param m
* @param n
* @param pn
* @param context
* @param reasonable
* @return Array of Poly containing layers representing a Scalable Transistor
*/
private void genShapeOfNodeScalable(AbstractShapeBuilder b, ImmutableNodeInst n, PrimitiveNode pn, VarContext context, boolean reasonable)
{
// determine special configurations (number of active contacts, inset of active contacts)
int numContacts = 2;
boolean insetContacts = false;
String pt = n.getVarValue(TRANS_CONTACT, String.class);
if (pt != null)
{
for(int i=0; i<pt.length(); i++)
{
char chr = pt.charAt(i);
if (chr == '0' || chr == '1' || chr == '2')
{
numContacts = chr - '0';
} else if (chr == 'i' || chr == 'I') insetContacts = true;
}
}
int boxOffset = 6 - numContacts * 3;
// determine width
double activeWidMax = n.size.getLambdaX() + 3;
// double nodeWid = ni.getXSize();
// double activeWidMax = nodeWid - 14;
double activeWid = activeWidMax;
Variable var = n.getVar(Schematics.ATTR_WIDTH);
if (var != null)
{
VarContext evalContext = context;
if (evalContext == null) evalContext = VarContext.globalContext;
NodeInst ni = null; // dummy node inst
String extra = var.describe(evalContext, ni);
Object o = evalContext.evalVar(var, ni);
if (o != null) extra = o.toString();
double requestedWid = TextUtils.atof(extra);
if (requestedWid > activeWid)
{
System.out.println("Warning: " + b.getCellBackup().toString() + ", " +
n.name + " requests width of " + requestedWid + " but is only " + activeWid + " wide");
}
if (requestedWid < activeWid && requestedWid > 0)
{
activeWid = requestedWid;
}
}
double shrinkGate = 0.5*(activeWidMax - activeWid);
// contacts must be 5 wide at a minimum
double shrinkCon = (int)(0.5*(activeWidMax + 2 - Math.max(activeWid, 5)));
// now compute the number of polygons
Technology.NodeLayer [] layers = pn.getNodeLayers();
assert layers.length == SCALABLE_TOTAL;
int count = SCALABLE_TOTAL - boxOffset;
Technology.NodeLayer [] newNodeLayers = new Technology.NodeLayer[count];
// load the basic layers
int fillIndex = 0;
for(int box = boxOffset; box < SCALABLE_TOTAL; box++)
{
TechPoint [] oldPoints = layers[box].getPoints();
TechPoint [] points = new TechPoint[oldPoints.length];
for(int i=0; i<oldPoints.length; i++) points[i] = oldPoints[i];
double shrinkX = 0;
TechPoint p0 = points[0];
TechPoint p1 = points[1];
double x0 = p0.getX().getAdder();
double x1 = p1.getX().getAdder();
double y0 = p0.getY().getAdder();
double y1 = p1.getY().getAdder();
switch (box)
{
case SCALABLE_ACTIVE_TOP:
case SCALABLE_METAL_TOP:
case SCALABLE_CUT_TOP:
shrinkX = shrinkCon;
if (insetContacts) {
y0 -= 0.5;
y1 -= 0.5;
}
break;
case SCALABLE_ACTIVE_BOT:
case SCALABLE_METAL_BOT:
case SCALABLE_CUT_BOT:
shrinkX = shrinkCon;
if (insetContacts) {
y0 -= 0.5;
y1 -= 0.5;
}
break;
case SCALABLE_ACTIVE_CTR: // active that passes through gate
case SCALABLE_POLY: // poly
shrinkX = shrinkGate;
break;
case SCALABLE_WELL: // well and select
case SCALABLE_SUBSTRATE:
if (insetContacts) {
y0 += 0.5;
y1 -= 0.5;
}
break;
}
x0 += shrinkX;
x1 -= shrinkX;
points[0] = p0.withX(p0.getX().withAdder(x0)).withY(p0.getY().withAdder(y0));
points[1] = p1.withX(p1.getX().withAdder(x1)).withY(p1.getY().withAdder(y1));
Technology.NodeLayer oldNl = layers[box];
if (oldNl.getRepresentation() == NodeLayer.MULTICUTBOX)
newNodeLayers[fillIndex] = Technology.NodeLayer.makeMulticut(oldNl.getLayer(), oldNl.getPortNum(),
oldNl.getStyle(), points, oldNl.getMulticutSizeX(), oldNl.getMulticutSizeY(), oldNl.getMulticutSep1D(), oldNl.getMulticutSep2D());
else
newNodeLayers[fillIndex] = new Technology.NodeLayer(oldNl.getLayer(), oldNl.getPortNum(),
oldNl.getStyle(), oldNl.getRepresentation(), points);
fillIndex++;
}
// now let the superclass convert it to Polys
b.genShapeOfNode(n, pn, newNodeLayers, null);
}
/******************** PARAMETERIZABLE DESIGN RULES ********************/
/**
* Method to build "factory" design rules, given the current technology settings.
* @return the "factory" design rules for this Technology.
* Returns null if there is an error loading the rules.
*/
@Override
protected XMLRules makeFactoryDesignRules()
{
Foundry foundry = getSelectedFoundry();
List<DRCTemplate> theRules = foundry.getRules();
XMLRules rules = new XMLRules(this);
boolean pWellProcess = User.isPWellProcessLayoutTechnology();
assert(foundry != null);
// load the DRC tables from the explanation table
int numMetals = getNumMetals();
int rulesMode = getRuleSet();
for(int pass=0; pass<2; pass++)
{
for(DRCTemplate rule : theRules)
{
// see if the rule applies
if (pass == 0)
{
if (rule.ruleType == DRCTemplate.DRCRuleType.NODSIZ) continue;
} else
{
if (rule.ruleType != DRCTemplate.DRCRuleType.NODSIZ) continue;
}
int when = rule.when;
boolean goodrule = true;
if ((when&(DRCTemplate.DRCMode.DE.mode()|DRCTemplate.DRCMode.SU.mode()|DRCTemplate.DRCMode.SC.mode())) != 0)
{
switch (rulesMode)
{
case DEEPRULES: if ((when&DRCTemplate.DRCMode.DE.mode()) == 0) goodrule = false; break;
case SUBMRULES: if ((when&DRCTemplate.DRCMode.SU.mode()) == 0) goodrule = false; break;
case SCMOSRULES: if ((when&DRCTemplate.DRCMode.SC.mode()) == 0) goodrule = false; break;
}
if (!goodrule) continue;
}
if ((when&(DRCTemplate.DRCMode.M2.mode()|DRCTemplate.DRCMode.M3.mode()|DRCTemplate.DRCMode.M4.mode()|DRCTemplate.DRCMode.M5.mode()|DRCTemplate.DRCMode.M6.mode())) != 0)
{
switch (numMetals)
{
case 2: if ((when&DRCTemplate.DRCMode.M2.mode()) == 0) goodrule = false; break;
case 3: if ((when&DRCTemplate.DRCMode.M3.mode()) == 0) goodrule = false; break;
case 4: if ((when&DRCTemplate.DRCMode.M4.mode()) == 0) goodrule = false; break;
case 5: if ((when&DRCTemplate.DRCMode.M5.mode()) == 0) goodrule = false; break;
case 6: if ((when&DRCTemplate.DRCMode.M6.mode()) == 0) goodrule = false; break;
}
if (!goodrule) continue;
}
if ((when&DRCTemplate.DRCMode.AC.mode()) != 0)
{
if (!isAlternateActivePolyRules()) continue;
}
if ((when&DRCTemplate.DRCMode.NAC.mode()) != 0)
{
if (isAlternateActivePolyRules()) continue;
}
if ((when&DRCTemplate.DRCMode.SV.mode()) != 0)
{
if (isDisallowStackedVias()) continue;
}
if ((when&DRCTemplate.DRCMode.NSV.mode()) != 0)
{
if (!isDisallowStackedVias()) continue;
}
if ((when&DRCTemplate.DRCMode.AN.mode()) != 0)
{
if (!isAnalog()) continue;
}
// get more information about the rule
String proc = "";
if ((when&(DRCTemplate.DRCMode.DE.mode()|DRCTemplate.DRCMode.SU.mode()|DRCTemplate.DRCMode.SC.mode())) != 0)
{
switch (rulesMode)
{
case DEEPRULES: proc = "DEEP"; break;
case SUBMRULES: proc = "SUBM"; break;
case SCMOSRULES: proc = "SCMOS"; break;
}
}
String metal = "";
if ((when&(DRCTemplate.DRCMode.M2.mode()|DRCTemplate.DRCMode.M3.mode()|DRCTemplate.DRCMode.M4.mode()|DRCTemplate.DRCMode.M5.mode()|DRCTemplate.DRCMode.M6.mode())) != 0)
{
switch (getNumMetals())
{
case 2: metal = "2m"; break;
case 3: metal = "3m"; break;
case 4: metal = "4m"; break;
case 5: metal = "5m"; break;
case 6: metal = "6m"; break;
}
if (!goodrule) continue;
}
String ruleName = rule.ruleName;
String extraString = metal + proc;
if (extraString.length() > 0 && ruleName.indexOf(extraString) == -1) {
rule = new DRCTemplate(rule);
rule.ruleName += ", " + extraString;
}
rules.loadDRCRules(this, foundry, rule, pWellProcess);
}
}
return rules;
}
@Override
public SizeCorrector getSizeCorrector(Version version, Map<Setting,Object> projectSettings, boolean isJelib, boolean keepExtendOverMin) {
SizeCorrector sc = super.getSizeCorrector(version, projectSettings, isJelib, keepExtendOverMin);
if (!keepExtendOverMin) return sc;
boolean newDefaults = version.compareTo(Version.parseVersion("8.04u")) >= 0;
int numMetals = newDefaults ? 6 : 4;
boolean isSecondPolysilicon = newDefaults ? true : false;
int ruleSet = SUBMRULES;
Object numMetalsValue = projectSettings.get(getNumMetalsSetting());
if (numMetalsValue instanceof Integer)
numMetals = ((Integer)numMetalsValue).intValue();
Object secondPolysiliconValue = projectSettings.get(getSecondPolysiliconSetting());
if (secondPolysiliconValue instanceof Boolean)
isSecondPolysilicon = ((Boolean)secondPolysiliconValue).booleanValue();
else if (secondPolysiliconValue instanceof Integer)
isSecondPolysilicon = ((Integer)secondPolysiliconValue).intValue() != 0;
Object ruleSetValue = projectSettings.get(getRuleSetSetting());
if (ruleSetValue instanceof Integer)
ruleSet = ((Integer)ruleSetValue).intValue();
if (numMetals == getNumMetals() && isSecondPolysilicon == isSecondPolysilicon() && ruleSet == getRuleSet() && version.compareTo(changeOfMetal6) >= 0)
return sc;
setArcCorrection(sc, "Polysilicon-2", ruleSet == SCMOSRULES ? 3 : 7);
setArcCorrection(sc, "Metal-3", numMetals <= 3 ? (ruleSet == SCMOSRULES ? 6 : 5) : 3);
setArcCorrection(sc, "Metal-4", numMetals <= 4 ? 6 : 3);
setArcCorrection(sc, "Metal-5", numMetals <= 5 ? 4 : 3);
if (version.compareTo(changeOfMetal6) < 0) // Fix of bug #357
setArcCorrection(sc, "Metal-6", 4);
return sc;
}
/******************** OPTIONS ********************/
private final Setting cacheRuleSet = makeIntSetting("MoCMOSRuleSet", "Technology tab", "MOSIS CMOS rule set",
techParamRuleSet.xmlPath.substring(TECH_NAME.length() + 1), 1, "SCMOS", "Submicron", "Deep");
/**
* Method to tell the current rule set for this Technology if Mosis is the foundry.
* @return the current rule set for this Technology:<BR>
* 0: SCMOS rules<BR>
* 1: Submicron rules (the default)<BR>
* 2: Deep rules
*/
public int getRuleSet() { return paramRuleSet.intValue(); }
// private static DRCTemplate.DRCMode getRuleMode()
// {
// switch (getRuleSet())
// {
// case DEEPRULES: return DRCTemplate.DRCMode.DE;
// case SUBMRULES: return DRCTemplate.DRCMode.SU;
// case SCMOSRULES: return DRCTemplate.DRCMode.SC;
// }
// return null;
// }
/**
* Method to set the rule set for this Technology.
* @return the new rule setting for this Technology, with values:<BR>
* 0: SCMOS rules<BR>
* 1: Submicron rules<BR>
* 2: Deep rules
*/
public Setting getRuleSetSetting() { return cacheRuleSet; }
private final Setting cacheSecondPolysilicon = makeBooleanSetting(getTechName() + "SecondPolysilicon", "Technology tab", getTechName().toUpperCase() + " CMOS: Second Polysilicon Layer",
techParamUseSecondPolysilicon.xmlPath.substring(TECH_NAME.length() + 1), true);
/**
* Method to tell the number of polysilicon layers in this Technology.
* The default is false.
* @return true if there are 2 polysilicon layers in this Technology.
* If false, there is only 1 polysilicon layer.
*/
public boolean isSecondPolysilicon() { return paramUseSecondPolysilicon.booleanValue(); }
/**
* Returns project preferences to tell a second polysilicon layer in this Technology.
* @return project preferences to tell a second polysilicon layer in this Technology.
*/
public Setting getSecondPolysiliconSetting() { return cacheSecondPolysilicon; }
private final Setting cacheDisallowStackedVias = makeBooleanSetting("MoCMOSDisallowStackedVias", "Technology tab", "MOSIS CMOS: Disallow Stacked Vias",
techParamDisallowStackedVias.xmlPath.substring(TECH_NAME.length() + 1), false);
/**
* Method to determine whether this Technology disallows stacked vias.
* The default is false (they are allowed).
* @return true if the MOCMOS technology disallows stacked vias.
*/
public boolean isDisallowStackedVias() { return paramDisallowStackedVias.booleanValue(); }
/**
* Returns project preferences to tell whether this Technology disallows stacked vias.
* @return project preferences to tell whether this Technology disallows stacked vias.
*/
public Setting getDisallowStackedViasSetting() { return cacheDisallowStackedVias; }
private final Setting cacheAlternateActivePolyRules = makeBooleanSetting("MoCMOSAlternateActivePolyRules", "Technology tab", "MOSIS CMOS: Alternate Active and Poly Contact Rules",
techParamUseAlternativeActivePolyRules.xmlPath.substring(TECH_NAME.length() + 1), false);
/**
* Method to determine whether this Technology is using alternate Active and Poly contact rules.
* The default is false.
* @return true if the MOCMOS technology is using alternate Active and Poly contact rules.
*/
public boolean isAlternateActivePolyRules() { return paramUseAlternativeActivePolyRules.booleanValue(); }
/**
* Returns project preferences to tell whether this Technology is using alternate Active and Poly contact rules.
* @return project preferences to tell whether this Technology is using alternate Active and Poly contact rules.
*/
public Setting getAlternateActivePolyRulesSetting() { return cacheAlternateActivePolyRules; }
private final Setting cacheAnalog = makeBooleanSetting(getTechName() + "Analog", "Technology tab", "MOSIS CMOS: Vertical NPN transistor pbase",
techParamAnalog.xmlPath.substring(TECH_NAME.length() + 1), false);
/**
* Method to tell whether this technology has layers for vertical NPN transistor pbase.
* The default is false.
* @return true if this Technology has layers for vertical NPN transistor pbase.
*/
public boolean isAnalog() { return paramAnalog.booleanValue(); }
/**
* Returns project preferences to tell whether this technology has layers for vertical NPN transistor pbase.
* @return project preferences to tell whether this technology has layers for vertical NPN transistor pbase.
*/
public Setting getAnalogSetting() { return cacheAnalog; }
/** set if no stacked vias allowed */ private static final int MOCMOSNOSTACKEDVIAS = 01;
// /** set for stick-figure display */ private static final int MOCMOSSTICKFIGURE = 02;
/** number of metal layers */ private static final int MOCMOSMETALS = 034;
/** 2-metal rules */ private static final int MOCMOS2METAL = 0;
/** 3-metal rules */ private static final int MOCMOS3METAL = 04;
/** 4-metal rules */ private static final int MOCMOS4METAL = 010;
/** 5-metal rules */ private static final int MOCMOS5METAL = 014;
/** 6-metal rules */ private static final int MOCMOS6METAL = 020;
/** type of rules */ private static final int MOCMOSRULESET = 0140;
/** set if submicron rules in use */ private static final int MOCMOSSUBMRULES = 0;
/** set if deep rules in use */ private static final int MOCMOSDEEPRULES = 040;
/** set if standard SCMOS rules in use */ private static final int MOCMOSSCMOSRULES = 0100;
/** set to use alternate active/poly rules */ private static final int MOCMOSALTAPRULES = 0200;
/** set to use second polysilicon layer */ private static final int MOCMOSTWOPOLY = 0400;
// /** set to show special transistors */ private static final int MOCMOSSPECIALTRAN = 01000;
/**
* Method to convert any old-style state information to the new options.
*/
/**
* Method to convert any old-style variable information to the new options.
* May be overrideen in subclasses.
* @param varName name of variable
* @param value value of variable
* @return true if variable was converted
*/
@Override
public Map<Setting,Object> convertOldVariable(String varName, Object value)
{
if (varName.equals("MoCMOSNumberOfMetalLayers") || varName.equals("MOCMOSNumberOfMetalLayers"))
return Collections.singletonMap(getNumMetalsSetting(), value);
if (varName.equals("MoCMOSSecondPolysilicon"))
return Collections.singletonMap(getSecondPolysiliconSetting(), value);
if (!varName.equalsIgnoreCase(TECH_LAST_STATE.getName())) return null;
if (!(value instanceof Integer)) return null;
int oldBits = ((Integer)value).intValue();
HashMap<Setting,Object> settings = new HashMap<Setting,Object>();
boolean oldNoStackedVias = (oldBits&MOCMOSNOSTACKEDVIAS) != 0;
settings.put(getDisallowStackedViasSetting(), new Integer(oldNoStackedVias?1:0));
int numMetals = 0;
switch (oldBits&MOCMOSMETALS)
{
case MOCMOS2METAL: numMetals = 2; break;
case MOCMOS3METAL: numMetals = 3; break;
case MOCMOS4METAL: numMetals = 4; break;
case MOCMOS5METAL: numMetals = 5; break;
case MOCMOS6METAL: numMetals = 6; break;
}
settings.put(getNumMetalsSetting(), new Integer(numMetals));
int ruleSet = 0;
switch (oldBits&MOCMOSRULESET)
{
case MOCMOSSUBMRULES: ruleSet = SUBMRULES; break;
case MOCMOSDEEPRULES: ruleSet = DEEPRULES; break;
case MOCMOSSCMOSRULES: ruleSet = SCMOSRULES; break;
}
settings.put(getRuleSetSetting(), new Integer(ruleSet));
boolean alternateContactRules = (oldBits&MOCMOSALTAPRULES) != 0;
settings.put(getAlternateActivePolyRulesSetting(), new Integer(alternateContactRules?1:0));
boolean secondPoly = (oldBits&MOCMOSTWOPOLY) != 0;
settings.put(getSecondPolysiliconSetting(), new Integer(secondPoly?1:0));
return settings;
}
/**
* This method is called from TechFactory by reflection. Don't remove.
* Returns a list of TechFactory.Params affecting this Technology
* @return list of TechFactory.Params affecting this Technology
*/
public static List<TechFactory.Param> getTechParams() {
return Arrays.asList(
techParamRuleSet,
techParamNumMetalLayers,
techParamUseSecondPolysilicon,
techParamDisallowStackedVias,
techParamUseAlternativeActivePolyRules,
techParamAnalog);
}
/**
* This method is called from TechFactory by reflection. Don't remove.
* Returns patched Xml description of this Technology for specified technology params
* @param params values of technology params
* @return patched Xml description of this Technology
*/
public static Xml.Technology getPatchedXml(Map<TechFactory.Param,Object> params) {
int ruleSet = ((Integer)params.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)params.get(techParamNumMetalLayers)).intValue();
boolean secondPolysilicon = ((Boolean)params.get(techParamUseSecondPolysilicon)).booleanValue();
boolean disallowStackedVias = ((Boolean)params.get(techParamDisallowStackedVias)).booleanValue();
boolean alternateContactRules = ((Boolean)params.get(techParamUseAlternativeActivePolyRules)).booleanValue();
boolean isAnalog = ((Boolean)params.get(techParamAnalog)).booleanValue();
Xml.Technology tech = Xml.parseTechnology(MoCMOS.class.getResource("mocmos.xml"));
if (tech == null) // errors while reading the XML file
return null;
Xml.Layer[] metalLayers = new Xml.Layer[6];
Xml.ArcProto[] metalArcs = new Xml.ArcProto[6];
Xml.ArcProto[] activeArcs = new Xml.ArcProto[2];
Xml.ArcProto[] polyArcs = new Xml.ArcProto[6];
Xml.PrimitiveNodeGroup[] metalPinNodes = new Xml.PrimitiveNodeGroup[9];
Xml.PrimitiveNodeGroup[] activePinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] polyPinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalContactNodes = new Xml.PrimitiveNodeGroup[8];
Xml.PrimitiveNodeGroup[] metalWellContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalActiveContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metal1PolyContactNodes = new Xml.PrimitiveNodeGroup[3];
Xml.PrimitiveNodeGroup[] transistorNodeGroups = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] scalableTransistorNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup npnTransistorNode = tech.findNodeGroup("NPN-Transistor");
Xml.PrimitiveNodeGroup polyCapNode = tech.findNodeGroup("Poly-Capacitor");
List<Xml.PrimitiveNodeGroup> analogElems = new ArrayList<Xml.PrimitiveNodeGroup>();
analogElems.add(tech.findNodeGroup("NPN-Transistor"));
+ analogElems.add(tech.findNodeGroup("Hi-Poly-Resistor"));
+ analogElems.add(tech.findNodeGroup("P-Active-Resistor"));
+ analogElems.add(tech.findNodeGroup("N-Active-Resistor"));
+ analogElems.add(tech.findNodeGroup("P-Well-Resistor"));
+ analogElems.add(tech.findNodeGroup("N-Well-Resistor"));
+ analogElems.add(tech.findNodeGroup("P-Poly-Resistor"));
+ analogElems.add(tech.findNodeGroup("N-Poly-Resistor"));
for (int i = 0; i < metalLayers.length; i++) {
metalLayers[i] = tech.findLayer("Metal-" + (i + 1));
metalArcs[i] = tech.findArc("Metal-" + (i + 1));
metalPinNodes[i] = tech.findNodeGroup("Metal-" + (i + 1) + "-Pin");
if (i >= metalContactNodes.length) continue;
metalContactNodes[i] = tech.findNodeGroup("Metal-" + (i + 1)+"-Metal-" + (i + 2) + "-Con");
}
for (int i = 0; i < 2; i++) {
polyArcs[i] = tech.findArc("Polysilicon-" + (i + 1));
polyPinNodes[i] = tech.findNodeGroup("Polysilicon-" + (i + 1) + "-Pin");
metal1PolyContactNodes[i] = tech.findNodeGroup("Metal-1-Polysilicon-" + (i + 1) + "-Con");
}
metal1PolyContactNodes[2] = tech.findNodeGroup("Metal-1-Polysilicon-1-2-Con");
for (int i = P_TYPE; i <= N_TYPE; i++) {
String ts = i == P_TYPE ? "P" : "N";
activeArcs[i] = tech.findArc(ts + "-Active");
activePinNodes[i] = tech.findNodeGroup(ts + "-Active-Pin");
metalWellContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Well-Con");
metalActiveContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Active-Con");
transistorNodeGroups[i] = tech.findNodeGroup(ts + "-Transistor");
scalableTransistorNodes[i] = tech.findNodeGroup(ts + "-Transistor-Scalable");
}
String rules = "";
switch (ruleSet)
{
case SCMOSRULES: rules = "now standard"; break;
case DEEPRULES: rules = "now deep"; break;
case SUBMRULES: rules = "now submicron"; break;
}
int numPolys = 1;
if (secondPolysilicon) numPolys = 2;
String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " +
numPolys + "], flex rules [" + rules + "]";
if (disallowStackedVias) description += ", stacked vias disallowed";
if (alternateContactRules) description += ", alternate contact rules";
description += ")";
tech.description = description;
Xml.NodeLayer nl;
ResizeData rd = new ResizeData(ruleSet, numMetals, alternateContactRules);
for (int i = 0; i < 6; i++) {
resizeArcPin(metalArcs[i], metalPinNodes[i], 0.5*rd.metal_width[i]);
if (i >= 5) continue;
Xml.PrimitiveNodeGroup via = metalContactNodes[i];
nl = via.nodeLayers.get(2);
nl.sizex = nl.sizey = rd.via_size[i];
nl.sep1d = rd.via_inline_spacing[i];
nl.sep2d = rd.via_array_spacing[i];
if (i + 1 >= numMetals) continue;
double halfSize = 0.5*rd.via_size[i] + rd.via_overhang[i + 1];
resizeSquare(via, halfSize, halfSize, halfSize, 0);
}
for (int i = P_TYPE; i <= N_TYPE; i++) {
double activeE = 0.5*rd.diff_width;
double wellE = activeE + rd.nwell_overhang_diff_p;
double selectE = activeE + rd.pplus_overhang_diff;
resizeArcPin(activeArcs[i], activePinNodes[i], activeE, wellE, selectE);
Xml.PrimitiveNodeGroup con = metalActiveContactNodes[i];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
con = metalWellContactNodes[i];
wellC = activeC + rd.nwell_overhang_diff_n;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
resizeSerpentineTransistor(transistorNodeGroups[i], rd);
resizeScalableTransistor(scalableTransistorNodes[i], rd);
}
resizeContacts(npnTransistorNode, rd);
{
Xml.PrimitiveNodeGroup con = metal1PolyContactNodes[0];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double polyC = 0.5*rd.contact_size + rd.contact_poly_overhang;
resizeSquare(con, polyC, metalC, polyC, 0);
}
for (int i = 0; i <= 2; i++)
resizeContacts(metal1PolyContactNodes[i], rd);
resizeArcPin(polyArcs[0], polyPinNodes[0], 0.5*rd.poly_width);
resizeArcPin(polyArcs[1], polyPinNodes[1], 0.5*rd.poly2_width);
for (int i = numMetals; i < 6; i++) {
metalArcs[i].notUsed = true;
metalPinNodes[i].notUsed = true;
metalContactNodes[i-1].notUsed = true;
// Remove palette rows with unused metal
assert tech.menuPalette.menuBoxes.get(3*(6 + numMetals)).get(0) == metalArcs[i];
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
}
// Clear palette box with unused contact
tech.menuPalette.menuBoxes.get(3*(6 + numMetals) - 1).clear();
if (!secondPolysilicon) {
polyArcs[1].notUsed = true;
polyPinNodes[1].notUsed = true;
metal1PolyContactNodes[1].notUsed = true;
metal1PolyContactNodes[2].notUsed = true;
// Remove palette row with polysilicon-2
assert tech.menuPalette.menuBoxes.get(3*5).get(0) == polyArcs[1];
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
}
boolean polyFlag, analogFlag;
if (isAnalog) {
analogFlag = false;
polyFlag = false;
// Clear palette box with capacitor if poly2 is on
if (!secondPolysilicon)
{
assert tech.menuPalette.menuBoxes.get(0).get(1) == polyCapNode.nodes.get(0);
// location of capacitor
tech.menuPalette.menuBoxes.get(0).remove(polyCapNode.nodes.get(0));
polyFlag = true;
}
} else {
// Clear palette box with NPN transisitor
assert tech.menuPalette.menuBoxes.get(0).get(0) == npnTransistorNode.nodes.get(0);
tech.menuPalette.menuBoxes.get(0).clear();
analogFlag = true;
polyFlag = true;
}
if (polyCapNode != null) polyCapNode.notUsed = polyFlag;
for (Xml.PrimitiveNodeGroup elem : analogElems)
{
if (elem != null) elem.notUsed = analogFlag;
}
-// if (npnTransistorNode != null) npnTransistorNode.notUsed = analogFlag;
return tech;
}
private static void resizeArcPin(Xml.ArcProto a, Xml.PrimitiveNodeGroup ng, double ... exts) {
assert a.arcLayers.size() == exts.length;
assert ng.nodeLayers.size() == exts.length;
double baseExt = exts[0];
double maxExt = 0;
for (int i = 0; i < exts.length; i++) {
Xml.ArcLayer al = a.arcLayers.get(i);
Xml.NodeLayer nl = ng.nodeLayers.get(i);
double ext = exts[i];
assert al.layer.equals(nl.layer);
assert nl.representation == Technology.NodeLayer.BOX;
al.extend.value = ext;
nl.hx.value = nl.hy.value = ext;
nl.lx.value = nl.ly.value = ext == 0 ? 0 : -ext;
maxExt = Math.max(maxExt, ext);
}
Integer version2 = Integer.valueOf(2);
if (baseExt != 0)
a.diskOffset.put(version2, Double.valueOf(baseExt));
else
a.diskOffset.clear();
ng.baseLX.value = ng.baseLY.value = baseExt != 0 ? -baseExt : 0;
ng.baseHX.value = ng.baseHY.value = baseExt;
// n.setDefSize
}
private static void resizeSquare(Xml.PrimitiveNodeGroup ng, double base, double... size) {
assert size.length == ng.nodeLayers.size();
double maxSz = 0;
for (int i = 0; i < ng.nodeLayers.size(); i++) {
Xml.NodeLayer nl = ng.nodeLayers.get(i);
assert nl.representation == Technology.NodeLayer.BOX || nl.representation == Technology.NodeLayer.MULTICUTBOX;
double sz = size[i];
assert sz >= 0;
nl.hx.value = nl.hy.value = sz;
nl.lx.value = nl.ly.value = sz == 0 ? 0 : -sz;
maxSz = Math.max(maxSz, sz);
}
Integer version1 = Integer.valueOf(1);
Integer version2 = Integer.valueOf(2);
EPoint sizeCorrector1 = ng.diskOffset.get(version1);
EPoint sizeCorrector2 = ng.diskOffset.get(version2);
if (sizeCorrector2 == null)
sizeCorrector2 = EPoint.ORIGIN;
if (sizeCorrector1 == null)
sizeCorrector1 = sizeCorrector2;
ng.baseLX.value = ng.baseLY.value = base != 0 ? -base : 0;
ng.baseHX.value = ng.baseHY.value = base;
sizeCorrector2 = EPoint.fromLambda(base, base);
ng.diskOffset.put(version2, sizeCorrector2);
if (sizeCorrector1.equals(sizeCorrector2))
ng.diskOffset.remove(version1);
else
ng.diskOffset.put(version1, sizeCorrector1);
}
private static void resizeContacts(Xml.PrimitiveNodeGroup ng, ResizeData rd) {
for (Xml.NodeLayer nl: ng.nodeLayers) {
if (nl.representation != Technology.NodeLayer.MULTICUTBOX) continue;
nl.sizex = nl.sizey = rd.contact_size;
nl.sep1d = rd.contact_spacing;
nl.sep2d = rd.contact_array_spacing;
}
}
private static void resizeSerpentineTransistor(Xml.PrimitiveNodeGroup transistor, ResizeData rd) {
Xml.NodeLayer activeTNode = transistor.nodeLayers.get(0); // active Top or Left
Xml.NodeLayer activeBNode = transistor.nodeLayers.get(1); // active Bottom or Right
Xml.NodeLayer polyCNode = transistor.nodeLayers.get(2); // poly center
Xml.NodeLayer polyLNode = transistor.nodeLayers.get(3); // poly left or Top
Xml.NodeLayer polyRNode = transistor.nodeLayers.get(4); // poly right or bottom
Xml.NodeLayer activeNode = transistor.nodeLayers.get(5); // active
Xml.NodeLayer polyNode = transistor.nodeLayers.get(6); // poly
Xml.NodeLayer wellNode = transistor.nodeLayers.get(7); // well
Xml.NodeLayer selNode = transistor.nodeLayers.get(8); // select
Xml.NodeLayer thickNode = transistor.nodeLayers.get(9); // thick
double hw = 0.5*rd.gate_width;
double hl = 0.5*rd.gate_length;
double gateX = hw;
double gateY = hl;
double polyX = gateX + rd.poly_endcap;
double polyY = gateY;
double diffX = gateX;
double diffY = gateY + rd.diff_poly_overhang;
double wellX = diffX + rd.nwell_overhang_diff_p;
double wellY = diffY + rd.nwell_overhang_diff_p;
double selX = diffX + rd.pplus_overhang_diff;
double selY = diffY + rd.pplus_overhang_diff;
double thickX = diffX + rd.thick_overhang;
double thickY = diffY + rd.thick_overhang;
resizeSerpentineLayer(activeTNode, hw, -gateX, gateX, gateY, diffY);
resizeSerpentineLayer(activeBNode, hw, -diffX, diffX, -diffY, -gateY);
resizeSerpentineLayer(polyCNode, hw, -gateX, gateX, -gateY, gateY);
resizeSerpentineLayer(polyLNode, hw, -polyX, -gateX, -polyY, polyY);
resizeSerpentineLayer(polyRNode, hw, gateX, polyX, -polyY, polyY);
resizeSerpentineLayer(activeNode, hw, -diffX, diffX, -diffY, diffY);
resizeSerpentineLayer(polyNode, hw, -polyX, polyX, -polyY, polyY);
resizeSerpentineLayer(wellNode, hw, -wellX, wellX, -wellY, wellY);
resizeSerpentineLayer(selNode, hw, -selX, selX, -selY, selY);
resizeSerpentineLayer(thickNode, hw, -thickX, thickX, -thickY, thickY);
}
private static void resizeSerpentineLayer(Xml.NodeLayer nl, double hw, double lx, double hx, double ly, double hy) {
nl.lx.value = lx;
nl.hx.value = hx;
nl.ly.value = ly;
nl.hy.value = hy;
nl.lWidth = nl.hy.k == 1 ? hy : 0;
nl.rWidth = nl.ly.k == -1 ? -ly : 0;
nl.tExtent = nl.hx.k == 1 ? hx - hw : 0;
nl.bExtent = nl.lx.k == -1 ? -lx - hw : 0;
}
private static void resizeScalableTransistor(Xml.PrimitiveNodeGroup transistor, ResizeData rd) {
Xml.NodeLayer activeTNode = transistor.nodeLayers.get(SCALABLE_ACTIVE_TOP); // active Top
Xml.NodeLayer metalTNode = transistor.nodeLayers.get(SCALABLE_METAL_TOP); // metal Top
Xml.NodeLayer cutTNode = transistor.nodeLayers.get(SCALABLE_CUT_TOP);
Xml.NodeLayer activeBNode = transistor.nodeLayers.get(SCALABLE_ACTIVE_BOT); // active Bottom
Xml.NodeLayer metalBNode = transistor.nodeLayers.get(SCALABLE_METAL_BOT); // metal Bot
Xml.NodeLayer cutBNode = transistor.nodeLayers.get(SCALABLE_CUT_BOT);
Xml.NodeLayer activeCNode = transistor.nodeLayers.get(SCALABLE_ACTIVE_CTR); // active center
Xml.NodeLayer polyCNode = transistor.nodeLayers.get(SCALABLE_POLY); // poly center
Xml.NodeLayer wellNode = transistor.nodeLayers.get(SCALABLE_WELL); // well
Xml.NodeLayer selNode = transistor.nodeLayers.get(SCALABLE_SUBSTRATE); // select
double hw = 0.5*rd.gate_width;
double hl = 0.5*rd.gate_length;
double gateX = hw;
double gateY = hl;
double polyX = gateX + rd.poly_endcap;
double polyY = gateY;
double diffX = gateX;
double diffY = gateY + rd.diff_poly_overhang;
// double wellX = diffX + rd.nwell_overhang_diff_p;
// double wellY = diffY + rd.nwell_overhang_diff_p;
// double selX = diffX + rd.pplus_overhang_diff;
// double selY = diffY + rd.pplus_overhang_diff;
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
double cutY = hl + rd.poly_diff_spacing + activeC;
resizeScalableLayer(activeTNode, -activeC, activeC, cutY - activeC, cutY + activeC);
resizeScalableLayer(metalTNode, -metalC, metalC, cutY - metalC, cutY + metalC);
resizeScalableLayer(cutTNode, 0, 0, cutY, cutY);
resizeScalableLayer(activeBNode, -activeC, activeC, -cutY - activeC, -cutY + activeC);
resizeScalableLayer(metalBNode, -metalC, metalC, -cutY - metalC, -cutY + metalC);
resizeScalableLayer(cutBNode, 0, 0, -cutY, -cutY);
resizeScalableLayer(activeCNode, -diffX, diffX, -diffY, diffY);
resizeScalableLayer(polyCNode, -polyX, polyX, -polyY, polyY);
resizeScalableLayer(wellNode, -wellC, wellC, -cutY-wellC, cutY+wellC);
resizeScalableLayer(selNode, -selectC, selectC, -cutY-selectC, cutY+selectC);
resizeContacts(transistor, rd);
}
private static void resizeScalableLayer(Xml.NodeLayer nl, double lx, double hx, double ly, double hy) {
nl.lx.value = lx;
nl.hx.value = hx;
nl.ly.value = ly;
nl.hy.value = hy;
}
private static class ResizeData {
private final double diff_width = 3; // 2.1
private final double diff_poly_overhang; // 3.4
private final double diff_contact_overhang; // 6.2 6.2b
private final double thick_overhang = 4;
private final double poly_width = 2; // 3.1
private final double poly_endcap; // 3.3
private final double poly_diff_spacing = 1; // 3.5
private final double gate_length = poly_width; // 3.1
private final double gate_width = diff_width; // 2.1
private final double gate_contact_spacing = 2; // 5.4
private final double poly2_width; // 11.1
private final double contact_size = 2; // 5.1
private final double contact_spacing; // 5.3
private final double contact_array_spacing; // 5.3
private final double contact_metal_overhang_all_sides = 1; // 7.3
private final double contact_poly_overhang; // 5.2 5.2b
private final double nplus_overhang_diff = 2; // 4.2
private final double pplus_overhang_diff = 2; // 4.2
private final double well_width;
private final double nwell_overhang_diff_p; // 2.3
private final double nwell_overhang_diff_n = 3; // 2.4
private final double[] metal_width; // 7.1 9.1 15.1 22.1 26.1 30.1
private final double[] via_size; // 8.1 14.1 21.1 25.1 29.1
private final double[] via_inline_spacing; // 8.2 14.2 21.2 25.2 29.2
private final double[] via_array_spacing; // 8.2 14.2 21.2 25.2 29.2
private final double[] via_overhang; // 8.3 14.3 21.3 25.3 29.3 30.3
ResizeData(int ruleSet, int numMetals, boolean alternateContactRules) {
switch (ruleSet) {
case SUBMRULES:
diff_poly_overhang = 3;
poly_endcap = 2;
poly2_width = 7;
contact_spacing = 3;
well_width = 12;
nwell_overhang_diff_p = 6;
switch (numMetals) {
case 2:
metal_width = new double[] { 3, 3, 0, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1 };
break;
case 3:
metal_width = new double[] { 3, 3, 5, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 2 };
break;
case 4:
metal_width = new double[] { 3, 3, 3, 6, 0, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 2 };
break;
case 5:
metal_width = new double[] { 3, 3, 3, 3, 4, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 1 };
break;
case 6:
metal_width = new double[] { 3, 3, 3, 3, 3, 5 };
via_size = new double[] { 2, 2, 2, 2, 3 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 1, 1 };
break;
default:
throw new IllegalArgumentException("Illegal number of metals " + numMetals + " in SUB rule set");
}
break;
case DEEPRULES:
diff_poly_overhang = 4;
poly_endcap = 2.5;
poly2_width = 0;
contact_spacing = 4;
well_width = 12;
nwell_overhang_diff_p = 6;
switch (numMetals) {
case 5:
metal_width = new double[] { 3, 3, 3, 3, 4, 5 };
via_size = new double[] { 3, 3, 3, 3, 4 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 2 };
break;
case 6:
metal_width = new double[] { 3, 3, 3, 3, 3, 5 };
via_size = new double[] { 3, 3, 3, 3, 4 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 1, 1, 2 };
break;
default:
throw new IllegalArgumentException("Illegal number of metals " + numMetals + " in DEEP rule set");
}
break;
case SCMOSRULES:
diff_poly_overhang = 3;
poly_endcap = 2;
poly2_width = 3;
contact_spacing = 2;
well_width = 10;
nwell_overhang_diff_p = 5;
switch (numMetals) {
case 2:
metal_width = new double[] { 3, 3, 0, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 0, 0 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1 };
break;
case 3:
metal_width = new double[] { 3, 3, 6, 0, 0, 5 };
via_size = new double[] { 2, 2, 2, 0, 0 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 2 };
break;
case 4:
metal_width = new double[] { 3, 3, 3, 6, 0, 5 };
via_size = new double[] { 2, 2, 2, 0, 0 };
via_inline_spacing = new double[] { 3, 3, 3, 3, 4 };
via_overhang = new double[] { 1, 1, 1, 2 };
break;
default:
throw new IllegalArgumentException("Illegal number of metals " + numMetals + " in SCMOS rule set");
}
break;
default:
throw new AssertionError("Illegal rule set " + ruleSet);
}
diff_contact_overhang = alternateContactRules ? 1 : 1.5;
contact_poly_overhang = alternateContactRules ? 1 : 1.5;
contact_array_spacing = contact_spacing;
via_array_spacing = via_inline_spacing;
}
}
/******************** OVERRIDES ********************/
/**
* Method to convert old primitive port names to their proper PortProtos.
* @param portName the unknown port name, read from an old Library.
* @param np the PrimitiveNode on which this port resides.
* @return the proper PrimitivePort to use for this name.
*/
@Override
public PrimitivePort convertOldPortName(String portName, PrimitiveNode np)
{
String[] transistorPorts = { "poly-left", "diff-top", "poly-right", "diff-bottom" };
for (int i = 0; i < transistorPorts.length; i++)
{
if (portName.endsWith(transistorPorts[i]))
return (PrimitivePort)np.findPortProto(transistorPorts[i]);
}
return super.convertOldPortName(portName, np);
}
// /**
// * Method to set the size of a transistor NodeInst in this Technology.
// * Override because for MOCMOS sense of "width" and "length" are
// * different for resistors and transistors.
// * @param ni the NodeInst
// * @param width the new width (positive values only)
// * @param length the new length (positive values only)
// */
// //@Override
// public void setPrimitiveNodeSize(NodeInst ni, double width, double length)
// {
// if (ni.getFunction().isResistor()) {
// super.setPrimitiveNodeSize(ni, length, width);
// } else {
// super.setPrimitiveNodeSize(ni, width, length);
// }
// }
/**
* Method to calculate extension of the poly gate from active layer or of the active from the poly gate.
* @param primNode
* @param poly true to calculate the poly extension
* @param rules
* @return value of the extension
*/
// private double getTransistorExtension(PrimitiveNode primNode, boolean poly, DRCRules rules)
// {
// if (rules == null)
// rules = DRC.getRules(this);
// if (!primNode.getFunction().isTransistor()) return 0.0;
//
// Technology.NodeLayer activeNode = primNode.getNodeLayers()[0]; // active
// Technology.NodeLayer polyCNode;
//
// if (scalableTransistorNodes != null && (primNode == scalableTransistorNodes[P_TYPE] || primNode == scalableTransistorNodes[N_TYPE]))
// {
// polyCNode = primNode.getNodeLayers()[SCALABLE_POLY]; // poly center
// }
// else
// {
// // Standard transistors
// polyCNode = primNode.getElectricalLayers()[2]; // poly center
// }
// DRCTemplate overhang = (poly) ?
// rules.getExtensionRule(polyCNode.getLayer(), activeNode.getLayer(), false) :
// rules.getExtensionRule(activeNode.getLayer(), polyCNode.getLayer(), false);
// return (overhang != null ? overhang.getValue(0) : 0.0);
// }
/** Return a substrate PortInst for this transistor NodeInst
* @param ni the NodeInst
* @return a PortInst for the substrate contact of the transistor
*/
@Override
public PortInst getTransistorBiasPort(NodeInst ni)
{
return ni.getPortInst(4);
}
}
| false | true | public static Xml.Technology getPatchedXml(Map<TechFactory.Param,Object> params) {
int ruleSet = ((Integer)params.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)params.get(techParamNumMetalLayers)).intValue();
boolean secondPolysilicon = ((Boolean)params.get(techParamUseSecondPolysilicon)).booleanValue();
boolean disallowStackedVias = ((Boolean)params.get(techParamDisallowStackedVias)).booleanValue();
boolean alternateContactRules = ((Boolean)params.get(techParamUseAlternativeActivePolyRules)).booleanValue();
boolean isAnalog = ((Boolean)params.get(techParamAnalog)).booleanValue();
Xml.Technology tech = Xml.parseTechnology(MoCMOS.class.getResource("mocmos.xml"));
if (tech == null) // errors while reading the XML file
return null;
Xml.Layer[] metalLayers = new Xml.Layer[6];
Xml.ArcProto[] metalArcs = new Xml.ArcProto[6];
Xml.ArcProto[] activeArcs = new Xml.ArcProto[2];
Xml.ArcProto[] polyArcs = new Xml.ArcProto[6];
Xml.PrimitiveNodeGroup[] metalPinNodes = new Xml.PrimitiveNodeGroup[9];
Xml.PrimitiveNodeGroup[] activePinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] polyPinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalContactNodes = new Xml.PrimitiveNodeGroup[8];
Xml.PrimitiveNodeGroup[] metalWellContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalActiveContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metal1PolyContactNodes = new Xml.PrimitiveNodeGroup[3];
Xml.PrimitiveNodeGroup[] transistorNodeGroups = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] scalableTransistorNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup npnTransistorNode = tech.findNodeGroup("NPN-Transistor");
Xml.PrimitiveNodeGroup polyCapNode = tech.findNodeGroup("Poly-Capacitor");
List<Xml.PrimitiveNodeGroup> analogElems = new ArrayList<Xml.PrimitiveNodeGroup>();
analogElems.add(tech.findNodeGroup("NPN-Transistor"));
for (int i = 0; i < metalLayers.length; i++) {
metalLayers[i] = tech.findLayer("Metal-" + (i + 1));
metalArcs[i] = tech.findArc("Metal-" + (i + 1));
metalPinNodes[i] = tech.findNodeGroup("Metal-" + (i + 1) + "-Pin");
if (i >= metalContactNodes.length) continue;
metalContactNodes[i] = tech.findNodeGroup("Metal-" + (i + 1)+"-Metal-" + (i + 2) + "-Con");
}
for (int i = 0; i < 2; i++) {
polyArcs[i] = tech.findArc("Polysilicon-" + (i + 1));
polyPinNodes[i] = tech.findNodeGroup("Polysilicon-" + (i + 1) + "-Pin");
metal1PolyContactNodes[i] = tech.findNodeGroup("Metal-1-Polysilicon-" + (i + 1) + "-Con");
}
metal1PolyContactNodes[2] = tech.findNodeGroup("Metal-1-Polysilicon-1-2-Con");
for (int i = P_TYPE; i <= N_TYPE; i++) {
String ts = i == P_TYPE ? "P" : "N";
activeArcs[i] = tech.findArc(ts + "-Active");
activePinNodes[i] = tech.findNodeGroup(ts + "-Active-Pin");
metalWellContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Well-Con");
metalActiveContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Active-Con");
transistorNodeGroups[i] = tech.findNodeGroup(ts + "-Transistor");
scalableTransistorNodes[i] = tech.findNodeGroup(ts + "-Transistor-Scalable");
}
String rules = "";
switch (ruleSet)
{
case SCMOSRULES: rules = "now standard"; break;
case DEEPRULES: rules = "now deep"; break;
case SUBMRULES: rules = "now submicron"; break;
}
int numPolys = 1;
if (secondPolysilicon) numPolys = 2;
String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " +
numPolys + "], flex rules [" + rules + "]";
if (disallowStackedVias) description += ", stacked vias disallowed";
if (alternateContactRules) description += ", alternate contact rules";
description += ")";
tech.description = description;
Xml.NodeLayer nl;
ResizeData rd = new ResizeData(ruleSet, numMetals, alternateContactRules);
for (int i = 0; i < 6; i++) {
resizeArcPin(metalArcs[i], metalPinNodes[i], 0.5*rd.metal_width[i]);
if (i >= 5) continue;
Xml.PrimitiveNodeGroup via = metalContactNodes[i];
nl = via.nodeLayers.get(2);
nl.sizex = nl.sizey = rd.via_size[i];
nl.sep1d = rd.via_inline_spacing[i];
nl.sep2d = rd.via_array_spacing[i];
if (i + 1 >= numMetals) continue;
double halfSize = 0.5*rd.via_size[i] + rd.via_overhang[i + 1];
resizeSquare(via, halfSize, halfSize, halfSize, 0);
}
for (int i = P_TYPE; i <= N_TYPE; i++) {
double activeE = 0.5*rd.diff_width;
double wellE = activeE + rd.nwell_overhang_diff_p;
double selectE = activeE + rd.pplus_overhang_diff;
resizeArcPin(activeArcs[i], activePinNodes[i], activeE, wellE, selectE);
Xml.PrimitiveNodeGroup con = metalActiveContactNodes[i];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
con = metalWellContactNodes[i];
wellC = activeC + rd.nwell_overhang_diff_n;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
resizeSerpentineTransistor(transistorNodeGroups[i], rd);
resizeScalableTransistor(scalableTransistorNodes[i], rd);
}
resizeContacts(npnTransistorNode, rd);
{
Xml.PrimitiveNodeGroup con = metal1PolyContactNodes[0];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double polyC = 0.5*rd.contact_size + rd.contact_poly_overhang;
resizeSquare(con, polyC, metalC, polyC, 0);
}
for (int i = 0; i <= 2; i++)
resizeContacts(metal1PolyContactNodes[i], rd);
resizeArcPin(polyArcs[0], polyPinNodes[0], 0.5*rd.poly_width);
resizeArcPin(polyArcs[1], polyPinNodes[1], 0.5*rd.poly2_width);
for (int i = numMetals; i < 6; i++) {
metalArcs[i].notUsed = true;
metalPinNodes[i].notUsed = true;
metalContactNodes[i-1].notUsed = true;
// Remove palette rows with unused metal
assert tech.menuPalette.menuBoxes.get(3*(6 + numMetals)).get(0) == metalArcs[i];
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
}
// Clear palette box with unused contact
tech.menuPalette.menuBoxes.get(3*(6 + numMetals) - 1).clear();
if (!secondPolysilicon) {
polyArcs[1].notUsed = true;
polyPinNodes[1].notUsed = true;
metal1PolyContactNodes[1].notUsed = true;
metal1PolyContactNodes[2].notUsed = true;
// Remove palette row with polysilicon-2
assert tech.menuPalette.menuBoxes.get(3*5).get(0) == polyArcs[1];
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
}
boolean polyFlag, analogFlag;
if (isAnalog) {
analogFlag = false;
polyFlag = false;
// Clear palette box with capacitor if poly2 is on
if (!secondPolysilicon)
{
assert tech.menuPalette.menuBoxes.get(0).get(1) == polyCapNode.nodes.get(0);
// location of capacitor
tech.menuPalette.menuBoxes.get(0).remove(polyCapNode.nodes.get(0));
polyFlag = true;
}
} else {
// Clear palette box with NPN transisitor
assert tech.menuPalette.menuBoxes.get(0).get(0) == npnTransistorNode.nodes.get(0);
tech.menuPalette.menuBoxes.get(0).clear();
analogFlag = true;
polyFlag = true;
}
if (polyCapNode != null) polyCapNode.notUsed = polyFlag;
for (Xml.PrimitiveNodeGroup elem : analogElems)
{
if (elem != null) elem.notUsed = analogFlag;
}
// if (npnTransistorNode != null) npnTransistorNode.notUsed = analogFlag;
return tech;
}
| public static Xml.Technology getPatchedXml(Map<TechFactory.Param,Object> params) {
int ruleSet = ((Integer)params.get(techParamRuleSet)).intValue();
int numMetals = ((Integer)params.get(techParamNumMetalLayers)).intValue();
boolean secondPolysilicon = ((Boolean)params.get(techParamUseSecondPolysilicon)).booleanValue();
boolean disallowStackedVias = ((Boolean)params.get(techParamDisallowStackedVias)).booleanValue();
boolean alternateContactRules = ((Boolean)params.get(techParamUseAlternativeActivePolyRules)).booleanValue();
boolean isAnalog = ((Boolean)params.get(techParamAnalog)).booleanValue();
Xml.Technology tech = Xml.parseTechnology(MoCMOS.class.getResource("mocmos.xml"));
if (tech == null) // errors while reading the XML file
return null;
Xml.Layer[] metalLayers = new Xml.Layer[6];
Xml.ArcProto[] metalArcs = new Xml.ArcProto[6];
Xml.ArcProto[] activeArcs = new Xml.ArcProto[2];
Xml.ArcProto[] polyArcs = new Xml.ArcProto[6];
Xml.PrimitiveNodeGroup[] metalPinNodes = new Xml.PrimitiveNodeGroup[9];
Xml.PrimitiveNodeGroup[] activePinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] polyPinNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalContactNodes = new Xml.PrimitiveNodeGroup[8];
Xml.PrimitiveNodeGroup[] metalWellContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metalActiveContactNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] metal1PolyContactNodes = new Xml.PrimitiveNodeGroup[3];
Xml.PrimitiveNodeGroup[] transistorNodeGroups = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup[] scalableTransistorNodes = new Xml.PrimitiveNodeGroup[2];
Xml.PrimitiveNodeGroup npnTransistorNode = tech.findNodeGroup("NPN-Transistor");
Xml.PrimitiveNodeGroup polyCapNode = tech.findNodeGroup("Poly-Capacitor");
List<Xml.PrimitiveNodeGroup> analogElems = new ArrayList<Xml.PrimitiveNodeGroup>();
analogElems.add(tech.findNodeGroup("NPN-Transistor"));
analogElems.add(tech.findNodeGroup("Hi-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("P-Active-Resistor"));
analogElems.add(tech.findNodeGroup("N-Active-Resistor"));
analogElems.add(tech.findNodeGroup("P-Well-Resistor"));
analogElems.add(tech.findNodeGroup("N-Well-Resistor"));
analogElems.add(tech.findNodeGroup("P-Poly-Resistor"));
analogElems.add(tech.findNodeGroup("N-Poly-Resistor"));
for (int i = 0; i < metalLayers.length; i++) {
metalLayers[i] = tech.findLayer("Metal-" + (i + 1));
metalArcs[i] = tech.findArc("Metal-" + (i + 1));
metalPinNodes[i] = tech.findNodeGroup("Metal-" + (i + 1) + "-Pin");
if (i >= metalContactNodes.length) continue;
metalContactNodes[i] = tech.findNodeGroup("Metal-" + (i + 1)+"-Metal-" + (i + 2) + "-Con");
}
for (int i = 0; i < 2; i++) {
polyArcs[i] = tech.findArc("Polysilicon-" + (i + 1));
polyPinNodes[i] = tech.findNodeGroup("Polysilicon-" + (i + 1) + "-Pin");
metal1PolyContactNodes[i] = tech.findNodeGroup("Metal-1-Polysilicon-" + (i + 1) + "-Con");
}
metal1PolyContactNodes[2] = tech.findNodeGroup("Metal-1-Polysilicon-1-2-Con");
for (int i = P_TYPE; i <= N_TYPE; i++) {
String ts = i == P_TYPE ? "P" : "N";
activeArcs[i] = tech.findArc(ts + "-Active");
activePinNodes[i] = tech.findNodeGroup(ts + "-Active-Pin");
metalWellContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Well-Con");
metalActiveContactNodes[i] = tech.findNodeGroup("Metal-1-" + ts + "-Active-Con");
transistorNodeGroups[i] = tech.findNodeGroup(ts + "-Transistor");
scalableTransistorNodes[i] = tech.findNodeGroup(ts + "-Transistor-Scalable");
}
String rules = "";
switch (ruleSet)
{
case SCMOSRULES: rules = "now standard"; break;
case DEEPRULES: rules = "now deep"; break;
case SUBMRULES: rules = "now submicron"; break;
}
int numPolys = 1;
if (secondPolysilicon) numPolys = 2;
String description = "MOSIS CMOS (2-6 metals [now " + numMetals + "], 1-2 polys [now " +
numPolys + "], flex rules [" + rules + "]";
if (disallowStackedVias) description += ", stacked vias disallowed";
if (alternateContactRules) description += ", alternate contact rules";
description += ")";
tech.description = description;
Xml.NodeLayer nl;
ResizeData rd = new ResizeData(ruleSet, numMetals, alternateContactRules);
for (int i = 0; i < 6; i++) {
resizeArcPin(metalArcs[i], metalPinNodes[i], 0.5*rd.metal_width[i]);
if (i >= 5) continue;
Xml.PrimitiveNodeGroup via = metalContactNodes[i];
nl = via.nodeLayers.get(2);
nl.sizex = nl.sizey = rd.via_size[i];
nl.sep1d = rd.via_inline_spacing[i];
nl.sep2d = rd.via_array_spacing[i];
if (i + 1 >= numMetals) continue;
double halfSize = 0.5*rd.via_size[i] + rd.via_overhang[i + 1];
resizeSquare(via, halfSize, halfSize, halfSize, 0);
}
for (int i = P_TYPE; i <= N_TYPE; i++) {
double activeE = 0.5*rd.diff_width;
double wellE = activeE + rd.nwell_overhang_diff_p;
double selectE = activeE + rd.pplus_overhang_diff;
resizeArcPin(activeArcs[i], activePinNodes[i], activeE, wellE, selectE);
Xml.PrimitiveNodeGroup con = metalActiveContactNodes[i];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double activeC = 0.5*rd.contact_size + rd.diff_contact_overhang;
double wellC = activeC + rd.nwell_overhang_diff_p;
double selectC = activeC + rd.nplus_overhang_diff;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
con = metalWellContactNodes[i];
wellC = activeC + rd.nwell_overhang_diff_n;
resizeSquare(con, activeC, metalC, activeC, wellC, selectC, 0);
resizeContacts(con, rd);
resizeSerpentineTransistor(transistorNodeGroups[i], rd);
resizeScalableTransistor(scalableTransistorNodes[i], rd);
}
resizeContacts(npnTransistorNode, rd);
{
Xml.PrimitiveNodeGroup con = metal1PolyContactNodes[0];
double metalC = 0.5*rd.contact_size + rd.contact_metal_overhang_all_sides;
double polyC = 0.5*rd.contact_size + rd.contact_poly_overhang;
resizeSquare(con, polyC, metalC, polyC, 0);
}
for (int i = 0; i <= 2; i++)
resizeContacts(metal1PolyContactNodes[i], rd);
resizeArcPin(polyArcs[0], polyPinNodes[0], 0.5*rd.poly_width);
resizeArcPin(polyArcs[1], polyPinNodes[1], 0.5*rd.poly2_width);
for (int i = numMetals; i < 6; i++) {
metalArcs[i].notUsed = true;
metalPinNodes[i].notUsed = true;
metalContactNodes[i-1].notUsed = true;
// Remove palette rows with unused metal
assert tech.menuPalette.menuBoxes.get(3*(6 + numMetals)).get(0) == metalArcs[i];
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
tech.menuPalette.menuBoxes.remove(3*(6 + numMetals));
}
// Clear palette box with unused contact
tech.menuPalette.menuBoxes.get(3*(6 + numMetals) - 1).clear();
if (!secondPolysilicon) {
polyArcs[1].notUsed = true;
polyPinNodes[1].notUsed = true;
metal1PolyContactNodes[1].notUsed = true;
metal1PolyContactNodes[2].notUsed = true;
// Remove palette row with polysilicon-2
assert tech.menuPalette.menuBoxes.get(3*5).get(0) == polyArcs[1];
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
tech.menuPalette.menuBoxes.remove(3*5);
}
boolean polyFlag, analogFlag;
if (isAnalog) {
analogFlag = false;
polyFlag = false;
// Clear palette box with capacitor if poly2 is on
if (!secondPolysilicon)
{
assert tech.menuPalette.menuBoxes.get(0).get(1) == polyCapNode.nodes.get(0);
// location of capacitor
tech.menuPalette.menuBoxes.get(0).remove(polyCapNode.nodes.get(0));
polyFlag = true;
}
} else {
// Clear palette box with NPN transisitor
assert tech.menuPalette.menuBoxes.get(0).get(0) == npnTransistorNode.nodes.get(0);
tech.menuPalette.menuBoxes.get(0).clear();
analogFlag = true;
polyFlag = true;
}
if (polyCapNode != null) polyCapNode.notUsed = polyFlag;
for (Xml.PrimitiveNodeGroup elem : analogElems)
{
if (elem != null) elem.notUsed = analogFlag;
}
return tech;
}
|
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Commands/impexp.java b/src/nl/giantit/minecraft/GiantShop/core/Commands/impexp.java
index 265960f..de3cf34 100644
--- a/src/nl/giantit/minecraft/GiantShop/core/Commands/impexp.java
+++ b/src/nl/giantit/minecraft/GiantShop/core/Commands/impexp.java
@@ -1,749 +1,749 @@
package nl.giantit.minecraft.GiantShop.core.Commands;
import nl.giantit.minecraft.GiantShop.GiantShop;
import nl.giantit.minecraft.GiantShop.Misc.*;
import nl.giantit.minecraft.GiantShop.core.Database.db;
import nl.giantit.minecraft.GiantShop.core.Items.Items;
import org.bukkit.command.CommandSender;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
/**
*
* @author Giant
*/
public class impexp {
private static db DB = db.Obtain();
private static Messages mH = GiantShop.getPlugin().getMsgHandler();
private static Items iH = GiantShop.getPlugin().getItemHandler();
public static void imp(CommandSender sender, String[] args) {
if(args.length > 1) {
ArrayList<String> fields;
ArrayList<HashMap<Integer, HashMap<String, String>>> values;
String type = "items";
String path = GiantShop.getPlugin().getDir() + File.separator + "csvs";
String file = null;
Boolean commence = true;
Boolean err = false;
for(int i = 0; i < args.length; i++) {
if(args[i].startsWith("-t:")) {
type = args[i].replaceFirst("-t:", "");
continue;
}else if(args[i].startsWith("-p:")) {
path = args[i].replaceFirst("-p:", "");
continue;
}else if(args[i].startsWith("-c:")) {
commence = Boolean.parseBoolean(args[i].replaceFirst("-c:", ""));
continue;
}else if(args[i].startsWith("-f:")) {
file = args[i].replaceFirst("-f:", "");
continue;
}
}
if(Misc.isEitherIgnoreCase(type, "items", "i")) {
file = (file == null) ? "items.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing items...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("itemID, itemType, sellFor, buyFor, perStack, stock, shops")) {
Heraut.say(sender, "The given file is not a proper items file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length >= 6) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed items import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("perStack");
fields.add("shops");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
int itemID, stock, perStack;
Integer itemType;
Double sellFor, buyFor;
try {
itemID = Integer.parseInt(item[0]);
if(!item[1].equals("null")) {
itemType = Integer.parseInt(item[1]);
}else{
itemType = null;
}
sellFor = Double.parseDouble(item[2]);
buyFor = Double.parseDouble(item[3]);
perStack = Integer.parseInt(item[4]);
stock = Integer.parseInt(item[5]);
}catch(NumberFormatException e) {
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
if(iH.isValidItem(itemID, itemType)) {
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("kind", "INT");
temp.put("data", "" + itemID);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("type")) {
temp.put("kind", "INT");
temp.put("data", "" + ((itemType == null) ? -1 : itemType));
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("sellFor")) {
temp.put("data", "" + sellFor);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("buyFor")) {
temp.put("data", "" + buyFor);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("stock")) {
temp.put("kind", "INT");
temp.put("data", "" + stock);
tmp.put(4, temp);
}else if(field.equalsIgnoreCase("perStack")) {
temp.put("kind", "INT");
temp.put("data", "" + perStack);
tmp.put(5, temp);
}else if(field.equalsIgnoreCase("shops")) {
if(item.length == 7)
temp.put("data", (item[6].equals("null") ? "" : item[6]));
else
temp.put("data", "");
tmp.put(6, temp);
}
}
values.add(tmp);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " items to import!");
}else{
Heraut.say(sender, "Truncating items table!");
DB.Truncate("#__items").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " items...");
DB.insert("#__items", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing items, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing items!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else if(Misc.isEitherIgnoreCase(type, "shops", "s")) {
file = (file == null) ? "shops.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing shops...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("name, perms, world, locMinX, locMinY, locMinZ, locMaxX, locMaxY, locMaxZ")) {
Heraut.say(sender, "The given file is not a proper shops file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 9) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed shops import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("name");
fields.add("perms");
fields.add("world");
fields.add("locMinX");
fields.add("locMinY");
fields.add("locMinZ");
fields.add("locMaxX");
fields.add("locMaxY");
fields.add("locMaxZ");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("name")) {
temp.put("data", "" + item[0]);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("perms")) {
temp.put("data", "" + item[1]);
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("world")) {
temp.put("data", "" + item[2]);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("locMinX")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMinY")) {
temp.put("data", item[3]);
- tmp.put(3, temp);
+ tmp.put(4, temp);
}else if(field.equalsIgnoreCase("locMinZ")) {
temp.put("data", item[3]);
- tmp.put(3, temp);
+ tmp.put(5, temp);
}else if(field.equalsIgnoreCase("locMaxX")) {
temp.put("data", item[3]);
- tmp.put(3, temp);
+ tmp.put(6, temp);
}else if(field.equalsIgnoreCase("locMaxY")) {
temp.put("data", item[3]);
- tmp.put(3, temp);
+ tmp.put(7, temp);
}else if(field.equalsIgnoreCase("locMaxZ")) {
temp.put("data", item[3]);
- tmp.put(3, temp);
+ tmp.put(8, temp);
}
}
values.add(tmp);
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " shops to import!");
}else{
Heraut.say(sender, "Truncating items shops!");
DB.Truncate("#__shops").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " shops...");
DB.insert("#__shops", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing shops, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing shops!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else if(Misc.isEitherIgnoreCase(type, "discounts", "d")) {
file = (file == null) ? "discounts.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing discounts...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("itemID, dicount, user, group")) {
Heraut.say(sender, "The given file is not a proper discounts file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 4) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed discounts import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("discount");
fields.add("user");
fields.add("group");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("data", "" + item[0]);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("discount")) {
temp.put("data", "" + item[1]);
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("user")) {
temp.put("data", "" + item[2]);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("group")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}
}
values.add(tmp);
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " discounts to import!");
}else{
Heraut.say(sender, "Truncating items __discounts!");
DB.Truncate("#__discounts").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " __discounts...");
DB.insert("#__discounts", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing discounts, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing discounts!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "import");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "import");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}
public static void impLegacy(CommandSender sender, String[] args) {
ArrayList<String> fields;
ArrayList<HashMap<Integer, HashMap<String, String>>> values;
String path = GiantShop.getPlugin().getDir() + File.separator + "csvs";
String file = "data.csv";
Boolean commence = true;
Boolean err = false;
if(args.length > 1) {
for(int i = 0; i < args.length; i++) {
if(args[i].startsWith("-p:")) {
path = args[i].replaceFirst("-p:", "");
continue;
}else if(args[i].startsWith("-c:")) {
commence = Boolean.parseBoolean(args[i].replaceFirst("-c:", ""));
continue;
}else if(args[i].startsWith("-f:")) {
file = args[i].replaceFirst("-f:", "");
continue;
}
}
}
Heraut.say(sender, "Beginning legacy import...");
File f = new File(path + File.separator + file);
if(f.exists()) {
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("id, dataType, sellFor, buyFor, amount")) {
Heraut.say(sender, "The given file is not a proper items file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 5) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Legacy import failed!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("sellFor");
fields.add("buyFor");
fields.add("perStack");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
int itemID, perStack;
Integer itemType;
Double sellFor, buyFor;
try {
itemID = Integer.parseInt(item[0]);
if(!item[1].equals("-1") && !item[1].equals("0")) {
itemType = Integer.parseInt(item[1]);
}else{
itemType = null;
}
sellFor = Double.parseDouble(item[2]);
buyFor = Double.parseDouble(item[3]);
perStack = Integer.parseInt(item[4]);
}catch(NumberFormatException e) {
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
if(iH.isValidItem(itemID, itemType)) {
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("kind", "INT");
temp.put("data", "" + itemID);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("type")) {
temp.put("kind", "INT");
temp.put("data", "" + ((itemType == null) ? -1 : itemType));
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("sellFor")) {
temp.put("data", "" + sellFor);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("buyFor")) {
temp.put("data", "" + buyFor);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("perStack")) {
temp.put("kind", "INT");
temp.put("data", "" + perStack);
tmp.put(5, temp);
}
}
values.add(tmp);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " items to import!");
}else{
Heraut.say(sender, "Truncating items table!");
DB.Truncate("#__items").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " items...");
DB.insert("#__items", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished legacy import, though some errors occured!");
}else{
Heraut.say(sender, "Finished legacy import!");
}
}else{
Heraut.say(sender, "Legacy import failed! File (" + path + File.separator + file + ") not found!");
}
}
public static void exp(CommandSender sender, String[] args) {
File dir = new File(GiantShop.getPlugin().getDir() + File.separator + "csvs");
if(!dir.exists()) {
dir.mkdir();
}else{
if(!dir.isDirectory()) {
Heraut.say(sender, "Output directory is not a directory!");
}
}
if(args.length > 1) {
ArrayList<String> fields = new ArrayList<String>();
fields.add("*");
if(Misc.isEitherIgnoreCase(args[1], "items", "i")) {
DB.select(fields).from("#__items");
ArrayList<HashMap<String, String>> iResSet = DB.execQuery();
Heraut.say(sender, "Found " + iResSet.size() + " items to export!");
if(iResSet.size() > 0) {
Heraut.say(sender, "Starting item export...");
if(!impexp.expItem(iResSet, GiantShop.getPlugin().getDir() + File.separator + "csvs", "items.csv")){
Heraut.say(sender, "Failed item export!");
}else{
Heraut.say(sender, "Finished item export!");
}
}
}else if(Misc.isEitherIgnoreCase(args[1], "shops", "s") || args[1].equalsIgnoreCase("x")) {
DB.select(fields).from("#__shops");
ArrayList<HashMap<String, String>> sResSet = DB.execQuery();
Heraut.say(sender, "Found " + sResSet.size() + " shops to export!");
if(sResSet.size() > 0) {
Heraut.say(sender, "Starting shops export...");
if(!impexp.expShop(sResSet, GiantShop.getPlugin().getDir() + File.separator + "csvs", "shops.csv")){
Heraut.say(sender, "Failed shops export!");
}else{
Heraut.say(sender, "Finished shops export!");
}
}
}else if(Misc.isEitherIgnoreCase(args[1], "discounts", "d")) {
DB.select(fields).from("#__discounts");
ArrayList<HashMap<String, String>> dResSet = DB.execQuery();
Heraut.say(sender, "Found " + dResSet.size() + " discounts to export!");
if(dResSet.size() > 0) {
Heraut.say(sender, "Starting discounts export...");
if(!impexp.expDiscount(dResSet, GiantShop.getPlugin().getDir() + File.separator + "csvs", "discounts.csv")){
Heraut.say(sender, "Failed discounts export!");
}else{
Heraut.say(sender, "Finished discounts export!");
}
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "export");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
Heraut.say(sender, "[GiantShop] Starting export...");
ArrayList<String> fields = new ArrayList<String>();
fields.add("*");
DB.select(fields).from("#__items");
ArrayList<HashMap<String, String>> iResSet = DB.execQuery();
Heraut.say(sender, "Found " + iResSet.size() + " items to export!");
DB.select(fields).from("#__shops");
ArrayList<HashMap<String, String>> sResSet = DB.execQuery();
Heraut.say(sender, "Found " + sResSet.size() + " shops to export!");
DB.select(fields).from("#__discounts");
ArrayList<HashMap<String, String>> dResSet = DB.execQuery();
Heraut.say(sender, "Found " + dResSet.size() + " discounts to export!");
if(iResSet.size() > 0) {
Heraut.say(sender, "Starting item export...");
if(!impexp.expItem(iResSet, GiantShop.getPlugin().getDir() + File.separator + "csvs", "items.csv")){
Heraut.say(sender, "Failed item export!");
}else{
Heraut.say(sender, "Finished item export!");
}
}
if(sResSet.size() > 0) {
Heraut.say(sender, "Starting shops export...");
if(!impexp.expShop(sResSet, GiantShop.getPlugin().getDir() + File.separator + "csvs", "shops.csv")){
Heraut.say(sender, "Failed shops export!");
}else{
Heraut.say(sender, "Finished shops export!");
}
}
if(dResSet.size() > 0) {
Heraut.say(sender, "Starting discounts export...");
if(!impexp.expDiscount(dResSet, GiantShop.getPlugin().getDir() + File.separator + "csvs", "discounts.csv")){
Heraut.say(sender, "Failed discounts export!");
}else{
Heraut.say(sender, "Finished discounts export!");
}
}
Heraut.say(sender, "[GiantShop] Finished export!");
}
}
private static boolean expItem(ArrayList<HashMap<String, String>> iResSet, String dir, String file) {
try{
BufferedWriter f = new BufferedWriter(new FileWriter(dir + File.separator + file));
f.write("itemID, itemType, sellFor, buyFor, perStack, stock, shops");
f.newLine();
for(int i = 0; i < iResSet.size(); i++) {
HashMap<String, String> data = iResSet.get(i);
String itemId = data.get("itemID");
String dataType = data.get("itemType");
String sellFor = data.get("sellFor");
String buyFor = data.get("buyFor");
String amount = data.get("perStack");
String stock = data.get("stock");
String shops = (!data.get("shops").isEmpty()) ? data.get("shops") : "null";
f.write(itemId + ", " + dataType + ", " + sellFor + ", " + buyFor + ", " + amount + ", " + stock + ", " + shops);
f.newLine();
}
f.flush();
f.close();
}catch(IOException e) {
return false;
}finally{
return true;
}
}
private static boolean expShop(ArrayList<HashMap<String, String>> sResSet, String dir, String file) {
try{
BufferedWriter f = new BufferedWriter(new FileWriter(dir + File.separator + file));
f.write("name, perms, world, locMinX, locMinY, locMinZ, locMaxX, locMaxY, locMaxZ");
f.newLine();
for(int i = 0; i < sResSet.size(); i++) {
HashMap<String, String> data = sResSet.get(i);
String name = data.get("name");
String perms = data.get("perms");
String world = data.get("world");
String locMinX = data.get("locMinX");
String locMinY = data.get("locMinY");
String locMinZ = data.get("locMinZ");
String locMaxX = data.get("locMaxX");
String locMaxY = data.get("locMaxY");
String locMaxZ = data.get("locMaxZ");
f.write(name + ", " + perms + ", " + world + ", " + locMinX + ", " + locMinY + ", " + locMinZ + ", " + locMaxX + ", " + locMaxY + ", " + locMaxZ);
f.newLine();
}
f.flush();
f.close();
}catch(IOException e) {
return false;
}finally{
return true;
}
}
private static boolean expDiscount(ArrayList<HashMap<String, String>> dResSet, String dir, String file) {
try{
BufferedWriter f = new BufferedWriter(new FileWriter(dir + File.separator + file));
f.write("itemID, dicount, user, group");
f.newLine();
for(int i = 0; i < dResSet.size(); i++) {
HashMap<String, String> data = dResSet.get(i);
String itemID = data.get("itemID");
String dicount = data.get("dicount");
String user = data.get("user");
String group = data.get("world");
f.write(itemID + ", " + dicount + ", " + user + ", " + group);
f.newLine();
}
f.flush();
f.close();
}catch(IOException e) {
return false;
}finally{
return true;
}
}
}
| false | true | public static void imp(CommandSender sender, String[] args) {
if(args.length > 1) {
ArrayList<String> fields;
ArrayList<HashMap<Integer, HashMap<String, String>>> values;
String type = "items";
String path = GiantShop.getPlugin().getDir() + File.separator + "csvs";
String file = null;
Boolean commence = true;
Boolean err = false;
for(int i = 0; i < args.length; i++) {
if(args[i].startsWith("-t:")) {
type = args[i].replaceFirst("-t:", "");
continue;
}else if(args[i].startsWith("-p:")) {
path = args[i].replaceFirst("-p:", "");
continue;
}else if(args[i].startsWith("-c:")) {
commence = Boolean.parseBoolean(args[i].replaceFirst("-c:", ""));
continue;
}else if(args[i].startsWith("-f:")) {
file = args[i].replaceFirst("-f:", "");
continue;
}
}
if(Misc.isEitherIgnoreCase(type, "items", "i")) {
file = (file == null) ? "items.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing items...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("itemID, itemType, sellFor, buyFor, perStack, stock, shops")) {
Heraut.say(sender, "The given file is not a proper items file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length >= 6) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed items import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("perStack");
fields.add("shops");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
int itemID, stock, perStack;
Integer itemType;
Double sellFor, buyFor;
try {
itemID = Integer.parseInt(item[0]);
if(!item[1].equals("null")) {
itemType = Integer.parseInt(item[1]);
}else{
itemType = null;
}
sellFor = Double.parseDouble(item[2]);
buyFor = Double.parseDouble(item[3]);
perStack = Integer.parseInt(item[4]);
stock = Integer.parseInt(item[5]);
}catch(NumberFormatException e) {
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
if(iH.isValidItem(itemID, itemType)) {
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("kind", "INT");
temp.put("data", "" + itemID);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("type")) {
temp.put("kind", "INT");
temp.put("data", "" + ((itemType == null) ? -1 : itemType));
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("sellFor")) {
temp.put("data", "" + sellFor);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("buyFor")) {
temp.put("data", "" + buyFor);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("stock")) {
temp.put("kind", "INT");
temp.put("data", "" + stock);
tmp.put(4, temp);
}else if(field.equalsIgnoreCase("perStack")) {
temp.put("kind", "INT");
temp.put("data", "" + perStack);
tmp.put(5, temp);
}else if(field.equalsIgnoreCase("shops")) {
if(item.length == 7)
temp.put("data", (item[6].equals("null") ? "" : item[6]));
else
temp.put("data", "");
tmp.put(6, temp);
}
}
values.add(tmp);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " items to import!");
}else{
Heraut.say(sender, "Truncating items table!");
DB.Truncate("#__items").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " items...");
DB.insert("#__items", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing items, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing items!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else if(Misc.isEitherIgnoreCase(type, "shops", "s")) {
file = (file == null) ? "shops.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing shops...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("name, perms, world, locMinX, locMinY, locMinZ, locMaxX, locMaxY, locMaxZ")) {
Heraut.say(sender, "The given file is not a proper shops file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 9) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed shops import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("name");
fields.add("perms");
fields.add("world");
fields.add("locMinX");
fields.add("locMinY");
fields.add("locMinZ");
fields.add("locMaxX");
fields.add("locMaxY");
fields.add("locMaxZ");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("name")) {
temp.put("data", "" + item[0]);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("perms")) {
temp.put("data", "" + item[1]);
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("world")) {
temp.put("data", "" + item[2]);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("locMinX")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMinY")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMinZ")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMaxX")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMaxY")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMaxZ")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}
}
values.add(tmp);
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " shops to import!");
}else{
Heraut.say(sender, "Truncating items shops!");
DB.Truncate("#__shops").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " shops...");
DB.insert("#__shops", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing shops, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing shops!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else if(Misc.isEitherIgnoreCase(type, "discounts", "d")) {
file = (file == null) ? "discounts.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing discounts...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("itemID, dicount, user, group")) {
Heraut.say(sender, "The given file is not a proper discounts file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 4) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed discounts import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("discount");
fields.add("user");
fields.add("group");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("data", "" + item[0]);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("discount")) {
temp.put("data", "" + item[1]);
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("user")) {
temp.put("data", "" + item[2]);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("group")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}
}
values.add(tmp);
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " discounts to import!");
}else{
Heraut.say(sender, "Truncating items __discounts!");
DB.Truncate("#__discounts").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " __discounts...");
DB.insert("#__discounts", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing discounts, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing discounts!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "import");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "import");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}
| public static void imp(CommandSender sender, String[] args) {
if(args.length > 1) {
ArrayList<String> fields;
ArrayList<HashMap<Integer, HashMap<String, String>>> values;
String type = "items";
String path = GiantShop.getPlugin().getDir() + File.separator + "csvs";
String file = null;
Boolean commence = true;
Boolean err = false;
for(int i = 0; i < args.length; i++) {
if(args[i].startsWith("-t:")) {
type = args[i].replaceFirst("-t:", "");
continue;
}else if(args[i].startsWith("-p:")) {
path = args[i].replaceFirst("-p:", "");
continue;
}else if(args[i].startsWith("-c:")) {
commence = Boolean.parseBoolean(args[i].replaceFirst("-c:", ""));
continue;
}else if(args[i].startsWith("-f:")) {
file = args[i].replaceFirst("-f:", "");
continue;
}
}
if(Misc.isEitherIgnoreCase(type, "items", "i")) {
file = (file == null) ? "items.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing items...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("itemID, itemType, sellFor, buyFor, perStack, stock, shops")) {
Heraut.say(sender, "The given file is not a proper items file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length >= 6) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed items import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("type");
fields.add("sellFor");
fields.add("buyFor");
fields.add("stock");
fields.add("perStack");
fields.add("shops");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
int itemID, stock, perStack;
Integer itemType;
Double sellFor, buyFor;
try {
itemID = Integer.parseInt(item[0]);
if(!item[1].equals("null")) {
itemType = Integer.parseInt(item[1]);
}else{
itemType = null;
}
sellFor = Double.parseDouble(item[2]);
buyFor = Double.parseDouble(item[3]);
perStack = Integer.parseInt(item[4]);
stock = Integer.parseInt(item[5]);
}catch(NumberFormatException e) {
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
if(iH.isValidItem(itemID, itemType)) {
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("kind", "INT");
temp.put("data", "" + itemID);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("type")) {
temp.put("kind", "INT");
temp.put("data", "" + ((itemType == null) ? -1 : itemType));
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("sellFor")) {
temp.put("data", "" + sellFor);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("buyFor")) {
temp.put("data", "" + buyFor);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("stock")) {
temp.put("kind", "INT");
temp.put("data", "" + stock);
tmp.put(4, temp);
}else if(field.equalsIgnoreCase("perStack")) {
temp.put("kind", "INT");
temp.put("data", "" + perStack);
tmp.put(5, temp);
}else if(field.equalsIgnoreCase("shops")) {
if(item.length == 7)
temp.put("data", (item[6].equals("null") ? "" : item[6]));
else
temp.put("data", "");
tmp.put(6, temp);
}
}
values.add(tmp);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + item.toString() + ")");
continue;
}
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " items to import!");
}else{
Heraut.say(sender, "Truncating items table!");
DB.Truncate("#__items").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " items...");
DB.insert("#__items", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing items, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing items!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else if(Misc.isEitherIgnoreCase(type, "shops", "s")) {
file = (file == null) ? "shops.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing shops...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("name, perms, world, locMinX, locMinY, locMinZ, locMaxX, locMaxY, locMaxZ")) {
Heraut.say(sender, "The given file is not a proper shops file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 9) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed shops import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("name");
fields.add("perms");
fields.add("world");
fields.add("locMinX");
fields.add("locMinY");
fields.add("locMinZ");
fields.add("locMaxX");
fields.add("locMaxY");
fields.add("locMaxZ");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("name")) {
temp.put("data", "" + item[0]);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("perms")) {
temp.put("data", "" + item[1]);
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("world")) {
temp.put("data", "" + item[2]);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("locMinX")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}else if(field.equalsIgnoreCase("locMinY")) {
temp.put("data", item[3]);
tmp.put(4, temp);
}else if(field.equalsIgnoreCase("locMinZ")) {
temp.put("data", item[3]);
tmp.put(5, temp);
}else if(field.equalsIgnoreCase("locMaxX")) {
temp.put("data", item[3]);
tmp.put(6, temp);
}else if(field.equalsIgnoreCase("locMaxY")) {
temp.put("data", item[3]);
tmp.put(7, temp);
}else if(field.equalsIgnoreCase("locMaxZ")) {
temp.put("data", item[3]);
tmp.put(8, temp);
}
}
values.add(tmp);
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " shops to import!");
}else{
Heraut.say(sender, "Truncating items shops!");
DB.Truncate("#__shops").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " shops...");
DB.insert("#__shops", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing shops, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing shops!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else if(Misc.isEitherIgnoreCase(type, "discounts", "d")) {
file = (file == null) ? "discounts.csv" : file;
File f = new File(path + File.separator + file);
if(f.exists()) {
Heraut.say(sender, "Starting importing discounts...");
ArrayList<String[]> items = new ArrayList<String[]>();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path + File.separator + file));
if(br.ready()) {
int lineNumber = 0;
while((line = br.readLine()) != null) {
lineNumber++;
if(lineNumber <= 1) {
if(!line.equals("itemID, dicount, user, group")) {
Heraut.say(sender, "The given file is not a proper discounts file!");
br.close();
return;
}
continue;
}
//break comma separated line using ", "
String[] st = line.split(", ");
if(st.length == 4) {
items.add(st);
}else{
err = true;
Heraut.say(sender, "Invalid entry detected! (" + lineNumber + ":" + line + ")");
continue;
}
}
}
br.close();
}catch(IOException e) {
Heraut.say(sender, "Failed discounts import!");
GiantShop.getPlugin().getLogger().log(Level.SEVERE, "" + e);
return;
}
fields = new ArrayList<String>();
fields.add("itemID");
fields.add("discount");
fields.add("user");
fields.add("group");
values = new ArrayList<HashMap<Integer, HashMap<String, String>>>();
int lineNumber = 0;
for(String[] item : items) {
lineNumber++;
HashMap<Integer, HashMap<String, String>> tmp = new HashMap<Integer, HashMap<String, String>>();
for(String field : fields) {
HashMap<String, String> temp = new HashMap<String, String>();
if(field.equalsIgnoreCase("itemID")) {
temp.put("data", "" + item[0]);
tmp.put(0, temp);
}else if(field.equalsIgnoreCase("discount")) {
temp.put("data", "" + item[1]);
tmp.put(1, temp);
}else if(field.equalsIgnoreCase("user")) {
temp.put("data", "" + item[2]);
tmp.put(2, temp);
}else if(field.equalsIgnoreCase("group")) {
temp.put("data", item[3]);
tmp.put(3, temp);
}
}
values.add(tmp);
}
if(!commence) {
Heraut.say(sender, "Found " + values.size() + " discounts to import!");
}else{
Heraut.say(sender, "Truncating items __discounts!");
DB.Truncate("#__discounts").updateQuery();
Heraut.say(sender, "Importing " + values.size() + " __discounts...");
DB.insert("#__discounts", fields, values).updateQuery();
}
if(err) {
Heraut.say(sender, "Finished importing discounts, though some errors occured!");
}else{
Heraut.say(sender, "Finished importing discounts!");
}
}else{
Heraut.say(sender, "Requested file does not exist!");
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "import");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}else{
HashMap<String, String> data = new HashMap<String, String>();
data.put("command", "import");
Heraut.say(sender, mH.getConsoleMsg(Messages.msgType.ERROR, "syntaxError", data));
}
}
|
diff --git a/src-tools/org/seasr/meandre/components/tools/geo/GeoLocationCleaner.java b/src-tools/org/seasr/meandre/components/tools/geo/GeoLocationCleaner.java
index fe16a892..15112987 100644
--- a/src-tools/org/seasr/meandre/components/tools/geo/GeoLocationCleaner.java
+++ b/src-tools/org/seasr/meandre/components/tools/geo/GeoLocationCleaner.java
@@ -1,688 +1,694 @@
/**
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2008, Board of Trustees-University of Illinois.
* All rights reserved.
*
* Developed by:
*
* Automated Learning Group
* National Center for Supercomputing Applications
* http://www.seasr.org
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal with 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of Automated Learning Group, The National Center for
* Supercomputing Applications, or University of Illinois, nor the names of
* its contributors may be used to endorse or promote products derived from
* this Software without specific prior written permission.
*
* 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
* CONTRIBUTORS 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
* WITH THE SOFTWARE.
*/
package org.seasr.meandre.components.tools.geo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.meandre.annotations.Component;
import org.meandre.annotations.ComponentInput;
import org.meandre.annotations.ComponentOutput;
import org.meandre.annotations.ComponentProperty;
import org.meandre.annotations.Component.FiringPolicy;
import org.meandre.annotations.Component.Licenses;
import org.meandre.annotations.Component.Mode;
import org.meandre.components.abstracts.AbstractExecutableComponent;
import org.meandre.core.ComponentContext;
import org.meandre.core.ComponentContextProperties;
import org.seasr.datatypes.BasicDataTypesTools;
import org.seasr.datatypes.BasicDataTypes.Strings;
import org.seasr.datatypes.BasicDataTypes.StringsArray;
import org.seasr.meandre.components.tools.Names;
import org.seasr.meandre.support.components.tuples.SimpleTuple;
import org.seasr.meandre.support.components.tuples.SimpleTuplePeer;
import org.seasr.meandre.support.components.geographic.GeoLocation;
/**
*
* @author Mike Haberman;
* ABQIAAAADV1H5JfZH41B6yxB1yGVFhQmgYtTImkVBc-VhblDgOLOdwhVaBSPwcEgsBl7atDdDJjnfl51p9fU5A
*
* Yahoo problems: location=New England
*
*/
@Component(
name = "GeoLocation Cleaner",
creator = "Mike Haberman",
baseURL = "meandre://seasr.org/components/foundry/",
firingPolicy = FiringPolicy.all,
mode = Mode.compute,
rights = Licenses.UofINCSA,
tags = "tuple, group",
description = "This component uses the Yahoo GeoService to attempt to fully qualify " +
"location entities within a single sentence." ,
dependency = {"trove-2.0.3.jar","protobuf-java-2.2.0.jar"}
)
public class GeoLocationCleaner extends AbstractExecutableComponent {
//------------------------------ INPUTS ------------------------------------------------------
@ComponentInput(
name = Names.PORT_TUPLES,
description = "set of labelled tuples to be grouped (e.g. startTokenPosition, token, concept)" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.StringsArray"
)
protected static final String IN_TUPLES = Names.PORT_TUPLES;
@ComponentInput(
name = Names.PORT_META_TUPLE,
description = "meta data for tuples to be labeled" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Strings"
)
protected static final String IN_META_TUPLE = Names.PORT_META_TUPLE;
//------------------------------ OUTPUTS -----------------------------------------------------
@ComponentOutput(
name = Names.PORT_TUPLES,
description = "set of grouped tuples" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.StringsArray"
)
protected static final String OUT_TUPLES = Names.PORT_TUPLES;
@ComponentOutput(
name = Names.PORT_META_TUPLE,
description = "meta data for the tuples (windowId, begin, end, concept, count, frequency)" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Strings"
)
protected static final String OUT_META_TUPLE = Names.PORT_META_TUPLE;
//----------------------------- PROPERTIES ---------------------------------------------------
@ComponentProperty(
description = "field name for the n.e. type",
name = "key",
defaultValue = "type"
)
protected static final String DATA_PROPERTY_KEY_FIELD = "key";
@ComponentProperty(
description = "field name for the value to use for windowing, must be numeric",
name = "windowField",
defaultValue = "sentenceId"
)
protected static final String DATA_PROPERTY_WINDOW_FIELD = "windowField";
/* NOT USED
@ComponentProperty(
description = "window size, -1 means use dynamic value based on maxWindows",
name = "windowSize",
defaultValue = "-1"
)
protected static final String DATA_PROPERTY_WINDOW_SIZE = "windowSize";
@ComponentProperty(
description = "max. number of windows, -1 means use dyanamic value based on windowSize",
name = "maxWindows",
defaultValue = "-1"
)
protected static final String DATA_PROPERTY_MAX_WINDOWS = "maxWindows";
*/
//--------------------------------------------------------------------------------------------
// fields for accessing the incoming tuples
private String keyField = "type";
private String valueField = "text";
private String windowField = "sentenceId";
// fields added to the outgoing tuples
private String locationField = "fqLocation";
private String latField = "lat";
private String longField = "long";
private String[] newFields = {locationField, latField, longField};
long windowSize = 1;
// TODO,(perhaps) make this a property
// number of sentences to consume before labeling them
// a better algorithm, might be to use a sliding window cache of sentences
// so sentence N gets resolved after processing sentence N-1 and N+1
//
//--------------------------------------------------------------------------------------------
private Map<String, GeoLocation> globalCache = new HashMap<String,GeoLocation>();
@Override
public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
this.keyField = ccp.getProperty(DATA_PROPERTY_KEY_FIELD);
this.windowField = ccp.getProperty(DATA_PROPERTY_WINDOW_FIELD);
}
@Override
public void executeCallBack(ComponentContext cc) throws Exception {
Strings inputMeta = (Strings) cc.getDataComponentFromInput(IN_META_TUPLE);
SimpleTuplePeer inPeer = new SimpleTuplePeer(inputMeta);
SimpleTuplePeer outPeer = new SimpleTuplePeer(inPeer, newFields);
StringsArray input = (StringsArray) cc.getDataComponentFromInput(IN_TUPLES);
Strings[] in = BasicDataTypesTools.stringsArrayToJavaArray(input);
SimpleTuple tuple = inPeer.createTuple();
SimpleTuple outTuple = outPeer.createTuple();
int KEY_IDX = inPeer.getIndexForFieldName(keyField);
int VALUE_IDX = inPeer.getIndexForFieldName(valueField);
int START_IDX = inPeer.getIndexForFieldName(windowField);
// cache the outgoing fields
int FQLOC_IDX = outPeer.getIndexForFieldName(locationField);
int LAT_IDX = outPeer.getIndexForFieldName(latField);
int LONG_IDX = outPeer.getIndexForFieldName(longField);
if (KEY_IDX == -1){
console.info(inPeer.toString());
throw new RuntimeException("tuple has no key field " + keyField);
}
if (START_IDX == -1){
throw new RuntimeException("tuple has no window field " + windowField);
}
List<Strings> output = new ArrayList<Strings>();
long lastPosition = 0;
List<String> locations = new ArrayList<String>();
int lastIdx = 0;
for (int i = 0; i < in.length; i++) {
tuple.setValues(in[i]);
String key = tuple.getValue(KEY_IDX);
String value = tuple.getValue(VALUE_IDX);
long currentPosition = Long.parseLong(tuple.getValue(START_IDX));
if (! key.equals("location")) {
continue;
}
if (value == null) {
console.info("warning, null location");
continue;
}
if (currentPosition - lastPosition >= windowSize || (i + 1 == in.length)) {
int end = i;
// if this is it, add the last location to our set
if (i + 1 == in.length) {
end = i + 1;
locations.add(value);
}
//
// resolve locations in the window
//
console.fine(lastPosition +"," + currentPosition + " locations to process: " + locations.size());
console.fine(lastIdx + " to " + end);
Map<String,GeoLocation> map = resolve(locations);
// now relabel each location
for (int j = lastIdx; j < end; j++) {
// relabel
tuple.setValues(in[j]);
key = tuple.getValue(VALUE_IDX);
GeoLocation geo = map.get(key);
if (geo == null) {
// check the global cache
geo = globalCache.get(key);
}
outTuple.setValue(tuple); // copy original values
if (geo != null) {
// ("MAP " + key + " : " + geo.toString());
outTuple.setValue(FQLOC_IDX, geo.getQueryLocation());
outTuple.setValue(LAT_IDX, geo.getLatitude());
outTuple.setValue(LONG_IDX, geo.getLongitude());
globalCache.put(key, geo);
}
else {
// console.fine("NO MAP for key " + key);
outTuple.setValue(FQLOC_IDX, "N.A");
outTuple.setValue(LAT_IDX, "-1");
outTuple.setValue(LONG_IDX, "-1");
}
output.add(outTuple.convert());
}
lastPosition = currentPosition;
lastIdx = i;
locations.clear();
}
// add the location
locations.add(value);
}
//
// push the whole collection, protocol safe
//
Strings[] results = new Strings[output.size()];
output.toArray(results);
StringsArray outputSafe = BasicDataTypesTools.javaArrayToStringsArray(results);
cc.pushDataComponentToOutput(OUT_TUPLES, outputSafe);
//
// metaData for this tuple producer
//
cc.pushDataComponentToOutput(OUT_META_TUPLE, outPeer.convert());
}
@Override
public void disposeCallBack(ComponentContextProperties ccp) throws Exception {
}
//
// This algorithm is based mostly on empirical data and heuristics
// it is mostly used for resolving city and state information
// if address or zip code resolution were needed, this will not work
// it is also tuned to the Yahoo GeoCaching service
// This algorithm MUST be re-written if another (more accurate) ? service
// is used.
// I am NOT proud of this code :) M.E.H
//
public Map<String,GeoLocation> resolve(List<String> locations)
{
- console.fine("request to resolve " + locations.size());
+ console.fine("request to resolve: " + locations.size());
Map<String,GeoLocation> out = new HashMap<String,GeoLocation>();
// reduce: A,B ==> AB
// if A + B ==> resolve to ONE location, remove B
List<String> more = new ArrayList<String>();
int size = locations.size();
for (int i = 0; i < size;) {
String a = locations.get(i++);
if (i < size) {
String b = locations.get(i++);
if (a.equals(b)) {
// if both are the same, just skip
i--;
continue;
}
//
// Hack for special case: states
//
// Pennsylvania, New York (a street in New York, or 2 states)
// Richmond, Virginia ==> both return unique
// Richmond --> returns "zip"
// Virginia --> returns "state"
// New York --> returns "zip" precision
// Pennsylvania --> returns "state" precision
List<GeoLocation> geosA = getLocations(GeoLocation.P_STATE, a);
List<GeoLocation> geosB = getLocations(GeoLocation.P_STATE, b);
// even though we requested state precision, the result may not be
- console.fine("A " + a + " " + geosA.size());
- console.fine("B " + b + " " + geosB.size());
+ console.fine(i + " A " + a + " " + geosA.size());
+ console.fine(i + " B " + b + " " + geosB.size());
GeoLocation geoA = null;
GeoLocation geoB = null;
if (geosA.size() == 1) {
geoA = geosA.get(0);
}
if (geosB.size() == 1) {
geoB = geosB.get(0);
}
if (geoA != null && geoB != null) {
//
// Virginia, Kentucky ==> is a city in KY
// assume if both are states, that wins
if (geoA.isState() && geoB.isState()) {
out.put(a, geoA);
out.put(b, geoB);
continue;
}
// check if one is within the other
// e.g. Richmond, VA AND Virgina
if (geoA.isFoundWithin(geoB)) {
// e.g Richmond, Virgina
String c = a + "," + b;
console.fine("A is in B " + c);
geoA.setQueryLocation(c);
out.put(a, geoA);
out.put(b, geoA);
continue;
}
else if (geoB.isFoundWithin(geoA)) {
// Virgina, Richmond
String c = b + "," + a;
console.fine("B is in A " + c);
geoB.setQueryLocation(c);
out.put(a, geoB); // or NULL ?
out.put(b, geoB);
continue;
}
else if (geoA.isState()) {
//
// I moved from Virginia to Burks County
//
out.put(a, geoA);
i--; // re-process B
continue;
}
else {
// we will tackle this case below
}
}
else if (geosA.size() > 1 && geosB.size() > 1) {
//
// try to find a commonn state
// while in Bloomington, I came across someone from Springfield
//
}
//
// try the two combined into a single location
//
//
//
//
String c = a + "," + b;
List<GeoLocation> geos = getLocations(c);
if (geos.size() == 1) {
GeoLocation geo = geos.get(0);
// Bloomington,Springfield ==> returns "address" precision
// Bolivia, Illinois ==> returns "zip" precision
if (geo.getPrecision() > GeoLocation.P_ZIP) {
// not what we want
- more.add(a); i--; // reprocess the b
+ more.add(a); i--; // reprocess b
continue;
}
if (geoB != null) {
//
// Springfield ==> lots
// Washington ==> DC (zip)
// Springfield, Washington == > KY (zip)
//
String stateB = geoB.getState();
String stateC = geo.getState();
- console.fine("b " + stateB + " " + geoB.toString());
- console.fine("c " + stateC + " " + geo.toString());
+ console.fine("b " + stateB + " ==> " + geoB.toString());
+ console.fine("c " + stateC + " ==> " + geo.toString());
if (stateB.equals(stateC)) {
+ console.fine(a + " AND " + b + " map to " + geo.toString());
out.put(a, geo);
out.put(b, geo);
}
+ else {
+ console.info("save for later " + a);
+ more.add(a); i--; // reprocess b
+ continue;
+ }
} else { // geoB == null (i.e. geoB.size() > 0)
// we got a unique location (geo != null)
// but it may NOT be because of a,b
// Wisconsin, New Salam --> WI, (state)
// Bolivia, Springfield --> Boliva (country)
// (google returns an address in springfield, yahoo, just the country)
if (geoA != null && geo.getState().equals(geoA.getState())) {
console.fine("adding each as separate geos " + a + " " + b);
out.put(a, geoA);
out.put(b, geoB); // could be null
}
else {
console.fine("adding combo " + a + " " + b);
out.put(a, geo);
out.put(b, geo);
}
}
}
else {
// geos.size() != 1
more.add(a);
i--; // reprocess the b
}
}
else {
more.add(a);
}
} // end of loop over locations
locations.clear();
locations.addAll(more);
//
// handle strange cases here
//
// Illinois, Springfield ==>
// Springfield --> many, one has IL as state
// Illinois --> the state
// ex, Frederick ---> a bunch, no virgina
// Virginia --> state
// Frederick, Virigina ==> YES
//
// Illinois,Paris ==> Paris France and IL (State)
// want a city
//
List<GeoLocation> keep = new ArrayList<GeoLocation>();
List<String> toResolve = new ArrayList<String>();
//
// remove those that resolve to a single location
//
console.fine("leftovers " + locations.size());
for (String loc : locations) {
List<GeoLocation> geos = getLocations(loc);
console.fine(loc + " " + geos.size());
if (geos.size() == 1) {
keep.addAll(geos);
out.put(loc, geos.get(0));
}
else if (geos.size() > 1) {
toResolve.add(loc);
}
}
if (toResolve.size() == 0) {
return out;
}
for (String loc : toResolve) {
List<GeoLocation> geos = getLocations(loc);
// see if any of the geos are found within any of the keepers
GeoLocation a = resolve(keep, geos);
if (a != null) {
console.fine("found keeper " + loc);
out.put(loc, a);
}
else { // a == null
// try adding loc to each value in keep until you get a unique value
for (GeoLocation geo: keep) {
if (geo.isState()) {
String newLocation = loc + "," + geo.getState();
List<GeoLocation> vals = getLocations(newLocation);
console.fine("Dx " + newLocation + ":" + vals.size());
if (vals.size() == 1) {
a = vals.get(0);
console.fine("YES " + a);
// WOW we found it
out.put(loc, a);
}
}
else {
console.fine("not state " + geo);
}
}
}
}
return out;
}
public GeoLocation resolve(List<GeoLocation> keepList, List<GeoLocation> geos)
{
for (GeoLocation tmp: geos) { // e.g. Springfield
for (GeoLocation k: keepList) { // e.g. Illinois
if (tmp.isFoundWithin(k)) {
String q = tmp.getQueryLocation() + "," + k.getQueryLocation();
System.out.println("check " + q);
List<GeoLocation> vals = getLocations(q);
if (vals.size() > 0) {
return vals.get(0);
}
}
}
}
return null;
}
Map<String, List<GeoLocation>> cache = new HashMap<String, List<GeoLocation>>();
public List<GeoLocation> getLocations(String location)
{
return getLocations(GeoLocation.P_LOCATION, location);
}
public List<GeoLocation> getLocations(int type, String location)
{
//
// TODO: cache the results
// apply remaps here Ill. --> Illinois
//
String key = location + "." + type;
List<GeoLocation> entry = cache.get(key);
if (entry == null) {
try {
entry = GeoLocation.getAllLocations(type, location);
cache.put(key, entry);
return entry;
}
catch (Exception e) {
console.fine("WARNING ERROR " + e.toString());
return new ArrayList<GeoLocation>();
}
}
return entry;
}
}
/*
Strings inputMeta = (Strings) cc.getDataComponentFromInput(IN_META_TUPLE);
String[] meta = DataTypeParser.parseAsString(inputMeta);
String fields = meta[0];
DynamicTuplePeer inPeer = new DynamicTuplePeer(fields);
Strings input = (Strings) cc.getDataComponentFromInput(IN_TUPLES);
String[] tuples = DataTypeParser.parseAsString(input);
*/
| false | true | public Map<String,GeoLocation> resolve(List<String> locations)
{
console.fine("request to resolve " + locations.size());
Map<String,GeoLocation> out = new HashMap<String,GeoLocation>();
// reduce: A,B ==> AB
// if A + B ==> resolve to ONE location, remove B
List<String> more = new ArrayList<String>();
int size = locations.size();
for (int i = 0; i < size;) {
String a = locations.get(i++);
if (i < size) {
String b = locations.get(i++);
if (a.equals(b)) {
// if both are the same, just skip
i--;
continue;
}
//
// Hack for special case: states
//
// Pennsylvania, New York (a street in New York, or 2 states)
// Richmond, Virginia ==> both return unique
// Richmond --> returns "zip"
// Virginia --> returns "state"
// New York --> returns "zip" precision
// Pennsylvania --> returns "state" precision
List<GeoLocation> geosA = getLocations(GeoLocation.P_STATE, a);
List<GeoLocation> geosB = getLocations(GeoLocation.P_STATE, b);
// even though we requested state precision, the result may not be
console.fine("A " + a + " " + geosA.size());
console.fine("B " + b + " " + geosB.size());
GeoLocation geoA = null;
GeoLocation geoB = null;
if (geosA.size() == 1) {
geoA = geosA.get(0);
}
if (geosB.size() == 1) {
geoB = geosB.get(0);
}
if (geoA != null && geoB != null) {
//
// Virginia, Kentucky ==> is a city in KY
// assume if both are states, that wins
if (geoA.isState() && geoB.isState()) {
out.put(a, geoA);
out.put(b, geoB);
continue;
}
// check if one is within the other
// e.g. Richmond, VA AND Virgina
if (geoA.isFoundWithin(geoB)) {
// e.g Richmond, Virgina
String c = a + "," + b;
console.fine("A is in B " + c);
geoA.setQueryLocation(c);
out.put(a, geoA);
out.put(b, geoA);
continue;
}
else if (geoB.isFoundWithin(geoA)) {
// Virgina, Richmond
String c = b + "," + a;
console.fine("B is in A " + c);
geoB.setQueryLocation(c);
out.put(a, geoB); // or NULL ?
out.put(b, geoB);
continue;
}
else if (geoA.isState()) {
//
// I moved from Virginia to Burks County
//
out.put(a, geoA);
i--; // re-process B
continue;
}
else {
// we will tackle this case below
}
}
else if (geosA.size() > 1 && geosB.size() > 1) {
//
// try to find a commonn state
// while in Bloomington, I came across someone from Springfield
//
}
//
// try the two combined into a single location
//
//
//
//
String c = a + "," + b;
List<GeoLocation> geos = getLocations(c);
if (geos.size() == 1) {
GeoLocation geo = geos.get(0);
// Bloomington,Springfield ==> returns "address" precision
// Bolivia, Illinois ==> returns "zip" precision
if (geo.getPrecision() > GeoLocation.P_ZIP) {
// not what we want
more.add(a); i--; // reprocess the b
continue;
}
if (geoB != null) {
//
// Springfield ==> lots
// Washington ==> DC (zip)
// Springfield, Washington == > KY (zip)
//
String stateB = geoB.getState();
String stateC = geo.getState();
console.fine("b " + stateB + " " + geoB.toString());
console.fine("c " + stateC + " " + geo.toString());
if (stateB.equals(stateC)) {
out.put(a, geo);
out.put(b, geo);
}
} else { // geoB == null (i.e. geoB.size() > 0)
// we got a unique location (geo != null)
// but it may NOT be because of a,b
// Wisconsin, New Salam --> WI, (state)
// Bolivia, Springfield --> Boliva (country)
// (google returns an address in springfield, yahoo, just the country)
if (geoA != null && geo.getState().equals(geoA.getState())) {
console.fine("adding each as separate geos " + a + " " + b);
out.put(a, geoA);
out.put(b, geoB); // could be null
}
else {
console.fine("adding combo " + a + " " + b);
out.put(a, geo);
out.put(b, geo);
}
}
}
else {
// geos.size() != 1
more.add(a);
i--; // reprocess the b
}
}
else {
more.add(a);
}
} // end of loop over locations
locations.clear();
locations.addAll(more);
//
// handle strange cases here
//
// Illinois, Springfield ==>
// Springfield --> many, one has IL as state
// Illinois --> the state
// ex, Frederick ---> a bunch, no virgina
// Virginia --> state
// Frederick, Virigina ==> YES
//
// Illinois,Paris ==> Paris France and IL (State)
// want a city
//
List<GeoLocation> keep = new ArrayList<GeoLocation>();
List<String> toResolve = new ArrayList<String>();
//
// remove those that resolve to a single location
//
console.fine("leftovers " + locations.size());
for (String loc : locations) {
List<GeoLocation> geos = getLocations(loc);
console.fine(loc + " " + geos.size());
if (geos.size() == 1) {
keep.addAll(geos);
out.put(loc, geos.get(0));
}
else if (geos.size() > 1) {
toResolve.add(loc);
}
}
if (toResolve.size() == 0) {
return out;
}
for (String loc : toResolve) {
List<GeoLocation> geos = getLocations(loc);
// see if any of the geos are found within any of the keepers
GeoLocation a = resolve(keep, geos);
if (a != null) {
console.fine("found keeper " + loc);
out.put(loc, a);
}
else { // a == null
// try adding loc to each value in keep until you get a unique value
for (GeoLocation geo: keep) {
if (geo.isState()) {
String newLocation = loc + "," + geo.getState();
List<GeoLocation> vals = getLocations(newLocation);
console.fine("Dx " + newLocation + ":" + vals.size());
if (vals.size() == 1) {
a = vals.get(0);
console.fine("YES " + a);
// WOW we found it
out.put(loc, a);
}
}
else {
console.fine("not state " + geo);
}
}
}
}
return out;
}
| public Map<String,GeoLocation> resolve(List<String> locations)
{
console.fine("request to resolve: " + locations.size());
Map<String,GeoLocation> out = new HashMap<String,GeoLocation>();
// reduce: A,B ==> AB
// if A + B ==> resolve to ONE location, remove B
List<String> more = new ArrayList<String>();
int size = locations.size();
for (int i = 0; i < size;) {
String a = locations.get(i++);
if (i < size) {
String b = locations.get(i++);
if (a.equals(b)) {
// if both are the same, just skip
i--;
continue;
}
//
// Hack for special case: states
//
// Pennsylvania, New York (a street in New York, or 2 states)
// Richmond, Virginia ==> both return unique
// Richmond --> returns "zip"
// Virginia --> returns "state"
// New York --> returns "zip" precision
// Pennsylvania --> returns "state" precision
List<GeoLocation> geosA = getLocations(GeoLocation.P_STATE, a);
List<GeoLocation> geosB = getLocations(GeoLocation.P_STATE, b);
// even though we requested state precision, the result may not be
console.fine(i + " A " + a + " " + geosA.size());
console.fine(i + " B " + b + " " + geosB.size());
GeoLocation geoA = null;
GeoLocation geoB = null;
if (geosA.size() == 1) {
geoA = geosA.get(0);
}
if (geosB.size() == 1) {
geoB = geosB.get(0);
}
if (geoA != null && geoB != null) {
//
// Virginia, Kentucky ==> is a city in KY
// assume if both are states, that wins
if (geoA.isState() && geoB.isState()) {
out.put(a, geoA);
out.put(b, geoB);
continue;
}
// check if one is within the other
// e.g. Richmond, VA AND Virgina
if (geoA.isFoundWithin(geoB)) {
// e.g Richmond, Virgina
String c = a + "," + b;
console.fine("A is in B " + c);
geoA.setQueryLocation(c);
out.put(a, geoA);
out.put(b, geoA);
continue;
}
else if (geoB.isFoundWithin(geoA)) {
// Virgina, Richmond
String c = b + "," + a;
console.fine("B is in A " + c);
geoB.setQueryLocation(c);
out.put(a, geoB); // or NULL ?
out.put(b, geoB);
continue;
}
else if (geoA.isState()) {
//
// I moved from Virginia to Burks County
//
out.put(a, geoA);
i--; // re-process B
continue;
}
else {
// we will tackle this case below
}
}
else if (geosA.size() > 1 && geosB.size() > 1) {
//
// try to find a commonn state
// while in Bloomington, I came across someone from Springfield
//
}
//
// try the two combined into a single location
//
//
//
//
String c = a + "," + b;
List<GeoLocation> geos = getLocations(c);
if (geos.size() == 1) {
GeoLocation geo = geos.get(0);
// Bloomington,Springfield ==> returns "address" precision
// Bolivia, Illinois ==> returns "zip" precision
if (geo.getPrecision() > GeoLocation.P_ZIP) {
// not what we want
more.add(a); i--; // reprocess b
continue;
}
if (geoB != null) {
//
// Springfield ==> lots
// Washington ==> DC (zip)
// Springfield, Washington == > KY (zip)
//
String stateB = geoB.getState();
String stateC = geo.getState();
console.fine("b " + stateB + " ==> " + geoB.toString());
console.fine("c " + stateC + " ==> " + geo.toString());
if (stateB.equals(stateC)) {
console.fine(a + " AND " + b + " map to " + geo.toString());
out.put(a, geo);
out.put(b, geo);
}
else {
console.info("save for later " + a);
more.add(a); i--; // reprocess b
continue;
}
} else { // geoB == null (i.e. geoB.size() > 0)
// we got a unique location (geo != null)
// but it may NOT be because of a,b
// Wisconsin, New Salam --> WI, (state)
// Bolivia, Springfield --> Boliva (country)
// (google returns an address in springfield, yahoo, just the country)
if (geoA != null && geo.getState().equals(geoA.getState())) {
console.fine("adding each as separate geos " + a + " " + b);
out.put(a, geoA);
out.put(b, geoB); // could be null
}
else {
console.fine("adding combo " + a + " " + b);
out.put(a, geo);
out.put(b, geo);
}
}
}
else {
// geos.size() != 1
more.add(a);
i--; // reprocess the b
}
}
else {
more.add(a);
}
} // end of loop over locations
locations.clear();
locations.addAll(more);
//
// handle strange cases here
//
// Illinois, Springfield ==>
// Springfield --> many, one has IL as state
// Illinois --> the state
// ex, Frederick ---> a bunch, no virgina
// Virginia --> state
// Frederick, Virigina ==> YES
//
// Illinois,Paris ==> Paris France and IL (State)
// want a city
//
List<GeoLocation> keep = new ArrayList<GeoLocation>();
List<String> toResolve = new ArrayList<String>();
//
// remove those that resolve to a single location
//
console.fine("leftovers " + locations.size());
for (String loc : locations) {
List<GeoLocation> geos = getLocations(loc);
console.fine(loc + " " + geos.size());
if (geos.size() == 1) {
keep.addAll(geos);
out.put(loc, geos.get(0));
}
else if (geos.size() > 1) {
toResolve.add(loc);
}
}
if (toResolve.size() == 0) {
return out;
}
for (String loc : toResolve) {
List<GeoLocation> geos = getLocations(loc);
// see if any of the geos are found within any of the keepers
GeoLocation a = resolve(keep, geos);
if (a != null) {
console.fine("found keeper " + loc);
out.put(loc, a);
}
else { // a == null
// try adding loc to each value in keep until you get a unique value
for (GeoLocation geo: keep) {
if (geo.isState()) {
String newLocation = loc + "," + geo.getState();
List<GeoLocation> vals = getLocations(newLocation);
console.fine("Dx " + newLocation + ":" + vals.size());
if (vals.size() == 1) {
a = vals.get(0);
console.fine("YES " + a);
// WOW we found it
out.put(loc, a);
}
}
else {
console.fine("not state " + geo);
}
}
}
}
return out;
}
|
diff --git a/src/java/org/apache/hadoop/ipc/Server.java b/src/java/org/apache/hadoop/ipc/Server.java
index c6c4d046f..eb508a6fb 100644
--- a/src/java/org/apache/hadoop/ipc/Server.java
+++ b/src/java/org/apache/hadoop/ipc/Server.java
@@ -1,686 +1,686 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.ipc;
import java.io.IOException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.BufferedOutputStream;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.logging.*;
import org.apache.hadoop.conf.Configurable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.ipc.SocketChannelOutputStream;
import org.apache.hadoop.util.*;
/** An abstract IPC service. IPC calls take a single {@link Writable} as a
* parameter, and return a {@link Writable} as their value. A service runs on
* a port and is defined by a parameter class and a value class.
*
* @author Doug Cutting
* @see Client
*/
public abstract class Server {
/**
* The first four bytes of Hadoop RPC connections
*/
public static final ByteBuffer HEADER = ByteBuffer.wrap("hrpc".getBytes());
/**
* How much time should be allocated for actually running the handler?
* Calls that are older than ipc.timeout * MAX_CALL_QUEUE_TIME
* are ignored when the handler takes them off the queue.
*/
private static final float MAX_CALL_QUEUE_TIME = 0.6f;
/**
* How many calls/handler are allowed in the queue.
*/
private static final int MAX_QUEUE_SIZE_PER_HANDLER = 100;
public static final Log LOG =
LogFactory.getLog("org.apache.hadoop.ipc.Server");
private static final ThreadLocal<Server> SERVER = new ThreadLocal<Server>();
/** Returns the server instance called under or null. May be called under
* {@link #call(Writable)} implementations, and under {@link Writable}
* methods of paramters and return values. Permits applications to access
* the server context.*/
public static Server get() {
return SERVER.get();
}
/** This is set to Call object before Handler invokes an RPC and reset
* after the call returns.
*/
private static final ThreadLocal<Call> CurCall = new ThreadLocal<Call>();
/** Returns the remote side ip address when invoked inside an RPC
* Returns null incase of an error.
*/
public static InetAddress getRemoteIp() {
Call call = CurCall.get();
if ( call != null ) {
return call.connection.socket.getInetAddress();
}
return null;
}
/** Returns remote address as a string when invoked inside an RPC.
* Returns null in case of an error.
*/
public static String getRemoteAddress() {
InetAddress addr = getRemoteIp();
return ( addr == null ) ? null : addr.getHostAddress();
}
private String bindAddress;
private int port; // port we listen on
private int handlerCount; // number of handler threads
private Class paramClass; // class of call parameters
private int maxIdleTime; // the maximum idle time after
// which a client may be disconnected
private int thresholdIdleConnections; // the number of idle connections
// after which we will start
// cleaning up idle
// connections
int maxConnectionsToNuke; // the max number of
// connections to nuke
//during a cleanup
private Configuration conf;
private int timeout;
private long maxCallStartAge;
private int maxQueueSize;
volatile private boolean running = true; // true while server runs
private LinkedList<Call> callQueue = new LinkedList<Call>(); // queued calls
private List<Connection> connectionList =
Collections.synchronizedList(new LinkedList<Connection>());
//maintain a list
//of client connections
private Listener listener = null;
private int numConnections = 0;
private Handler[] handlers = null;
/** A call queued for handling. */
private static class Call {
private int id; // the client's call id
private Writable param; // the parameter passed
private Connection connection; // connection to client
private long receivedTime; // the time received
public Call(int id, Writable param, Connection connection) {
this.id = id;
this.param = param;
this.connection = connection;
this.receivedTime = System.currentTimeMillis();
}
public String toString() {
return param.toString() + " from " + connection.toString();
}
}
/** Listens on the socket. Creates jobs for the handler threads*/
private class Listener extends Thread {
private ServerSocketChannel acceptChannel = null; //the accept channel
private Selector selector = null; //the selector that we use for the server
private InetSocketAddress address; //the address we bind at
private Random rand = new Random();
private long lastCleanupRunTime = 0; //the last time when a cleanup connec-
//-tion (for idle connections) ran
private long cleanupInterval = 10000; //the minimum interval between
//two cleanup runs
private int backlogLength = conf.getInt("ipc.server.listen.queue.size", 128);
public Listener() throws IOException {
address = new InetSocketAddress(bindAddress,port);
// Create a new server socket and set to non blocking mode
acceptChannel = ServerSocketChannel.open();
acceptChannel.configureBlocking(false);
// Bind the server socket to the local host and port
acceptChannel.socket().bind(address, backlogLength);
port = acceptChannel.socket().getLocalPort(); //Could be an ephemeral port
// create a selector;
selector= Selector.open();
// Register accepts on the server socket with the selector.
acceptChannel.register(selector, SelectionKey.OP_ACCEPT);
this.setName("IPC Server listener on " + port);
this.setDaemon(true);
}
/** cleanup connections from connectionList. Choose a random range
* to scan and also have a limit on the number of the connections
* that will be cleanedup per run. The criteria for cleanup is the time
* for which the connection was idle. If 'force' is true then all
* connections will be looked at for the cleanup.
*/
private void cleanupConnections(boolean force) {
if (force || numConnections > thresholdIdleConnections) {
long currentTime = System.currentTimeMillis();
if (!force && (currentTime - lastCleanupRunTime) < cleanupInterval) {
return;
}
int start = 0;
int end = numConnections - 1;
if (!force) {
start = rand.nextInt() % numConnections;
end = rand.nextInt() % numConnections;
int temp;
if (end < start) {
temp = start;
start = end;
end = temp;
}
}
int i = start;
int numNuked = 0;
while (i <= end) {
Connection c;
synchronized (connectionList) {
try {
c = (Connection)connectionList.get(i);
} catch (Exception e) {return;}
}
if (c.timedOut(currentTime)) {
synchronized (connectionList) {
if (connectionList.remove(c))
numConnections--;
}
try {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
c.close();
} catch (Exception e) {}
numNuked++;
end--;
c = null;
if (!force && numNuked == maxConnectionsToNuke) break;
}
else i++;
}
lastCleanupRunTime = System.currentTimeMillis();
}
}
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
SelectionKey key = null;
try {
selector.select();
Iterator iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
key = (SelectionKey)iter.next();
iter.remove();
try {
if (key.isValid()) {
if (key.isAcceptable())
doAccept(key);
else if (key.isReadable())
doRead(key);
}
} catch (IOException e) {
key.cancel();
}
key = null;
}
} catch (OutOfMemoryError e) {
// we can run out of memory if we have too many threads
// log the event and sleep for a minute and give
// some thread(s) a chance to finish
LOG.warn("Out of Memory in server select", e);
closeCurrentConnection(key, e);
cleanupConnections(true);
try { Thread.sleep(60000); } catch (Exception ie) {}
} catch (Exception e) {
closeCurrentConnection(key, e);
}
cleanupConnections(false);
}
LOG.info("Stopping " + this.getName());
try {
acceptChannel.close();
selector.close();
} catch (IOException e) { }
synchronized (this) {
selector= null;
acceptChannel= null;
connectionList = null;
}
}
private void closeCurrentConnection(SelectionKey key, Throwable e) {
if (key != null) {
Connection c = (Connection)key.attachment();
if (c != null) {
synchronized (connectionList) {
if (connectionList.remove(c))
numConnections--;
}
try {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " + c.getHostAddress());
c.close();
} catch (Exception ex) {}
c = null;
}
}
}
InetSocketAddress getAddress() {
return new InetSocketAddress(acceptChannel.socket().getInetAddress(), acceptChannel.socket().getLocalPort());
}
void doAccept(SelectionKey key) throws IOException, OutOfMemoryError {
Connection c = null;
ServerSocketChannel server = (ServerSocketChannel) key.channel();
SocketChannel channel = server.accept();
channel.configureBlocking(false);
SelectionKey readKey = channel.register(selector, SelectionKey.OP_READ);
c = new Connection(readKey, channel, System.currentTimeMillis());
readKey.attach(c);
synchronized (connectionList) {
connectionList.add(numConnections, c);
numConnections++;
}
if (LOG.isDebugEnabled())
LOG.debug("Server connection from " + c.toString() +
"; # active connections: " + numConnections +
"; # queued calls: " + callQueue.size() );
}
void doRead(SelectionKey key) {
int count = 0;
Connection c = (Connection)key.attachment();
if (c == null) {
return;
}
c.setLastContact(System.currentTimeMillis());
try {
count = c.readAndProcess();
} catch (Exception e) {
key.cancel();
LOG.debug(getName() + ": readAndProcess threw exception " + e + ". Count of bytes read: " + count, e);
count = -1; //so that the (count < 0) block is executed
}
if (count < 0) {
synchronized (connectionList) {
if (connectionList.remove(c))
numConnections--;
}
try {
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": disconnecting client " +
c.getHostAddress() + ". Number of active connections: "+
numConnections);
c.close();
} catch (Exception e) {}
c = null;
}
else {
c.setLastContact(System.currentTimeMillis());
}
}
synchronized void doStop() {
if (selector != null) {
selector.wakeup();
Thread.yield();
}
if (acceptChannel != null) {
try {
acceptChannel.socket().close();
} catch (IOException e) {
LOG.info(getName() + ":Exception in closing listener socket. " + e);
}
}
}
}
/** Reads calls from a connection and queues them for handling. */
private class Connection {
private boolean firstData = true;
private SocketChannel channel;
private SelectionKey key;
private ByteBuffer data;
private ByteBuffer dataLengthBuffer;
private DataOutputStream out;
private SocketChannelOutputStream channelOut;
private long lastContact;
private int dataLength;
private Socket socket;
// Cache the remote host & port info so that even if the socket is
// disconnected, we can say where it used to connect to.
private String hostAddress;
private int remotePort;
public Connection(SelectionKey key, SocketChannel channel,
long lastContact) {
this.key = key;
this.channel = channel;
this.lastContact = lastContact;
this.data = null;
this.dataLengthBuffer = ByteBuffer.allocate(4);
this.socket = channel.socket();
this.out = new DataOutputStream
(new BufferedOutputStream(
this.channelOut = new SocketChannelOutputStream( channel )));
InetAddress addr = socket.getInetAddress();
if (addr == null) {
this.hostAddress = "*Unknown*";
} else {
this.hostAddress = addr.getHostAddress();
}
this.remotePort = socket.getPort();
}
public String toString() {
return getHostAddress() + ":" + remotePort;
}
public String getHostAddress() {
return hostAddress;
}
public void setLastContact(long lastContact) {
this.lastContact = lastContact;
}
public long getLastContact() {
return lastContact;
}
private boolean timedOut() {
if(System.currentTimeMillis() - lastContact > maxIdleTime)
return true;
return false;
}
private boolean timedOut(long currentTime) {
if(currentTime - lastContact > maxIdleTime)
return true;
return false;
}
public int readAndProcess() throws IOException, InterruptedException {
int count = -1;
if (dataLengthBuffer.remaining() > 0) {
count = channel.read(dataLengthBuffer);
if ( count < 0 || dataLengthBuffer.remaining() > 0 )
return count;
dataLengthBuffer.flip();
// Is this a new style header?
if (firstData && HEADER.equals(dataLengthBuffer)) {
// If so, read the version
ByteBuffer versionBuffer = ByteBuffer.allocate(1);
count = channel.read(versionBuffer);
if (count < 0) {
return count;
}
// read the first length
dataLengthBuffer.clear();
count = channel.read(dataLengthBuffer);
if (count < 0 || dataLengthBuffer.remaining() > 0) {
return count;
}
dataLengthBuffer.flip();
firstData = false;
}
dataLength = dataLengthBuffer.getInt();
data = ByteBuffer.allocate(dataLength);
}
count = channel.read(data);
if (data.remaining() == 0) {
data.flip();
processData();
dataLengthBuffer.flip();
data = null;
}
return count;
}
private void processData() throws IOException, InterruptedException {
DataInputStream dis =
new DataInputStream(new ByteArrayInputStream( data.array() ));
int id = dis.readInt(); // try to read an id
if (LOG.isDebugEnabled())
LOG.debug(" got #" + id);
Writable param = (Writable)ReflectionUtils.newInstance(paramClass, conf); // read param
param.readFields(dis);
Call call = new Call(id, param, this);
synchronized (callQueue) {
if (callQueue.size() >= maxQueueSize) {
Call oldCall = (Call) callQueue.removeFirst();
LOG.warn("Call queue overflow discarding oldest call " + oldCall);
}
callQueue.addLast(call); // queue the call
callQueue.notify(); // wake up a waiting handler
}
}
private void close() throws IOException {
data = null;
dataLengthBuffer = null;
if (!channel.isOpen())
return;
try {socket.shutdownOutput();} catch(Exception e) {}
try {out.close();} catch(Exception e) {}
try {channelOut.destroy();} catch(Exception e) {}
if (channel.isOpen()) {
try {channel.close();} catch(Exception e) {}
}
try {socket.close();} catch(Exception e) {}
try {key.cancel();} catch(Exception e) {}
key = null;
}
}
/** Handles queued calls . */
private class Handler extends Thread {
public Handler(int instanceNumber) {
this.setDaemon(true);
this.setName("IPC Server handler "+ instanceNumber + " on " + port);
}
public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
try {
Call call;
synchronized (callQueue) {
while (running && callQueue.size()==0) { // wait for a call
callQueue.wait(timeout);
}
if (!running) break;
call = (Call)callQueue.removeFirst(); // pop the queue
}
// throw the message away if it is too old
if (System.currentTimeMillis() - call.receivedTime >
maxCallStartAge) {
ReflectionUtils.logThreadInfo(LOG, "Discarding call " + call, 30);
- LOG.warn("Call " + call.toString() +
- " discarded for being too old (" +
+ LOG.warn(getName()+", call "+call
+ +": discarded for being too old (" +
(System.currentTimeMillis() - call.receivedTime) + ")");
continue;
}
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": has #" + call.id + " from " +
call.connection);
String errorClass = null;
String error = null;
Writable value = null;
CurCall.set( call );
try {
value = call(call.param); // make the call
} catch (Throwable e) {
- LOG.info(getName() + " call error: " + e, e);
+ LOG.info(getName()+", call "+call+": error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
}
CurCall.set( null );
DataOutputStream out = call.connection.out;
synchronized (out) {
try {
out.writeInt(call.id); // write call id
out.writeBoolean(error!=null); // write error flag
if (error == null) {
value.write(out);
} else {
WritableUtils.writeString(out, errorClass);
WritableUtils.writeString(out, error);
}
out.flush();
} catch (Exception e) {
- LOG.warn("handler output error", e);
+ LOG.warn(getName()+", call "+call+": output error", e);
synchronized (connectionList) {
if (connectionList.remove(call.connection))
numConnections--;
}
call.connection.close();
}
}
} catch (Exception e) {
LOG.info(getName() + " caught: " + e, e);
}
}
LOG.info(getName() + ": exiting");
}
}
/** Constructs a server listening on the named port and address. Parameters passed must
* be of the named class. The <code>handlerCount</handlerCount> determines
* the number of handler threads that will be used to process calls.
*
*/
protected Server(String bindAddress, int port, Class paramClass, int handlerCount, Configuration conf)
throws IOException {
this.bindAddress = bindAddress;
this.conf = conf;
this.port = port;
this.paramClass = paramClass;
this.handlerCount = handlerCount;
this.timeout = conf.getInt("ipc.client.timeout",10000);
maxCallStartAge = (long) (timeout * MAX_CALL_QUEUE_TIME);
maxQueueSize = handlerCount * MAX_QUEUE_SIZE_PER_HANDLER;
this.maxIdleTime = conf.getInt("ipc.client.maxidletime", 120000);
this.maxConnectionsToNuke = conf.getInt("ipc.client.kill.max", 10);
this.thresholdIdleConnections = conf.getInt("ipc.client.idlethreshold", 4000);
// Start the listener here and let it bind to the port
listener = new Listener();
this.port = listener.getAddress().getPort();
}
/** Sets the timeout used for network i/o. */
public void setTimeout(int timeout) { this.timeout = timeout; }
/** Starts the service. Must be called before any calls will be handled. */
public synchronized void start() throws IOException {
listener.start();
handlers = new Handler[handlerCount];
for (int i = 0; i < handlerCount; i++) {
handlers[i] = new Handler(i);
handlers[i].start();
}
}
/** Stops the service. No new calls will be handled after this is called. */
public synchronized void stop() {
LOG.info("Stopping server on " + port);
running = false;
if (handlers != null) {
for (int i = 0; i < handlerCount; i++) {
if (handlers[i] != null) {
handlers[i].interrupt();
}
}
}
listener.interrupt();
listener.doStop();
notifyAll();
}
/** Wait for the server to be stopped.
* Does not wait for all subthreads to finish.
* See {@link #stop()}.
*/
public synchronized void join() throws InterruptedException {
while (running) {
wait();
}
}
/**
* Return the socket (ip+port) on which the RPC server is listening to.
* @return the socket (ip+port) on which the RPC server is listening to.
*/
public synchronized InetSocketAddress getListenerAddress() {
return listener.getAddress();
}
/** Called for each call. */
public abstract Writable call(Writable param) throws IOException;
}
| false | true | public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
try {
Call call;
synchronized (callQueue) {
while (running && callQueue.size()==0) { // wait for a call
callQueue.wait(timeout);
}
if (!running) break;
call = (Call)callQueue.removeFirst(); // pop the queue
}
// throw the message away if it is too old
if (System.currentTimeMillis() - call.receivedTime >
maxCallStartAge) {
ReflectionUtils.logThreadInfo(LOG, "Discarding call " + call, 30);
LOG.warn("Call " + call.toString() +
" discarded for being too old (" +
(System.currentTimeMillis() - call.receivedTime) + ")");
continue;
}
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": has #" + call.id + " from " +
call.connection);
String errorClass = null;
String error = null;
Writable value = null;
CurCall.set( call );
try {
value = call(call.param); // make the call
} catch (Throwable e) {
LOG.info(getName() + " call error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
}
CurCall.set( null );
DataOutputStream out = call.connection.out;
synchronized (out) {
try {
out.writeInt(call.id); // write call id
out.writeBoolean(error!=null); // write error flag
if (error == null) {
value.write(out);
} else {
WritableUtils.writeString(out, errorClass);
WritableUtils.writeString(out, error);
}
out.flush();
} catch (Exception e) {
LOG.warn("handler output error", e);
synchronized (connectionList) {
if (connectionList.remove(call.connection))
numConnections--;
}
call.connection.close();
}
}
} catch (Exception e) {
LOG.info(getName() + " caught: " + e, e);
}
}
LOG.info(getName() + ": exiting");
}
| public void run() {
LOG.info(getName() + ": starting");
SERVER.set(Server.this);
while (running) {
try {
Call call;
synchronized (callQueue) {
while (running && callQueue.size()==0) { // wait for a call
callQueue.wait(timeout);
}
if (!running) break;
call = (Call)callQueue.removeFirst(); // pop the queue
}
// throw the message away if it is too old
if (System.currentTimeMillis() - call.receivedTime >
maxCallStartAge) {
ReflectionUtils.logThreadInfo(LOG, "Discarding call " + call, 30);
LOG.warn(getName()+", call "+call
+": discarded for being too old (" +
(System.currentTimeMillis() - call.receivedTime) + ")");
continue;
}
if (LOG.isDebugEnabled())
LOG.debug(getName() + ": has #" + call.id + " from " +
call.connection);
String errorClass = null;
String error = null;
Writable value = null;
CurCall.set( call );
try {
value = call(call.param); // make the call
} catch (Throwable e) {
LOG.info(getName()+", call "+call+": error: " + e, e);
errorClass = e.getClass().getName();
error = StringUtils.stringifyException(e);
}
CurCall.set( null );
DataOutputStream out = call.connection.out;
synchronized (out) {
try {
out.writeInt(call.id); // write call id
out.writeBoolean(error!=null); // write error flag
if (error == null) {
value.write(out);
} else {
WritableUtils.writeString(out, errorClass);
WritableUtils.writeString(out, error);
}
out.flush();
} catch (Exception e) {
LOG.warn(getName()+", call "+call+": output error", e);
synchronized (connectionList) {
if (connectionList.remove(call.connection))
numConnections--;
}
call.connection.close();
}
}
} catch (Exception e) {
LOG.info(getName() + " caught: " + e, e);
}
}
LOG.info(getName() + ": exiting");
}
|
diff --git a/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetBasicTelephonyJabberImpl.java b/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetBasicTelephonyJabberImpl.java
index ac6bfa2cf..ab316502e 100644
--- a/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetBasicTelephonyJabberImpl.java
+++ b/src/net/java/sip/communicator/impl/protocol/jabber/OperationSetBasicTelephonyJabberImpl.java
@@ -1,867 +1,867 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.jabber;
import java.util.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.jingle.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.packet.IQ.*;
import org.jivesoftware.smack.provider.*;
import org.jivesoftware.smackx.packet.*;
/**
* Implements all call management logic and exports basic telephony support by
* implementing <tt>OperationSetBasicTelephony</tt>.
*
* @author Emil Ivov
* @author Symphorien Wanko
* @author Lyubomir Marinov
*/
public class OperationSetBasicTelephonyJabberImpl
extends AbstractOperationSetBasicTelephony<ProtocolProviderServiceJabberImpl>
implements RegistrationStateChangeListener,
PacketListener,
PacketFilter,
OperationSetSecureTelephony,
OperationSetAdvancedTelephony<ProtocolProviderServiceJabberImpl>
{
/**
* The <tt>Logger</tt> used by the
* <tt>OperationSetBasicTelephonyJabberImpl</tt> class and its instances for
* logging output.
*/
private static final Logger logger
= Logger.getLogger(OperationSetBasicTelephonyJabberImpl.class);
/**
* A reference to the <tt>ProtocolProviderServiceJabberImpl</tt> instance
* that created us.
*/
private final ProtocolProviderServiceJabberImpl protocolProvider;
/**
* Contains references for all currently active (non ended) calls.
*/
private ActiveCallsRepositoryJabberImpl activeCallsRepository
= new ActiveCallsRepositoryJabberImpl(this);
/**
* Creates a new instance.
*
* @param protocolProvider a reference to the
* <tt>ProtocolProviderServiceJabberImpl</tt> instance that created us.
*/
public OperationSetBasicTelephonyJabberImpl(
ProtocolProviderServiceJabberImpl protocolProvider)
{
this.protocolProvider = protocolProvider;
this.protocolProvider.addRegistrationStateChangeListener(this);
}
/**
* Implementation of method <tt>registrationStateChange</tt> from
* interface RegistrationStateChangeListener for setting up (or down)
* our <tt>JingleManager</tt> when an <tt>XMPPConnection</tt> is available
*
* @param evt the event received
*/
public void registrationStateChanged(RegistrationStateChangeEvent evt)
{
RegistrationState registrationState = evt.getNewState();
if (registrationState == RegistrationState.REGISTERING)
{
ProviderManager.getInstance().addIQProvider(
JingleIQ.ELEMENT_NAME,
JingleIQ.NAMESPACE,
new JingleIQProvider());
subscribeForJinglePackets();
if (logger.isInfoEnabled())
logger.info("Jingle : ON ");
}
else if (registrationState == RegistrationState.UNREGISTERED)
{
// TODO plug jingle unregistration
if (logger.isInfoEnabled())
logger.info("Jingle : OFF ");
}
}
/**
* Create a new call and invite the specified CallPeer to it.
*
* @param callee the jabber address of the callee that we should invite to a
* new call.
* @return CallPeer the CallPeer that will represented by
* the specified uri. All following state change events will be
* delivered through that call peer. The Call that this
* peer is a member of could be retrieved from the
* CallParticipatn instance with the use of the corresponding method.
* @throws OperationFailedException with the corresponding code if we fail
* to create the call.
*/
public Call createCall(String callee)
throws OperationFailedException
{
CallJabberImpl call = new CallJabberImpl(this);
if (createOutgoingCall(call, callee) == null)
{
throw new OperationFailedException(
"Failed to create outgoing call"
+ " because no peer was created",
OperationFailedException.INTERNAL_ERROR);
}
return call;
}
/**
* Create a new call and invite the specified CallPeer to it.
*
* @param callee the address of the callee that we should invite to a
* new call.
* @return CallPeer the CallPeer that will represented by
* the specified uri. All following state change events will be
* delivered through that call peer. The Call that this
* peer is a member of could be retrieved from the
* CallParticipatn instance with the use of the corresponding method.
* @throws OperationFailedException with the corresponding code if we fail
* to create the call.
*/
public Call createCall(Contact callee)
throws OperationFailedException
{
return createCall(callee.getAddress());
}
/**
* Init and establish the specified call.
*
* @param call the <tt>CallJabberImpl</tt> that will be used
* to initiate the call
* @param calleeAddress the address of the callee that we'd like to connect
* with.
*
* @return the <tt>CallPeer</tt> that represented by the specified uri. All
* following state change events will be delivered through that call peer.
* The <tt>Call</tt> that this peer is a member of could be retrieved from
* the <tt>CallPeer</tt> instance with the use of the corresponding method.
*
* @throws OperationFailedException with the corresponding code if we fail
* to create the call.
*/
CallPeerJabberImpl createOutgoingCall(
CallJabberImpl call,
String calleeAddress)
throws OperationFailedException
{
return createOutgoingCall(call, calleeAddress, null);
}
/**
* Init and establish the specified call.
*
* @param call the <tt>CallJabberImpl</tt> that will be used
* to initiate the call
* @param calleeAddress the address of the callee that we'd like to connect
* with.
* @param sessionInitiateExtensions a collection of additional and optional
* <tt>PacketExtension</tt>s to be added to the <tt>session-initiate</tt>
* {@link JingleIQ} which is to init the specified <tt>call</tt>
*
* @return the <tt>CallPeer</tt> that represented by the specified uri. All
* following state change events will be delivered through that call peer.
* The <tt>Call</tt> that this peer is a member of could be retrieved from
* the <tt>CallPeer</tt> instance with the use of the corresponding method.
*
* @throws OperationFailedException with the corresponding code if we fail
* to create the call.
*/
CallPeerJabberImpl createOutgoingCall(
CallJabberImpl call,
String calleeAddress,
Iterable<PacketExtension> sessionInitiateExtensions)
throws OperationFailedException
{
if (logger.isInfoEnabled())
logger.info("creating outgoing call...");
if (protocolProvider.getConnection() == null || call == null)
{
throw new OperationFailedException(
"Failed to create OutgoingJingleSession."
+ " We don't have a valid XMPPConnection.",
OperationFailedException.INTERNAL_ERROR);
}
// we determine on which resource the remote user is connected if the
// resource isn't already provided
- String fullCalleeURI = null; //getFullCalleeURI(calleeAddress);
+ String fullCalleeURI = null;
DiscoverInfo di = null;
- int bestPriority = 0;
+ int bestPriority = -1;
Iterator<Presence> it =
getProtocolProvider().getConnection().getRoster().getPresences(
calleeAddress);
// choose the resource that has the highest priority AND support Jingle
while(it.hasNext())
{
Presence presence = it.next();
String calleeURI = presence.getFrom();
int priority = (presence.getPriority() == Integer.MIN_VALUE) ? 0 :
presence.getPriority();
try
{
// check if the remote client supports telephony.
DiscoverInfo discoverInfo =
protocolProvider.getDiscoveryManager().
discoverInfo(calleeURI);
if (discoverInfo.containsFeature(
ProtocolProviderServiceJabberImpl.URN_XMPP_JINGLE))
{
if(priority > bestPriority)
{
bestPriority = priority;
di = discoverInfo;
fullCalleeURI = calleeURI;
}
}
}
catch (XMPPException ex)
{
logger.warn("could not retrieve info for " + fullCalleeURI, ex);
}
}
/* in case we figure that calling people without a resource id is
impossible, we'll have to uncomment the following lines. keep in mind
that this would mean - no calls to pstn though
if (fullCalleeURI.indexOf('/') < 0)
{
throw new OperationFailedException(
"Failed to create OutgoingJingleSession.\n"
+ "User " + calleeAddress + " is unknown to us."
, OperationFailedException.INTERNAL_ERROR);
}
*/
if(di != null)
{
if (logger.isInfoEnabled())
logger.info(calleeAddress + ": jingle supported ");
}
else
{
if (logger.isInfoEnabled())
logger.info(calleeAddress + ": jingle not supported ?");
throw new OperationFailedException(
"Failed to create OutgoingJingleSession.\n"
+ calleeAddress + " does not support jingle",
OperationFailedException.INTERNAL_ERROR);
}
if(logger.isInfoEnabled())
{
logger.info("Choose one is: " + fullCalleeURI + " " + bestPriority);
}
CallPeerJabberImpl peer = null;
// initiate call
try
{
peer
= call.initiateSession(
fullCalleeURI,
di,
sessionInitiateExtensions);
}
catch(Throwable t)
{
/*
* The Javadoc on ThreadDeath says: If ThreadDeath is caught by a
* method, it is important that it be rethrown so that the thread
* actually dies.
*/
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
throw new OperationFailedException(
"Failed to create a call",
OperationFailedException.INTERNAL_ERROR,
t);
}
return peer;
}
/**
* Gets the full callee URI for a specific callee address.
*
* @param calleeAddress the callee address to get the full callee URI for
* @return the full callee URI for the specified <tt>calleeAddress</tt>
*/
String getFullCalleeURI(String calleeAddress)
{
return
(calleeAddress.indexOf('/') > 0)
? calleeAddress
: protocolProvider
.getConnection()
.getRoster()
.getPresence(calleeAddress)
.getFrom();
}
/**
* Returns an iterator over all currently active calls.
*
* @return an iterator over all currently active calls.
*/
public Iterator<CallJabberImpl> getActiveCalls()
{
return activeCallsRepository.getActiveCalls();
}
/**
* Resumes communication with a call peer previously put on hold.
*
* @param peer the call peer to put on hold.
*
* @throws OperationFailedException if we fail to send the "hold" message.
*/
public synchronized void putOffHold(CallPeer peer)
throws OperationFailedException
{
putOnHold(peer, false);
}
/**
* Puts the specified CallPeer "on hold".
*
* @param peer the peer that we'd like to put on hold.
*
* @throws OperationFailedException if we fail to send the "hold" message.
*/
public synchronized void putOnHold(CallPeer peer)
throws OperationFailedException
{
putOnHold(peer, true);
}
/**
* Puts the specified <tt>CallPeer</tt> on or off hold.
*
* @param peer the <tt>CallPeer</tt> to be put on or off hold
* @param on <tt>true</tt> to have the specified <tt>CallPeer</tt>
* put on hold; <tt>false</tt>, otherwise
*
* @throws OperationFailedException if we fail to send the "hold" message.
*/
private void putOnHold(CallPeer peer, boolean on)
throws OperationFailedException
{
((CallPeerJabberImpl) peer).putOnHold(on);
}
/**
* Sets the mute state of the <tt>CallJabberImpl</tt>.
*
* @param call the <tt>CallJabberImpl</tt> whose mute state is set
* @param mute <tt>true</tt> to mute the call streams being sent to
* <tt>peers</tt>; otherwise, <tt>false</tt>
*/
@Override
public void setMute(Call call, boolean mute)
{
((CallJabberImpl) call).setMute(mute);
}
/**
* Ends the call with the specified <tt>peer</tt>.
*
* @param peer the peer that we'd like to hang up on.
*
* @throws ClassCastException if peer is not an instance of this
* CallPeerSipImpl.
* @throws OperationFailedException if we fail to terminate the call.
*/
public synchronized void hangupCallPeer(CallPeer peer)
throws ClassCastException,
OperationFailedException
{
((CallPeerJabberImpl) peer).hangup(null, null);
}
/**
* Implements method <tt>answerCallPeer</tt>
* from <tt>OperationSetBasicTelephony</tt>.
*
* @param peer the call peer that we want to answer
* @throws OperationFailedException if we fails to answer
*/
public void answerCallPeer(CallPeer peer)
throws OperationFailedException
{
((CallPeerJabberImpl) peer).answer();
}
/**
* Closes all active calls. And releases resources.
*/
public void shutdown()
{
if (logger.isTraceEnabled())
logger.trace("Ending all active calls. ");
Iterator<CallJabberImpl> activeCalls
= this.activeCallsRepository.getActiveCalls();
// this is fast, but events aren't triggered ...
//jingleManager.disconnectAllSessions();
//go through all active calls.
while(activeCalls.hasNext())
{
CallJabberImpl call = activeCalls.next();
Iterator<CallPeerJabberImpl> callPeers = call.getCallPeers();
//go through all call peers and say bye to every one.
while (callPeers.hasNext())
{
CallPeer peer = callPeers.next();
try
{
this.hangupCallPeer(peer);
}
catch (Exception ex)
{
logger.warn("Failed to properly hangup peer " + peer, ex);
}
}
}
}
/**
* Subscribes us to notifications about incoming jingle packets.
*/
private void subscribeForJinglePackets()
{
protocolProvider.getConnection().addPacketListener(this, this);
}
/**
* Tests whether or not the specified packet should be handled by this
* operation set. This method is called by smack prior to packet delivery
* and it would only accept <tt>JingleIQ</tt>s that are either session
* initiations with RTP content or belong to sessions that are already
* handled by this operation set.
*
* @param packet the packet to test.
* @return true if and only if <tt>packet</tt> passes the filter.
*/
public boolean accept(Packet packet)
{
//we only handle JingleIQ-s
if( ! (packet instanceof JingleIQ) )
{
CallPeerJabberImpl callPeer =
activeCallsRepository.findCallPeerBySessInitPacketID(
packet.getPacketID());
if(callPeer != null)
{
/* packet is a response to a Jingle call but is not a JingleIQ
* so it is for sure an error (peer does not support Jingle or
* does not belong to our roster)
*/
XMPPError error = packet.getError();
if (error != null)
{
logger.error("Received an error: code=" + error.getCode()
+ " message=" + error.getMessage());
String message = "Service unavailable";
Roster roster = getProtocolProvider().getConnection().
getRoster();
if(!roster.contains(packet.getFrom()))
{
message += ": try adding the contact to your contact " +
"list first.";
}
if (error.getMessage() != null)
message = error.getMessage();
callPeer.setState(CallPeerState.FAILED, message);
}
}
return false;
}
JingleIQ jingleIQ = (JingleIQ)packet;
if( jingleIQ.getAction() == JingleAction.SESSION_INITIATE)
{
//we only accept session-initiate-s dealing RTP
return
jingleIQ.containsContentChildOfType(
RtpDescriptionPacketExtension.class);
}
//if this is not a session-initiate we'll only take it if we've
//already seen its session ID.
return (activeCallsRepository.findJingleSID(jingleIQ.getSID()) != null);
}
/**
* Handles incoming jingle packets and passes them to the corresponding
* method based on their action.
*
* @param packet the packet to process.
*/
public void processPacket(Packet packet)
{
//this is not supposed to happen because of the filter ... but still
if (! (packet instanceof JingleIQ) )
return;
JingleIQ jingleIQ = (JingleIQ)packet;
//to prevent hijacking sessions from other jingle based features
//like file transfer for example, we should only send the
//ack if this is a session-initiate with rtp content or if we are
//the owners of this packet's sid
//first ack all "set" requests.
if(jingleIQ.getType() == IQ.Type.SET)
{
IQ ack = IQ.createResultIQ(jingleIQ);
protocolProvider.getConnection().sendPacket(ack);
}
try
{
processJingleIQ(jingleIQ);
}
catch(Throwable t)
{
logger.info("Error while handling incoming Jingle packet: ", t);
/*
* The Javadoc on ThreadDeath says: If ThreadDeath is caught by a
* method, it is important that it be rethrown so that the thread
* actually dies.
*/
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
}
}
/**
* Analyzes the <tt>jingleIQ</tt>'s action and passes it to the
* corresponding handler.
*
* @param jingleIQ the {@link JingleIQ} packet we need to be analyzing.
*/
private void processJingleIQ(JingleIQ jingleIQ)
{
//let's first see whether we have a peer that's concerned by this IQ
CallPeerJabberImpl callPeer
= activeCallsRepository.findCallPeer(jingleIQ.getSID());
IQ.Type type = jingleIQ.getType();
if (type == Type.ERROR)
{
logger.error("Received error");
XMPPError error = jingleIQ.getError();
String message = "Remote party returned an error!";
if(error != null)
{
logger.error(" code=" + error.getCode()
+ " message=" + error.getMessage());
if (error.getMessage() != null)
message = error.getMessage();
}
if (callPeer != null)
callPeer.setState(CallPeerState.FAILED, message);
return;
}
JingleAction action = jingleIQ.getAction();
if(action == JingleAction.SESSION_INITIATE)
{
CallJabberImpl call = new CallJabberImpl(this);
call.processSessionInitiate(jingleIQ);
return;
}
else if (callPeer == null)
{
if (logger.isDebugEnabled())
logger.debug("Received a stray trying response.");
return;
}
//the rest of these cases deal with existing peers
else if(action == JingleAction.SESSION_TERMINATE)
{
callPeer.processSessionTerminate(jingleIQ);
}
else if(action == JingleAction.SESSION_ACCEPT)
{
callPeer.processSessionAccept(jingleIQ);
}
else if (action == JingleAction.SESSION_INFO)
{
SessionInfoPacketExtension info = jingleIQ.getSessionInfo();
if(info != null)
{
// change status.
callPeer.processSessionInfo(info);
}
else
{
PacketExtension packetExtension
= jingleIQ.getExtension(
TransferPacketExtension.ELEMENT_NAME,
TransferPacketExtension.NAMESPACE);
if (packetExtension instanceof TransferPacketExtension)
{
TransferPacketExtension transfer
= (TransferPacketExtension) packetExtension;
if (transfer.getFrom() == null)
transfer.setFrom(jingleIQ.getFrom());
try
{
callPeer.processTransfer(transfer);
}
catch (OperationFailedException ofe)
{
logger.error(
"Failed to transfer to " + transfer.getTo(),
ofe);
}
}
}
}
else if (action == JingleAction.CONTENT_ACCEPT)
{
callPeer.processContentAccept(jingleIQ);
}
else if (action == JingleAction.CONTENT_ADD)
{
callPeer.processContentAdd(jingleIQ);
}
else if (action == JingleAction.CONTENT_MODIFY)
{
callPeer.processContentModify(jingleIQ);
}
else if (action == JingleAction.CONTENT_REJECT)
{
callPeer.processContentReject(jingleIQ);
}
else if (action == JingleAction.CONTENT_REMOVE)
{
callPeer.processContentRemove(jingleIQ);
}
else if (action == JingleAction.TRANSPORT_INFO)
{
callPeer.processTransportInfo(jingleIQ);
}
}
/**
* Returns a reference to the {@link ActiveCallsRepositoryJabberImpl} that
* we are currently using.
*
* @return a reference to the {@link ActiveCallsRepositoryJabberImpl} that
* we are currently using.
*/
protected ActiveCallsRepositoryJabberImpl getActiveCallsRepository()
{
return activeCallsRepository;
}
/**
* Returns the protocol provider that this operation set belongs to.
*
* @return a reference to the <tt>ProtocolProviderService</tt> that created
* this operation set.
*/
public ProtocolProviderServiceJabberImpl getProtocolProvider()
{
return protocolProvider;
}
/**
* Gets the secure state of the call session in which a specific peer
* is involved
*
* @param peer the peer for who the call state is required
* @return the call state
*/
public boolean isSecure(CallPeer peer)
{
return ((CallPeerJabberImpl) peer).getMediaHandler().isSecure();
}
/**
* Sets the SAS verifications state of the call session in which a specific
* peer is involved
*
* @param peer the peer who toggled (or for whom is remotely
* toggled) the SAS verified flag
* @param verified the new SAS verification status
*/
public void setSasVerified(CallPeer peer, boolean verified)
{
((CallPeerJabberImpl) peer).getMediaHandler().setSasVerified(verified);
}
/**
* Transfers (in the sense of call transfer) a specific <tt>CallPeer</tt> to
* a specific callee address which already participates in an active
* <tt>Call</tt>.
* <p>
* The method is suitable for providing the implementation of attended call
* transfer (though no such requirement is imposed).
* </p>
*
* @param peer the <tt>CallPeer</tt> to be transfered to the specified
* callee address
* @param target the address in the form of <tt>CallPeer</tt> of the callee
* to transfer <tt>peer</tt> to
* @throws OperationFailedException if something goes wrong
* @see OperationSetAdvancedTelephony#transfer(CallPeer, CallPeer)
*/
public void transfer(CallPeer peer, CallPeer target)
throws OperationFailedException
{
CallPeerJabberImpl targetJabberImpl = (CallPeerJabberImpl) target;
String to = getFullCalleeURI(targetJabberImpl.getAddress());
/*
* XEP-0251: Jingle Session Transfer says: Before doing
* [attended transfer], the attendant SHOULD verify that the callee
* supports Jingle session transfer.
*/
try
{
DiscoverInfo discoverInfo
= protocolProvider.getDiscoveryManager().discoverInfo(to);
if (!discoverInfo.containsFeature(
ProtocolProviderServiceJabberImpl
.URN_XMPP_JINGLE_TRANSFER_0))
{
throw new OperationFailedException(
"Callee "
+ to
+ " does not support"
+ " XEP-0251: Jingle Session Transfer",
OperationFailedException.INTERNAL_ERROR);
}
}
catch (XMPPException xmppe)
{
logger.warn("Failed to retrieve DiscoverInfo for " + to, xmppe);
}
transfer(
peer,
to, targetJabberImpl.getJingleSID());
}
/**
* Transfers (in the sense of call transfer) a specific <tt>CallPeer</tt> to
* a specific callee address which may or may not already be participating
* in an active <tt>Call</tt>.
* <p>
* The method is suitable for providing the implementation of unattended
* call transfer (though no such requirement is imposed).
* </p>
*
* @param peer the <tt>CallPeer</tt> to be transfered to the specified
* callee address
* @param target the address of the callee to transfer <tt>peer</tt> to
* @throws OperationFailedException if something goes wrong
* @see OperationSetAdvancedTelephony#transfer(CallPeer, String)
*/
public void transfer(CallPeer peer, String target)
throws OperationFailedException
{
transfer(peer, target, null);
}
/**
* Transfer (in the sense of call transfer) a specific <tt>CallPeer</tt> to
* a specific callee address which may optionally be participating in an
* active <tt>Call</tt>.
*
* @param peer the <tt>CallPeer</tt> to be transfered to the specified
* callee address
* @param to the address of the callee to transfer <tt>peer</tt> to
* @param sid the Jingle session ID of the active <tt>Call</tt> between the
* local peer and the callee in the case of attended transfer; <tt>null</tt>
* in the case of unattended transfer
* @throws OperationFailedException if something goes wrong
*/
private void transfer(CallPeer peer, String to, String sid)
throws OperationFailedException
{
String caller = getFullCalleeURI(peer.getAddress());
try
{
DiscoverInfo discoverInfo
= protocolProvider.getDiscoveryManager().discoverInfo(caller);
if (!discoverInfo.containsFeature(
ProtocolProviderServiceJabberImpl
.URN_XMPP_JINGLE_TRANSFER_0))
{
throw new OperationFailedException(
"Caller "
+ caller
+ " does not support"
+ " XEP-0251: Jingle Session Transfer",
OperationFailedException.INTERNAL_ERROR);
}
}
catch (XMPPException xmppe)
{
logger.warn("Failed to retrieve DiscoverInfo for " + to, xmppe);
}
((CallPeerJabberImpl) peer).transfer(getFullCalleeURI(to), sid);
}
}
| false | true | CallPeerJabberImpl createOutgoingCall(
CallJabberImpl call,
String calleeAddress,
Iterable<PacketExtension> sessionInitiateExtensions)
throws OperationFailedException
{
if (logger.isInfoEnabled())
logger.info("creating outgoing call...");
if (protocolProvider.getConnection() == null || call == null)
{
throw new OperationFailedException(
"Failed to create OutgoingJingleSession."
+ " We don't have a valid XMPPConnection.",
OperationFailedException.INTERNAL_ERROR);
}
// we determine on which resource the remote user is connected if the
// resource isn't already provided
String fullCalleeURI = null; //getFullCalleeURI(calleeAddress);
DiscoverInfo di = null;
int bestPriority = 0;
Iterator<Presence> it =
getProtocolProvider().getConnection().getRoster().getPresences(
calleeAddress);
// choose the resource that has the highest priority AND support Jingle
while(it.hasNext())
{
Presence presence = it.next();
String calleeURI = presence.getFrom();
int priority = (presence.getPriority() == Integer.MIN_VALUE) ? 0 :
presence.getPriority();
try
{
// check if the remote client supports telephony.
DiscoverInfo discoverInfo =
protocolProvider.getDiscoveryManager().
discoverInfo(calleeURI);
if (discoverInfo.containsFeature(
ProtocolProviderServiceJabberImpl.URN_XMPP_JINGLE))
{
if(priority > bestPriority)
{
bestPriority = priority;
di = discoverInfo;
fullCalleeURI = calleeURI;
}
}
}
catch (XMPPException ex)
{
logger.warn("could not retrieve info for " + fullCalleeURI, ex);
}
}
/* in case we figure that calling people without a resource id is
impossible, we'll have to uncomment the following lines. keep in mind
that this would mean - no calls to pstn though
if (fullCalleeURI.indexOf('/') < 0)
{
throw new OperationFailedException(
"Failed to create OutgoingJingleSession.\n"
+ "User " + calleeAddress + " is unknown to us."
, OperationFailedException.INTERNAL_ERROR);
}
*/
if(di != null)
{
if (logger.isInfoEnabled())
logger.info(calleeAddress + ": jingle supported ");
}
else
{
if (logger.isInfoEnabled())
logger.info(calleeAddress + ": jingle not supported ?");
throw new OperationFailedException(
"Failed to create OutgoingJingleSession.\n"
+ calleeAddress + " does not support jingle",
OperationFailedException.INTERNAL_ERROR);
}
if(logger.isInfoEnabled())
{
logger.info("Choose one is: " + fullCalleeURI + " " + bestPriority);
}
CallPeerJabberImpl peer = null;
// initiate call
try
{
peer
= call.initiateSession(
fullCalleeURI,
di,
sessionInitiateExtensions);
}
catch(Throwable t)
{
/*
* The Javadoc on ThreadDeath says: If ThreadDeath is caught by a
* method, it is important that it be rethrown so that the thread
* actually dies.
*/
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
throw new OperationFailedException(
"Failed to create a call",
OperationFailedException.INTERNAL_ERROR,
t);
}
return peer;
}
| CallPeerJabberImpl createOutgoingCall(
CallJabberImpl call,
String calleeAddress,
Iterable<PacketExtension> sessionInitiateExtensions)
throws OperationFailedException
{
if (logger.isInfoEnabled())
logger.info("creating outgoing call...");
if (protocolProvider.getConnection() == null || call == null)
{
throw new OperationFailedException(
"Failed to create OutgoingJingleSession."
+ " We don't have a valid XMPPConnection.",
OperationFailedException.INTERNAL_ERROR);
}
// we determine on which resource the remote user is connected if the
// resource isn't already provided
String fullCalleeURI = null;
DiscoverInfo di = null;
int bestPriority = -1;
Iterator<Presence> it =
getProtocolProvider().getConnection().getRoster().getPresences(
calleeAddress);
// choose the resource that has the highest priority AND support Jingle
while(it.hasNext())
{
Presence presence = it.next();
String calleeURI = presence.getFrom();
int priority = (presence.getPriority() == Integer.MIN_VALUE) ? 0 :
presence.getPriority();
try
{
// check if the remote client supports telephony.
DiscoverInfo discoverInfo =
protocolProvider.getDiscoveryManager().
discoverInfo(calleeURI);
if (discoverInfo.containsFeature(
ProtocolProviderServiceJabberImpl.URN_XMPP_JINGLE))
{
if(priority > bestPriority)
{
bestPriority = priority;
di = discoverInfo;
fullCalleeURI = calleeURI;
}
}
}
catch (XMPPException ex)
{
logger.warn("could not retrieve info for " + fullCalleeURI, ex);
}
}
/* in case we figure that calling people without a resource id is
impossible, we'll have to uncomment the following lines. keep in mind
that this would mean - no calls to pstn though
if (fullCalleeURI.indexOf('/') < 0)
{
throw new OperationFailedException(
"Failed to create OutgoingJingleSession.\n"
+ "User " + calleeAddress + " is unknown to us."
, OperationFailedException.INTERNAL_ERROR);
}
*/
if(di != null)
{
if (logger.isInfoEnabled())
logger.info(calleeAddress + ": jingle supported ");
}
else
{
if (logger.isInfoEnabled())
logger.info(calleeAddress + ": jingle not supported ?");
throw new OperationFailedException(
"Failed to create OutgoingJingleSession.\n"
+ calleeAddress + " does not support jingle",
OperationFailedException.INTERNAL_ERROR);
}
if(logger.isInfoEnabled())
{
logger.info("Choose one is: " + fullCalleeURI + " " + bestPriority);
}
CallPeerJabberImpl peer = null;
// initiate call
try
{
peer
= call.initiateSession(
fullCalleeURI,
di,
sessionInitiateExtensions);
}
catch(Throwable t)
{
/*
* The Javadoc on ThreadDeath says: If ThreadDeath is caught by a
* method, it is important that it be rethrown so that the thread
* actually dies.
*/
if (t instanceof ThreadDeath)
throw (ThreadDeath) t;
throw new OperationFailedException(
"Failed to create a call",
OperationFailedException.INTERNAL_ERROR,
t);
}
return peer;
}
|
diff --git a/src/net/mcft/copy/betterstorage/api/BetterStorageUtils.java b/src/net/mcft/copy/betterstorage/api/BetterStorageUtils.java
index 474733c..4e0931a 100644
--- a/src/net/mcft/copy/betterstorage/api/BetterStorageUtils.java
+++ b/src/net/mcft/copy/betterstorage/api/BetterStorageUtils.java
@@ -1,24 +1,24 @@
package net.mcft.copy.betterstorage.api;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
public final class BetterStorageUtils {
private BetterStorageUtils() { }
/** Returns if the stack matches the match stack. Stack size is ignored. <br>
* If the match stack damage is WILDCARD_VALUE, it will match any damage. <br>
* If the match stack doesn't have an NBT compound, it will match any NBT data. <br>
* (If the match stack has an empty NBT compound it'll only match stacks without NBT data.) */
public static boolean wildcardMatch(ItemStack match, ItemStack stack) {
- boolean matchDamage = (match.getItemDamage() == OreDictionary.WILDCARD_VALUE);
return ((match == null) ? (stack == null) :
((stack != null) && (match.itemID == stack.itemID) &&
- (matchDamage || (match.getItemDamage() == stack.getItemDamage())) &&
+ ((match.getItemDamage() == OreDictionary.WILDCARD_VALUE) ||
+ (match.getItemDamage() == stack.getItemDamage())) &&
(!match.hasTagCompound() ||
(match.getTagCompound().hasNoTags() && !stack.hasTagCompound()) ||
(match.getTagCompound().equals(stack.getTagCompound())))));
}
}
| false | true | public static boolean wildcardMatch(ItemStack match, ItemStack stack) {
boolean matchDamage = (match.getItemDamage() == OreDictionary.WILDCARD_VALUE);
return ((match == null) ? (stack == null) :
((stack != null) && (match.itemID == stack.itemID) &&
(matchDamage || (match.getItemDamage() == stack.getItemDamage())) &&
(!match.hasTagCompound() ||
(match.getTagCompound().hasNoTags() && !stack.hasTagCompound()) ||
(match.getTagCompound().equals(stack.getTagCompound())))));
}
| public static boolean wildcardMatch(ItemStack match, ItemStack stack) {
return ((match == null) ? (stack == null) :
((stack != null) && (match.itemID == stack.itemID) &&
((match.getItemDamage() == OreDictionary.WILDCARD_VALUE) ||
(match.getItemDamage() == stack.getItemDamage())) &&
(!match.hasTagCompound() ||
(match.getTagCompound().hasNoTags() && !stack.hasTagCompound()) ||
(match.getTagCompound().equals(stack.getTagCompound())))));
}
|
diff --git a/src/main/java/nl/topicus/onderwijs/dashboard/modules/RandomDataRepositoryImpl.java b/src/main/java/nl/topicus/onderwijs/dashboard/modules/RandomDataRepositoryImpl.java
index a2d91dd..6e668e1 100644
--- a/src/main/java/nl/topicus/onderwijs/dashboard/modules/RandomDataRepositoryImpl.java
+++ b/src/main/java/nl/topicus/onderwijs/dashboard/modules/RandomDataRepositoryImpl.java
@@ -1,323 +1,325 @@
package nl.topicus.onderwijs.dashboard.modules;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import nl.topicus.onderwijs.dashboard.datasources.Alerts;
import nl.topicus.onderwijs.dashboard.datasources.DataSourceAnnotationReader;
import nl.topicus.onderwijs.dashboard.datatypes.Alert;
import nl.topicus.onderwijs.dashboard.datatypes.Commit;
import nl.topicus.onderwijs.dashboard.datatypes.DotColor;
import nl.topicus.onderwijs.dashboard.datatypes.Event;
import nl.topicus.onderwijs.dashboard.datatypes.Issue;
import nl.topicus.onderwijs.dashboard.datatypes.IssuePriority;
import nl.topicus.onderwijs.dashboard.datatypes.IssueSeverity;
import nl.topicus.onderwijs.dashboard.datatypes.IssueStatus;
import nl.topicus.onderwijs.dashboard.datatypes.WeatherReport;
import nl.topicus.onderwijs.dashboard.datatypes.WeatherType;
import nl.topicus.onderwijs.dashboard.keys.Key;
import nl.topicus.onderwijs.dashboard.keys.Project;
import nl.topicus.onderwijs.dashboard.keys.Summary;
import nl.topicus.onderwijs.dashboard.modules.ns.model.Train;
import nl.topicus.onderwijs.dashboard.modules.ns.model.TrainType;
import nl.topicus.onderwijs.dashboard.modules.wettercom.WetterComService;
import org.apache.wicket.util.time.Duration;
import twitter4j.Status;
public class RandomDataRepositoryImpl extends TimerTask implements Repository {
private Repository base;
private Set<Class<? extends DataSource<?>>> sources = new HashSet<Class<? extends DataSource<?>>>();
private ConcurrentHashMap<String, Object> dataCache = new ConcurrentHashMap<String, Object>();
private Map<Key, List<Event>> eventCache = new HashMap<Key, List<Event>>();
private Timer timer;
public RandomDataRepositoryImpl(Repository base) {
this.base = base;
start();
}
public void stop() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void start() {
if (timer == null) {
timer = new Timer("Random Data Updater", true);
timer.scheduleAtFixedRate(this, 0, Duration.seconds(5)
.getMilliseconds());
}
}
public <T extends DataSource<?>> void addDataSource(Key key,
Class<T> datasourceType, T dataSource) {
sources.add(datasourceType);
base.addDataSource(key, datasourceType, dataSource);
}
public List<Project> getProjects() {
return base.getProjects();
}
public <T extends Key> List<T> getKeys(Class<T> keyType) {
return base.getKeys(keyType);
}
public Collection<DataSource<?>> getData(Key key) {
Collection<DataSource<?>> ret = new ArrayList<DataSource<?>>();
for (Class<? extends DataSource<?>> curDataSource : sources)
ret.add(createDataSource(key, curDataSource));
return ret;
}
@Override
public <T extends DataSource<?>> Map<Key, T> getData(Class<T> datasource) {
Map<Key, T> ret = new HashMap<Key, T>();
for (Key curKey : getKeys(Key.class)) {
T dataSource = createDataSource(curKey, datasource);
if (dataSource != null)
ret.put(curKey, dataSource);
}
return ret;
}
@SuppressWarnings("unchecked")
private <T extends DataSource<?>> T createDataSource(final Key key,
final Class<T> dataSource) {
// summary is a special case, use the original datasource
if (key.equals(Summary.get()))
return base.getData(dataSource).get(key);
// summary is a special case, use the original datasource
if (Alerts.class.isAssignableFrom(dataSource)
&& !(key instanceof Project))
return null;
final DataSourceSettings settings = DataSourceAnnotationReader
.getSettings(dataSource);
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.getName().equals("getValue")) {
String dataKey = key.getCode() + "-" + dataSource.getName();
Object value;
if (settings.type().equals(Integer.class))
value = Math.round(Math.random() * 1000);
else if (settings.type().equals(Duration.class))
value = Duration.milliseconds(Math
.round(Math.random() * 100000000));
else if (settings.type().equals(String.class))
value = "random";
else if (settings.type().equals(WeatherReport.class)) {
value = createRandomWeather();
} else if (settings.type().equals(DotColor.class)
&& settings.list()) {
Random random = new Random();
List<DotColor> ret = new ArrayList<DotColor>();
for (int count = 4; count >= 0; count--) {
ret.add(DotColor.values()[random.nextInt(4)]);
}
value = ret;
} else if (settings.type().equals(Train.class)
&& settings.list()) {
value = createRandomTrains();
} else if (settings.type().equals(Alert.class)
&& settings.list()) {
value = createRandomAlerts(key);
} else if (settings.type().equals(Commit.class)
&& settings.list()) {
value = createRandomCommits(key);
} else if (settings.type().equals(Issue.class)
&& settings.list()) {
value = createRandomIssues(key);
} else if (settings.type().equals(Event.class)
&& settings.list()) {
value = createRandomEvents(key);
} else if (settings.type().equals(Status.class)
&& settings.list()) {
value = createRandomTweets(key);
} else
throw new IllegalStateException("Unsupported type "
+ settings.type());
Object ret = dataCache.putIfAbsent(dataKey, value);
return ret == null ? value : ret;
} else if (method.getName().equals("toString")) {
String dataKey = key.getCode() + "-" + dataSource.getName();
return dataKey;
}
throw new UnsupportedOperationException();
}
private WeatherReport createRandomWeather() {
Random random = new Random();
WeatherReport ret = new WeatherReport();
- ret.setMaxTemperature(random.nextDouble() * 50.0 - 15.0);
- ret.setMinTemperature(ret.getMaxTemperature()
- - random.nextDouble() * 10.0);
+ ret.setMaxTemperature(Math
+ .round(random.nextDouble() * 500.0 - 150.0) / 10.0);
+ ret.setMinTemperature(Math.round(ret.getMaxTemperature() * 10.0
+ - random.nextDouble() * 100.0) / 10.0);
ret.setRainfallProbability(random.nextInt(100));
ret.setType(WeatherType.values()[random.nextInt(WeatherType
.values().length)]);
ret.setWindDirection(random.nextInt(360));
- ret.setWindSpeed(random.nextDouble() * 100.0);
- double lat = random.nextDouble() * 180.0 - 90.0;
- double lon = random.nextDouble() * 180.0 - 90.0;
+ ret
+ .setWindSpeed(Math.round(random.nextDouble() * 1000.0) / 10.0);
+ double lat = 52.25;
+ double lon = 6.2;
ret.setSunrise(WetterComService.getSunrize(lat, lon));
ret.setSunset(WetterComService.getSunset(lat, lon));
return ret;
}
private List<Train> createRandomTrains() {
Random random = new Random();
List<Train> ret = new ArrayList<Train>();
for (int count = 0; count < 10; count++) {
Train train = new Train();
train.setType(TrainType.values()[random.nextInt(TrainType
.values().length)]);
train.setDestination("random random random centraal");
int minute = random.nextInt(60);
train.setDepartureTime(random.nextInt(24) + ":"
+ (minute < 10 ? "0" : "") + minute);
train.setDelay(random.nextInt(10));
train.setPlatform(Integer.toString(random.nextInt(10)));
ret.add(train);
}
Collections.sort(ret, new Comparator<Train>() {
@Override
public int compare(Train o1, Train o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
return ret;
}
private List<Alert> createRandomAlerts(Key key) {
if (!(key instanceof Project))
return null;
Random random = new Random();
List<Alert> ret = new ArrayList<Alert>();
for (int count = 0; count < random.nextInt(3); count++) {
Alert alert = new Alert();
alert.setProject(key);
alert.setOverlayVisible(random.nextInt(10) == 0);
alert.setColor(DotColor.values()[random.nextInt(3)]);
int minute = random.nextInt(60);
alert.setTime(random.nextInt(24) + ":"
+ (minute < 10 ? "0" : "") + minute);
alert.setMessage("random exception with long message");
ret.add(alert);
}
Collections.sort(ret, new Comparator<Alert>() {
@Override
public int compare(Alert o1, Alert o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
return ret;
}
private List<Commit> createRandomCommits(Key key) {
Random random = new Random();
List<Commit> ret = new ArrayList<Commit>();
for (int count = 0; count < 5; count++) {
Commit commit = new Commit();
commit.setProject(key);
commit.setRevision(random.nextInt(100000));
commit.setDateTime(new Date(System.currentTimeMillis()
- random.nextInt(3600000)));
commit.setMessage("random commit with long message");
commit.setAuthor("random");
ret.add(commit);
}
return ret;
}
private List<Issue> createRandomIssues(Key key) {
Random random = new Random();
List<Issue> ret = new ArrayList<Issue>();
for (int count = 0; count < 5; count++) {
Issue issue = new Issue();
issue.setProject(key);
issue.setId(random.nextInt(100000));
issue.setDateTime(new Date(System.currentTimeMillis()
- random.nextInt(3600000)));
issue.setSummary("random issue with long message");
issue.setStatus(IssueStatus.NEW);
issue.setSeverity(IssueSeverity.values()[random
.nextInt(IssueSeverity.values().length)]);
issue.setPriority(IssuePriority.values()[random
.nextInt(IssuePriority.values().length)]);
ret.add(issue);
}
return ret;
}
private synchronized List<Event> createRandomEvents(Key key) {
List<Event> ret = eventCache.get(key);
if (ret != null)
return ret;
Random random = new Random();
ret = new ArrayList<Event>();
for (int count = 0; count < 2; count++) {
Event event = new Event();
event.setKey(key);
event.setTitle("random");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, random.nextInt(30));
event.setDateTime(cal.getTime());
event.setMajor(random.nextInt(5) == 0);
if (event.isMajor())
event.getTags().add("#major");
event.setColor(Integer.toHexString(random
.nextInt(256 * 256 * 256)));
while (event.getColor().length() < 0)
event.setColor("0" + event.getColor());
event.setColor("#" + event.getColor());
ret.add(event);
}
Collections.sort(ret, new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
eventCache.put(key, ret);
return ret;
}
private List<Status> createRandomTweets(Key key) {
List<Status> ret = new ArrayList<Status>();
return ret;
}
};
return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] { dataSource }, handler);
}
@Override
public void run() {
dataCache.clear();
}
}
| false | true | private <T extends DataSource<?>> T createDataSource(final Key key,
final Class<T> dataSource) {
// summary is a special case, use the original datasource
if (key.equals(Summary.get()))
return base.getData(dataSource).get(key);
// summary is a special case, use the original datasource
if (Alerts.class.isAssignableFrom(dataSource)
&& !(key instanceof Project))
return null;
final DataSourceSettings settings = DataSourceAnnotationReader
.getSettings(dataSource);
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.getName().equals("getValue")) {
String dataKey = key.getCode() + "-" + dataSource.getName();
Object value;
if (settings.type().equals(Integer.class))
value = Math.round(Math.random() * 1000);
else if (settings.type().equals(Duration.class))
value = Duration.milliseconds(Math
.round(Math.random() * 100000000));
else if (settings.type().equals(String.class))
value = "random";
else if (settings.type().equals(WeatherReport.class)) {
value = createRandomWeather();
} else if (settings.type().equals(DotColor.class)
&& settings.list()) {
Random random = new Random();
List<DotColor> ret = new ArrayList<DotColor>();
for (int count = 4; count >= 0; count--) {
ret.add(DotColor.values()[random.nextInt(4)]);
}
value = ret;
} else if (settings.type().equals(Train.class)
&& settings.list()) {
value = createRandomTrains();
} else if (settings.type().equals(Alert.class)
&& settings.list()) {
value = createRandomAlerts(key);
} else if (settings.type().equals(Commit.class)
&& settings.list()) {
value = createRandomCommits(key);
} else if (settings.type().equals(Issue.class)
&& settings.list()) {
value = createRandomIssues(key);
} else if (settings.type().equals(Event.class)
&& settings.list()) {
value = createRandomEvents(key);
} else if (settings.type().equals(Status.class)
&& settings.list()) {
value = createRandomTweets(key);
} else
throw new IllegalStateException("Unsupported type "
+ settings.type());
Object ret = dataCache.putIfAbsent(dataKey, value);
return ret == null ? value : ret;
} else if (method.getName().equals("toString")) {
String dataKey = key.getCode() + "-" + dataSource.getName();
return dataKey;
}
throw new UnsupportedOperationException();
}
private WeatherReport createRandomWeather() {
Random random = new Random();
WeatherReport ret = new WeatherReport();
ret.setMaxTemperature(random.nextDouble() * 50.0 - 15.0);
ret.setMinTemperature(ret.getMaxTemperature()
- random.nextDouble() * 10.0);
ret.setRainfallProbability(random.nextInt(100));
ret.setType(WeatherType.values()[random.nextInt(WeatherType
.values().length)]);
ret.setWindDirection(random.nextInt(360));
ret.setWindSpeed(random.nextDouble() * 100.0);
double lat = random.nextDouble() * 180.0 - 90.0;
double lon = random.nextDouble() * 180.0 - 90.0;
ret.setSunrise(WetterComService.getSunrize(lat, lon));
ret.setSunset(WetterComService.getSunset(lat, lon));
return ret;
}
private List<Train> createRandomTrains() {
Random random = new Random();
List<Train> ret = new ArrayList<Train>();
for (int count = 0; count < 10; count++) {
Train train = new Train();
train.setType(TrainType.values()[random.nextInt(TrainType
.values().length)]);
train.setDestination("random random random centraal");
int minute = random.nextInt(60);
train.setDepartureTime(random.nextInt(24) + ":"
+ (minute < 10 ? "0" : "") + minute);
train.setDelay(random.nextInt(10));
train.setPlatform(Integer.toString(random.nextInt(10)));
ret.add(train);
}
Collections.sort(ret, new Comparator<Train>() {
@Override
public int compare(Train o1, Train o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
return ret;
}
private List<Alert> createRandomAlerts(Key key) {
if (!(key instanceof Project))
return null;
Random random = new Random();
List<Alert> ret = new ArrayList<Alert>();
for (int count = 0; count < random.nextInt(3); count++) {
Alert alert = new Alert();
alert.setProject(key);
alert.setOverlayVisible(random.nextInt(10) == 0);
alert.setColor(DotColor.values()[random.nextInt(3)]);
int minute = random.nextInt(60);
alert.setTime(random.nextInt(24) + ":"
+ (minute < 10 ? "0" : "") + minute);
alert.setMessage("random exception with long message");
ret.add(alert);
}
Collections.sort(ret, new Comparator<Alert>() {
@Override
public int compare(Alert o1, Alert o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
return ret;
}
private List<Commit> createRandomCommits(Key key) {
Random random = new Random();
List<Commit> ret = new ArrayList<Commit>();
for (int count = 0; count < 5; count++) {
Commit commit = new Commit();
commit.setProject(key);
commit.setRevision(random.nextInt(100000));
commit.setDateTime(new Date(System.currentTimeMillis()
- random.nextInt(3600000)));
commit.setMessage("random commit with long message");
commit.setAuthor("random");
ret.add(commit);
}
return ret;
}
private List<Issue> createRandomIssues(Key key) {
Random random = new Random();
List<Issue> ret = new ArrayList<Issue>();
for (int count = 0; count < 5; count++) {
Issue issue = new Issue();
issue.setProject(key);
issue.setId(random.nextInt(100000));
issue.setDateTime(new Date(System.currentTimeMillis()
- random.nextInt(3600000)));
issue.setSummary("random issue with long message");
issue.setStatus(IssueStatus.NEW);
issue.setSeverity(IssueSeverity.values()[random
.nextInt(IssueSeverity.values().length)]);
issue.setPriority(IssuePriority.values()[random
.nextInt(IssuePriority.values().length)]);
ret.add(issue);
}
return ret;
}
private synchronized List<Event> createRandomEvents(Key key) {
List<Event> ret = eventCache.get(key);
if (ret != null)
return ret;
Random random = new Random();
ret = new ArrayList<Event>();
for (int count = 0; count < 2; count++) {
Event event = new Event();
event.setKey(key);
event.setTitle("random");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, random.nextInt(30));
event.setDateTime(cal.getTime());
event.setMajor(random.nextInt(5) == 0);
if (event.isMajor())
event.getTags().add("#major");
event.setColor(Integer.toHexString(random
.nextInt(256 * 256 * 256)));
while (event.getColor().length() < 0)
event.setColor("0" + event.getColor());
event.setColor("#" + event.getColor());
ret.add(event);
}
Collections.sort(ret, new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
eventCache.put(key, ret);
return ret;
}
private List<Status> createRandomTweets(Key key) {
List<Status> ret = new ArrayList<Status>();
return ret;
}
};
return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] { dataSource }, handler);
}
| private <T extends DataSource<?>> T createDataSource(final Key key,
final Class<T> dataSource) {
// summary is a special case, use the original datasource
if (key.equals(Summary.get()))
return base.getData(dataSource).get(key);
// summary is a special case, use the original datasource
if (Alerts.class.isAssignableFrom(dataSource)
&& !(key instanceof Project))
return null;
final DataSourceSettings settings = DataSourceAnnotationReader
.getSettings(dataSource);
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if (method.getName().equals("getValue")) {
String dataKey = key.getCode() + "-" + dataSource.getName();
Object value;
if (settings.type().equals(Integer.class))
value = Math.round(Math.random() * 1000);
else if (settings.type().equals(Duration.class))
value = Duration.milliseconds(Math
.round(Math.random() * 100000000));
else if (settings.type().equals(String.class))
value = "random";
else if (settings.type().equals(WeatherReport.class)) {
value = createRandomWeather();
} else if (settings.type().equals(DotColor.class)
&& settings.list()) {
Random random = new Random();
List<DotColor> ret = new ArrayList<DotColor>();
for (int count = 4; count >= 0; count--) {
ret.add(DotColor.values()[random.nextInt(4)]);
}
value = ret;
} else if (settings.type().equals(Train.class)
&& settings.list()) {
value = createRandomTrains();
} else if (settings.type().equals(Alert.class)
&& settings.list()) {
value = createRandomAlerts(key);
} else if (settings.type().equals(Commit.class)
&& settings.list()) {
value = createRandomCommits(key);
} else if (settings.type().equals(Issue.class)
&& settings.list()) {
value = createRandomIssues(key);
} else if (settings.type().equals(Event.class)
&& settings.list()) {
value = createRandomEvents(key);
} else if (settings.type().equals(Status.class)
&& settings.list()) {
value = createRandomTweets(key);
} else
throw new IllegalStateException("Unsupported type "
+ settings.type());
Object ret = dataCache.putIfAbsent(dataKey, value);
return ret == null ? value : ret;
} else if (method.getName().equals("toString")) {
String dataKey = key.getCode() + "-" + dataSource.getName();
return dataKey;
}
throw new UnsupportedOperationException();
}
private WeatherReport createRandomWeather() {
Random random = new Random();
WeatherReport ret = new WeatherReport();
ret.setMaxTemperature(Math
.round(random.nextDouble() * 500.0 - 150.0) / 10.0);
ret.setMinTemperature(Math.round(ret.getMaxTemperature() * 10.0
- random.nextDouble() * 100.0) / 10.0);
ret.setRainfallProbability(random.nextInt(100));
ret.setType(WeatherType.values()[random.nextInt(WeatherType
.values().length)]);
ret.setWindDirection(random.nextInt(360));
ret
.setWindSpeed(Math.round(random.nextDouble() * 1000.0) / 10.0);
double lat = 52.25;
double lon = 6.2;
ret.setSunrise(WetterComService.getSunrize(lat, lon));
ret.setSunset(WetterComService.getSunset(lat, lon));
return ret;
}
private List<Train> createRandomTrains() {
Random random = new Random();
List<Train> ret = new ArrayList<Train>();
for (int count = 0; count < 10; count++) {
Train train = new Train();
train.setType(TrainType.values()[random.nextInt(TrainType
.values().length)]);
train.setDestination("random random random centraal");
int minute = random.nextInt(60);
train.setDepartureTime(random.nextInt(24) + ":"
+ (minute < 10 ? "0" : "") + minute);
train.setDelay(random.nextInt(10));
train.setPlatform(Integer.toString(random.nextInt(10)));
ret.add(train);
}
Collections.sort(ret, new Comparator<Train>() {
@Override
public int compare(Train o1, Train o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
return ret;
}
private List<Alert> createRandomAlerts(Key key) {
if (!(key instanceof Project))
return null;
Random random = new Random();
List<Alert> ret = new ArrayList<Alert>();
for (int count = 0; count < random.nextInt(3); count++) {
Alert alert = new Alert();
alert.setProject(key);
alert.setOverlayVisible(random.nextInt(10) == 0);
alert.setColor(DotColor.values()[random.nextInt(3)]);
int minute = random.nextInt(60);
alert.setTime(random.nextInt(24) + ":"
+ (minute < 10 ? "0" : "") + minute);
alert.setMessage("random exception with long message");
ret.add(alert);
}
Collections.sort(ret, new Comparator<Alert>() {
@Override
public int compare(Alert o1, Alert o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
return ret;
}
private List<Commit> createRandomCommits(Key key) {
Random random = new Random();
List<Commit> ret = new ArrayList<Commit>();
for (int count = 0; count < 5; count++) {
Commit commit = new Commit();
commit.setProject(key);
commit.setRevision(random.nextInt(100000));
commit.setDateTime(new Date(System.currentTimeMillis()
- random.nextInt(3600000)));
commit.setMessage("random commit with long message");
commit.setAuthor("random");
ret.add(commit);
}
return ret;
}
private List<Issue> createRandomIssues(Key key) {
Random random = new Random();
List<Issue> ret = new ArrayList<Issue>();
for (int count = 0; count < 5; count++) {
Issue issue = new Issue();
issue.setProject(key);
issue.setId(random.nextInt(100000));
issue.setDateTime(new Date(System.currentTimeMillis()
- random.nextInt(3600000)));
issue.setSummary("random issue with long message");
issue.setStatus(IssueStatus.NEW);
issue.setSeverity(IssueSeverity.values()[random
.nextInt(IssueSeverity.values().length)]);
issue.setPriority(IssuePriority.values()[random
.nextInt(IssuePriority.values().length)]);
ret.add(issue);
}
return ret;
}
private synchronized List<Event> createRandomEvents(Key key) {
List<Event> ret = eventCache.get(key);
if (ret != null)
return ret;
Random random = new Random();
ret = new ArrayList<Event>();
for (int count = 0; count < 2; count++) {
Event event = new Event();
event.setKey(key);
event.setTitle("random");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, random.nextInt(30));
event.setDateTime(cal.getTime());
event.setMajor(random.nextInt(5) == 0);
if (event.isMajor())
event.getTags().add("#major");
event.setColor(Integer.toHexString(random
.nextInt(256 * 256 * 256)));
while (event.getColor().length() < 0)
event.setColor("0" + event.getColor());
event.setColor("#" + event.getColor());
ret.add(event);
}
Collections.sort(ret, new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
eventCache.put(key, ret);
return ret;
}
private List<Status> createRandomTweets(Key key) {
List<Status> ret = new ArrayList<Status>();
return ret;
}
};
return (T) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[] { dataSource }, handler);
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/JREProfilesPreferencePage.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/JREProfilesPreferencePage.java
index d2340a0ba..f76becb12 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/JREProfilesPreferencePage.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/jres/JREProfilesPreferencePage.java
@@ -1,214 +1,218 @@
/*******************************************************************************
* Copyright (c) 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.jres;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.internal.debug.ui.IJavaDebugHelpContextIds;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.environments.IExecutionEnvironment;
import org.eclipse.jdt.launching.environments.IExecutionEnvironmentsManager;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
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.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
/**
* Sets default VM per execution environment.
*
* @since 3.2
*/
public class JREProfilesPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private TableViewer fProfilesViewer;
private CheckboxTableViewer fJREsViewer;
private Text fDescription;
/**
* Working copy "EE Profile -> Default JRE"
*/
private Map fDefaults = new HashMap();
class JREsContentProvider implements IStructuredContentProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
public Object[] getElements(Object inputElement) {
return JavaRuntime.getExecutionEnvironmentsManager().getVMInstalls((IExecutionEnvironment)inputElement);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
public void dispose() {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public JREProfilesPreferencePage() {
super();
// only used when page is shown programatically
setTitle(JREMessages.JREProfilesPreferencePage_0);
setDescription(JREMessages.JREProfilesPreferencePage_1);
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
protected Control createContents(Composite ancestor) {
initializeDialogUnits(ancestor);
noDefaultAndApplyButton();
// TODO: fix help
PlatformUI.getWorkbench().getHelpSystem().setHelp(ancestor, IJavaDebugHelpContextIds.JRE_PROFILES_PAGE);
// init default mappings
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment[] environments = manager.getExecutionEnvironments();
for (int i = 0; i < environments.length; i++) {
IExecutionEnvironment environment = environments[i];
IVMInstall install = manager.getDefaultVMInstall(environment);
if (install != null) {
fDefaults.put(environment, install);
}
}
Composite container = new Composite(ancestor, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.makeColumnsEqualWidth = true;
container.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
container.setLayoutData(gd);
container.setFont(ancestor.getFont());
Label label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_2);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false));
label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_3);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false));
Table table= new Table(container, SWT.BORDER | SWT.SINGLE);
table.setLayout(new GridLayout());
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fProfilesViewer = new TableViewer(table);
fProfilesViewer.setContentProvider(new ArrayContentProvider());
fProfilesViewer.setLabelProvider(new ExecutionEnvironmentsLabelProvider());
fProfilesViewer.setSorter(new ViewerSorter());
fProfilesViewer.setInput(JavaRuntime.getExecutionEnvironmentsManager().getExecutionEnvironments());
table= new Table(container, SWT.CHECK | SWT.BORDER | SWT.SINGLE);
table.setLayout(new GridLayout());
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fJREsViewer = new CheckboxTableViewer(table);
fJREsViewer.setContentProvider(new JREsContentProvider());
fJREsViewer.setLabelProvider(new JREsLabelProvider());
fJREsViewer.setSorter(new ViewerSorter());
label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_4);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false, 2, 1));
Text text = new Text(container, SWT.READ_ONLY | SWT.WRAP | SWT.BORDER);
text.setFont(ancestor.getFont());
text.setLayoutData(new GridData(SWT.FILL, 0, true, false, 2, 1));
fDescription = text;
fProfilesViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IExecutionEnvironment env = (IExecutionEnvironment) ((IStructuredSelection)event.getSelection()).getFirstElement();
fJREsViewer.setInput(env);
- fDescription.setText(env.getDescription());
+ String description = env.getDescription();
+ if (description == null) {
+ description = ""; //$NON-NLS-1$
+ }
+ fDescription.setText(description);
IVMInstall jre = (IVMInstall) fDefaults.get(env);
if (jre != null) {
fJREsViewer.setCheckedElements(new Object[]{jre});
}
}
});
fJREsViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
if (event.getChecked()) {
Object element = event.getElement();
fDefaults.put(fJREsViewer.getInput(), element);
fJREsViewer.setCheckedElements(new Object[]{element});
} else {
fDefaults.remove(fJREsViewer.getInput());
}
}
});
return ancestor;
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.IPreferencePage#performOk()
*/
public boolean performOk() {
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment[] environments = manager.getExecutionEnvironments();
for (int i = 0; i < environments.length; i++) {
IExecutionEnvironment environment = environments[i];
IVMInstall vm = (IVMInstall) fDefaults.get(environment);
try {
manager.setDefaultVMInstall(environment, vm);
} catch (CoreException e) {
setErrorMessage(e.getMessage());
return false;
}
}
return super.performOk();
}
}
| true | true | protected Control createContents(Composite ancestor) {
initializeDialogUnits(ancestor);
noDefaultAndApplyButton();
// TODO: fix help
PlatformUI.getWorkbench().getHelpSystem().setHelp(ancestor, IJavaDebugHelpContextIds.JRE_PROFILES_PAGE);
// init default mappings
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment[] environments = manager.getExecutionEnvironments();
for (int i = 0; i < environments.length; i++) {
IExecutionEnvironment environment = environments[i];
IVMInstall install = manager.getDefaultVMInstall(environment);
if (install != null) {
fDefaults.put(environment, install);
}
}
Composite container = new Composite(ancestor, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.makeColumnsEqualWidth = true;
container.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
container.setLayoutData(gd);
container.setFont(ancestor.getFont());
Label label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_2);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false));
label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_3);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false));
Table table= new Table(container, SWT.BORDER | SWT.SINGLE);
table.setLayout(new GridLayout());
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fProfilesViewer = new TableViewer(table);
fProfilesViewer.setContentProvider(new ArrayContentProvider());
fProfilesViewer.setLabelProvider(new ExecutionEnvironmentsLabelProvider());
fProfilesViewer.setSorter(new ViewerSorter());
fProfilesViewer.setInput(JavaRuntime.getExecutionEnvironmentsManager().getExecutionEnvironments());
table= new Table(container, SWT.CHECK | SWT.BORDER | SWT.SINGLE);
table.setLayout(new GridLayout());
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fJREsViewer = new CheckboxTableViewer(table);
fJREsViewer.setContentProvider(new JREsContentProvider());
fJREsViewer.setLabelProvider(new JREsLabelProvider());
fJREsViewer.setSorter(new ViewerSorter());
label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_4);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false, 2, 1));
Text text = new Text(container, SWT.READ_ONLY | SWT.WRAP | SWT.BORDER);
text.setFont(ancestor.getFont());
text.setLayoutData(new GridData(SWT.FILL, 0, true, false, 2, 1));
fDescription = text;
fProfilesViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IExecutionEnvironment env = (IExecutionEnvironment) ((IStructuredSelection)event.getSelection()).getFirstElement();
fJREsViewer.setInput(env);
fDescription.setText(env.getDescription());
IVMInstall jre = (IVMInstall) fDefaults.get(env);
if (jre != null) {
fJREsViewer.setCheckedElements(new Object[]{jre});
}
}
});
fJREsViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
if (event.getChecked()) {
Object element = event.getElement();
fDefaults.put(fJREsViewer.getInput(), element);
fJREsViewer.setCheckedElements(new Object[]{element});
} else {
fDefaults.remove(fJREsViewer.getInput());
}
}
});
return ancestor;
}
| protected Control createContents(Composite ancestor) {
initializeDialogUnits(ancestor);
noDefaultAndApplyButton();
// TODO: fix help
PlatformUI.getWorkbench().getHelpSystem().setHelp(ancestor, IJavaDebugHelpContextIds.JRE_PROFILES_PAGE);
// init default mappings
IExecutionEnvironmentsManager manager = JavaRuntime.getExecutionEnvironmentsManager();
IExecutionEnvironment[] environments = manager.getExecutionEnvironments();
for (int i = 0; i < environments.length; i++) {
IExecutionEnvironment environment = environments[i];
IVMInstall install = manager.getDefaultVMInstall(environment);
if (install != null) {
fDefaults.put(environment, install);
}
}
Composite container = new Composite(ancestor, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.makeColumnsEqualWidth = true;
container.setLayout(layout);
GridData gd = new GridData(GridData.FILL_BOTH);
container.setLayoutData(gd);
container.setFont(ancestor.getFont());
Label label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_2);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false));
label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_3);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false));
Table table= new Table(container, SWT.BORDER | SWT.SINGLE);
table.setLayout(new GridLayout());
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fProfilesViewer = new TableViewer(table);
fProfilesViewer.setContentProvider(new ArrayContentProvider());
fProfilesViewer.setLabelProvider(new ExecutionEnvironmentsLabelProvider());
fProfilesViewer.setSorter(new ViewerSorter());
fProfilesViewer.setInput(JavaRuntime.getExecutionEnvironmentsManager().getExecutionEnvironments());
table= new Table(container, SWT.CHECK | SWT.BORDER | SWT.SINGLE);
table.setLayout(new GridLayout());
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
fJREsViewer = new CheckboxTableViewer(table);
fJREsViewer.setContentProvider(new JREsContentProvider());
fJREsViewer.setLabelProvider(new JREsLabelProvider());
fJREsViewer.setSorter(new ViewerSorter());
label = new Label(container, SWT.NONE);
label.setFont(ancestor.getFont());
label.setText(JREMessages.JREProfilesPreferencePage_4);
label.setLayoutData(new GridData(SWT.FILL, 0, true, false, 2, 1));
Text text = new Text(container, SWT.READ_ONLY | SWT.WRAP | SWT.BORDER);
text.setFont(ancestor.getFont());
text.setLayoutData(new GridData(SWT.FILL, 0, true, false, 2, 1));
fDescription = text;
fProfilesViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IExecutionEnvironment env = (IExecutionEnvironment) ((IStructuredSelection)event.getSelection()).getFirstElement();
fJREsViewer.setInput(env);
String description = env.getDescription();
if (description == null) {
description = ""; //$NON-NLS-1$
}
fDescription.setText(description);
IVMInstall jre = (IVMInstall) fDefaults.get(env);
if (jre != null) {
fJREsViewer.setCheckedElements(new Object[]{jre});
}
}
});
fJREsViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
if (event.getChecked()) {
Object element = event.getElement();
fDefaults.put(fJREsViewer.getInput(), element);
fJREsViewer.setCheckedElements(new Object[]{element});
} else {
fDefaults.remove(fJREsViewer.getInput());
}
}
});
return ancestor;
}
|
diff --git a/src/test/org/apache/nutch/fetcher/TestFetcher.java b/src/test/org/apache/nutch/fetcher/TestFetcher.java
index 0e0d57b2..3ea8c33f 100644
--- a/src/test/org/apache/nutch/fetcher/TestFetcher.java
+++ b/src/test/org/apache/nutch/fetcher/TestFetcher.java
@@ -1,133 +1,134 @@
/*
* Copyright 2006 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.fetcher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.UTF8;
import org.apache.nutch.crawl.CrawlDBTestUtil;
import org.apache.nutch.crawl.Generator;
import org.apache.nutch.crawl.Injector;
import org.apache.nutch.protocol.Content;
import org.mortbay.jetty.Server;
import junit.framework.TestCase;
/**
* Basic fetcher test
* 1. generate seedlist
* 2. inject
* 3. generate
* 3. fetch
* 4. Verify contents
* @author nutch-dev <nutch-dev at lucene.apache.org>
*
*/
public class TestFetcher extends TestCase {
final static Path testdir=new Path("build/test/fetch-test");
Configuration conf;
FileSystem fs;
Path crawldbPath;
Path segmentsPath;
Path urlPath;
Server server;
protected void setUp() throws Exception{
conf=CrawlDBTestUtil.createConfiguration();
fs=FileSystem.get(conf);
fs.delete(testdir);
urlPath=new Path(testdir,"urls");
crawldbPath=new Path(testdir,"crawldb");
segmentsPath=new Path(testdir,"segments");
server=CrawlDBTestUtil.getServer(conf.getInt("content.server.port",50000), "build/test/data/fetch-test-site");
server.start();
}
protected void tearDown() throws InterruptedException, IOException{
server.stop();
fs.delete(testdir);
}
public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
- assertTrue(1000*time > (urls.size() + 1 * conf.getInt("fetcher.server.delay",5)));
+ int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
+ assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
handledurls.add(key.toString());
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
private void addUrl(ArrayList<String> urls, String page) {
urls.add("http://127.0.0.1:" + server.getListeners()[0].getPort() + "/" + page);
}
}
| true | true | public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
assertTrue(1000*time > (urls.size() + 1 * conf.getInt("fetcher.server.delay",5)));
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
handledurls.add(key.toString());
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
| public void testFetch() throws IOException {
//generate seedlist
ArrayList<String> urls=new ArrayList<String>();
addUrl(urls,"index.html");
addUrl(urls,"pagea.html");
addUrl(urls,"pageb.html");
addUrl(urls,"dup_of_pagea.html");
CrawlDBTestUtil.generateSeedList(fs, urlPath, urls);
//inject
Injector injector=new Injector(conf);
injector.inject(crawldbPath, urlPath);
//generate
Generator g=new Generator(conf);
Path generatedSegment=g.generate(crawldbPath, segmentsPath, 1, Long.MAX_VALUE, Long.MAX_VALUE);
long time=System.currentTimeMillis();
//fetch
Fetcher fetcher=new Fetcher(conf);
fetcher.fetch(generatedSegment, 1, true);
time=System.currentTimeMillis()-time;
//verify politeness, time taken should be more than (num_of_pages +1)*delay
int minimumTime=(int) ((urls.size()+1)*1000*conf.getFloat("fetcher.server.delay",5));
assertTrue(time > minimumTime);
//verify results
Path content=new Path(new Path(generatedSegment, Content.DIR_NAME),"part-00000/data");
SequenceFile.Reader reader=new SequenceFile.Reader(fs, content, conf);
ArrayList<String> handledurls=new ArrayList<String>();
READ:
do {
UTF8 key=new UTF8();
Content value=new Content();
if(!reader.next(key, value)) break READ;
handledurls.add(key.toString());
} while(true);
reader.close();
Collections.sort(urls);
Collections.sort(handledurls);
//verify that enough pages were handled
assertEquals(urls.size(), handledurls.size());
//verify that correct pages were handled
assertTrue(handledurls.containsAll(urls));
assertTrue(urls.containsAll(handledurls));
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/business/sales/panes/controllers/impl/SaleDescPaneControllerImpl.java b/OpERP/src/main/java/devopsdistilled/operp/client/business/sales/panes/controllers/impl/SaleDescPaneControllerImpl.java
index e39f75d4..07542b70 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/business/sales/panes/controllers/impl/SaleDescPaneControllerImpl.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/business/sales/panes/controllers/impl/SaleDescPaneControllerImpl.java
@@ -1,127 +1,127 @@
package devopsdistilled.operp.client.business.sales.panes.controllers.impl;
import javax.inject.Inject;
import javax.swing.JPanel;
import devopsdistilled.operp.client.abstracts.EntityOperation;
import devopsdistilled.operp.client.business.sales.panes.SaleDescPane;
import devopsdistilled.operp.client.business.sales.panes.controllers.SaleDescPaneController;
import devopsdistilled.operp.client.business.sales.panes.controllers.SaleDescRowPaneController;
import devopsdistilled.operp.client.business.sales.panes.models.SaleDescPaneModel;
import devopsdistilled.operp.client.exceptions.EntityValidationException;
import devopsdistilled.operp.client.exceptions.NullFieldException;
import devopsdistilled.operp.client.stock.models.StockModel;
import devopsdistilled.operp.server.data.entity.business.SaleDesc;
import devopsdistilled.operp.server.data.entity.business.SaleDescRow;
import devopsdistilled.operp.server.data.entity.stock.Stock;
public class SaleDescPaneControllerImpl implements SaleDescPaneController {
@Inject
private SaleDescPane view;
@Inject
private SaleDescPaneModel model;
@Inject
private StockModel stockModel;
@Inject
private SaleDescRowPaneController saleDescRowPaneController;
@Override
public void validate() throws EntityValidationException {
Long quantity = model.getSaleDescRow().getQuantity();
Double rate = model.getSaleDescRow().getRate();
if (model.getSaleDescRow().getItem() == null
|| model.getSaleDescRow().getWarehouse() == null
|| quantity.equals(0L) || rate.equals(0.0)) {
throw new NullFieldException();
}
if (quantity.compareTo(0L) <= 0)
throw new EntityValidationException(
"Quantity shouldnt' be negative value");
if (rate.compareTo(0.0) < 0)
throw new EntityValidationException("Rate can't be negative");
// Check if quantity exceeds stock
for (Stock stock : stockModel.getEntities())
if (stock.getWarehouse().compareTo(
model.getSaleDescRow().getWarehouse()) == 0
&& stock.getItem().compareTo(
model.getSaleDescRow().getItem()) == 0)
- if (stock.getQuantity().compareTo(quantity) <= 0)
+ if (stock.getQuantity().compareTo(quantity) < 0)
throw new EntityValidationException("Only "
+ stock.getQuantity() + " " + stock.getItem()
+ " available in " + stock.getWarehouse());
}
@Override
public SaleDesc save() {
return null;
}
@Override
public SaleDescPaneModel getModel() {
return model;
}
@Override
public SaleDescPane getView() {
return view;
}
@Override
public void init(SaleDesc saleDesc, EntityOperation entityOperation) {
if (EntityOperation.Create == entityOperation) {
SaleDescRow saleDescRow = new SaleDescRow();
model.setSaleDescRow(saleDescRow);
saleDescRowPaneController.init(saleDescRow, entityOperation);
}
view.setSaleDescRowpanel((JPanel) saleDescRowPaneController.getView()
.getPane());
view.setController(this);
view.resetComponents();
model.registerObserver(view);
model.setEntityAndEntityOperation(saleDesc, entityOperation);
}
@Override
public void addNewSaleDescRow() {
model.getSaleDescRow().setBusinessDesc(model.getEntity());
if (EntityOperation.Edit != model.getEntityOperation()) {
model.getEntity().getDescRows().add(model.getSaleDescRow());
}
model.getEntity().setTotalAmount(
model.getEntity().getTotalAmount()
+ model.getSaleDescRow().getAmount());
model.setEntityAndEntityOperation(model.getEntity(),
EntityOperation.Create);
SaleDescRow saleDescRow = new SaleDescRow();
model.setSaleDescRow(saleDescRow);
saleDescRowPaneController.init(saleDescRow, EntityOperation.Create);
}
@Override
public void initEditSaleDescRow(SaleDescRow saleDescRow) {
model.setSaleDescRow(saleDescRow);
model.getEntity().setTotalAmount(
model.getEntity().getTotalAmount()
- model.getSaleDescRow().getAmount());
model.setEntityAndEntityOperation(model.getEntity(),
EntityOperation.Edit);
saleDescRowPaneController.init(saleDescRow, EntityOperation.Edit);
}
}
| true | true | public void validate() throws EntityValidationException {
Long quantity = model.getSaleDescRow().getQuantity();
Double rate = model.getSaleDescRow().getRate();
if (model.getSaleDescRow().getItem() == null
|| model.getSaleDescRow().getWarehouse() == null
|| quantity.equals(0L) || rate.equals(0.0)) {
throw new NullFieldException();
}
if (quantity.compareTo(0L) <= 0)
throw new EntityValidationException(
"Quantity shouldnt' be negative value");
if (rate.compareTo(0.0) < 0)
throw new EntityValidationException("Rate can't be negative");
// Check if quantity exceeds stock
for (Stock stock : stockModel.getEntities())
if (stock.getWarehouse().compareTo(
model.getSaleDescRow().getWarehouse()) == 0
&& stock.getItem().compareTo(
model.getSaleDescRow().getItem()) == 0)
if (stock.getQuantity().compareTo(quantity) <= 0)
throw new EntityValidationException("Only "
+ stock.getQuantity() + " " + stock.getItem()
+ " available in " + stock.getWarehouse());
}
| public void validate() throws EntityValidationException {
Long quantity = model.getSaleDescRow().getQuantity();
Double rate = model.getSaleDescRow().getRate();
if (model.getSaleDescRow().getItem() == null
|| model.getSaleDescRow().getWarehouse() == null
|| quantity.equals(0L) || rate.equals(0.0)) {
throw new NullFieldException();
}
if (quantity.compareTo(0L) <= 0)
throw new EntityValidationException(
"Quantity shouldnt' be negative value");
if (rate.compareTo(0.0) < 0)
throw new EntityValidationException("Rate can't be negative");
// Check if quantity exceeds stock
for (Stock stock : stockModel.getEntities())
if (stock.getWarehouse().compareTo(
model.getSaleDescRow().getWarehouse()) == 0
&& stock.getItem().compareTo(
model.getSaleDescRow().getItem()) == 0)
if (stock.getQuantity().compareTo(quantity) < 0)
throw new EntityValidationException("Only "
+ stock.getQuantity() + " " + stock.getItem()
+ " available in " + stock.getWarehouse());
}
|
diff --git a/src/com/vishnurajeevan/android/PredictionDisplay.java b/src/com/vishnurajeevan/android/PredictionDisplay.java
index 84438af..bfc22ce 100644
--- a/src/com/vishnurajeevan/android/PredictionDisplay.java
+++ b/src/com/vishnurajeevan/android/PredictionDisplay.java
@@ -1,72 +1,73 @@
package com.vishnurajeevan.android;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class PredictionDisplay extends Activity{
private static final String TAG = PredictionDisplay.class.getSimpleName();
private String stop;
private ArrayList<String> predicitons;
private TextView first,second,third;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.prediction_display);
predicitons = new ArrayList<String>();
first = (TextView)findViewById(R.id.txtFirstPrediction);
second = (TextView)findViewById(R.id.txtSecondPrediction);
third = (TextView)findViewById(R.id.txtThirdPrediciton);
Intent intent = getIntent();
stop = intent.getStringExtra("STOP");
Log.v(TAG,"before cleansing: "+stop);
- stop = stop.substring(0,6)+"Prediction"+stop.substring(20);
+ if(!stop.substring(0,16).equals("simplePrediction"))
+ stop = stop.substring(0,6)+"Prediction"+stop.substring(20);
stop = stop.replaceAll("&","&");
Log.v(TAG,stop);
Document predicitonDisplay;
try {
predicitonDisplay = Jsoup.connect("http://nextbus.com/predictor/"+stop).get();
String title = predicitonDisplay.title();
Log.v(TAG,title);
Element table = predicitonDisplay.select("table[cellspacing=0]").first();
String tableText = table.toString();
Log.v(TAG,tableText);
Iterator<Element> ite = table.select("div.right").iterator();
while(ite.hasNext()){
Element currentElement = ite.next();
predicitons.add(currentElement.text());
Log.v(TAG,currentElement.text());
}
// Iterator<Element> ite2 = table.select("")
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
first.setText(predicitons.get(0) + " Minutes");
second.setText(predicitons.get(1)+ " Minutes");
third.setText(predicitons.get(2)+ " Minutes");
}
}
| true | true | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.prediction_display);
predicitons = new ArrayList<String>();
first = (TextView)findViewById(R.id.txtFirstPrediction);
second = (TextView)findViewById(R.id.txtSecondPrediction);
third = (TextView)findViewById(R.id.txtThirdPrediciton);
Intent intent = getIntent();
stop = intent.getStringExtra("STOP");
Log.v(TAG,"before cleansing: "+stop);
stop = stop.substring(0,6)+"Prediction"+stop.substring(20);
stop = stop.replaceAll("&","&");
Log.v(TAG,stop);
Document predicitonDisplay;
try {
predicitonDisplay = Jsoup.connect("http://nextbus.com/predictor/"+stop).get();
String title = predicitonDisplay.title();
Log.v(TAG,title);
Element table = predicitonDisplay.select("table[cellspacing=0]").first();
String tableText = table.toString();
Log.v(TAG,tableText);
Iterator<Element> ite = table.select("div.right").iterator();
while(ite.hasNext()){
Element currentElement = ite.next();
predicitons.add(currentElement.text());
Log.v(TAG,currentElement.text());
}
// Iterator<Element> ite2 = table.select("")
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
first.setText(predicitons.get(0) + " Minutes");
second.setText(predicitons.get(1)+ " Minutes");
third.setText(predicitons.get(2)+ " Minutes");
}
| public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.prediction_display);
predicitons = new ArrayList<String>();
first = (TextView)findViewById(R.id.txtFirstPrediction);
second = (TextView)findViewById(R.id.txtSecondPrediction);
third = (TextView)findViewById(R.id.txtThirdPrediciton);
Intent intent = getIntent();
stop = intent.getStringExtra("STOP");
Log.v(TAG,"before cleansing: "+stop);
if(!stop.substring(0,16).equals("simplePrediction"))
stop = stop.substring(0,6)+"Prediction"+stop.substring(20);
stop = stop.replaceAll("&","&");
Log.v(TAG,stop);
Document predicitonDisplay;
try {
predicitonDisplay = Jsoup.connect("http://nextbus.com/predictor/"+stop).get();
String title = predicitonDisplay.title();
Log.v(TAG,title);
Element table = predicitonDisplay.select("table[cellspacing=0]").first();
String tableText = table.toString();
Log.v(TAG,tableText);
Iterator<Element> ite = table.select("div.right").iterator();
while(ite.hasNext()){
Element currentElement = ite.next();
predicitons.add(currentElement.text());
Log.v(TAG,currentElement.text());
}
// Iterator<Element> ite2 = table.select("")
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
first.setText(predicitons.get(0) + " Minutes");
second.setText(predicitons.get(1)+ " Minutes");
third.setText(predicitons.get(2)+ " Minutes");
}
|
diff --git a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskAttachmentActionsTest.java b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskAttachmentActionsTest.java
index dcf6da023..824c2c277 100644
--- a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskAttachmentActionsTest.java
+++ b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/TaskAttachmentActionsTest.java
@@ -1,85 +1,86 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 Mylar committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylar.tasks.tests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.net.URL;
import java.net.URLConnection;
import junit.framework.TestCase;
import org.eclipse.mylar.internal.tasks.ui.actions.CopyToClipboardAction;
import org.eclipse.mylar.internal.tasks.ui.actions.SaveRemoteFileAction;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
/**
* Test task attachment actions.
*
* @author Jeff Pound
*/
public class TaskAttachmentActionsTest extends TestCase {
/**
* Copy some text to the clipboard using the CopyToClipboardAction and
* ensure the contents of the clipboard match.
*
* @throws Exception
*/
public void testCopyToClipboardAction() throws Exception {
String contents = "Sample clipboard text";
CopyToClipboardAction action = new CopyToClipboardAction();
action.setContents(contents);
Control c = new Shell();
action.setControl(c);
action.run();
Clipboard clipboard = new Clipboard(c.getDisplay());
assertEquals(contents, clipboard.getContents(TextTransfer.getInstance()));
}
/**
* Save a file using the SaveRemoteFileAction and ensure it exists and the
* contents are correct
*
* @throws Exception
*/
public void testSaveRemoteFileAction() throws Exception {
String localFile = "TaskAttachmentActionsTest.testfile";
String url = "http://mylar.eclipse.org/bugs222/attachment.cgi?id=189";
int lineCount = 11;
SaveRemoteFileAction action = new SaveRemoteFileAction();
URLConnection urlConnect;
urlConnect = (new URL(url)).openConnection();
urlConnect.connect();
action.setInputStream(urlConnect.getInputStream());
action.setDestinationFilePath(localFile);
action.run();
- File file = new File(localFile);
+ File file = new File(localFile);
assertTrue(file.exists());
BufferedReader reader = new BufferedReader(new FileReader(file));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
assertEquals(lineCount, lines);
+ file.delete();
}
}
| false | true | public void testSaveRemoteFileAction() throws Exception {
String localFile = "TaskAttachmentActionsTest.testfile";
String url = "http://mylar.eclipse.org/bugs222/attachment.cgi?id=189";
int lineCount = 11;
SaveRemoteFileAction action = new SaveRemoteFileAction();
URLConnection urlConnect;
urlConnect = (new URL(url)).openConnection();
urlConnect.connect();
action.setInputStream(urlConnect.getInputStream());
action.setDestinationFilePath(localFile);
action.run();
File file = new File(localFile);
assertTrue(file.exists());
BufferedReader reader = new BufferedReader(new FileReader(file));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
assertEquals(lineCount, lines);
}
| public void testSaveRemoteFileAction() throws Exception {
String localFile = "TaskAttachmentActionsTest.testfile";
String url = "http://mylar.eclipse.org/bugs222/attachment.cgi?id=189";
int lineCount = 11;
SaveRemoteFileAction action = new SaveRemoteFileAction();
URLConnection urlConnect;
urlConnect = (new URL(url)).openConnection();
urlConnect.connect();
action.setInputStream(urlConnect.getInputStream());
action.setDestinationFilePath(localFile);
action.run();
File file = new File(localFile);
assertTrue(file.exists());
BufferedReader reader = new BufferedReader(new FileReader(file));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
assertEquals(lineCount, lines);
file.delete();
}
|
diff --git a/src/com/modcrafting/ultrabans/commands/Unban.java b/src/com/modcrafting/ultrabans/commands/Unban.java
index df809db..cbfff79 100644
--- a/src/com/modcrafting/ultrabans/commands/Unban.java
+++ b/src/com/modcrafting/ultrabans/commands/Unban.java
@@ -1,121 +1,123 @@
package com.modcrafting.ultrabans.commands;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import com.modcrafting.ultrabans.UltraBan;
public class Unban implements CommandExecutor{
public static final Logger log = Logger.getLogger("Minecraft");
UltraBan plugin;
public Unban(UltraBan ultraBan) {
this.plugin = ultraBan;
}
public boolean autoComplete;
public String expandName(String p) {
int m = 0;
String Result = "";
for (int n = 0; n < plugin.getServer().getOnlinePlayers().length; n++) {
String str = plugin.getServer().getOnlinePlayers()[n].getName();
if (str.matches("(?i).*" + p + ".*")) {
m++;
Result = str;
if(m==2) {
return null;
}
}
if (str.equalsIgnoreCase(p))
return str;
}
if (m == 1)
return Result;
if (m > 1) {
return null;
}
if (m < 1) {
return p;
}
return p;
}
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.unban")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1)return false;
String p = args[0];
if(plugin.db.permaBan(p.toLowerCase())){
sender.sendMessage(ChatColor.BLUE + p + ChatColor.GRAY + " is PermaBanned.");
log.log(Level.INFO, "[UltraBan] " + p + " is PermaBanned.");
return true;
}
- if(plugin.bannedPlayers.remove(p.toLowerCase())){
+ if(plugin.bannedPlayers.contains(p.toLowerCase())){
+ plugin.bannedPlayers.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
if(plugin.tempBans.containsKey(p.toLowerCase())){
plugin.tempBans.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
+ plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
+ return true;
}else{
String unbanMsgFailed = config.getString("messages.unbanMsgFailed", "%victim% is already unbanned!");
unbanMsgFailed = unbanMsgFailed.replaceAll("%admin%", admin);
unbanMsgFailed = unbanMsgFailed.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgFailed));
return true;
}
}
- return false;
}
public String formatMessage(String str){
String funnyChar = new Character((char) 167).toString();
str = str.replaceAll("&", funnyChar);
return str;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.unban")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1)return false;
String p = args[0];
if(plugin.db.permaBan(p.toLowerCase())){
sender.sendMessage(ChatColor.BLUE + p + ChatColor.GRAY + " is PermaBanned.");
log.log(Level.INFO, "[UltraBan] " + p + " is PermaBanned.");
return true;
}
if(plugin.bannedPlayers.remove(p.toLowerCase())){
plugin.db.removeFromBanlist(p);
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
if(plugin.tempBans.containsKey(p.toLowerCase())){
plugin.tempBans.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
}else{
String unbanMsgFailed = config.getString("messages.unbanMsgFailed", "%victim% is already unbanned!");
unbanMsgFailed = unbanMsgFailed.replaceAll("%admin%", admin);
unbanMsgFailed = unbanMsgFailed.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgFailed));
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
YamlConfiguration config = (YamlConfiguration) plugin.getConfig();
boolean auth = false;
Player player = null;
String admin = "server";
if (sender instanceof Player){
player = (Player)sender;
if (plugin.setupPermissions()){
if (plugin.permission.has(player, "ultraban.unban")) auth = true;
}else{
if (player.isOp()) auth = true; //defaulting to Op if no vault doesn't take or node
}
admin = player.getName();
}else{
auth = true; //if sender is not a player - Console
}
if (!auth){
sender.sendMessage(ChatColor.RED + "You do not have the required permissions.");
return true;
}
// Has enough arguments?
if (args.length < 1)return false;
String p = args[0];
if(plugin.db.permaBan(p.toLowerCase())){
sender.sendMessage(ChatColor.BLUE + p + ChatColor.GRAY + " is PermaBanned.");
log.log(Level.INFO, "[UltraBan] " + p + " is PermaBanned.");
return true;
}
if(plugin.bannedPlayers.contains(p.toLowerCase())){
plugin.bannedPlayers.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
Bukkit.getOfflinePlayer(p).setBanned(false);
String ip = plugin.db.getAddress(p);
if(plugin.bannedIPs.contains(ip)){
plugin.bannedIPs.remove(ip);
Bukkit.unbanIP(ip);
System.out.println("Also removed the IP ban!");
}
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
if(plugin.tempBans.containsKey(p.toLowerCase())){
plugin.tempBans.remove(p.toLowerCase());
plugin.db.removeFromBanlist(p);
plugin.db.addPlayer(p, "Unbanned", admin, 0, 5);
log.log(Level.INFO, "[UltraBan] " + admin + " unbanned player " + p + ".");
String unbanMsgBroadcast = config.getString("messages.unbanMsgBroadcast", "%victim% was unbanned by %admin%!");
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%admin%", admin);
unbanMsgBroadcast = unbanMsgBroadcast.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgBroadcast));
return true;
}else{
String unbanMsgFailed = config.getString("messages.unbanMsgFailed", "%victim% is already unbanned!");
unbanMsgFailed = unbanMsgFailed.replaceAll("%admin%", admin);
unbanMsgFailed = unbanMsgFailed.replaceAll("%victim%", p);
sender.sendMessage(formatMessage(unbanMsgFailed));
return true;
}
}
}
|
diff --git a/components/patient-tools/src/main/java/edu/toronto/cs/phenotips/tools/PropertyDisplayer.java b/components/patient-tools/src/main/java/edu/toronto/cs/phenotips/tools/PropertyDisplayer.java
index ef226435b..5eb359c9b 100644
--- a/components/patient-tools/src/main/java/edu/toronto/cs/phenotips/tools/PropertyDisplayer.java
+++ b/components/patient-tools/src/main/java/edu/toronto/cs/phenotips/tools/PropertyDisplayer.java
@@ -1,310 +1,316 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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 edu.toronto.cs.phenotips.tools;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.common.SolrDocument;
import com.xpn.xwiki.api.Property;
import edu.toronto.cs.phenotips.solr.HPOScriptService;
public class PropertyDisplayer
{
private static final String TYPE_KEY = "type";
private static final String GROUP_TYPE_KEY = "group_type";
private static final String ID_KEY = "id";
private static final String TITLE_KEY = "title";
private static final String CATEGORIES_KEY = "categories";
private static final String DATA_KEY = "data";
private static final String ITEM_TYPE_SECTION = "section";
private static final String ITEM_TYPE_SUBSECTION = "subsection";
private static final String ITEM_TYPE_FIELD = "field";
private static final String INDEXED_NAME_KEY = "name";
private static final String INDEXED_CATEGORY_KEY = "term_category";
private static final String INDEXED_PARENT_KEY = "is_a";
protected HPOScriptService ontologyService;
private final FormData data;
protected final String[] fieldNames;
protected final String propertyName;
private Map<String, Map<String, String>> metadata;
private List<FormSection> sections = new LinkedList<FormSection>();
PropertyDisplayer(Collection<Map<String, ? >> template, FormData data, HPOScriptService ontologyService)
{
this.data = data;
this.ontologyService = ontologyService;
this.fieldNames = new String[2];
this.fieldNames[0] = data.getPositiveFieldName();
this.fieldNames[1] = data.getNegativeFieldName();
this.propertyName = data.getPositivePropertyName();
this.prepareMetaData();
List<String> customYesSelected = new LinkedList<String>();
if (data.getSelectedValues() != null) {
customYesSelected.addAll(data.getSelectedValues());
}
List<String> customNoSelected = new LinkedList<String>();
if (data.getNegativeFieldName() != null && data.getSelectedNegativeValues() != null) {
customNoSelected.addAll(data.getSelectedNegativeValues());
}
for (Map<String, ? > sectionTemplate : template) {
if (isSection(sectionTemplate)) {
this.sections.add(generateSection(sectionTemplate, customYesSelected, customNoSelected));
}
}
Map<String, List<String>> yCustomCategories = new HashMap<String, List<String>>();
Map<String, List<String>> nCustomCategories = new HashMap<String, List<String>>();
for (String value : customYesSelected) {
List<String> categories = new LinkedList<String>();
categories.addAll(this.getCategoriesFromOntology(value));
categories.addAll(this.getCategoriesFromCustomMapping(value, data.getCustomCategories()));
+ if (categories.isEmpty()) {
+ categories.add("HP:0000118");
+ }
yCustomCategories.put(value, categories);
}
for (String value : customNoSelected) {
List<String> categories = new LinkedList<String>();
categories.addAll(this.getCategoriesFromOntology(value));
categories.addAll(this.getCategoriesFromCustomMapping(value, data.getCustomNegativeCategories()));
+ if (categories.isEmpty()) {
+ categories.add("HP:0000118");
+ }
nCustomCategories.put(value, categories);
}
for (FormSection section : this.sections) {
List<String> yCustomFieldIDs = this.assignCustomFields(section, yCustomCategories);
List<String> nCustomFieldIDs = this.assignCustomFields(section, nCustomCategories);
for (String val : yCustomFieldIDs) {
section.addCustomElement(this.generateField(val, null, false, true, false));
yCustomCategories.remove(val);
}
for (String val : nCustomFieldIDs) {
section.addCustomElement(this.generateField(val, null, false, false, true));
nCustomCategories.remove(val);
}
}
}
public String display()
{
StringBuilder str = new StringBuilder();
for (FormSection section : this.sections) {
str.append(section.display(this.data.getMode(), this.fieldNames));
}
return str.toString();
}
private boolean isSection(Map<String, ? > item)
{
return ITEM_TYPE_SECTION.equals(item.get(TYPE_KEY)) && Collection.class.isInstance(item.get(CATEGORIES_KEY))
&& String.class.isInstance(item.get(TITLE_KEY)) && Collection.class.isInstance(item.get(DATA_KEY));
}
private boolean isSubsection(Map<String, ? > item)
{
return ITEM_TYPE_SUBSECTION.equals(item.get(TYPE_KEY)) && String.class.isInstance(item.get(TITLE_KEY))
&& Collection.class.isInstance(item.get(DATA_KEY));
}
private boolean isField(Map<String, ? > item)
{
return item.get(TYPE_KEY) == null || ITEM_TYPE_FIELD.equals(item.get(TYPE_KEY)) && item.get(ID_KEY) != null
&& String.class.isAssignableFrom(item.get(ID_KEY).getClass());
}
@SuppressWarnings("unchecked")
private FormSection generateSection(Map<String, ? > sectionTemplate, List<String> customYesSelected,
List<String> customNoSelected)
{
String title = (String) sectionTemplate.get(TITLE_KEY);
Collection<String> categories = (Collection<String>) sectionTemplate.get(CATEGORIES_KEY);
FormSection section = new FormSection(title, this.propertyName, categories);
generateData(section, sectionTemplate, customYesSelected, customNoSelected);
return section;
}
private FormElement generateSubsection(Map<String, ? > subsectionTemplate, List<String> customYesSelected,
List<String> customNoSelected)
{
String title = (String) subsectionTemplate.get(TITLE_KEY);
String type = (String) subsectionTemplate.get(GROUP_TYPE_KEY);
if (type == null) {
type = "";
}
FormGroup subsection = new FormSubsection(title, type);
generateData(subsection, subsectionTemplate, customYesSelected, customNoSelected);
return subsection;
}
@SuppressWarnings("unchecked")
private void generateData(FormGroup formGroup, Map<String, ? > groupTemplate, List<String> customYesSelected,
List<String> customNoSelected)
{
Collection<Map<String, ? >> data = (Collection<Map<String, ? >>) groupTemplate.get(DATA_KEY);
for (Map<String, ? > item : data) {
if (isSubsection(item)) {
formGroup.addElement(generateSubsection(item, customYesSelected, customNoSelected));
} else if (isField(item)) {
formGroup.addElement(generateField(item, customYesSelected, customNoSelected));
}
}
}
private FormElement generateField(Map<String, ? > fieldTemplate, List<String> customYesSelected,
List<String> customNoSelected)
{
String id = (String) fieldTemplate.get(ID_KEY);
boolean yesSelected = customYesSelected.remove(id);
boolean noSelected = customNoSelected.remove(id);
return this.generateField(id, (String) fieldTemplate.get(TITLE_KEY), yesSelected, noSelected);
}
private FormElement generateField(String id, String title, boolean expandable, boolean yesSelected,
boolean noSelected)
{
String hint = getLabelFromOntology(id);
if (id.equals(hint) && title != null) {
hint = title;
}
String metadata = "";
Map<String, String> metadataValues = this.metadata.get(id);
if (metadataValues != null) {
metadata =
metadataValues.get(noSelected ? this.data.getNegativePropertyName() : this.data
.getPositivePropertyName());
}
return new FormField(id, StringUtils.defaultIfEmpty(title, hint), hint, StringUtils.defaultString(metadata),
expandable, yesSelected, noSelected);
}
private FormElement generateField(String id, String title, boolean yesSelected, boolean noSelected)
{
return generateField(id, title, hasDescendantsInOntology(id), yesSelected, noSelected);
}
private List<String> assignCustomFields(FormSection section, Map<String, List<String>> customCategories)
{
List<String> assigned = new LinkedList<String>();
if (section.getCategories().size() == 0) {
assigned.addAll(customCategories.keySet());
} else {
for (String value : customCategories.keySet()) {
List<String> categories = customCategories.get(value);
for (String c : categories) {
if (section.getCategories().contains(c)) {
assigned.add(value);
break;
}
}
}
}
return assigned;
}
private String getLabelFromOntology(String id)
{
SolrDocument phObj = this.ontologyService.get(id);
if (phObj != null) {
return (String) phObj.get(INDEXED_NAME_KEY);
}
return id;
}
private boolean hasDescendantsInOntology(String id)
{
Map<String, String> params = new HashMap<String, String>();
params.put(INDEXED_PARENT_KEY, id);
return (this.ontologyService.get(params) != null);
}
@SuppressWarnings("unchecked")
private List<String> getCategoriesFromOntology(String value)
{
SolrDocument termObj = this.ontologyService.get(value);
if (termObj != null && termObj.get(INDEXED_CATEGORY_KEY) != null
&& List.class.isAssignableFrom(termObj.get(INDEXED_CATEGORY_KEY).getClass())) {
return (List<String>) termObj.get(INDEXED_CATEGORY_KEY);
}
return new LinkedList<String>();
}
private List<String> getCategoriesFromCustomMapping(String value, Map<String, List<String>> customCategories)
{
for (Map.Entry<String, List<String>> category : customCategories.entrySet()) {
if (StringUtils.equals(value, category.getKey()) && category.getValue() != null) {
return category.getValue();
}
}
return new LinkedList<String>();
}
private void prepareMetaData()
{
this.metadata = new HashMap<String, Map<String, String>>();
for (com.xpn.xwiki.api.Object o : this.data.getDocument().getObjects("PhenoTips.PhenotypeMetaClass")) {
String name = "";
String category = "";
StringBuilder value = new StringBuilder();
for (String propname : o.getxWikiClass().getEnabledPropertyNames()) {
Property property = o.getProperty(propname);
Object propvalue = property.getValue();
if (propvalue == null) {
continue;
}
if (StringUtils.equals("target_property_name", propname)) {
category = propvalue.toString();
} else if (StringUtils.equals("target_property_value", propname)) {
name = propvalue.toString();
} else {
value.append(o.get(propname).toString().replaceAll("\\{\\{/?html[^}]*+}}", "").replaceAll(
"<(/?)p>", "<$1dd>"));
}
}
if (StringUtils.isNotBlank(name) && value.length() > 0) {
Map<String, String> subvalues = this.metadata.get(name);
if (subvalues == null) {
subvalues = new HashMap<String, String>();
this.metadata.put(name, subvalues);
}
subvalues.put(category, "<div class='phenotype-details'><dl>" + value.toString() + "</dl></div>");
}
}
}
}
| false | true | PropertyDisplayer(Collection<Map<String, ? >> template, FormData data, HPOScriptService ontologyService)
{
this.data = data;
this.ontologyService = ontologyService;
this.fieldNames = new String[2];
this.fieldNames[0] = data.getPositiveFieldName();
this.fieldNames[1] = data.getNegativeFieldName();
this.propertyName = data.getPositivePropertyName();
this.prepareMetaData();
List<String> customYesSelected = new LinkedList<String>();
if (data.getSelectedValues() != null) {
customYesSelected.addAll(data.getSelectedValues());
}
List<String> customNoSelected = new LinkedList<String>();
if (data.getNegativeFieldName() != null && data.getSelectedNegativeValues() != null) {
customNoSelected.addAll(data.getSelectedNegativeValues());
}
for (Map<String, ? > sectionTemplate : template) {
if (isSection(sectionTemplate)) {
this.sections.add(generateSection(sectionTemplate, customYesSelected, customNoSelected));
}
}
Map<String, List<String>> yCustomCategories = new HashMap<String, List<String>>();
Map<String, List<String>> nCustomCategories = new HashMap<String, List<String>>();
for (String value : customYesSelected) {
List<String> categories = new LinkedList<String>();
categories.addAll(this.getCategoriesFromOntology(value));
categories.addAll(this.getCategoriesFromCustomMapping(value, data.getCustomCategories()));
yCustomCategories.put(value, categories);
}
for (String value : customNoSelected) {
List<String> categories = new LinkedList<String>();
categories.addAll(this.getCategoriesFromOntology(value));
categories.addAll(this.getCategoriesFromCustomMapping(value, data.getCustomNegativeCategories()));
nCustomCategories.put(value, categories);
}
for (FormSection section : this.sections) {
List<String> yCustomFieldIDs = this.assignCustomFields(section, yCustomCategories);
List<String> nCustomFieldIDs = this.assignCustomFields(section, nCustomCategories);
for (String val : yCustomFieldIDs) {
section.addCustomElement(this.generateField(val, null, false, true, false));
yCustomCategories.remove(val);
}
for (String val : nCustomFieldIDs) {
section.addCustomElement(this.generateField(val, null, false, false, true));
nCustomCategories.remove(val);
}
}
}
| PropertyDisplayer(Collection<Map<String, ? >> template, FormData data, HPOScriptService ontologyService)
{
this.data = data;
this.ontologyService = ontologyService;
this.fieldNames = new String[2];
this.fieldNames[0] = data.getPositiveFieldName();
this.fieldNames[1] = data.getNegativeFieldName();
this.propertyName = data.getPositivePropertyName();
this.prepareMetaData();
List<String> customYesSelected = new LinkedList<String>();
if (data.getSelectedValues() != null) {
customYesSelected.addAll(data.getSelectedValues());
}
List<String> customNoSelected = new LinkedList<String>();
if (data.getNegativeFieldName() != null && data.getSelectedNegativeValues() != null) {
customNoSelected.addAll(data.getSelectedNegativeValues());
}
for (Map<String, ? > sectionTemplate : template) {
if (isSection(sectionTemplate)) {
this.sections.add(generateSection(sectionTemplate, customYesSelected, customNoSelected));
}
}
Map<String, List<String>> yCustomCategories = new HashMap<String, List<String>>();
Map<String, List<String>> nCustomCategories = new HashMap<String, List<String>>();
for (String value : customYesSelected) {
List<String> categories = new LinkedList<String>();
categories.addAll(this.getCategoriesFromOntology(value));
categories.addAll(this.getCategoriesFromCustomMapping(value, data.getCustomCategories()));
if (categories.isEmpty()) {
categories.add("HP:0000118");
}
yCustomCategories.put(value, categories);
}
for (String value : customNoSelected) {
List<String> categories = new LinkedList<String>();
categories.addAll(this.getCategoriesFromOntology(value));
categories.addAll(this.getCategoriesFromCustomMapping(value, data.getCustomNegativeCategories()));
if (categories.isEmpty()) {
categories.add("HP:0000118");
}
nCustomCategories.put(value, categories);
}
for (FormSection section : this.sections) {
List<String> yCustomFieldIDs = this.assignCustomFields(section, yCustomCategories);
List<String> nCustomFieldIDs = this.assignCustomFields(section, nCustomCategories);
for (String val : yCustomFieldIDs) {
section.addCustomElement(this.generateField(val, null, false, true, false));
yCustomCategories.remove(val);
}
for (String val : nCustomFieldIDs) {
section.addCustomElement(this.generateField(val, null, false, false, true));
nCustomCategories.remove(val);
}
}
}
|
diff --git a/src/common/dries007/SimpleCore/Commands/CommandSetSpawn.java b/src/common/dries007/SimpleCore/Commands/CommandSetSpawn.java
index 307c6a2..efee5bb 100644
--- a/src/common/dries007/SimpleCore/Commands/CommandSetSpawn.java
+++ b/src/common/dries007/SimpleCore/Commands/CommandSetSpawn.java
@@ -1,87 +1,87 @@
package dries007.SimpleCore.Commands;
import java.util.Iterator;
import java.util.List;
import dries007.SimpleCore.*;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.*;
public class CommandSetSpawn extends CommandBase
{
public String getCommandName()
{
return "setspawn";
}
public String getCommandUsage(ICommandSender par1ICommandSender)
{
return "/" + getCommandName() + " [rank] [nameOfSpawn]";
}
public List getCommandAliases()
{
return null;
}
public void processCommand(ICommandSender sender, String[] args)
{
EntityPlayer player = ((EntityPlayer)sender);
if (args.length==0)
{
Double X = player.posX;
Double Y = player.posY;
Double Z = player.posZ;
player.worldObj.getWorldInfo().setSpawnPosition(X.intValue(),Y.intValue(),Z.intValue());
player.sendChatToPlayer("Serverspawn set. All ranks with no seperate spawn will spawn here.");
}
else
{
String rank = getRank(args[0]);
NBTTagCompound rankdata = SimpleCore.rankData.getCompoundTag(rank);
NBTTagCompound spawn = new NBTTagCompound();
try {spawn.setString("name", args[1]);} catch (Exception e) {spawn.setString("name", "spawn");}
spawn.setDouble("X", player.posX);
- spawn.setDouble("Y", player.posY + 5D);
+ spawn.setDouble("Y", player.posY);
spawn.setDouble("Z", player.posZ);
spawn.setFloat("yaw", player.rotationYaw);
spawn.setFloat("pitch", player.rotationPitch);
spawn.setInteger("dim", player.dimension);
rankdata.setCompoundTag("Spawn", spawn );
SimpleCore.rankData.setCompoundTag(rank, rankdata);
player.sendChatToPlayer("Spawn for rank " + rank + " set. Name:" + spawn.getString("name") + ".");
}
}
public boolean canCommandSenderUseCommand(ICommandSender sender)
{
return Permissions.hasPermission(sender.getCommandSenderName(), "SC.admin");
}
/**
* Adds the strings available in this command to the given list of tab completion options.
*/
public List addTabCompletionOptions(ICommandSender sender, String[] args)
{
if(args.length == 1)
{
String msg = "";
for(String st : Permissions.getPermissions()) msg = msg + st + ", ";
sender.sendChatToPlayer("List of permissions: " + msg);
return getListOfStringsMatchingLastWord(args, Permissions.getPermissions());
}
return null;
}
protected String getRank(String input)
{
Iterator ranks = SimpleCore.rankData.getTags().iterator();
while (ranks.hasNext())
{
NBTTagCompound rank = (NBTTagCompound) ranks.next();
if (rank.getName().equalsIgnoreCase(input)) return rank.getName();
}
throw new WrongUsageException("Rank '" + input + "' not found!", new Object[0]);
}
}
| true | true | public void processCommand(ICommandSender sender, String[] args)
{
EntityPlayer player = ((EntityPlayer)sender);
if (args.length==0)
{
Double X = player.posX;
Double Y = player.posY;
Double Z = player.posZ;
player.worldObj.getWorldInfo().setSpawnPosition(X.intValue(),Y.intValue(),Z.intValue());
player.sendChatToPlayer("Serverspawn set. All ranks with no seperate spawn will spawn here.");
}
else
{
String rank = getRank(args[0]);
NBTTagCompound rankdata = SimpleCore.rankData.getCompoundTag(rank);
NBTTagCompound spawn = new NBTTagCompound();
try {spawn.setString("name", args[1]);} catch (Exception e) {spawn.setString("name", "spawn");}
spawn.setDouble("X", player.posX);
spawn.setDouble("Y", player.posY + 5D);
spawn.setDouble("Z", player.posZ);
spawn.setFloat("yaw", player.rotationYaw);
spawn.setFloat("pitch", player.rotationPitch);
spawn.setInteger("dim", player.dimension);
rankdata.setCompoundTag("Spawn", spawn );
SimpleCore.rankData.setCompoundTag(rank, rankdata);
player.sendChatToPlayer("Spawn for rank " + rank + " set. Name:" + spawn.getString("name") + ".");
}
}
| public void processCommand(ICommandSender sender, String[] args)
{
EntityPlayer player = ((EntityPlayer)sender);
if (args.length==0)
{
Double X = player.posX;
Double Y = player.posY;
Double Z = player.posZ;
player.worldObj.getWorldInfo().setSpawnPosition(X.intValue(),Y.intValue(),Z.intValue());
player.sendChatToPlayer("Serverspawn set. All ranks with no seperate spawn will spawn here.");
}
else
{
String rank = getRank(args[0]);
NBTTagCompound rankdata = SimpleCore.rankData.getCompoundTag(rank);
NBTTagCompound spawn = new NBTTagCompound();
try {spawn.setString("name", args[1]);} catch (Exception e) {spawn.setString("name", "spawn");}
spawn.setDouble("X", player.posX);
spawn.setDouble("Y", player.posY);
spawn.setDouble("Z", player.posZ);
spawn.setFloat("yaw", player.rotationYaw);
spawn.setFloat("pitch", player.rotationPitch);
spawn.setInteger("dim", player.dimension);
rankdata.setCompoundTag("Spawn", spawn );
SimpleCore.rankData.setCompoundTag(rank, rankdata);
player.sendChatToPlayer("Spawn for rank " + rank + " set. Name:" + spawn.getString("name") + ".");
}
}
|
diff --git a/core/src/classes/org/jdesktop/wonderland/client/jme/VMeter.java b/core/src/classes/org/jdesktop/wonderland/client/jme/VMeter.java
index d6f9284ce..c758d757a 100644
--- a/core/src/classes/org/jdesktop/wonderland/client/jme/VMeter.java
+++ b/core/src/classes/org/jdesktop/wonderland/client/jme/VMeter.java
@@ -1,206 +1,206 @@
/*
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.client.jme;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.text.DecimalFormat;
import javax.swing.JPanel;
/**
*
* @author nsimpson
*/
public class VMeter extends JPanel {
private String label;
private double value;
private double warning;
private double max;
private int leftIndent = 2;
private int rightIndent = 2;
private int labelGap = 2;
private int topIndent = 5;
private int bottomIndent = 5;
private int barHeight = 0;
private int barWidth = 0;
private int barGap = 2;
private int tickLength = 5;
private int fontSize = 12;
private boolean showValue = true;
private boolean showTicks = true;
private String fontName = "Arial";
private RoundRectangle2D.Double bar;
private Color normalStartColor = new Color(89, 149, 37); // green
private Color normalEndColor = new Color(219, 250, 203);
private Color warningStartColor = new Color(255, 0, 0); // red
private Color warningEndColor = new Color(255, 84, 84);
private DecimalFormat floatFormat = new DecimalFormat("##0.0");
private Font font;
private FontMetrics fontMetrics;
private int labelWidth = 0;
private int labelHeight = 0;
private int valueWidth = 0;
private int valueHeight = 0;
private GradientPaint paint;
public VMeter(String label) {
super();
this.label = label;
bar = new RoundRectangle2D.Double();
font = new Font(fontName, Font.BOLD, fontSize);
}
public void setMaxValue(double max) {
this.max = max;
}
public void setValue(double value) {
this.value = value;
if (value > max) {
// value exceeded specified max, raise the max value to
// accommodate the overage
max = Math.ceil(value);
}
repaint();
}
public void setShowValue(boolean showValue) {
this.showValue = showValue;
}
public boolean getShowValue() {
return showValue;
}
public void setShowTicks(boolean showTicks) {
this.showTicks = showTicks;
}
public boolean getShowTicks() {
return showTicks;
}
public void setWarningValue(double warning) {
this.warning = warning;
}
@Override
public void paintComponent(Graphics g) {
//Calendar then = Calendar.getInstance();
Color startColor = warningEndColor; //((warning > 0) && (value >= warning)) ? warningStartColor : normalStartColor;
Color endColor = normalStartColor; //((warning > 0) && (value >= warning)) ? warningEndColor : normalEndColor;
String valueString = floatFormat.format(value);
Graphics2D g2 = (Graphics2D) g;
if (fontMetrics == null) {
fontMetrics = g.getFontMetrics(font);
}
// configure meter to show or hide current numeric value
if (showValue) {
valueWidth = fontMetrics.stringWidth(valueString);
valueHeight = fontMetrics.getHeight();
} else {
valueWidth = 0;
valueHeight = 0;
labelGap = 0;
}
// configure meter to show or hide the meter label (at bottom of meter)
- if (!label.isEmpty()) {
+ if (label.length() > 0) {
labelWidth = fontMetrics.stringWidth(label);
labelHeight = fontMetrics.getHeight();
} else {
labelWidth = 0;
labelHeight = 0;
labelGap = 0;
}
// calculate space available for meter
int w = this.getWidth();
int h = this.getHeight();
int availableHeight = h - topIndent - bottomIndent - labelHeight - valueHeight - 2 * labelGap;
int availableWidth = w - leftIndent - rightIndent;
int y;
// paint the background
g2.setColor(this.getBackground());
g2.fillRect(0, 0, w, h);
y = h - bottomIndent - labelHeight - labelGap;
if (showTicks) {
// paint the tick marks
g2.setColor(Color.LIGHT_GRAY);
double tickSpace = (double) availableHeight / 10d;
double x = w - rightIndent - tickLength;
for (int tick = 0;
tick <=
10; tick++) {
g2.drawLine((int) x, y, (int) (x + tickLength), y);
y -= tickSpace;
}
}
y = h;
// determine bar dimensions
barHeight = (int) ((value / max) * availableHeight);
barWidth = availableWidth - tickLength;
// set the bar's clip rect
bar.setFrame(leftIndent + 5, h - bottomIndent - labelHeight - labelGap - barHeight,
barWidth - 5, barHeight);
g2.setClip(bar);
// paint gradient clipped by the bar's clip rect
paint = new GradientPaint(leftIndent, topIndent + valueHeight + labelGap, startColor,
barWidth, availableHeight, endColor);
g2.setPaint(paint);
g2.fillRect(leftIndent, topIndent + valueHeight + labelGap, availableWidth, availableHeight);
// reset clip rect
g2.setClip(0, 0, w, h);
- if (!label.isEmpty() || showValue) {
+ if ((label.length() > 0) || showValue) {
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(this.getForeground());
g2.setFont(font);
}
- if (!label.isEmpty()) {
+ if (label.length() > 0) {
// draw the label
g2.drawString(label, (w - labelWidth) / 2, h - bottomIndent);
}
if (showValue) {
// draw the value
g2.drawString(valueString, (w - valueWidth) / 2, topIndent + valueHeight);
}
//Calendar now = Calendar.getInstance();
//System.err.println("cost: " + (now.getTimeInMillis() - then.getTimeInMillis()));
}
}
| false | true | public void paintComponent(Graphics g) {
//Calendar then = Calendar.getInstance();
Color startColor = warningEndColor; //((warning > 0) && (value >= warning)) ? warningStartColor : normalStartColor;
Color endColor = normalStartColor; //((warning > 0) && (value >= warning)) ? warningEndColor : normalEndColor;
String valueString = floatFormat.format(value);
Graphics2D g2 = (Graphics2D) g;
if (fontMetrics == null) {
fontMetrics = g.getFontMetrics(font);
}
// configure meter to show or hide current numeric value
if (showValue) {
valueWidth = fontMetrics.stringWidth(valueString);
valueHeight = fontMetrics.getHeight();
} else {
valueWidth = 0;
valueHeight = 0;
labelGap = 0;
}
// configure meter to show or hide the meter label (at bottom of meter)
if (!label.isEmpty()) {
labelWidth = fontMetrics.stringWidth(label);
labelHeight = fontMetrics.getHeight();
} else {
labelWidth = 0;
labelHeight = 0;
labelGap = 0;
}
// calculate space available for meter
int w = this.getWidth();
int h = this.getHeight();
int availableHeight = h - topIndent - bottomIndent - labelHeight - valueHeight - 2 * labelGap;
int availableWidth = w - leftIndent - rightIndent;
int y;
// paint the background
g2.setColor(this.getBackground());
g2.fillRect(0, 0, w, h);
y = h - bottomIndent - labelHeight - labelGap;
if (showTicks) {
// paint the tick marks
g2.setColor(Color.LIGHT_GRAY);
double tickSpace = (double) availableHeight / 10d;
double x = w - rightIndent - tickLength;
for (int tick = 0;
tick <=
10; tick++) {
g2.drawLine((int) x, y, (int) (x + tickLength), y);
y -= tickSpace;
}
}
y = h;
// determine bar dimensions
barHeight = (int) ((value / max) * availableHeight);
barWidth = availableWidth - tickLength;
// set the bar's clip rect
bar.setFrame(leftIndent + 5, h - bottomIndent - labelHeight - labelGap - barHeight,
barWidth - 5, barHeight);
g2.setClip(bar);
// paint gradient clipped by the bar's clip rect
paint = new GradientPaint(leftIndent, topIndent + valueHeight + labelGap, startColor,
barWidth, availableHeight, endColor);
g2.setPaint(paint);
g2.fillRect(leftIndent, topIndent + valueHeight + labelGap, availableWidth, availableHeight);
// reset clip rect
g2.setClip(0, 0, w, h);
if (!label.isEmpty() || showValue) {
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(this.getForeground());
g2.setFont(font);
}
if (!label.isEmpty()) {
// draw the label
g2.drawString(label, (w - labelWidth) / 2, h - bottomIndent);
}
if (showValue) {
// draw the value
g2.drawString(valueString, (w - valueWidth) / 2, topIndent + valueHeight);
}
//Calendar now = Calendar.getInstance();
//System.err.println("cost: " + (now.getTimeInMillis() - then.getTimeInMillis()));
}
| public void paintComponent(Graphics g) {
//Calendar then = Calendar.getInstance();
Color startColor = warningEndColor; //((warning > 0) && (value >= warning)) ? warningStartColor : normalStartColor;
Color endColor = normalStartColor; //((warning > 0) && (value >= warning)) ? warningEndColor : normalEndColor;
String valueString = floatFormat.format(value);
Graphics2D g2 = (Graphics2D) g;
if (fontMetrics == null) {
fontMetrics = g.getFontMetrics(font);
}
// configure meter to show or hide current numeric value
if (showValue) {
valueWidth = fontMetrics.stringWidth(valueString);
valueHeight = fontMetrics.getHeight();
} else {
valueWidth = 0;
valueHeight = 0;
labelGap = 0;
}
// configure meter to show or hide the meter label (at bottom of meter)
if (label.length() > 0) {
labelWidth = fontMetrics.stringWidth(label);
labelHeight = fontMetrics.getHeight();
} else {
labelWidth = 0;
labelHeight = 0;
labelGap = 0;
}
// calculate space available for meter
int w = this.getWidth();
int h = this.getHeight();
int availableHeight = h - topIndent - bottomIndent - labelHeight - valueHeight - 2 * labelGap;
int availableWidth = w - leftIndent - rightIndent;
int y;
// paint the background
g2.setColor(this.getBackground());
g2.fillRect(0, 0, w, h);
y = h - bottomIndent - labelHeight - labelGap;
if (showTicks) {
// paint the tick marks
g2.setColor(Color.LIGHT_GRAY);
double tickSpace = (double) availableHeight / 10d;
double x = w - rightIndent - tickLength;
for (int tick = 0;
tick <=
10; tick++) {
g2.drawLine((int) x, y, (int) (x + tickLength), y);
y -= tickSpace;
}
}
y = h;
// determine bar dimensions
barHeight = (int) ((value / max) * availableHeight);
barWidth = availableWidth - tickLength;
// set the bar's clip rect
bar.setFrame(leftIndent + 5, h - bottomIndent - labelHeight - labelGap - barHeight,
barWidth - 5, barHeight);
g2.setClip(bar);
// paint gradient clipped by the bar's clip rect
paint = new GradientPaint(leftIndent, topIndent + valueHeight + labelGap, startColor,
barWidth, availableHeight, endColor);
g2.setPaint(paint);
g2.fillRect(leftIndent, topIndent + valueHeight + labelGap, availableWidth, availableHeight);
// reset clip rect
g2.setClip(0, 0, w, h);
if ((label.length() > 0) || showValue) {
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setColor(this.getForeground());
g2.setFont(font);
}
if (label.length() > 0) {
// draw the label
g2.drawString(label, (w - labelWidth) / 2, h - bottomIndent);
}
if (showValue) {
// draw the value
g2.drawString(valueString, (w - valueWidth) / 2, topIndent + valueHeight);
}
//Calendar now = Calendar.getInstance();
//System.err.println("cost: " + (now.getTimeInMillis() - then.getTimeInMillis()));
}
|
diff --git a/lm/src/main/java/zemberek/lm/compression/MultiFileUncompressedLm.java b/lm/src/main/java/zemberek/lm/compression/MultiFileUncompressedLm.java
index fa189709..61da5a08 100644
--- a/lm/src/main/java/zemberek/lm/compression/MultiFileUncompressedLm.java
+++ b/lm/src/main/java/zemberek/lm/compression/MultiFileUncompressedLm.java
@@ -1,412 +1,413 @@
package zemberek.lm.compression;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;
import zemberek.core.SpaceTabTokenizer;
import zemberek.core.logging.Log;
import zemberek.core.quantization.DoubleLookup;
import zemberek.core.quantization.Quantizer;
import zemberek.core.quantization.QuantizerType;
import zemberek.lm.LmVocabulary;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
/**
* This is a multiple file representation of an uncompressed backoff language model.
* Files are:
* <p/>info
* <p/>int32 order
* <p/>int32 1 gram count
* <p/>int32 2 gram count
* <p/>...
* <p/>[n].gram
* <p/>int32 order
* <p/>int32 count
* <p/>int32... id[0,..,n]
* <p/>
* <p/>[n].prob
* <p/>int32 count
* <p/>float32 prob
* <p/>....
* <p/>
* <p/>[n].backoff
* <p/>int32 count
* <p/>float32 prob
* <p/>....
* <p/>
* <p/>vocab
* <p/>int32 count
* <p/>UTF-8... word0...n
*/
public class MultiFileUncompressedLm {
int[] counts;
int order;
File dir;
int[] probabilityRankCount;
int[] backoffRankCount;
public MultiFileUncompressedLm(File dir) throws IOException {
this.dir = dir;
DataInputStream dis = new DataInputStream(new FileInputStream(getFile("info")));
order = dis.readInt();
counts = new int[order + 1];
for (int i = 0; i < order; i++) {
counts[i + 1] = dis.readInt();
}
dis.close();
}
public int getRankSize(File f) throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(f));
int count = dis.readInt();
dis.close();
return count;
}
public int getRankBlockSize(File f) throws IOException {
DataInputStream dis = new DataInputStream(new FileInputStream(f));
dis.readInt();
int blockSize = dis.readInt();
dis.close();
return blockSize;
}
public File getGramFile(int n) {
return new File(dir, n + ".gram");
}
public File getProbFile(int n) {
return new File(dir, n + ".prob");
}
public File getProbRankFile(int n) {
return new File(dir, n + ".prob.rank");
}
public File getBackoffRankFile(int n) {
return new File(dir, n + ".backoff.rank");
}
public File getBackoffFile(int n) {
return new File(dir, n + ".backoff");
}
public File getProbabilityLookupFile(int n) {
return new File(dir, getProbFile(n).getName() + ".lookup");
}
public File getBackoffLookupFile(int n) {
return new File(dir, getBackoffFile(n).getName() + ".lookup");
}
public int getOrder() {
return order;
}
public int getCount(int n) {
return counts[n];
}
private File getFile(String name) {
return new File(dir, name);
}
public void generateRankFiles(int i, int bit, QuantizerType quantizerType) throws IOException {
if (bit > 24)
throw new IllegalArgumentException("Cannot generate rank file larger than 24 bits but it is:" + bit);
Log.info("Calculating probabilty rank values for :" + i + " Grams");
File probFile = getProbFile(i);
generateRankFile(bit, i, probFile, new File(dir, i + ".prob.rank"), quantizerType);
if (i < counts.length - 1) {
File backoffFile = getBackoffFile(i);
Log.info("Calculating back-off rank values for :" + i + " Grams");
generateRankFile(bit, i, backoffFile, new File(dir, i + ".backoff.rank"), quantizerType);
}
}
public void generateRankFiles(int bit, QuantizerType quantizerType) throws IOException {
if (bit > 24)
throw new IllegalArgumentException("Cannot generate rank file larger than 24 bits but it is:" + bit);
for (int i = 1; i < counts.length; i++) {
Log.info("Calculating probabilty lookup values for :" + i + " Grams");
File probFile = getProbFile(i);
generateRankFile(bit, i, probFile, new File(dir, i + ".prob.rank"), quantizerType);
if (i < counts.length - 1) {
File backoffFile = getBackoffFile(i);
Log.info("Calculating lookup values for " + i + " Grams");
generateRankFile(bit, i, backoffFile, new File(dir, i + ".backoff.rank"), quantizerType);
}
}
}
private void generateRankFile(int bit, int i, File probFile, File rankFile, QuantizerType quantizerType) throws IOException {
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(probFile)));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(rankFile)))) {
int count = dis.readInt();
Quantizer quantizer = BinaryFloatFileReader.getQuantizer(probFile, bit, quantizerType);
dos.writeInt(count);
Log.info("Writing Rank file for " + i + " grams");
int bytecount = (bit % 8 == 0 ? bit / 8 : bit / 8 + 1);
if (bytecount == 0)
bytecount = 1;
dos.writeInt(bytecount);
byte[] bytez = new byte[3];
for (int j = 0; j < count; j++) {
final int rank = quantizer.getQuantizationIndex(dis.readFloat());
switch (bytecount) {
case 1:
dos.write(rank & 0xff);
break;
case 2:
dos.writeShort(rank & 0xffff);
break;
case 3:
bytez[0] = (byte) ((rank >>> 16) & 0xff);
bytez[1] = (byte) ((rank >>> 8) & 0xff);
bytez[2] = (byte) (rank & 0xff);
dos.write(bytez);
break;
}
}
DoubleLookup lookup = quantizer.getDequantizer();
Log.info("Writing lookups for " + i + " grams. Size= " + lookup.getRange());
lookup.save(new File(dir, probFile.getName() + ".lookup"));
}
}
public static MultiFileUncompressedLm generate(File arpaFile, File dir, String encoding) throws IOException {
if (dir.exists() && !dir.isDirectory()) {
throw new IllegalArgumentException(dir + " is not a directory!");
}
if (!dir.exists() && !dir.mkdirs())
throw new IllegalArgumentException("Cannot create directory:" + dir);
long elapsedTime = Files.readLines(arpaFile, Charset.forName(encoding), new ArpaToBinaryConverter(dir));
Log.info("Multi file uncompressed binary model is generated in " + (double) elapsedTime / 1000d + " seconds");
return new MultiFileUncompressedLm(dir);
}
public File getVocabularyFile() {
return new File(dir, "vocab");
}
private static class ArpaToBinaryConverter implements LineProcessor<Long> {
public static final int DEFAULT_UNKNOWN_PROBABILTY = -20;
int ngramCounter = 0;
int _n;
enum State {
BEGIN, UNIGRAMS, NGRAMS, VOCABULARY
}
State state = State.BEGIN;
List<Integer> ngramCounts = new ArrayList<>();
boolean started = false;
File dir;
DataOutputStream gramOs;
DataOutputStream probOs;
DataOutputStream backoffOs;
int order;
long start;
SpaceTabTokenizer tokenizer = new SpaceTabTokenizer();
LmVocabulary.Builder vocabularyBuilder = new LmVocabulary.Builder();
// This will be generated after reading unigrams.
LmVocabulary lmVocabulary;
ArpaToBinaryConverter(File dir) throws FileNotFoundException {
this.dir = dir;
start = System.currentTimeMillis();
}
private void newGramStream(int n) throws IOException {
if (gramOs != null)
gramOs.close();
gramOs = getDos(n + ".gram");
gramOs.writeInt(n);
gramOs.writeInt(ngramCounts.get(n - 1));
}
private void newProbStream(int n) throws IOException {
if (probOs != null)
probOs.close();
probOs = getDos(n + ".prob");
probOs.writeInt(ngramCounts.get(n - 1));
}
private void newBackoffStream(int n) throws IOException {
if (backoffOs != null)
backoffOs.close();
backoffOs = getDos(n + ".backoff");
backoffOs.writeInt(ngramCounts.get(n - 1));
}
public boolean processLine(String s) throws IOException {
String clean = s.trim();
switch (state) {
// read n value and ngram counts.
case BEGIN:
if (clean.startsWith("\\data\\"))
started = true;
else if (started && clean.startsWith("ngram")) {
started = true;
int count = 0, i = 0;
for (String str : Splitter.on("=").trimResults().split(clean)) {
if (i++ == 0)
continue;
count = Integer.parseInt(str);
}
ngramCounts.add(count);
} else if (started) {
state = State.UNIGRAMS;
newGramStream(1);
newProbStream(1);
newBackoffStream(1);
- Log.info("Gram counts: " + Joiner.on(" ").join(ngramCounts));
+ Log.info("Gram counts in Arpa file: " + Joiner.on(" ").join(ngramCounts));
Log.info("Writing unigrams.");
_n++;
}
break;
// read ngrams. if unigram values, we store the strings and related indexes.
case UNIGRAMS:
if (clean.length() == 0 || clean.startsWith("\\")) {
break;
}
String[] tokens = tokenizer.split(clean);
// parse probabilty
float logProbability = Float.parseFloat(tokens[0]);
String word = tokens[1];
float logBackoff = 0;
if (tokens.length == 3)
logBackoff = Float.parseFloat(tokens[_n + 1]);
// write unigram id, log-probability and log-backoff value.
int wordIndex = vocabularyBuilder.add(word);
gramOs.writeInt(wordIndex);
probOs.writeFloat(logProbability);
// if there are only ngrams, do not write backoff value.
if (ngramCounts.size() > 1)
backoffOs.writeFloat(logBackoff);
ngramCounter++;
if (ngramCounter == ngramCounts.get(0)) {
handleSpecialToken(LmVocabulary.SENTENCE_START);
handleSpecialToken(LmVocabulary.SENTENCE_END);
handleSpecialToken(LmVocabulary.UNKNOWN_WORD);
lmVocabulary = vocabularyBuilder.generate();
+ ngramCounts.set(0, lmVocabulary.size());
// we write info file after reading unigrams because we may add special tokens to unigrams
// so count information may have been changed.
order = ngramCounts.size();
try (DataOutputStream infos = getDos("info")) {
infos.writeInt(order);
for (Integer ngramCount : ngramCounts) {
infos.writeInt(ngramCount);
}
}
ngramCounter = 0;
state = State.NGRAMS;
_n++;
// if there is only unigrams in the arpa file, exit
if (ngramCounts.size() == 1) {
state = State.VOCABULARY;
} else {
newGramStream(2);
newProbStream(2);
if (order > 2)
newBackoffStream(2);
Log.info("Writing 2-grams.");
}
}
break;
case NGRAMS:
if (clean.length() == 0 || clean.startsWith("\\")) {
break;
}
tokens = tokenizer.split(clean);
logProbability = Float.parseFloat(tokens[0]);
for (int i = 0; i < _n; i++) {
int id = lmVocabulary.indexOf(tokens[i + 1]);
gramOs.writeInt(id);
}
// probabilities
probOs.writeFloat(logProbability);
if (_n < ngramCounts.size()) {
logBackoff = 0;
if (tokens.length == _n + 2)
logBackoff = Float.parseFloat(tokens[_n + 1]);
backoffOs.writeFloat(logBackoff);
}
if (ngramCounter > 0 && ngramCounter % 500000 == 0)
Log.info(ngramCounter + " grams are written so far.");
ngramCounter++;
if (ngramCounter == ngramCounts.get(_n - 1)) {
ngramCounter = 0;
// if there is no more ngrams, exit
if (ngramCounts.size() == _n) {
state = State.VOCABULARY;
} else {
_n++;
newGramStream(_n);
newProbStream(_n);
if (order > _n) {
newBackoffStream(_n);
}
Log.info("Writing " + _n + "-grams.");
}
}
break;
case VOCABULARY:
Closeables.close(gramOs, true);
Closeables.close(probOs, true);
Closeables.close(backoffOs, true);
Log.info("Writing model vocabulary.");
lmVocabulary.saveBinary(new File(dir, "vocab"));
return false; // we are done.
}
return true;
}
// adds special token with default probability.
private void handleSpecialToken(String word) throws IOException {
if (vocabularyBuilder.indexOf(word) == -1) {
Log.warn("Special token " + word +
" does not exist in model. It is added with default unknown probability: " +
DEFAULT_UNKNOWN_PROBABILTY);
int index = vocabularyBuilder.add(word);
gramOs.writeInt(index);
probOs.writeFloat(DEFAULT_UNKNOWN_PROBABILTY);
if (ngramCounts.size() > 1)
backoffOs.writeFloat(0);
}
}
private DataOutputStream getDos(String name) throws FileNotFoundException {
return new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(dir, name)), 100000));
}
public Long getResult() {
// just return the time..
return System.currentTimeMillis() - start;
}
}
}
| false | true | public boolean processLine(String s) throws IOException {
String clean = s.trim();
switch (state) {
// read n value and ngram counts.
case BEGIN:
if (clean.startsWith("\\data\\"))
started = true;
else if (started && clean.startsWith("ngram")) {
started = true;
int count = 0, i = 0;
for (String str : Splitter.on("=").trimResults().split(clean)) {
if (i++ == 0)
continue;
count = Integer.parseInt(str);
}
ngramCounts.add(count);
} else if (started) {
state = State.UNIGRAMS;
newGramStream(1);
newProbStream(1);
newBackoffStream(1);
Log.info("Gram counts: " + Joiner.on(" ").join(ngramCounts));
Log.info("Writing unigrams.");
_n++;
}
break;
// read ngrams. if unigram values, we store the strings and related indexes.
case UNIGRAMS:
if (clean.length() == 0 || clean.startsWith("\\")) {
break;
}
String[] tokens = tokenizer.split(clean);
// parse probabilty
float logProbability = Float.parseFloat(tokens[0]);
String word = tokens[1];
float logBackoff = 0;
if (tokens.length == 3)
logBackoff = Float.parseFloat(tokens[_n + 1]);
// write unigram id, log-probability and log-backoff value.
int wordIndex = vocabularyBuilder.add(word);
gramOs.writeInt(wordIndex);
probOs.writeFloat(logProbability);
// if there are only ngrams, do not write backoff value.
if (ngramCounts.size() > 1)
backoffOs.writeFloat(logBackoff);
ngramCounter++;
if (ngramCounter == ngramCounts.get(0)) {
handleSpecialToken(LmVocabulary.SENTENCE_START);
handleSpecialToken(LmVocabulary.SENTENCE_END);
handleSpecialToken(LmVocabulary.UNKNOWN_WORD);
lmVocabulary = vocabularyBuilder.generate();
// we write info file after reading unigrams because we may add special tokens to unigrams
// so count information may have been changed.
order = ngramCounts.size();
try (DataOutputStream infos = getDos("info")) {
infos.writeInt(order);
for (Integer ngramCount : ngramCounts) {
infos.writeInt(ngramCount);
}
}
ngramCounter = 0;
state = State.NGRAMS;
_n++;
// if there is only unigrams in the arpa file, exit
if (ngramCounts.size() == 1) {
state = State.VOCABULARY;
} else {
newGramStream(2);
newProbStream(2);
if (order > 2)
newBackoffStream(2);
Log.info("Writing 2-grams.");
}
}
break;
case NGRAMS:
if (clean.length() == 0 || clean.startsWith("\\")) {
break;
}
tokens = tokenizer.split(clean);
logProbability = Float.parseFloat(tokens[0]);
for (int i = 0; i < _n; i++) {
int id = lmVocabulary.indexOf(tokens[i + 1]);
gramOs.writeInt(id);
}
// probabilities
probOs.writeFloat(logProbability);
if (_n < ngramCounts.size()) {
logBackoff = 0;
if (tokens.length == _n + 2)
logBackoff = Float.parseFloat(tokens[_n + 1]);
backoffOs.writeFloat(logBackoff);
}
if (ngramCounter > 0 && ngramCounter % 500000 == 0)
Log.info(ngramCounter + " grams are written so far.");
ngramCounter++;
if (ngramCounter == ngramCounts.get(_n - 1)) {
ngramCounter = 0;
// if there is no more ngrams, exit
if (ngramCounts.size() == _n) {
state = State.VOCABULARY;
} else {
_n++;
newGramStream(_n);
newProbStream(_n);
if (order > _n) {
newBackoffStream(_n);
}
Log.info("Writing " + _n + "-grams.");
}
}
break;
case VOCABULARY:
Closeables.close(gramOs, true);
Closeables.close(probOs, true);
Closeables.close(backoffOs, true);
Log.info("Writing model vocabulary.");
lmVocabulary.saveBinary(new File(dir, "vocab"));
return false; // we are done.
}
return true;
}
| public boolean processLine(String s) throws IOException {
String clean = s.trim();
switch (state) {
// read n value and ngram counts.
case BEGIN:
if (clean.startsWith("\\data\\"))
started = true;
else if (started && clean.startsWith("ngram")) {
started = true;
int count = 0, i = 0;
for (String str : Splitter.on("=").trimResults().split(clean)) {
if (i++ == 0)
continue;
count = Integer.parseInt(str);
}
ngramCounts.add(count);
} else if (started) {
state = State.UNIGRAMS;
newGramStream(1);
newProbStream(1);
newBackoffStream(1);
Log.info("Gram counts in Arpa file: " + Joiner.on(" ").join(ngramCounts));
Log.info("Writing unigrams.");
_n++;
}
break;
// read ngrams. if unigram values, we store the strings and related indexes.
case UNIGRAMS:
if (clean.length() == 0 || clean.startsWith("\\")) {
break;
}
String[] tokens = tokenizer.split(clean);
// parse probabilty
float logProbability = Float.parseFloat(tokens[0]);
String word = tokens[1];
float logBackoff = 0;
if (tokens.length == 3)
logBackoff = Float.parseFloat(tokens[_n + 1]);
// write unigram id, log-probability and log-backoff value.
int wordIndex = vocabularyBuilder.add(word);
gramOs.writeInt(wordIndex);
probOs.writeFloat(logProbability);
// if there are only ngrams, do not write backoff value.
if (ngramCounts.size() > 1)
backoffOs.writeFloat(logBackoff);
ngramCounter++;
if (ngramCounter == ngramCounts.get(0)) {
handleSpecialToken(LmVocabulary.SENTENCE_START);
handleSpecialToken(LmVocabulary.SENTENCE_END);
handleSpecialToken(LmVocabulary.UNKNOWN_WORD);
lmVocabulary = vocabularyBuilder.generate();
ngramCounts.set(0, lmVocabulary.size());
// we write info file after reading unigrams because we may add special tokens to unigrams
// so count information may have been changed.
order = ngramCounts.size();
try (DataOutputStream infos = getDos("info")) {
infos.writeInt(order);
for (Integer ngramCount : ngramCounts) {
infos.writeInt(ngramCount);
}
}
ngramCounter = 0;
state = State.NGRAMS;
_n++;
// if there is only unigrams in the arpa file, exit
if (ngramCounts.size() == 1) {
state = State.VOCABULARY;
} else {
newGramStream(2);
newProbStream(2);
if (order > 2)
newBackoffStream(2);
Log.info("Writing 2-grams.");
}
}
break;
case NGRAMS:
if (clean.length() == 0 || clean.startsWith("\\")) {
break;
}
tokens = tokenizer.split(clean);
logProbability = Float.parseFloat(tokens[0]);
for (int i = 0; i < _n; i++) {
int id = lmVocabulary.indexOf(tokens[i + 1]);
gramOs.writeInt(id);
}
// probabilities
probOs.writeFloat(logProbability);
if (_n < ngramCounts.size()) {
logBackoff = 0;
if (tokens.length == _n + 2)
logBackoff = Float.parseFloat(tokens[_n + 1]);
backoffOs.writeFloat(logBackoff);
}
if (ngramCounter > 0 && ngramCounter % 500000 == 0)
Log.info(ngramCounter + " grams are written so far.");
ngramCounter++;
if (ngramCounter == ngramCounts.get(_n - 1)) {
ngramCounter = 0;
// if there is no more ngrams, exit
if (ngramCounts.size() == _n) {
state = State.VOCABULARY;
} else {
_n++;
newGramStream(_n);
newProbStream(_n);
if (order > _n) {
newBackoffStream(_n);
}
Log.info("Writing " + _n + "-grams.");
}
}
break;
case VOCABULARY:
Closeables.close(gramOs, true);
Closeables.close(probOs, true);
Closeables.close(backoffOs, true);
Log.info("Writing model vocabulary.");
lmVocabulary.saveBinary(new File(dir, "vocab"));
return false; // we are done.
}
return true;
}
|
diff --git a/src/com/simple/calculator/MainActivity.java b/src/com/simple/calculator/MainActivity.java
index 096ee0d..8e9e528 100644
--- a/src/com/simple/calculator/MainActivity.java
+++ b/src/com/simple/calculator/MainActivity.java
@@ -1,328 +1,327 @@
package com.simple.calculator;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
/**
* Project Simple Calculator : Main Activity
* This class is main activity class for Simple Calculator project
* In this class is portrait mode for calculator interface found in activity_main.xml
* This is only interface class and all calculations are done in different class
* Class tries to be smart about what inputs are valid and what are not and that way prevent user errors
*/
public ArrayList<String> calculate = new ArrayList<String>(); //This ArrayList holds calculation
public String buffer = null; //This String is buffer for adding numbers to the calculate Sting ArrayList
public String ans = "0"; //This Sting holds last answer that is calculated and it has default value of 0
/*
* Here is interface TextView
*/
TextView screen;
/*
* Hear is few static variables for some important chars
*/
public static String POTENS = "²";
public static String SQROOT = "√";
public static String OBRACKET = "(";
public static String CBRACKET = ")";
public static String DIVISION = "÷";
public static String MULTIPLY = "x";
public static String PLUS = "+";
public static String MINUS = "-";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView) findViewById(R.id.view);
}
public void updScreen(){
/**
* updScreen() is method for updating TextView called screen for giving user feedback
* screen shows calculation that is entered
*/
if (this.calculate.size() == 0){
// Set number 0 for screen if no calculation has been given
this.screen.setText("0");
return;
}
// Idea is show user everything that has been set for ArrayList calculate by getting all Strings and adding them into one and setting that string text for TextView screen
String tmp = "";
for (String s : this.calculate) tmp = tmp + s;
this.screen.setText(tmp);
}
public void don(View v){
/**
* don() is method used as button listener for number buttons
*/
if (this.buffer == null){
if (calculate.size() == 0){
// if calculate size is 0 and ans is pushed then ans value is set to buffer and calculate
if ("ans".equals((String) v.getTag())){
buffer = ans;
calculate.add(buffer);
}
// if calculate size is 0 and number button is pushed then that number is set to buffer and calculate
else{
buffer = (String) v.getTag();
calculate.add(this.buffer);
}
}
// if calculate size is one or more and last symbol is potens it is replaced by number
else if (calculate.get(this.calculate.size()-1).equals(POTENS) && calculate.size() != 0){
calculate.remove(calculate.size()-1);
buffer = calculate.get(calculate.size()-1);
buffer = buffer + ( (String) v.getTag());
calculate.set(calculate.size()-1, buffer);
}
// if calculate size is one or more and last symbol is closing bracket nothing will be done
else if (calculate.get(this.calculate.size()-1).equals(CBRACKET)) return;
// if calculate size is one or more and last symbol isn't potens or closing bracket then number of tag is added to calculator
else {
if ("ans".equals((String) v.getTag())){
buffer = ans;
calculate.add(buffer);
}
else {
this.buffer = (String) v.getTag();
this.calculate.add(this.buffer);
}
}
}
else {
// if point or ans is given then nothing will be done
if ( ((String) v.getTag()).equals(".") && buffer.contains(".")) return;
if ( ((String) v.getTag()).equals("ans")) return;
// In other case number is add to buffer and calulate is updated
this.buffer = this.buffer + ( (String) v.getTag() );
this.calculate.set(this.calculate.size()-1, this.buffer);
}
this.updScreen();
}
public void doact(View v){
/**
* doact() is used button listener for actions/symbol (like +, - or x) buttons like
*/
// symbol is get from component tag witch is found from View
if (calculate.size() == 0){
// if calculate size is 0 then ans is added to calculate and after that symbol is add to calculate
calculate.add(ans);
this.calculate.add((String) v.getTag());
}
else if (this.buffer != null){
// if buffer isn't empty symbol is added to calculate and buffer is emptied
this.calculate.add((String) v.getTag());
buffer = null;
this.updScreen();
return;
}
else {
String tmp = this.calculate.get(this.calculate.size()-1);
// if buffer is empty and if last symbol in calculate is potens or closing bracket then symbol is added to calculate
if (tmp.equals(POTENS) || tmp.equals(CBRACKET)){
calculate.add((String) v.getTag());
}
// if buffer is empty and last symbol is square root nothing will be done
else if (tmp.equals(SQROOT)) return;
// if buffer is empty and last symbol isn't potens, square root or closing bracket then symbol is added to calculate in way that it replaces last symbol
else {
this.calculate.set(calculate.size()-1, (String) v.getTag());
}
}
this.updScreen();
}
public void clear(View v){
/**
* clear() is button listener method for clear button and it clear buffer and calculate ArrayList
*/
this.calculate = new ArrayList<String>();
this.buffer = null;
this.updScreen();
}
public void erase(View v){
/**
* erase() is button listener method for erasing one char or number from TextView screen
*/
// if calculate size is 0 then nothing will be done
if (calculate.size() == 0) return;
if (buffer != null){
// If buffer isn't empty and buffer is longer than 1 char
// Then last char from buffer is removed and change is updated to calculate
if (buffer.length() != 1){
buffer = buffer.substring(0, buffer.length()-1);
calculate.set(calculate.size()-1, buffer);
}
// In other case (buffer isn't empty and buffer has only 1 char) buffer is emptied and last string (number) is removed from calculate
else {
calculate.remove(calculate.size()-1);
buffer = null;
}
}
else {
String tmp = this.calculate.get(this.calculate.size()-1);
// if buffer is empty and last symbol is square root then square root is removed
if (tmp.equals(SQROOT)){
calculate.remove(calculate.size()-1);
}
// if buffer is empty and last symbol is opening bracket then opening bracket is removed
else if (tmp.equals(OBRACKET)){
calculate.remove(calculate.size()-1);
}
// In other case last symbol is removed and if next to last string is number string then it will be set to buffer
else {
calculate.remove(calculate.size()-1);
tmp = this.calculate.get(this.calculate.size()-1);
if (tmp.equals(POTENS)) ;
else if (tmp.equals(CBRACKET)) ;
else buffer = tmp;
}
}
this.updScreen();
}
public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
- int tt = (int) test;
- this.ans = Integer.toString(tt);
+ this.ans = this.ans.substring(0, this.ans.length()-2);
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
//System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
public void brac(View v){
/**
* brac() is button listener method for brackets button and tries to be smart for adding brackets
*/
//if calculate size is 0 then "(" will be added
if (calculate.size() == 0){
calculate.add(OBRACKET);
}
else {
int open = 0; //if calculate size is not 0 then we count "(" and ")" in calculate
int close = 0;
for (String st: calculate){ //bracket count is done with for loop
if (st.equals(OBRACKET)) open ++;
else if (st.equals(CBRACKET)) close++;
}
String tmp = calculate.get(calculate.size()-1);
if (buffer == null && tmp.compareTo(POTENS) != 0){ //if buffer is empty and last symbol is not potens symbol then:
if (close < open && tmp.equals(CBRACKET)) calculate.add(CBRACKET); // -if there are open brackets and last symbol is closing bracket then closing bracket will be added
else if (close == open && tmp.equals(CBRACKET)) return; // -if there are no open brackets and last symbol is closing bracket then nothing will be done
else calculate.add(OBRACKET); // -in all other cases we will add opening bracket
}
else if (tmp.equals(POTENS) && close < open) calculate.add(CBRACKET);
else if (buffer != null && close < open){ //if buffer isn't empty and there are open brackets then buffer will be emptied and closing bracket
buffer = null;
calculate.add(CBRACKET);
}
}
this.updScreen();
}
public void tosecond(View v){
/**
* tosecond() is button listener method for potency button
*/
if (this.buffer == null ){ //if buffer is empty and if last symbol is closing bracket then potens will be added
if (calculate.size() == 0) return;
if (calculate.get(calculate.size()-1).equals(CBRACKET)){
calculate.add(POTENS);
}
else return;
}
else { //if buffer isn't empty then buffer is emptied and potens symbol will be added
buffer = null;
calculate.add(POTENS);
}
this.updScreen();
}
public void squeroot(View v){
/**
* squeroot() is button listener for square root button
*/
if (this.buffer != null) return; //if buffer isn't null then nothing will be done
if (calculate.size() != 0){
if (calculate.get(calculate.size()-1).equals(POTENS)) return;
else if (calculate.get(calculate.size()-1).equals(SQROOT)){
calculate.add(OBRACKET);
calculate.add(SQROOT);
}
else calculate.add(SQROOT);
}
else calculate.add(SQROOT); //if last symbol is not potens then square root will be added
this.updScreen();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true | true | public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
int tt = (int) test;
this.ans = Integer.toString(tt);
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
//System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
| public void calc(View v){
/**
* calc() is button listener for "=" symbol and does the calculating. calc() calls Calculate.java with does calculating in this application
*/
//if calculate size is 1 then nothing will be done
if (this.calculate.size() == 0) return;
String tmp = this.calculate.get(this.calculate.size()-1);
//if last symbol in calculate is of the following [ +, -, x, ÷, √, ( ] then last symbol will be removed from calculate because it would cause error
if (tmp.equals(SQROOT) || tmp.equals(MULTIPLY) || tmp.equals(MINUS) || tmp.equals(PLUS) || tmp.equals(DIVISION) || tmp.equals(OBRACKET)){
// if only symbol in calculate is "(" then calculate will be initialized and nothing else will be done
if (this.calculate.size() == 1 && tmp.equals(OBRACKET)){
this.calculate = new ArrayList<String>();
this.updScreen();
return;
}
else if (tmp.equals(OBRACKET)){
// if last symbol is "(" and calculate is longer than 1 then last two symbol are removed from calculate
this.calculate.remove(this.calculate.size()-1);
this.calculate.remove(this.calculate.size()-1);
}
else{
// in other cases last symbol will be removed
this.calculate.remove(this.calculate.size()-1);
}
}
int open = 0;
for (int i = 0; i < this.calculate.size(); i++){
// This for loop has two purposes:
// 1. count how many open brackets are in calculate
// 2. change "x" symbols to "*" symbols
if (this.calculate.get(i).equals(OBRACKET)) open++;
else if (this.calculate.get(i).equals(CBRACKET)) open--;
else if (this.calculate.get(i).equals(MULTIPLY)) this.calculate.set(i, "*");
}
while (open > 0){
// This while loop will close all open brackets
this.calculate.add(CBRACKET);
open--;
}
this.updScreen();
try {
// Try Catch is used to ensure that if some illegal calculate is give for Calculate.java then application don't crash and gives user error message
// First in this try calculate we call Calculate.java and give calculate for it
new Calculate(this.calculate);
// Then answer from calculation is saved to ans
this.ans = Calculate.getResult();
// Then ans will be simplified if possible by using double and integer variables
double test = Double.parseDouble(this.ans);
if (test%1==0){
this.ans = this.ans.substring(0, this.ans.length()-2);
}
// Last ans will be set for screen
String lastText = (String) this.screen.getText();
this.screen.setText(lastText + "=\n"+this.ans);
}
catch(java.lang.Exception e) {
// if there is error or exception in try bloc and error message will be given for user
this.screen.setText("ERROR");
//System.out.print(e.toString());
this.ans = "0";
}
// Buffer is emptied and if calculate is initialize
this.calculate = new ArrayList<String>();
this.buffer = null;
}
|
diff --git a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/model/WholeDayTasks.java b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/model/WholeDayTasks.java
index 6f3dd3f..86fc8cc 100644
--- a/com.uwusoft.timesheet/src/com/uwusoft/timesheet/model/WholeDayTasks.java
+++ b/com.uwusoft.timesheet/src/com/uwusoft/timesheet/model/WholeDayTasks.java
@@ -1,125 +1,125 @@
package com.uwusoft.timesheet.model;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.eclipse.jface.preference.IPreferenceStore;
import com.uwusoft.timesheet.Activator;
import com.uwusoft.timesheet.TimesheetApp;
import com.uwusoft.timesheet.extensionpoint.LocalStorageService;
import com.uwusoft.timesheet.extensionpoint.StorageService;
import com.uwusoft.timesheet.util.BusinessDayUtil;
import com.uwusoft.timesheet.util.ExtensionManager;
import com.uwusoft.timesheet.util.MessageBox;
public class WholeDayTasks {
private static WholeDayTasks instance;
private static String BEGIN_WDT = "BEGIN_WDT";
private static LocalStorageService localStorageService;
private Date nextBegin;
private float total;
private EntityManager em;
public static WholeDayTasks getInstance() {
if (instance == null) instance = new WholeDayTasks();
return instance;
}
private WholeDayTasks() {
em = TimesheetApp.factory.createEntityManager();
Query q = em.createQuery("select t from TaskEntry t where t.wholeDay=true order by t.dateTime desc");
@SuppressWarnings("unchecked")
List<TaskEntry> taskEntryList = q.getResultList();
Date begin;
if (taskEntryList.isEmpty()) {
begin = BusinessDayUtil.getNextBusinessDay(new Date());
em.getTransaction().begin();
@SuppressWarnings("unchecked")
List<Task> beginTasks = em.createQuery("select t from Task t where t.name = :name")
.setParameter("name", BEGIN_WDT)
.getResultList();
Task beginTask;
if (beginTasks.isEmpty()) {
beginTask = new Task(BEGIN_WDT);
em.persist(beginTask);
}
else
beginTask = beginTasks.iterator().next();
em.persist(new TaskEntry(begin, beginTask));
em.getTransaction().commit();
}
else
begin = BusinessDayUtil.getNextBusinessDay(taskEntryList.iterator().next().getDateTime());
nextBegin = begin;
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
total = new Float(preferenceStore.getInt(TimesheetApp.WORKING_HOURS) / 5); // TODO define non working days
localStorageService = new LocalStorageService();
}
public void addNextTask(Date to, String name) {
em.getTransaction().begin();
Task task = TimesheetApp.createTask(name);
Project project = localStorageService.findProjectByNameAndSystem(task.getProject().getName(), task.getProject().getSystem());
if (project == null) em.persist(task.getProject());
else task.setProject(project);
Task foundTask = localStorageService.findTaskByNameProjectAndSystem(
task.getName(), task.getProject().getName(), task.getProject().getSystem());
if (foundTask == null) em.persist(task);
else task = foundTask;
TaskEntry taskEntry = new TaskEntry(to, task, total, true);
em.persist(taskEntry);
em.getTransaction().commit();
nextBegin = BusinessDayUtil.getNextBusinessDay(to);
}
/**
* @return next business day after end date of all stored whole day tasks
*/
public Date getNextBegin() {
return nextBegin;
}
public void createTaskEntries() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
StorageService storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(preferenceStore.getString(StorageService.PROPERTY));
@SuppressWarnings("unchecked")
List<TaskEntry> taskEntryList = em.createQuery("select t from TaskEntry t where t.wholeDay=true order by t.dateTime asc")
.getResultList();
if (taskEntryList.isEmpty()) return;
@SuppressWarnings("unchecked")
List<TaskEntry> beginTaskEntryList = em.createQuery("select t from TaskEntry t where t.task.name = :name")
.setParameter("name", BEGIN_WDT)
.getResultList();
if (beginTaskEntryList.isEmpty()) return;
em.getTransaction().begin();
TaskEntry beginTaskEntry = beginTaskEntryList.iterator().next();
Date begin = beginTaskEntry.getDateTime();
em.remove(beginTaskEntry);
for (TaskEntry taskEntry : taskEntryList) {
Date end = new Date(taskEntry.getDateTime().getTime());
do {
- if (BusinessDayUtil.isAnotherWeek(begin, end))
- storageService.storeLastWeekTotal(preferenceStore.getString(TimesheetApp.WORKING_HOURS)); // store Week and Overtime
taskEntry.setDateTime(new Timestamp(begin.getTime()));
storageService.createTaskEntry(taskEntry);
+ if (BusinessDayUtil.isAnotherWeek(begin, BusinessDayUtil.getNextBusinessDay(begin)))
+ storageService.storeLastWeekTotal(preferenceStore.getString(TimesheetApp.WORKING_HOURS)); // store Week and Overtime
MessageBox.setMessage("Set whole day task", begin + "\n" + taskEntry); // TODO create confirm dialog
} while (!(begin = BusinessDayUtil.getNextBusinessDay(begin)).after(end));
em.remove(taskEntry);
}
em.getTransaction().commit();
}
}
| false | true | public void createTaskEntries() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
StorageService storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(preferenceStore.getString(StorageService.PROPERTY));
@SuppressWarnings("unchecked")
List<TaskEntry> taskEntryList = em.createQuery("select t from TaskEntry t where t.wholeDay=true order by t.dateTime asc")
.getResultList();
if (taskEntryList.isEmpty()) return;
@SuppressWarnings("unchecked")
List<TaskEntry> beginTaskEntryList = em.createQuery("select t from TaskEntry t where t.task.name = :name")
.setParameter("name", BEGIN_WDT)
.getResultList();
if (beginTaskEntryList.isEmpty()) return;
em.getTransaction().begin();
TaskEntry beginTaskEntry = beginTaskEntryList.iterator().next();
Date begin = beginTaskEntry.getDateTime();
em.remove(beginTaskEntry);
for (TaskEntry taskEntry : taskEntryList) {
Date end = new Date(taskEntry.getDateTime().getTime());
do {
if (BusinessDayUtil.isAnotherWeek(begin, end))
storageService.storeLastWeekTotal(preferenceStore.getString(TimesheetApp.WORKING_HOURS)); // store Week and Overtime
taskEntry.setDateTime(new Timestamp(begin.getTime()));
storageService.createTaskEntry(taskEntry);
MessageBox.setMessage("Set whole day task", begin + "\n" + taskEntry); // TODO create confirm dialog
} while (!(begin = BusinessDayUtil.getNextBusinessDay(begin)).after(end));
em.remove(taskEntry);
}
em.getTransaction().commit();
}
| public void createTaskEntries() {
IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
StorageService storageService = new ExtensionManager<StorageService>(StorageService.SERVICE_ID)
.getService(preferenceStore.getString(StorageService.PROPERTY));
@SuppressWarnings("unchecked")
List<TaskEntry> taskEntryList = em.createQuery("select t from TaskEntry t where t.wholeDay=true order by t.dateTime asc")
.getResultList();
if (taskEntryList.isEmpty()) return;
@SuppressWarnings("unchecked")
List<TaskEntry> beginTaskEntryList = em.createQuery("select t from TaskEntry t where t.task.name = :name")
.setParameter("name", BEGIN_WDT)
.getResultList();
if (beginTaskEntryList.isEmpty()) return;
em.getTransaction().begin();
TaskEntry beginTaskEntry = beginTaskEntryList.iterator().next();
Date begin = beginTaskEntry.getDateTime();
em.remove(beginTaskEntry);
for (TaskEntry taskEntry : taskEntryList) {
Date end = new Date(taskEntry.getDateTime().getTime());
do {
taskEntry.setDateTime(new Timestamp(begin.getTime()));
storageService.createTaskEntry(taskEntry);
if (BusinessDayUtil.isAnotherWeek(begin, BusinessDayUtil.getNextBusinessDay(begin)))
storageService.storeLastWeekTotal(preferenceStore.getString(TimesheetApp.WORKING_HOURS)); // store Week and Overtime
MessageBox.setMessage("Set whole day task", begin + "\n" + taskEntry); // TODO create confirm dialog
} while (!(begin = BusinessDayUtil.getNextBusinessDay(begin)).after(end));
em.remove(taskEntry);
}
em.getTransaction().commit();
}
|
diff --git a/src/java/org/infoglue/cms/applications/contenttool/actions/ViewContentVersionHistoryAction.java b/src/java/org/infoglue/cms/applications/contenttool/actions/ViewContentVersionHistoryAction.java
index 64399214..38918e27 100644
--- a/src/java/org/infoglue/cms/applications/contenttool/actions/ViewContentVersionHistoryAction.java
+++ b/src/java/org/infoglue/cms/applications/contenttool/actions/ViewContentVersionHistoryAction.java
@@ -1,102 +1,102 @@
/* ===============================================================================
*
* Part of the InfoGlue Content Management Platform (www.infoglue.org)
*
* ===============================================================================
*
* Copyright (C)
*
* 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. See the file LICENSE.html for more information.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, including 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.infoglue.cms.applications.contenttool.actions;
import java.util.List;
import org.infoglue.cms.applications.common.actions.InfoGlueAbstractAction;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentController;
import org.infoglue.cms.controllers.kernel.impl.simple.ContentVersionController;
import org.infoglue.cms.entities.content.ContentVO;
/**
*
* @author Mattias Bogeblad
*
* Present a list of contentVersion under a given content, showing off what has happened.
*/
public class ViewContentVersionHistoryAction extends InfoGlueAbstractAction
{
private static final long serialVersionUID = 1L;
private Integer contentId;
private List contentVersionVOList;
private Boolean inline = false;
private ContentVO contentVO = null;
protected String doExecute() throws Exception
{
this.contentVO = ContentController.getContentController().getContentVOWithId(this.contentId);
- contentVersionVOList = ContentVersionController.getContentVersionController().getSmallestContentVersionVOList(contentId);
+ contentVersionVOList = ContentVersionController.getContentVersionController().getContentVersionVOList(contentId);
return "success";
}
public String doV3() throws Exception
{
doExecute();
return "successV3";
}
/**
* @return
*/
public Integer getContentId()
{
return contentId;
}
/**
* @param integer
*/
public void setContentId(Integer integer)
{
contentId = integer;
}
public List getContentVersionVOList()
{
return contentVersionVOList;
}
public void setInline(Boolean inline)
{
this.inline = inline;
}
public Boolean getInline()
{
return inline;
}
public ContentVO getContentVO()
{
return this.contentVO;
}
}
| true | true | protected String doExecute() throws Exception
{
this.contentVO = ContentController.getContentController().getContentVOWithId(this.contentId);
contentVersionVOList = ContentVersionController.getContentVersionController().getSmallestContentVersionVOList(contentId);
return "success";
}
| protected String doExecute() throws Exception
{
this.contentVO = ContentController.getContentController().getContentVOWithId(this.contentId);
contentVersionVOList = ContentVersionController.getContentVersionController().getContentVersionVOList(contentId);
return "success";
}
|
diff --git a/src/org/nines/RDFIndexer.java b/src/org/nines/RDFIndexer.java
index 997173a..d5c8db8 100644
--- a/src/org/nines/RDFIndexer.java
+++ b/src/org/nines/RDFIndexer.java
@@ -1,601 +1,608 @@
/**
* Copyright 2007 Applied Research in Patacriticism and the University of Virginia
*
* 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.nines;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
public class RDFIndexer {
private int numFiles = 0;
private int numObjects = 0;
private String guid = "";
private RDFIndexerConfig config;
private ConcurrentLinkedQueue<File> dataFileQueue;
private ErrorReport errorReport;
private LinkCollector linkCollector;
private int progressMilestone = 0;
private long lastTime;
private Logger log;
private String targetArchive = "";
private static final int SOLR_REQUEST_NUM_RETRIES = 5; // how many times we should try to connect with solr before giving up
private static final int SOLR_REQUEST_RETRY_INTERVAL = 30 * 1000; // milliseconds
public static final int HTTP_CLIENT_TIMEOUT = 2*60*1000; // 2 minutes
private static final int NUMBER_OF_INDEXER_THREADS = 5;
private static final int PROGRESS_MILESTONE_INTERVAL = 100;
private static final int DOCUMENTS_PER_POST = 100;
public RDFIndexer(File rdfSource, String archiveName, RDFIndexerConfig config) {
targetArchive = archiveName;
// Use the archive name as the log file name
String reportFilename = archiveName;
reportFilename = reportFilename.replaceAll("/", "_").replaceAll(":", "_").replaceAll(" ", "_");
String logFileRelativePath = "../../../log/";
initSystem(logFileRelativePath + reportFilename);
log.info(config.retrieveFullText ? "Online: Indexing Full Text" : "Offline: Not Indexing Full Text");
this.config = config;
// this.solrURL = config.solrBaseURL + config.solrNewIndex + "/update";
// File reportFile = new File(rdfSource.getPath() + File.separatorChar + "report.txt"); // original place for the
// report file.
File reportFile = new File(logFileRelativePath + reportFilename + "_error.log"); // keep report file in the same
// folder as the log file.
try {
errorReport = new ErrorReport(reportFile);
} catch (IOException e1) {
log.error("Unable to open error report log for writing, aborting indexer.");
return;
}
linkCollector = new LinkCollector(logFileRelativePath + reportFilename);
HttpClient client = new HttpClient();
try {
beSureCoreExists(client, archiveToCore(archiveName));
} catch (IOException e) {
errorReport.addError(new IndexerError("Creating core", "", e.getMessage()));
}
// if (rdfSource.isDirectory()) {
createGUID(rdfSource);
Date start = new Date();
log.info("Started indexing at " + start);
indexDirectory(rdfSource);
if (config.commitToSolr) {
// for (String archive : archives)
commitDocumentsToSolr(client, archiveToCore(archiveName));
} else
log.info("Skipping Commit to SOLR...");
// report done
Date end = new Date();
long duration = (end.getTime() - start.getTime()) / 60000;
log.info("Indexed " + numFiles + " files (" + numObjects + " objects) in " + duration + " minutes");
// }
// else {
// errorReport.addError(new IndexerError("","","No objects found"));
// }
// if (config.commitToSolr && archive != null) {
// // find out how many items will be deleted
// numToDelete = numToDelete(guid, archive, client );
// log.info("Deleting "+numToDelete+" duplicate existing documents from index.");
//
// // remove content that isn't from this batch
// cleanUp(guid, archive, client);
// }
errorReport.close();
linkCollector.close();
}
private void commitDocumentsToSolr( HttpClient client, String archive ) {
try {
if (numObjects > 0) {
postToSolr("<optimize waitFlush=\"true\" waitSearcher=\"true\"/>",client, archive);
postToSolr("<commit/>",client, archive);
}
}
catch( IOException e ) {
errorReport.addError(new IndexerError("","","Unable to POST commit message to SOLR. "+e.getLocalizedMessage()));
}
}
private void createGUID( File rdfSource ) {
String path = rdfSource.getPath();
String file = path.substring(path.lastIndexOf('/') + 1);
try {
guid = file.substring(0, file.indexOf('.'));
} catch (StringIndexOutOfBoundsException e) {
/*
* In cases where the indexer is run manually against a directory that doesn't
* specify the GUID, create one automatically.
*/
guid = java.util.UUID.randomUUID().toString();
}
}
private void initSystem(String logName) {
// Use the SAX2-compliant Xerces parser:
System.setProperty(
"org.xml.sax.driver",
"org.apache.xerces.parsers.SAXParser");
try {
// don't purge old log on startup -- that is handled before calling this app.
String logPath = logName + "_progress.log";
FileAppender fa = new FileAppender(new PatternLayout("%d{E MMM dd, HH:mm:ss} [%p] - %m\n"), logPath);
BasicConfigurator.configure( fa );
log = Logger.getLogger(RDFIndexer.class.getName());
}
catch( IOException e ) {
log.error("Error, unable to initialize logging, exiting.");
System.exit(0);
}
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
}
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("java -jar rdf-indexer.jar <rdf dir|file> <archive name> [--fulltext] [--reindex] [--ignore=ignore_filename] [--include=include_filename] [--maxDocs=99]");
System.exit(-1);
}
String fullTextFlag = "--fulltext"; // This goes to the website to get the full text.
String reindexFlag = "--reindex"; // This gets the full text from the current index instead of going to the website.
String maxDocsFlag = "--maxDocs"; // This just looks at the first few docs in each folder.
String useIgnoreFile = "--ignore"; // This ignores the folders specified in the file.
String useIncludeFile = "--include"; // This ignores the folders specified in the file.
File rdfSource = new File(args[0]);
String archiveName = new String(args[1]);
RDFIndexerConfig config = new RDFIndexerConfig();
for (int i = 2; i < args.length; i++) {
if (args[i].equals(fullTextFlag))
config.retrieveFullText = true;
else if (args[i].equals(reindexFlag))
config.reindexFullText = true;
else if (args[i].startsWith(maxDocsFlag))
config.maxDocsPerFolder = Integer.parseInt(args[i].substring(maxDocsFlag.length()+1));
else if (args[i].startsWith(useIgnoreFile)) {
String ignoreFile = rdfSource + "/" + args[i].substring(useIgnoreFile.length()+1);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(ignoreFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
config.ignoreFolders.add(rdfSource + "/" + strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
else if (args[i].startsWith(useIncludeFile)) {
String includeFile = rdfSource + "/" + args[i].substring(useIncludeFile.length()+1);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(includeFile);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
config.includeFolders.add(rdfSource + "/" + strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
new RDFIndexer(rdfSource, archiveName, config);
}
private void recursivelyQueueFiles(File dir) {
if (dir.isDirectory()) {
log.info("loading directory: " + dir.getPath());
int numFilesInFolder = 0;
File fileList[] = dir.listFiles();
for (File entry : fileList) {
if (entry.isDirectory() && !entry.getName().endsWith(".svn")) {
String path = entry.toString();
if (config.ignoreFolders.size() > 0) {
int index = config.ignoreFolders.indexOf(path);
if (index == -1) {
recursivelyQueueFiles(entry);
}
} else if (config.includeFolders.size() > 0) {
int index = config.includeFolders.indexOf(path);
if (index != -1) {
recursivelyQueueFiles(entry);
}
} else {
recursivelyQueueFiles(entry);
}
}
if (entry.getName().endsWith(".rdf") || entry.getName().endsWith(".xml")) {
numFilesInFolder++;
if (numFilesInFolder < config.maxDocsPerFolder) {
dataFileQueue.add(entry);
}
}
}
}
else // a file was passed in, not a folder
{
log.info("loading file: " + dir.getPath());
dataFileQueue.add(dir);
}
}
private void indexDirectory(File rdfDir) {
dataFileQueue = new ConcurrentLinkedQueue<File>();
recursivelyQueueFiles(rdfDir);
numFiles = dataFileQueue.size();
log.info("=> Indexing " + rdfDir + " total files: " + numFiles);
initSpeedReporting();
// fire off the indexing threads
ArrayList<IndexerThread> threads = new ArrayList<IndexerThread>();
for( int i = 0; i < NUMBER_OF_INDEXER_THREADS; i++ ) {
IndexerThread thread = new IndexerThread(i);
threads.add(thread);
thread.start();
}
waitForIndexingThreads(threads);
}
private void waitForIndexingThreads(ArrayList<IndexerThread> threads) {
boolean done = false;
while (!done) {
// nap between checks
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
// check status
done = true;
for (IndexerThread thread : threads) {
done = done && thread.isDone();
}
}
}
/**
* Generate a core name given the archive. The core
* name is of the format: archive_[name]
*
* @param archive
* @return
*/
private String archiveToCore(String archive) {
String core = archive.replaceAll(":", "_");
core = core.replaceAll(" ", "_");
//core = core.replaceAll("-", "_");
core = core.replaceAll(",", "_");
return "archive_" + core;
}
private void indexFile(File file, HttpClient client) {
try {
// Parse a file into a hashmap.
// Key is object URI, Value is a set of key-value pairs
// that describe the object
HashMap<String, HashMap<String, ArrayList<String>>> objects = RdfDocumentParser.parse(file, errorReport,
linkCollector, config);
// Log an error for no objects abd bail if size is zero
if (objects.size() == 0) {
errorReport.addError(new IndexerError(file.getName(), "", "No objects in this file."));
errorReport.flush();
return;
}
// XML doc containing rdf docs to be posted to solr
Document solrDoc = new Document();
Element root = new Element("add");
solrDoc.addContent(root);
int docCount = 0;
String tgtArchive = "";
XMLOutputter outputter = new XMLOutputter();
for (Map.Entry<String, HashMap<String, ArrayList<String>>> entry: objects.entrySet()) {
String uri = entry.getKey();
HashMap<String, ArrayList<String>> object = entry.getValue();
// Validate archive and push objects intop new archive map
ArrayList<String> objectArray = object.get("archive");
if (objectArray != null) {
String objArchive = objectArray.get(0);
tgtArchive = archiveToCore(objArchive);
if (!objArchive.equals(this.targetArchive)) {
this.errorReport.addError(new IndexerError(file.getName(), uri, "The wrong archive was found. "
+ objArchive + " should be " + this.targetArchive));
}
} else {
this.errorReport.addError(new IndexerError(file.getName(), uri, "Unable to determine archive for this object."));
}
// validate all other parts of object and generate error report
- ArrayList<ErrorMessage> messages = ValidationUtility.validateObject(object);
- for ( ErrorMessage message : messages ) {
- IndexerError e = new IndexerError(file.getName(), uri, message.getErrorMessage());
+ try {
+ ArrayList<ErrorMessage> messages = ValidationUtility.validateObject(object);
+ for ( ErrorMessage message : messages ) {
+ IndexerError e = new IndexerError(file.getName(), uri, message.getErrorMessage());
+ errorReport.addError(e);
+ }
+ } catch (Exception valEx) {
+ System.err.println("ERROR Validating file:" + file.getName() + " URI: " + uri);
+ valEx.printStackTrace();
+ IndexerError e = new IndexerError(file.getName(), uri, valEx.getMessage());
errorReport.addError(e);
}
// turn this object into an XML solr doc and add it to the xml post
Element document = convertObjectToSolrDOM(uri, object);
root.addContent(document);
docCount++;
// once threashold met, post all docs
if ( docCount >= DOCUMENTS_PER_POST) {
log.info(" posting:" + docCount + " documents to SOLR");
postToSolr( outputter.outputString(solrDoc), client, tgtArchive);
solrDoc = new Document();
root = new Element("add");
solrDoc.addContent(root);
docCount = 0;
}
}
// dump any remaining docs out to solr
if ( docCount >= 0) {
log.info(" posting:" + docCount + " documents to SOLR");
postToSolr( outputter.outputString(solrDoc), client, tgtArchive);
}
numObjects += objects.size();
reportIndexingSpeed(numObjects);
} catch (IOException e) {
errorReport.addError(new IndexerError(file.getName(), "", e.getMessage()));
}
errorReport.flush();
}
private void initSpeedReporting() {
lastTime = System.currentTimeMillis();
}
private void reportIndexingSpeed( int objectCount ) {
if( objectCount > (progressMilestone + PROGRESS_MILESTONE_INTERVAL) ) {
long currentTime = System.currentTimeMillis();
float rate = (float)(currentTime-lastTime)/(float)(objectCount-progressMilestone);
progressMilestone = objectCount;
lastTime = currentTime;
log.info("total objects indexed: "+numObjects+" current rate: "+rate+"ms per object.");
}
}
private void beSureCoreExists(HttpClient httpclient, String core) throws IOException {
GetMethod request = new GetMethod(config.solrBaseURL + "/admin/cores?action=STATUS");
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(HTTP_CLIENT_TIMEOUT);
httpclient.getHttpConnectionManager().getParams()
.setIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 10000 * 1024);
// Execute request
try {
int result;
int solrRequestNumRetries = SOLR_REQUEST_NUM_RETRIES;
do {
result = httpclient.executeMethod(request);
solrRequestNumRetries--;
if (result != 200) {
try {
Thread.sleep(SOLR_REQUEST_RETRY_INTERVAL);
log.info(">>>> postToSolr error: " + result + " (retrying...)");
log.info(">>>> getting core information");
} catch (InterruptedException e) {
log.info(">>>> Thread Interrupted");
}
}
} while (result != 200 && solrRequestNumRetries > 0);
if (result != 200) {
throw new IOException("Non-OK response: " + result + "\n\n");
}
String response = getResponseString( request );
int exists = response.indexOf(">" + core + "<");
if (exists <= 0) {
// The core doesn't exist: create it.
request = new GetMethod(config.solrBaseURL + "/admin/cores?action=CREATE&name=" + core + "&instanceDir=.");
result = httpclient.executeMethod(request);
log.info(">>>> Created core: " + core);
try {
Thread.sleep(SOLR_REQUEST_RETRY_INTERVAL);
} catch (InterruptedException e) {
log.info(">>>> Thread Interrupted");
}
}
} finally {
// Release current connection to the connection pool once you are done
request.releaseConnection();
}
}
private String getResponseString(HttpMethod httpMethod) throws IOException {
InputStream is = httpMethod.getResponseBodyAsStream();
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
BufferedReader reader = new BufferedReader( new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
return writer.toString();
}
public void postToSolr(String xml, HttpClient httpclient, String archive) throws IOException {
PostMethod post = new PostMethod(config.solrBaseURL + "/" + archive + "/update");
// PostMethod post = new PostMethod(config.solrBaseURL + config.solrNewIndex + "/update");
post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
post.setRequestHeader("Content-type", "text/xml; charset=utf-8");
httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(HTTP_CLIENT_TIMEOUT);
httpclient.getHttpConnectionManager().getParams()
.setIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 10000 * 1024);
// Execute request
try {
int result;
int solrRequestNumRetries = SOLR_REQUEST_NUM_RETRIES;
do {
result = httpclient.executeMethod(post);
if (result != 200) {
try {
Thread.sleep(SOLR_REQUEST_RETRY_INTERVAL);
log.info(">>>> postToSolr error in archive " + archive + ": " + result + " (retrying...)");
} catch (InterruptedException e) {
log.info(">>>> Thread Interrupted");
}
} else {
if (solrRequestNumRetries != SOLR_REQUEST_NUM_RETRIES)
log.info(">>>> postToSolr: " + archive + ": (succeeded!)");
}
solrRequestNumRetries--;
} while (result != 200 && solrRequestNumRetries > 0);
if (result != 200) {
throw new IOException("Non-OK response: " + result + "\n\n" + xml);
}
String response = getResponseString(post);
// log.info(response);
Pattern pattern = Pattern.compile("status=\\\"(\\d*)\\\">(.*)\\<\\/result\\>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(response);
while (matcher.find()) {
String status = matcher.group(1);
String message = matcher.group(2);
if (!"0".equals(status)) {
throw new IOException(message);
}
}
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
private Element convertObjectToSolrDOM(String documentName, HashMap<String, ArrayList<String>> fields) {
Element doc = new Element("doc");
for (Map.Entry<String, ArrayList<String>> entry: fields.entrySet()) {
String field = entry.getKey();
ArrayList<String> valList = entry.getValue();
for (String value : valList) {
Element f = new Element("field");
f.setAttribute("name", field);
ValidationUtility.populateTextField(f, value);
doc.addContent(f);
}
}
// tag the document with the batch id
Element f = new Element("field");
f.setAttribute("name", "batch");
f.setText(guid);
doc.addContent(f);
return doc;
}
private class IndexerThread extends Thread {
private boolean done;
private HttpClient httpClient;
public IndexerThread(int threadID) {
setName("IndexerThread" + threadID);
httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(HTTP_CLIENT_TIMEOUT);
done = false;
}
@Override
public void run() {
File file = null;
while ((file = dataFileQueue.poll()) != null) {
indexFile(file, httpClient);
}
done = true;
}
public boolean isDone() {
return done;
}
}
}
| true | true | private void indexFile(File file, HttpClient client) {
try {
// Parse a file into a hashmap.
// Key is object URI, Value is a set of key-value pairs
// that describe the object
HashMap<String, HashMap<String, ArrayList<String>>> objects = RdfDocumentParser.parse(file, errorReport,
linkCollector, config);
// Log an error for no objects abd bail if size is zero
if (objects.size() == 0) {
errorReport.addError(new IndexerError(file.getName(), "", "No objects in this file."));
errorReport.flush();
return;
}
// XML doc containing rdf docs to be posted to solr
Document solrDoc = new Document();
Element root = new Element("add");
solrDoc.addContent(root);
int docCount = 0;
String tgtArchive = "";
XMLOutputter outputter = new XMLOutputter();
for (Map.Entry<String, HashMap<String, ArrayList<String>>> entry: objects.entrySet()) {
String uri = entry.getKey();
HashMap<String, ArrayList<String>> object = entry.getValue();
// Validate archive and push objects intop new archive map
ArrayList<String> objectArray = object.get("archive");
if (objectArray != null) {
String objArchive = objectArray.get(0);
tgtArchive = archiveToCore(objArchive);
if (!objArchive.equals(this.targetArchive)) {
this.errorReport.addError(new IndexerError(file.getName(), uri, "The wrong archive was found. "
+ objArchive + " should be " + this.targetArchive));
}
} else {
this.errorReport.addError(new IndexerError(file.getName(), uri, "Unable to determine archive for this object."));
}
// validate all other parts of object and generate error report
ArrayList<ErrorMessage> messages = ValidationUtility.validateObject(object);
for ( ErrorMessage message : messages ) {
IndexerError e = new IndexerError(file.getName(), uri, message.getErrorMessage());
errorReport.addError(e);
}
// turn this object into an XML solr doc and add it to the xml post
Element document = convertObjectToSolrDOM(uri, object);
root.addContent(document);
docCount++;
// once threashold met, post all docs
if ( docCount >= DOCUMENTS_PER_POST) {
log.info(" posting:" + docCount + " documents to SOLR");
postToSolr( outputter.outputString(solrDoc), client, tgtArchive);
solrDoc = new Document();
root = new Element("add");
solrDoc.addContent(root);
docCount = 0;
}
}
// dump any remaining docs out to solr
if ( docCount >= 0) {
log.info(" posting:" + docCount + " documents to SOLR");
postToSolr( outputter.outputString(solrDoc), client, tgtArchive);
}
numObjects += objects.size();
reportIndexingSpeed(numObjects);
} catch (IOException e) {
errorReport.addError(new IndexerError(file.getName(), "", e.getMessage()));
}
errorReport.flush();
}
| private void indexFile(File file, HttpClient client) {
try {
// Parse a file into a hashmap.
// Key is object URI, Value is a set of key-value pairs
// that describe the object
HashMap<String, HashMap<String, ArrayList<String>>> objects = RdfDocumentParser.parse(file, errorReport,
linkCollector, config);
// Log an error for no objects abd bail if size is zero
if (objects.size() == 0) {
errorReport.addError(new IndexerError(file.getName(), "", "No objects in this file."));
errorReport.flush();
return;
}
// XML doc containing rdf docs to be posted to solr
Document solrDoc = new Document();
Element root = new Element("add");
solrDoc.addContent(root);
int docCount = 0;
String tgtArchive = "";
XMLOutputter outputter = new XMLOutputter();
for (Map.Entry<String, HashMap<String, ArrayList<String>>> entry: objects.entrySet()) {
String uri = entry.getKey();
HashMap<String, ArrayList<String>> object = entry.getValue();
// Validate archive and push objects intop new archive map
ArrayList<String> objectArray = object.get("archive");
if (objectArray != null) {
String objArchive = objectArray.get(0);
tgtArchive = archiveToCore(objArchive);
if (!objArchive.equals(this.targetArchive)) {
this.errorReport.addError(new IndexerError(file.getName(), uri, "The wrong archive was found. "
+ objArchive + " should be " + this.targetArchive));
}
} else {
this.errorReport.addError(new IndexerError(file.getName(), uri, "Unable to determine archive for this object."));
}
// validate all other parts of object and generate error report
try {
ArrayList<ErrorMessage> messages = ValidationUtility.validateObject(object);
for ( ErrorMessage message : messages ) {
IndexerError e = new IndexerError(file.getName(), uri, message.getErrorMessage());
errorReport.addError(e);
}
} catch (Exception valEx) {
System.err.println("ERROR Validating file:" + file.getName() + " URI: " + uri);
valEx.printStackTrace();
IndexerError e = new IndexerError(file.getName(), uri, valEx.getMessage());
errorReport.addError(e);
}
// turn this object into an XML solr doc and add it to the xml post
Element document = convertObjectToSolrDOM(uri, object);
root.addContent(document);
docCount++;
// once threashold met, post all docs
if ( docCount >= DOCUMENTS_PER_POST) {
log.info(" posting:" + docCount + " documents to SOLR");
postToSolr( outputter.outputString(solrDoc), client, tgtArchive);
solrDoc = new Document();
root = new Element("add");
solrDoc.addContent(root);
docCount = 0;
}
}
// dump any remaining docs out to solr
if ( docCount >= 0) {
log.info(" posting:" + docCount + " documents to SOLR");
postToSolr( outputter.outputString(solrDoc), client, tgtArchive);
}
numObjects += objects.size();
reportIndexingSpeed(numObjects);
} catch (IOException e) {
errorReport.addError(new IndexerError(file.getName(), "", e.getMessage()));
}
errorReport.flush();
}
|
diff --git a/pmd/src/net/sourceforge/pmd/ast/ASTFieldDeclaration.java b/pmd/src/net/sourceforge/pmd/ast/ASTFieldDeclaration.java
index 10c163eb3..d93f1eed5 100644
--- a/pmd/src/net/sourceforge/pmd/ast/ASTFieldDeclaration.java
+++ b/pmd/src/net/sourceforge/pmd/ast/ASTFieldDeclaration.java
@@ -1,57 +1,57 @@
/* Generated By:JJTree: Do not edit this line. ASTFieldDeclaration.java */
package net.sourceforge.pmd.ast;
public class ASTFieldDeclaration extends AccessNode implements Dimensionable{
public ASTFieldDeclaration(int id) {
super(id);
}
public ASTFieldDeclaration(JavaParser p, int id) {
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(JavaParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
public boolean isArray() {
return checkType() + checkDecl() > 0;
}
public int getArrayDepth() {
if (!isArray()) {
return 0;
}
return checkType() + checkDecl();
}
private int checkType() {
if (jjtGetNumChildren() == 0 || !(jjtGetChild(0) instanceof ASTType)) {
return 0;
}
return ((ASTType)jjtGetChild(0)).getArrayDepth();
}
private int checkDecl() {
if (jjtGetNumChildren() < 2 || !(jjtGetChild(1) instanceof ASTVariableDeclarator)) {
return 0;
}
return ((ASTVariableDeclaratorId)(jjtGetChild(1).jjtGetChild(0))).getArrayDepth();
}
public void dump(String prefix) {
String out = collectDumpedModifiers(prefix);
if (isArray()) {
out += "(array";
for (int i=0;i<getArrayDepth();i++) {
out += "[";
}
out += ")";
}
- System.out.println(toString(prefix) + out);
+ System.out.println(out);
dumpChildren(prefix);
}
}
| true | true | public void dump(String prefix) {
String out = collectDumpedModifiers(prefix);
if (isArray()) {
out += "(array";
for (int i=0;i<getArrayDepth();i++) {
out += "[";
}
out += ")";
}
System.out.println(toString(prefix) + out);
dumpChildren(prefix);
}
| public void dump(String prefix) {
String out = collectDumpedModifiers(prefix);
if (isArray()) {
out += "(array";
for (int i=0;i<getArrayDepth();i++) {
out += "[";
}
out += ")";
}
System.out.println(out);
dumpChildren(prefix);
}
|
diff --git a/src/main/java/com/cloudbees/run/CloudBeesAgent.java b/src/main/java/com/cloudbees/run/CloudBeesAgent.java
index 8d14cd5..91cec62 100644
--- a/src/main/java/com/cloudbees/run/CloudBeesAgent.java
+++ b/src/main/java/com/cloudbees/run/CloudBeesAgent.java
@@ -1,102 +1,102 @@
package com.cloudbees.run;
import java.io.*;
import java.lang.instrument.Instrumentation;
import java.util.*;
/**
* @author Fabian Donze
*/
public class CloudBeesAgent {
protected Map<String, String> options = new HashMap<String, String>();
protected Instrumentation instrumentation;
public static void main(String[] args) {
if (args.length == 1) {
premain(args[0], null);
}
System.out.println(System.getProperties());
Properties p = System.getProperties();
SortedMap sortedSystemProperties = new TreeMap(p);
Set keySet = sortedSystemProperties.keySet();
for (Object aKeySet : keySet) {
String key = (String) aKeySet;
String value = (String) p.get(key);
System.out.println("[" +key + "]=[" + value + "]");
}
}
public static void premain(String agentArgs, Instrumentation inst) {
CloudBeesAgent agent = new CloudBeesAgent(agentArgs, inst);
try {
agent.loadSystemProperties();
} catch (IOException e) {
System.err.println("Cannot load properties: " + e.getMessage());
}
}
public CloudBeesAgent(String agentArgs, Instrumentation inst) {
if (agentArgs != null) {
String[] opts = agentArgs.split(",");
for (String opt : opts) {
String[] parts = opt.split(":");
if (parts.length == 2)
options.put(parts[0], parts[1]);
}
}
instrumentation = inst;
// instrumentation.addTransformer(this);
}
public void loadSystemProperties() throws IOException {
String propFileName = options.get("sys_prop");
if (propFileName != null) {
File propertyFile = new File(propFileName);
if (propertyFile.exists()) {
BufferedReader br = new BufferedReader(new FileReader(propertyFile));
try {
String line = br.readLine();
while (line != null) {
- String[] parts = line.split("=");
- if (parts.length == 2) {
- String name = parts[0];
- String value = parts[1];
+ int idx = line.indexOf("=");
+ if (idx > -1) {
+ String name = line.substring(0, idx);
+ String value = line.substring(idx+1);
if (value.startsWith("\"") && value.endsWith("\""))
value = value.substring(1, value.length()-1);
// System.out.println("Set: [" + name + "=" + value + "]");
// un-escape \" to "
value = value.replaceAll("\\\\\"", "\"");
// System.out.println("Set: [" + name + "=" + value + "]");
// un-escape \\ to \
value = value.replaceAll("\\\\\\\\", "\\\\");
// System.out.println("Set: [" + name + "=" + value + "]");
System.setProperty(name, value);
}
line = br.readLine();
}
} finally {
br.close();
}
} else {
System.err.println("Property file not found: " + propFileName);
}
} else {
System.err.println("Property file not defined");
}
}
/*
public byte[] transform(ClassLoader loader,
String className,
Class<?> classBeingRedefined,
ProtectionDomain protectionDomain,
byte[] classfileBuffer)
throws IllegalClassFormatException {
System.out.println("transform(): class: " + className + " (" + classfileBuffer.length + " bytes)");
return null;
}
*/
}
| true | true | public void loadSystemProperties() throws IOException {
String propFileName = options.get("sys_prop");
if (propFileName != null) {
File propertyFile = new File(propFileName);
if (propertyFile.exists()) {
BufferedReader br = new BufferedReader(new FileReader(propertyFile));
try {
String line = br.readLine();
while (line != null) {
String[] parts = line.split("=");
if (parts.length == 2) {
String name = parts[0];
String value = parts[1];
if (value.startsWith("\"") && value.endsWith("\""))
value = value.substring(1, value.length()-1);
// System.out.println("Set: [" + name + "=" + value + "]");
// un-escape \" to "
value = value.replaceAll("\\\\\"", "\"");
// System.out.println("Set: [" + name + "=" + value + "]");
// un-escape \\ to \
value = value.replaceAll("\\\\\\\\", "\\\\");
// System.out.println("Set: [" + name + "=" + value + "]");
System.setProperty(name, value);
}
line = br.readLine();
}
} finally {
br.close();
}
} else {
System.err.println("Property file not found: " + propFileName);
}
} else {
System.err.println("Property file not defined");
}
}
| public void loadSystemProperties() throws IOException {
String propFileName = options.get("sys_prop");
if (propFileName != null) {
File propertyFile = new File(propFileName);
if (propertyFile.exists()) {
BufferedReader br = new BufferedReader(new FileReader(propertyFile));
try {
String line = br.readLine();
while (line != null) {
int idx = line.indexOf("=");
if (idx > -1) {
String name = line.substring(0, idx);
String value = line.substring(idx+1);
if (value.startsWith("\"") && value.endsWith("\""))
value = value.substring(1, value.length()-1);
// System.out.println("Set: [" + name + "=" + value + "]");
// un-escape \" to "
value = value.replaceAll("\\\\\"", "\"");
// System.out.println("Set: [" + name + "=" + value + "]");
// un-escape \\ to \
value = value.replaceAll("\\\\\\\\", "\\\\");
// System.out.println("Set: [" + name + "=" + value + "]");
System.setProperty(name, value);
}
line = br.readLine();
}
} finally {
br.close();
}
} else {
System.err.println("Property file not found: " + propFileName);
}
} else {
System.err.println("Property file not defined");
}
}
|
diff --git a/common/logisticspipes/pipes/PipeItemsLiquidSupplier.java b/common/logisticspipes/pipes/PipeItemsLiquidSupplier.java
index d78fc7ab..130fe343 100644
--- a/common/logisticspipes/pipes/PipeItemsLiquidSupplier.java
+++ b/common/logisticspipes/pipes/PipeItemsLiquidSupplier.java
@@ -1,101 +1,101 @@
package logisticspipes.pipes;
import logisticspipes.interfaces.ILogisticsModule;
import logisticspipes.interfaces.routing.IRequestItems;
import logisticspipes.logic.LogicLiquidSupplier;
import logisticspipes.logisticspipes.IRoutedItem;
import logisticspipes.pipes.basic.RoutedPipe;
import logisticspipes.proxy.SimpleServiceLocator;
import logisticspipes.textures.Textures;
import logisticspipes.textures.Textures.TextureType;
import logisticspipes.transport.PipeTransportLogistics;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ITankContainer;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import buildcraft.transport.EntityData;
import buildcraft.transport.IItemTravelingHook;
import buildcraft.transport.PipeTransportItems;
import buildcraft.transport.TileGenericPipe;
public class PipeItemsLiquidSupplier extends RoutedPipe implements IRequestItems, IItemTravelingHook{
public PipeItemsLiquidSupplier(int itemID) {
super(new PipeTransportLogistics() {
@Override
public boolean isPipeConnected(TileEntity tile, ForgeDirection dir) {
if(super.isPipeConnected(tile, dir)) return true;
if(tile instanceof TileGenericPipe) return false;
if (tile instanceof ITankContainer) {
ITankContainer liq = (ITankContainer) tile;
if (liq.getTanks(ForgeDirection.UNKNOWN) != null && liq.getTanks(ForgeDirection.UNKNOWN).length > 0)
return true;
}
return false;
}
}, new LogicLiquidSupplier(), itemID);
((PipeTransportItems) transport).travelHook = this;
((LogicLiquidSupplier) logic)._power = this;
}
@Override
public TextureType getCenterTexture() {
return Textures.LOGISTICSPIPE_LIQUIDSUPPLIER_TEXTURE;
}
@Override
public ILogisticsModule getLogisticsModule() {
return null;
}
@Override
public void endReached(PipeTransportItems pipe, EntityData data, TileEntity tile) {
if (!(tile instanceof ITankContainer)) return;
if (tile instanceof TileGenericPipe) return;
ITankContainer container = (ITankContainer) tile;
//container.getLiquidSlots()[0].getLiquidQty();
if (data.item == null) return;
if (data.item.getItemStack() == null) return;
LiquidStack liquidId = LiquidContainerRegistry.getLiquidForFilledItem(data.item.getItemStack());
if (liquidId == null) return;
- ForgeDirection orientation = data.output;
+ ForgeDirection orientation = data.output.getOpposite();
if(getUpgradeManager().hasSneakyUpgrade()) {
orientation = getUpgradeManager().getSneakyUpgrade().getSneakyOrientation();
if(orientation == null) {
- orientation = data.output;
+ orientation = data.output.getOpposite();
}
}
while (data.item.getItemStack().stackSize > 0 && container.fill(orientation, liquidId, false) == liquidId.amount && this.useEnergy(5)) {
container.fill(orientation, liquidId, true);
data.item.getItemStack().stackSize--;
if (data.item.getItemStack().itemID >= 0 && data.item.getItemStack().itemID < Item.itemsList.length){
Item item = Item.itemsList[data.item.getItemStack().itemID];
if (item.hasContainerItem()){
Item containerItem = item.getContainerItem();
IRoutedItem itemToSend = SimpleServiceLocator.buildCraftProxy.CreateRoutedItem(new ItemStack(containerItem, 1), this.worldObj);
itemToSend.setSource(this.getRouter().getId());
this.queueRoutedItem(itemToSend, data.output);
}
}
}
if (data.item.getItemStack().stackSize < 1){
((PipeTransportItems)this.transport).scheduleRemoval(data.item);
}
}
@Override
public void drop(PipeTransportItems pipe, EntityData data) {}
@Override
public void centerReached(PipeTransportItems pipe, EntityData data) {}
@Override
public ItemSendMode getItemSendMode() {
return ItemSendMode.Normal;
}
}
| false | true | public void endReached(PipeTransportItems pipe, EntityData data, TileEntity tile) {
if (!(tile instanceof ITankContainer)) return;
if (tile instanceof TileGenericPipe) return;
ITankContainer container = (ITankContainer) tile;
//container.getLiquidSlots()[0].getLiquidQty();
if (data.item == null) return;
if (data.item.getItemStack() == null) return;
LiquidStack liquidId = LiquidContainerRegistry.getLiquidForFilledItem(data.item.getItemStack());
if (liquidId == null) return;
ForgeDirection orientation = data.output;
if(getUpgradeManager().hasSneakyUpgrade()) {
orientation = getUpgradeManager().getSneakyUpgrade().getSneakyOrientation();
if(orientation == null) {
orientation = data.output;
}
}
while (data.item.getItemStack().stackSize > 0 && container.fill(orientation, liquidId, false) == liquidId.amount && this.useEnergy(5)) {
container.fill(orientation, liquidId, true);
data.item.getItemStack().stackSize--;
if (data.item.getItemStack().itemID >= 0 && data.item.getItemStack().itemID < Item.itemsList.length){
Item item = Item.itemsList[data.item.getItemStack().itemID];
if (item.hasContainerItem()){
Item containerItem = item.getContainerItem();
IRoutedItem itemToSend = SimpleServiceLocator.buildCraftProxy.CreateRoutedItem(new ItemStack(containerItem, 1), this.worldObj);
itemToSend.setSource(this.getRouter().getId());
this.queueRoutedItem(itemToSend, data.output);
}
}
}
if (data.item.getItemStack().stackSize < 1){
((PipeTransportItems)this.transport).scheduleRemoval(data.item);
}
}
| public void endReached(PipeTransportItems pipe, EntityData data, TileEntity tile) {
if (!(tile instanceof ITankContainer)) return;
if (tile instanceof TileGenericPipe) return;
ITankContainer container = (ITankContainer) tile;
//container.getLiquidSlots()[0].getLiquidQty();
if (data.item == null) return;
if (data.item.getItemStack() == null) return;
LiquidStack liquidId = LiquidContainerRegistry.getLiquidForFilledItem(data.item.getItemStack());
if (liquidId == null) return;
ForgeDirection orientation = data.output.getOpposite();
if(getUpgradeManager().hasSneakyUpgrade()) {
orientation = getUpgradeManager().getSneakyUpgrade().getSneakyOrientation();
if(orientation == null) {
orientation = data.output.getOpposite();
}
}
while (data.item.getItemStack().stackSize > 0 && container.fill(orientation, liquidId, false) == liquidId.amount && this.useEnergy(5)) {
container.fill(orientation, liquidId, true);
data.item.getItemStack().stackSize--;
if (data.item.getItemStack().itemID >= 0 && data.item.getItemStack().itemID < Item.itemsList.length){
Item item = Item.itemsList[data.item.getItemStack().itemID];
if (item.hasContainerItem()){
Item containerItem = item.getContainerItem();
IRoutedItem itemToSend = SimpleServiceLocator.buildCraftProxy.CreateRoutedItem(new ItemStack(containerItem, 1), this.worldObj);
itemToSend.setSource(this.getRouter().getId());
this.queueRoutedItem(itemToSend, data.output);
}
}
}
if (data.item.getItemStack().stackSize < 1){
((PipeTransportItems)this.transport).scheduleRemoval(data.item);
}
}
|
diff --git a/apollo-tcp/src/main/java/org/apache/activemq/apollo/transport/tcp/SslTransport.java b/apollo-tcp/src/main/java/org/apache/activemq/apollo/transport/tcp/SslTransport.java
index ebc80f91..b8c1beaf 100644
--- a/apollo-tcp/src/main/java/org/apache/activemq/apollo/transport/tcp/SslTransport.java
+++ b/apollo-tcp/src/main/java/org/apache/activemq/apollo/transport/tcp/SslTransport.java
@@ -1,309 +1,313 @@
package org.apache.activemq.apollo.transport.tcp;
import org.apache.activemq.apollo.util.ApolloThreadPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
/**
* An SSL Transport for secure communications.
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
public class SslTransport extends TcpTransport {
private static final Logger LOG = LoggerFactory.getLogger(TcpTransport.class);
private SSLContext sslContext;
private SSLEngine engine;
private ByteBuffer readBuffer;
private boolean readUnderflow;
private ByteBuffer writeBuffer;
private boolean writeFlushing;
private ByteBuffer readOverflowBuffer;
public void setSSLContext(SSLContext ctx) {
this.sslContext = ctx;
}
class SSLChannel implements ReadableByteChannel, WritableByteChannel {
public int write(ByteBuffer plain) throws IOException {
return secure_write(plain);
}
public int read(ByteBuffer plain) throws IOException {
return secure_read(plain);
}
public boolean isOpen() {
return channel.isOpen();
}
public void close() throws IOException {
channel.close();
}
}
public SSLSession getSSLSession() {
return engine==null ? null : engine.getSession();
}
public X509Certificate[] getPeerX509Certificates() {
if( engine==null ) {
return null;
}
try {
ArrayList<X509Certificate> rc = new ArrayList<X509Certificate>();
for( Certificate c:engine.getSession().getPeerCertificates() ) {
if(c instanceof X509Certificate) {
rc.add((X509Certificate) c);
}
}
return rc.toArray(new X509Certificate[rc.size()]);
} catch (SSLPeerUnverifiedException e) {
return null;
}
}
@Override
protected void initializeCodec() {
SSLChannel channel = new SSLChannel();
codec.setReadableByteChannel(channel);
codec.setWritableByteChannel(channel);
}
@Override
public void connecting(URI remoteLocation, URI localLocation) throws Exception {
assert engine == null;
engine = sslContext.createSSLEngine();
engine.setUseClientMode(true);
super.connecting(remoteLocation, localLocation);
}
@Override
public void connected(SocketChannel channel) throws Exception {
if (engine == null) {
engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
engine.setWantClientAuth(true);
}
SSLSession session = engine.getSession();
readBuffer = ByteBuffer.allocateDirect(session.getPacketBufferSize());
readBuffer.flip();
writeBuffer = ByteBuffer.allocateDirect(session.getPacketBufferSize());
super.connected(channel);
}
@Override
protected void onConnected() throws IOException {
super.onConnected();
engine.setWantClientAuth(true);
engine.beginHandshake();
handshake_done();
}
@Override
protected void drainOutbound() {
if ( handshake_done() ) {
super.drainOutbound();
}
}
@Override
protected void drainInbound() {
if ( handshake_done() ) {
super.drainInbound();
}
}
/**
* @return true if fully flushed.
* @throws IOException
*/
protected boolean flush() throws IOException {
while (true) {
if(writeFlushing) {
channel.write(writeBuffer);
if( !writeBuffer.hasRemaining() ) {
writeBuffer.clear();
writeFlushing = false;
return true;
} else {
return false;
}
} else {
if( writeBuffer.position()!=0 ) {
writeBuffer.flip();
writeFlushing = true;
} else {
return true;
}
}
}
}
private int secure_write(ByteBuffer plain) throws IOException {
if( !flush() ) {
// can't write anymore until the write_secured_buffer gets fully flushed out..
return 0;
}
int rc = 0;
while ( plain.hasRemaining() || engine.getHandshakeStatus()==NEED_WRAP ) {
SSLEngineResult result = engine.wrap(plain, writeBuffer);
assert result.getStatus()!= BUFFER_OVERFLOW;
rc += result.bytesConsumed();
if( !flush() ) {
break;
}
}
return rc;
}
private int secure_read(ByteBuffer plain) throws IOException {
int rc=0;
while ( plain.hasRemaining() || engine.getHandshakeStatus() == NEED_UNWRAP ) {
if( readOverflowBuffer !=null ) {
- // lets drain the overflow buffer before trying to suck down anymore
- // network bytes.
- int size = Math.min(plain.remaining(), readOverflowBuffer.remaining());
- plain.put(readOverflowBuffer.array(), readOverflowBuffer.position(), size);
- readOverflowBuffer.position(readOverflowBuffer.position()+size);
- if( !readOverflowBuffer.hasRemaining() ) {
- readOverflowBuffer = null;
+ if( plain.hasRemaining() ) {
+ // lets drain the overflow buffer before trying to suck down anymore
+ // network bytes.
+ int size = Math.min(plain.remaining(), readOverflowBuffer.remaining());
+ plain.put(readOverflowBuffer.array(), readOverflowBuffer.position(), size);
+ readOverflowBuffer.position(readOverflowBuffer.position()+size);
+ if( !readOverflowBuffer.hasRemaining() ) {
+ readOverflowBuffer = null;
+ }
+ rc += size;
+ } else {
+ return rc;
}
- rc += size;
} else if( readUnderflow ) {
int count = channel.read(readBuffer);
if( count == -1 ) { // peer closed socket.
if (rc==0) {
engine.closeInbound();
return -1;
} else {
return rc;
}
}
if( count==0 ) { // no data available right now.
return rc;
}
// read in some more data, perhaps now we can unwrap.
readUnderflow = false;
readBuffer.flip();
} else {
SSLEngineResult result = engine.unwrap(readBuffer, plain);
rc += result.bytesProduced();
if( result.getStatus() == BUFFER_OVERFLOW ) {
readOverflowBuffer = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
result = engine.unwrap(readBuffer, readOverflowBuffer);
if( readOverflowBuffer.position()==0 ) {
readOverflowBuffer = null;
} else {
readOverflowBuffer.flip();
}
}
switch( result.getStatus() ) {
case CLOSED:
if (rc==0) {
engine.closeInbound();
return -1;
} else {
return rc;
}
case OK:
break;
case BUFFER_UNDERFLOW:
readBuffer.compact();
readUnderflow = true;
break;
case BUFFER_OVERFLOW:
throw new AssertionError("Unexpected case.");
}
}
}
return rc;
}
public boolean handshake_done() {
while (true) {
switch (engine.getHandshakeStatus()) {
case NEED_TASK:
final Runnable task = engine.getDelegatedTask();
if( task!=null ) {
ApolloThreadPool.INSTANCE.execute(new Runnable() {
public void run() {
task.run();
dispatchQueue.execute(new Runnable() {
public void run() {
if (isConnected()) {
handshake_done();
}
}
});
}
});
return false;
}
break;
case NEED_WRAP:
try {
secure_write(ByteBuffer.allocate(0));
if( writeFlushing && writeSource.isSuspended() ) {
writeSource.resume();
return false;
}
} catch(IOException e) {
onTransportFailure(e);
}
break;
case NEED_UNWRAP:
try {
secure_read(ByteBuffer.allocate(0));
if( readUnderflow && readSource.isSuspended() ) {
readSource.resume();
return false;
}
} catch(IOException e) {
onTransportFailure(e);
return true;
}
break;
case FINISHED:
case NOT_HANDSHAKING:
return true;
default:
SSLEngineResult.HandshakeStatus status = engine.getHandshakeStatus();
System.out.println("Unexpected ssl engine handshake status: "+ status);
}
}
}
}
| false | true | private int secure_read(ByteBuffer plain) throws IOException {
int rc=0;
while ( plain.hasRemaining() || engine.getHandshakeStatus() == NEED_UNWRAP ) {
if( readOverflowBuffer !=null ) {
// lets drain the overflow buffer before trying to suck down anymore
// network bytes.
int size = Math.min(plain.remaining(), readOverflowBuffer.remaining());
plain.put(readOverflowBuffer.array(), readOverflowBuffer.position(), size);
readOverflowBuffer.position(readOverflowBuffer.position()+size);
if( !readOverflowBuffer.hasRemaining() ) {
readOverflowBuffer = null;
}
rc += size;
} else if( readUnderflow ) {
int count = channel.read(readBuffer);
if( count == -1 ) { // peer closed socket.
if (rc==0) {
engine.closeInbound();
return -1;
} else {
return rc;
}
}
if( count==0 ) { // no data available right now.
return rc;
}
// read in some more data, perhaps now we can unwrap.
readUnderflow = false;
readBuffer.flip();
} else {
SSLEngineResult result = engine.unwrap(readBuffer, plain);
rc += result.bytesProduced();
if( result.getStatus() == BUFFER_OVERFLOW ) {
readOverflowBuffer = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
result = engine.unwrap(readBuffer, readOverflowBuffer);
if( readOverflowBuffer.position()==0 ) {
readOverflowBuffer = null;
} else {
readOverflowBuffer.flip();
}
}
switch( result.getStatus() ) {
case CLOSED:
if (rc==0) {
engine.closeInbound();
return -1;
} else {
return rc;
}
case OK:
break;
case BUFFER_UNDERFLOW:
readBuffer.compact();
readUnderflow = true;
break;
case BUFFER_OVERFLOW:
throw new AssertionError("Unexpected case.");
}
}
}
return rc;
}
| private int secure_read(ByteBuffer plain) throws IOException {
int rc=0;
while ( plain.hasRemaining() || engine.getHandshakeStatus() == NEED_UNWRAP ) {
if( readOverflowBuffer !=null ) {
if( plain.hasRemaining() ) {
// lets drain the overflow buffer before trying to suck down anymore
// network bytes.
int size = Math.min(plain.remaining(), readOverflowBuffer.remaining());
plain.put(readOverflowBuffer.array(), readOverflowBuffer.position(), size);
readOverflowBuffer.position(readOverflowBuffer.position()+size);
if( !readOverflowBuffer.hasRemaining() ) {
readOverflowBuffer = null;
}
rc += size;
} else {
return rc;
}
} else if( readUnderflow ) {
int count = channel.read(readBuffer);
if( count == -1 ) { // peer closed socket.
if (rc==0) {
engine.closeInbound();
return -1;
} else {
return rc;
}
}
if( count==0 ) { // no data available right now.
return rc;
}
// read in some more data, perhaps now we can unwrap.
readUnderflow = false;
readBuffer.flip();
} else {
SSLEngineResult result = engine.unwrap(readBuffer, plain);
rc += result.bytesProduced();
if( result.getStatus() == BUFFER_OVERFLOW ) {
readOverflowBuffer = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
result = engine.unwrap(readBuffer, readOverflowBuffer);
if( readOverflowBuffer.position()==0 ) {
readOverflowBuffer = null;
} else {
readOverflowBuffer.flip();
}
}
switch( result.getStatus() ) {
case CLOSED:
if (rc==0) {
engine.closeInbound();
return -1;
} else {
return rc;
}
case OK:
break;
case BUFFER_UNDERFLOW:
readBuffer.compact();
readUnderflow = true;
break;
case BUFFER_OVERFLOW:
throw new AssertionError("Unexpected case.");
}
}
}
return rc;
}
|
diff --git a/Homework2/src/Utility.java b/Homework2/src/Utility.java
index 39829e4..9b86439 100644
--- a/Homework2/src/Utility.java
+++ b/Homework2/src/Utility.java
@@ -1,17 +1,17 @@
import java.util.Collection;
public class Utility {
public static <T> String join(Collection<T> collection, String separator) {
String out = "";
Boolean firstElement = true;
for (T t : collection) {
- out += t;
if (!firstElement)
out += separator;
+ out += t;
firstElement = false;
}
return out;
}
}
| false | true | public static <T> String join(Collection<T> collection, String separator) {
String out = "";
Boolean firstElement = true;
for (T t : collection) {
out += t;
if (!firstElement)
out += separator;
firstElement = false;
}
return out;
}
| public static <T> String join(Collection<T> collection, String separator) {
String out = "";
Boolean firstElement = true;
for (T t : collection) {
if (!firstElement)
out += separator;
out += t;
firstElement = false;
}
return out;
}
|
diff --git a/com/zolli/rodolffoutilsreloaded/utils/configUtils.java b/com/zolli/rodolffoutilsreloaded/utils/configUtils.java
index 7138296..4b01b2f 100644
--- a/com/zolli/rodolffoutilsreloaded/utils/configUtils.java
+++ b/com/zolli/rodolffoutilsreloaded/utils/configUtils.java
@@ -1,63 +1,63 @@
package com.zolli.rodolffoutilsreloaded.utils;
import java.util.Set;
import org.bukkit.Location;
import com.zolli.rodolffoutilsreloaded.rodolffoUtilsReloaded;
public class configUtils {
public String[] returnArray = new String[2];
private rodolffoUtilsReloaded plugin;
public configUtils(rodolffoUtilsReloaded instance) {
plugin = instance;
}
public void setLocation(Location loc, String type, String name) {
double x = loc.getX();
double y = loc.getY();
double z = loc.getZ();
String world = loc.getWorld().getName().toString();
plugin.button.set("specialbutton." + name + ".type", type);
plugin.button.set("specialbutton." + name + ".world", world);
plugin.button.set("specialbutton." + name + ".x", x);
plugin.button.set("specialbutton." + name + ".y", y);
plugin.button.set("specialbutton." + name + ".z", z);
}
public String[] scanButton(Location loc) {
Set<String> names = plugin.button.getConfigurationSection("specialbutton").getKeys(false);
String WorldButton = loc.getWorld().getName().toString();
double xButton = loc.getX();
double yButton = loc.getY();
double zButton = loc.getZ();
for(String s : names) {
String WorldConfig = plugin.button.getString("specialbutton." + s + ".world");
double xConfig = plugin.button.getDouble("specialbutton." + s + ".x");
double yConfig = plugin.button.getDouble("specialbutton." + s + ".y");
double zConfig = plugin.button.getDouble("specialbutton." + s + ".z");
if(WorldButton.equalsIgnoreCase(WorldConfig) && xButton == xConfig && yButton == yConfig && zButton == zConfig) {
returnArray[0] = plugin.button.getString("specialbutton." + s + ".type");
- returnArray[1] = plugin.button.getString("specialbutton." + s + ".value", null);
+ returnArray[1] = plugin.button.getString("specialbutton." + s + ".value", "0");
return returnArray;
}
}
return null;
}
}
| true | true | public String[] scanButton(Location loc) {
Set<String> names = plugin.button.getConfigurationSection("specialbutton").getKeys(false);
String WorldButton = loc.getWorld().getName().toString();
double xButton = loc.getX();
double yButton = loc.getY();
double zButton = loc.getZ();
for(String s : names) {
String WorldConfig = plugin.button.getString("specialbutton." + s + ".world");
double xConfig = plugin.button.getDouble("specialbutton." + s + ".x");
double yConfig = plugin.button.getDouble("specialbutton." + s + ".y");
double zConfig = plugin.button.getDouble("specialbutton." + s + ".z");
if(WorldButton.equalsIgnoreCase(WorldConfig) && xButton == xConfig && yButton == yConfig && zButton == zConfig) {
returnArray[0] = plugin.button.getString("specialbutton." + s + ".type");
returnArray[1] = plugin.button.getString("specialbutton." + s + ".value", null);
return returnArray;
}
}
return null;
}
| public String[] scanButton(Location loc) {
Set<String> names = plugin.button.getConfigurationSection("specialbutton").getKeys(false);
String WorldButton = loc.getWorld().getName().toString();
double xButton = loc.getX();
double yButton = loc.getY();
double zButton = loc.getZ();
for(String s : names) {
String WorldConfig = plugin.button.getString("specialbutton." + s + ".world");
double xConfig = plugin.button.getDouble("specialbutton." + s + ".x");
double yConfig = plugin.button.getDouble("specialbutton." + s + ".y");
double zConfig = plugin.button.getDouble("specialbutton." + s + ".z");
if(WorldButton.equalsIgnoreCase(WorldConfig) && xButton == xConfig && yButton == yConfig && zButton == zConfig) {
returnArray[0] = plugin.button.getString("specialbutton." + s + ".type");
returnArray[1] = plugin.button.getString("specialbutton." + s + ".value", "0");
return returnArray;
}
}
return null;
}
|
diff --git a/src/com/modcrafting/diablodrops/listeners/SetListener.java b/src/com/modcrafting/diablodrops/listeners/SetListener.java
index a320912..ed547b6 100644
--- a/src/com/modcrafting/diablodrops/listeners/SetListener.java
+++ b/src/com/modcrafting/diablodrops/listeners/SetListener.java
@@ -1,87 +1,93 @@
package com.modcrafting.diablodrops.listeners;
import java.util.List;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import com.modcrafting.diablodrops.DiabloDrops;
import com.modcrafting.diablodrops.effects.EffectsAPI;
import com.modcrafting.diablodrops.sets.ArmorSet;
public class SetListener implements Listener
{
DiabloDrops plugin;
public SetListener(DiabloDrops instance)
{
plugin = instance;
}
@EventHandler(priority = EventPriority.LOW)
public void onEntityDamageByEntity(EntityDamageEvent event)
{
if (event instanceof EntityDamageByEntityEvent)
{
EntityDamageByEntityEvent ev = (EntityDamageByEntityEvent) event;
Entity struckEntity = ev.getEntity();
Entity strikerEntity = ev.getDamager();
if (!(struckEntity instanceof LivingEntity))
return;
LivingEntity struck = (LivingEntity) struckEntity;
if (strikerEntity instanceof Player)
{
Player striker = (Player) strikerEntity;
if (plugin.setsAPI.wearingSet(striker))
{
String sName = plugin.setsAPI.getNameOfSet(striker);
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
- List<String> effects = aSet.getBonuses();
- for (String s : effects)
- EffectsAPI.addEffect(struck, striker, s, event);
+ if (aSet != null)
+ {
+ List<String> effects = aSet.getBonuses();
+ for (String s : effects)
+ EffectsAPI.addEffect(struck, striker, s, event);
+ }
}
}
if (strikerEntity instanceof Projectile
&& ((Projectile) strikerEntity).getShooter() instanceof Player)
{
Player shooter = (Player) ((Projectile) strikerEntity)
.getShooter();
if (plugin.setsAPI.wearingSet(shooter))
{
String sName = plugin.setsAPI.getNameOfSet(shooter);
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
- List<String> effects = aSet.getBonuses();
- for (String s : effects)
- EffectsAPI.addEffect(struck, shooter, s, event);
+ if (aSet != null)
+ {
+ List<String> effects = aSet.getBonuses();
+ for (String s : effects)
+ EffectsAPI.addEffect(struck, shooter, s, event);
+ }
}
}
}
else
{
if (event.getEntity() instanceof Player
&& plugin.setsAPI.wearingSet((Player) event.getEntity()))
{
String sName = plugin.setsAPI.getNameOfSet((Player) event
.getEntity());
if (sName == null || sName.length() < 1)
return;
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
if (aSet == null)
return;
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect((LivingEntity) event.getEntity(),
null, s, event);
}
}
}
}
| false | true | public void onEntityDamageByEntity(EntityDamageEvent event)
{
if (event instanceof EntityDamageByEntityEvent)
{
EntityDamageByEntityEvent ev = (EntityDamageByEntityEvent) event;
Entity struckEntity = ev.getEntity();
Entity strikerEntity = ev.getDamager();
if (!(struckEntity instanceof LivingEntity))
return;
LivingEntity struck = (LivingEntity) struckEntity;
if (strikerEntity instanceof Player)
{
Player striker = (Player) strikerEntity;
if (plugin.setsAPI.wearingSet(striker))
{
String sName = plugin.setsAPI.getNameOfSet(striker);
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect(struck, striker, s, event);
}
}
if (strikerEntity instanceof Projectile
&& ((Projectile) strikerEntity).getShooter() instanceof Player)
{
Player shooter = (Player) ((Projectile) strikerEntity)
.getShooter();
if (plugin.setsAPI.wearingSet(shooter))
{
String sName = plugin.setsAPI.getNameOfSet(shooter);
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect(struck, shooter, s, event);
}
}
}
else
{
if (event.getEntity() instanceof Player
&& plugin.setsAPI.wearingSet((Player) event.getEntity()))
{
String sName = plugin.setsAPI.getNameOfSet((Player) event
.getEntity());
if (sName == null || sName.length() < 1)
return;
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
if (aSet == null)
return;
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect((LivingEntity) event.getEntity(),
null, s, event);
}
}
}
| public void onEntityDamageByEntity(EntityDamageEvent event)
{
if (event instanceof EntityDamageByEntityEvent)
{
EntityDamageByEntityEvent ev = (EntityDamageByEntityEvent) event;
Entity struckEntity = ev.getEntity();
Entity strikerEntity = ev.getDamager();
if (!(struckEntity instanceof LivingEntity))
return;
LivingEntity struck = (LivingEntity) struckEntity;
if (strikerEntity instanceof Player)
{
Player striker = (Player) strikerEntity;
if (plugin.setsAPI.wearingSet(striker))
{
String sName = plugin.setsAPI.getNameOfSet(striker);
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
if (aSet != null)
{
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect(struck, striker, s, event);
}
}
}
if (strikerEntity instanceof Projectile
&& ((Projectile) strikerEntity).getShooter() instanceof Player)
{
Player shooter = (Player) ((Projectile) strikerEntity)
.getShooter();
if (plugin.setsAPI.wearingSet(shooter))
{
String sName = plugin.setsAPI.getNameOfSet(shooter);
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
if (aSet != null)
{
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect(struck, shooter, s, event);
}
}
}
}
else
{
if (event.getEntity() instanceof Player
&& plugin.setsAPI.wearingSet((Player) event.getEntity()))
{
String sName = plugin.setsAPI.getNameOfSet((Player) event
.getEntity());
if (sName == null || sName.length() < 1)
return;
ArmorSet aSet = plugin.setsAPI.getArmorSet(sName);
if (aSet == null)
return;
List<String> effects = aSet.getBonuses();
for (String s : effects)
EffectsAPI.addEffect((LivingEntity) event.getEntity(),
null, s, event);
}
}
}
|
diff --git a/src/util/UnsafeDirectByteBuffer.java b/src/util/UnsafeDirectByteBuffer.java
index 8aa8eff..1e67b01 100644
--- a/src/util/UnsafeDirectByteBuffer.java
+++ b/src/util/UnsafeDirectByteBuffer.java
@@ -1,78 +1,81 @@
package util;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class UnsafeDirectByteBuffer {
private static final long addressOffset;
public static final int CACHE_LINE_SIZE = 64;
public static final int PAGE_SIZE = UnsafeAccess.unsafe.pageSize();
static {
try {
addressOffset = UnsafeAccess.unsafe.objectFieldOffset(Buffer.class
.getDeclaredField("address"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static long getAddress(ByteBuffer buffy) {
return UnsafeAccess.unsafe.getLong(buffy, addressOffset);
}
/**
* put byte and skip position update and boundary checks
*
* @param buffy
* @param b
*/
public static void putByte(long address, int position, byte b) {
UnsafeAccess.unsafe.putByte(address + (position << 0), b);
}
public static void putByte(long address, byte b) {
UnsafeAccess.unsafe.putByte(address, b);
}
public static ByteBuffer allocateAlignedByteBuffer(int capacity, long align){
if(Long.bitCount(align) != 1){
throw new IllegalArgumentException("Alignment must be a power of 2");
}
- ByteBuffer buffy = ByteBuffer.allocateDirect((int)(capacity+align)).order(ByteOrder.nativeOrder());
+ ByteBuffer buffy = ByteBuffer.allocateDirect((int)(capacity+align));
long address = getAddress(buffy);
if((address & (align-1)) == 0){
+ buffy.limit(capacity);
+ buffy = buffy.slice().order(ByteOrder.nativeOrder());;
return buffy;
}
else{
int newPosition = (int)(align - (address & (align - 1)));
buffy.position(newPosition);
int newLimit = newPosition + capacity;
buffy.limit(newLimit);
- return buffy.slice();
+ buffy = buffy.slice().order(ByteOrder.nativeOrder());;
+ return buffy;
}
}
public static boolean isPageAligned(ByteBuffer buffy){
return isPageAligned(getAddress(buffy));
}
/**
* This assumes cache line is 64b
*/
public static boolean isCacheAligned(ByteBuffer buffy){
return isCacheAligned(getAddress(buffy));
}
public static boolean isPageAligned(long address){
return (address & (PAGE_SIZE-1)) == 0;
}
/**
* This assumes cache line is 64b
*/
public static boolean isCacheAligned(long address){
return (address & (CACHE_LINE_SIZE-1)) == 0;
}
public static boolean isAligned(long address, long align){
if(Long.bitCount(align) != 1){
throw new IllegalArgumentException("Alignment must be a power of 2");
}
return (address & (align-1)) == 0;
}
}
| false | true | public static ByteBuffer allocateAlignedByteBuffer(int capacity, long align){
if(Long.bitCount(align) != 1){
throw new IllegalArgumentException("Alignment must be a power of 2");
}
ByteBuffer buffy = ByteBuffer.allocateDirect((int)(capacity+align)).order(ByteOrder.nativeOrder());
long address = getAddress(buffy);
if((address & (align-1)) == 0){
return buffy;
}
else{
int newPosition = (int)(align - (address & (align - 1)));
buffy.position(newPosition);
int newLimit = newPosition + capacity;
buffy.limit(newLimit);
return buffy.slice();
}
}
| public static ByteBuffer allocateAlignedByteBuffer(int capacity, long align){
if(Long.bitCount(align) != 1){
throw new IllegalArgumentException("Alignment must be a power of 2");
}
ByteBuffer buffy = ByteBuffer.allocateDirect((int)(capacity+align));
long address = getAddress(buffy);
if((address & (align-1)) == 0){
buffy.limit(capacity);
buffy = buffy.slice().order(ByteOrder.nativeOrder());;
return buffy;
}
else{
int newPosition = (int)(align - (address & (align - 1)));
buffy.position(newPosition);
int newLimit = newPosition + capacity;
buffy.limit(newLimit);
buffy = buffy.slice().order(ByteOrder.nativeOrder());;
return buffy;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.