code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.vercer.engine.persist.standard;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.google.appengine.api.datastore.AsyncDatastoreHelper;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query.SortPredicate;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.Restriction;
import com.vercer.engine.persist.FindCommand.BaseFindCommand;
import com.vercer.engine.persist.util.RestrictionToPredicateAdaptor;
import com.vercer.engine.persist.util.SortedMergeIterator;
/**
* Contains functionality common to all both TypedFindCommand and ParentsCommand
*
* @author John Patterson <john@vercer.com>
*
* @param <T> The type of the instance that will be returned
* @param <C> The concrete type that is returned from chained methods
*/
abstract class StandardBaseFindCommand<T, C extends BaseFindCommand<C>> implements BaseFindCommand<C>
{
Restriction<Entity> entityPredicate;
Restriction<Property> propertyPredicate;
final StrategyObjectDatastore datastore;
StandardBaseFindCommand(StrategyObjectDatastore datastore)
{
this.datastore = datastore;
}
@SuppressWarnings("unchecked")
@Override
public C restrictEntities(Restriction<Entity> filter)
{
if (this.entityPredicate != null)
{
throw new IllegalStateException("Entity filter was already set");
}
this.entityPredicate = filter;
return (C) this;
}
@SuppressWarnings("unchecked")
@Override
public C restrictProperties(Restriction<Property> filter)
{
if (this.propertyPredicate != null)
{
throw new IllegalStateException("Property filter was already set");
}
this.propertyPredicate = filter;
return (C) this;
}
Iterator<Entity> applyEntityFilter(Iterator<Entity> entities)
{
if (this.entityPredicate != null)
{
entities = Iterators.filter(entities, new RestrictionToPredicateAdaptor<Entity>(entityPredicate));
}
return entities;
}
Iterator<Entity> mergeEntities(List<Iterator<Entity>> iterators, List<SortPredicate> sorts)
{
Iterator<Entity> merged;
if (sorts != null && !sorts.isEmpty())
{
Comparator<Entity> comparator = AsyncDatastoreHelper.newEntityComparator(sorts);
merged = new SortedMergeIterator<Entity>(comparator, iterators, true);
}
else
{
merged = Iterators.concat(iterators.iterator());
}
return merged;
}
<R> Iterator<R> entityToInstanceIterator(Iterator<Entity> entities, boolean keysOnly)
{
Function<Entity, R> function = new EntityToInstanceFunction<R>(new RestrictionToPredicateAdaptor<Property>(propertyPredicate));
return Iterators.transform(entities, function);
}
private final class EntityToInstanceFunction<R> implements Function<Entity, R>
{
private final Predicate<Property> predicate;
public EntityToInstanceFunction(Predicate<Property> predicate)
{
this.predicate = predicate;
}
@SuppressWarnings("unchecked")
@Override
public R apply(Entity entity)
{
return (R) datastore.entityToInstance(entity, predicate);
}
}
}
| Java |
/**
*
*/
package com.vercer.engine.persist.standard;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;
import com.google.appengine.api.datastore.Key;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.util.reference.ReadOnlyObjectReference;
final class ParentEntityTranslator implements PropertyTranslator
{
private final StrategyObjectDatastore datastore;
/**
* @param datastore
*/
ParentEntityTranslator(StrategyObjectDatastore datastore)
{
this.datastore = datastore;
}
public Object propertiesToTypesafe(Set<Property> properties, Path prefix, Type type)
{
// properties are not used as the parent is found by the key
assert properties.isEmpty();
// put the key in a property
Key parentKey = datastore.decodeKey.getParent();
if (parentKey == null)
{
throw new IllegalStateException("No parent for key: " + datastore.decodeKey);
}
return this.datastore.keyToInstance(parentKey, null);
}
public Set<Property> typesafeToProperties(final Object instance, final Path prefix, final boolean indexed)
{
ReadOnlyObjectReference<Key> keyReference = new ReadOnlyObjectReference<Key>()
{
public Key get()
{
return ParentEntityTranslator.this.datastore.instanceToKey(instance, null);
}
};
// an existing parent key ref shows parent is still being stored
if (datastore.encodeKeySpec != null && datastore.encodeKeySpec.getParentKeyReference() == null)
{
// store the parent key inside the current key
datastore.encodeKeySpec.setParentKeyReference(keyReference);
}
// no fields are stored for parent
return Collections.emptySet();
}
} | Java |
package com.vercer.engine.persist.standard;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ImmediateFuture<T> implements Future<T>
{
private final T result;
public ImmediateFuture(T result)
{
this.result = result;
}
public boolean cancel(boolean mayInterruptIfRunning)
{
return false;
}
public T get() throws InterruptedException, ExecutionException
{
return result;
}
public T get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException
{
return result;
}
public boolean isCancelled()
{
return false;
}
public boolean isDone()
{
return false;
}
}
| Java |
package com.vercer.engine.persist.standard;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.common.collect.Maps;
import com.vercer.engine.persist.StoreCommand.MultipleStoreCommand;
import com.vercer.util.LazyProxy;
public class StandardMultipleStoreCommand<T> extends StandardBaseStoreCommand<T, MultipleStoreCommand<T>> implements MultipleStoreCommand<T>
{
public StandardMultipleStoreCommand(StandardStoreCommand command, Collection<T> instances)
{
super(command);
this.instances = instances;
}
public Future<Map<T, Key>> returnKeysLater()
{
return storeResultsLater();
}
public Map<T, Key> returnKeysNow()
{
final Map<T, Entity> entities = command.datastore.instancesToEntities(instances, parent, batch);
if (unique)
{
checkUniqueKeys(entities.values());
}
final List<Key> put = command.datastore.entitiesToKeys(entities.values());
// use a lazy map because often keys ignored
return new LazyProxy<Map<T, Key>>(Map.class)
{
@Override
protected Map<T, Key> newInstance()
{
LinkedHashMap<T, Key> result = Maps.newLinkedHashMap();
Iterator<T> instances = entities.keySet().iterator();
Iterator<Key> keys = put.iterator();
while (instances.hasNext())
{
result.put(instances.next(), keys.next());
}
return result;
}
}.newProxy();
}
}
| Java |
/**
*
*/
package com.vercer.engine.persist.standard;
import com.google.appengine.api.datastore.Key;
class ChildEntityTranslator extends EntityTranslator
{
ChildEntityTranslator(StrategyObjectDatastore strategyObjectDatastore)
{
super(strategyObjectDatastore);
}
@Override
protected Key getParentKey()
{
return datastore.encodeKeySpec.toKey();
}
} | Java |
package com.vercer.engine.persist.standard;
import java.util.Iterator;
import com.google.appengine.api.datastore.Entity;
public class StandardSingleParentsCommand<P> extends StandardBaseParentsCommand<P>
{
private final Iterator<Entity> childEntities;
public StandardSingleParentsCommand(StandardTypedFindCommand<?, ?> command, Iterator<Entity> childEntities)
{
super(command);
this.childEntities = childEntities;
}
public Iterator<P> returnParentsNow()
{
// no need to cache entities because there are no duplicates
Iterator<Entity> parentEntities = childEntitiesToParentEntities(childEntities, null);
parentEntities = applyEntityFilter(parentEntities);
return childCommand.entityToInstanceIterator(parentEntities, false);
}
}
| Java |
package com.vercer.engine.persist.standard;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.common.base.Function;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
public class PrefetchParentIterator extends AbstractIterator<Entity>
{
private final Iterator<Entity> children;
private Iterator<Entity> parents;
private final int fetchBy;
private final StrategyObjectDatastore datastore;
PrefetchParentIterator(Iterator<Entity> children, StrategyObjectDatastore datastore, int fetchBy)
{
this.children = children;
this.datastore = datastore;
this.fetchBy = fetchBy;
}
@Override
protected Entity computeNext()
{
if (parents == null)
{
if (!children.hasNext())
{
return endOfData();
}
// match the key iterator chunk size
List<Key> keys = new ArrayList<Key>(fetchBy);
for (int i = 0; i < fetchBy && children.hasNext(); i++)
{
keys.add(children.next().getKey().getParent());
}
// do a bulk get of the keys
final Map<Key, Entity> keyToEntity = keysToEntities(keys);
// keep the order of the original keys
parents = Iterators.transform(keys.iterator(), new Function<Key, Entity>()
{
public Entity apply(Key from)
{
return keyToEntity.get(from);
}
});
if (parents.hasNext() == false)
{
return endOfData();
}
}
if (parents.hasNext())
{
return parents.next();
}
else
{
parents = null;
return computeNext();
}
}
protected Map<Key, Entity> keysToEntities(List<Key> keys)
{
return datastore.keysToEntities(keys);
}
} | Java |
package com.vercer.engine.persist.standard;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.vercer.engine.persist.FindCommand;
import com.vercer.engine.persist.LoadCommand;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.StoreCommand;
import com.vercer.engine.persist.annotation.Id;
import com.vercer.engine.persist.conversion.DefaultTypeConverter;
import com.vercer.engine.persist.conversion.TypeConverter;
import com.vercer.engine.persist.strategy.ActivationStrategy;
import com.vercer.engine.persist.strategy.CacheStrategy;
import com.vercer.engine.persist.strategy.CombinedStrategy;
import com.vercer.engine.persist.strategy.FieldStrategy;
import com.vercer.engine.persist.strategy.RelationshipStrategy;
import com.vercer.engine.persist.strategy.StorageStrategy;
import com.vercer.engine.persist.translator.ChainedTranslator;
import com.vercer.engine.persist.translator.CoreStringTypesTranslator;
import com.vercer.engine.persist.translator.EnumTranslator;
import com.vercer.engine.persist.translator.ListTranslator;
import com.vercer.engine.persist.translator.MapTranslator;
import com.vercer.engine.persist.translator.NativeDirectTranslator;
import com.vercer.engine.persist.translator.ObjectFieldTranslator;
import com.vercer.engine.persist.translator.PolymorphicTranslator;
import com.vercer.engine.persist.util.Entities;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.util.Reflection;
import com.vercer.util.reference.ObjectReference;
/**
* Stateful layer responsible for caching key-object references and
* creating a PropertyTranslator that can be configured using Strategy
* instances.
*
* @author John Patterson <john@vercer.com>
*/
public class StrategyObjectDatastore extends BaseObjectDatastore
{
KeySpecification encodeKeySpec;
Key decodeKey;
// activation depth cannot be in decode context because it is defined per field
private Deque<Integer> activationDepthDeque= new ArrayDeque<Integer>();
private boolean indexed;
private final PropertyTranslator objectFieldTranslator;
private final PropertyTranslator embedTranslator;
private final PropertyTranslator polyMorphicComponentTranslator;
private final PropertyTranslator parentTranslator;
private final PropertyTranslator independantTranslator;
private final PropertyTranslator keyFieldTranslator;
private final PropertyTranslator childTranslator;
private final ChainedTranslator valueTranslatorChain;
private final PropertyTranslator defaultTranslator;
// TODO refactor this into an InstanceStrategy
private final KeyCache keyCache;
/**
* Flag that indicates we are associating instances with this session so do not store them
*/
// TODO store key field to do this - remove this flag
private boolean associating;
private Object refresh;
private Map<Object, Entity> batched;
private TypeConverter converter;
// TODO make all these private when commands have no logic
protected final RelationshipStrategy relationshipStrategy;
protected final FieldStrategy fieldStrategy;
protected final ActivationStrategy activationStrategy;
protected final StorageStrategy storageStrategy;
protected final CacheStrategy cacheStrategy;
public StrategyObjectDatastore(CombinedStrategy strategy)
{
this(strategy, strategy, strategy, strategy, strategy);
}
public StrategyObjectDatastore(
RelationshipStrategy relationshipStrategy,
StorageStrategy storageStrategy,
CacheStrategy cacheStrategy,
ActivationStrategy activationStrategy,
FieldStrategy fieldStrategy)
{
// push the default depth onto the stack
activationDepthDeque.push(Integer.MAX_VALUE);
this.activationStrategy = activationStrategy;
this.cacheStrategy = cacheStrategy;
this.fieldStrategy = fieldStrategy;
this.relationshipStrategy = relationshipStrategy;
this.storageStrategy = storageStrategy;
converter = createTypeConverter();
// the main translator which converts to and from objects
objectFieldTranslator = new StrategyObjectFieldTranslator(converter);
valueTranslatorChain = createValueTranslatorChain();
parentTranslator = new ParentEntityTranslator(this);
independantTranslator = new EntityTranslator(this);
keyFieldTranslator = new KeyFieldTranslator(this, valueTranslatorChain, converter);
childTranslator = new ChildEntityTranslator(this);
embedTranslator = new ListTranslator(objectFieldTranslator);
polyMorphicComponentTranslator = new ListTranslator(new MapTranslator(new PolymorphicTranslator(objectFieldTranslator, fieldStrategy), converter));
defaultTranslator = new ListTranslator(new MapTranslator(new ChainedTranslator(valueTranslatorChain, getFallbackTranslator()), converter));
keyCache = createKeyCache();
}
protected KeyCache createKeyCache()
{
return new KeyCache();
}
protected PropertyTranslator decoder(Entity entity)
{
return objectFieldTranslator;
}
protected PropertyTranslator encoder(Object instance)
{
return objectFieldTranslator;
}
protected PropertyTranslator decoder(Field field, Set<Property> properties)
{
return translator(field);
}
protected PropertyTranslator encoder(Field field, Object instance)
{
return translator(field);
}
protected PropertyTranslator translator(Field field)
{
if (storageStrategy.entity(field))
{
PropertyTranslator translator;
if (relationshipStrategy.parent(field))
{
translator = parentTranslator;
}
else if (relationshipStrategy.child(field))
{
translator = childTranslator;
}
else
{
translator = independantTranslator;
}
// if (cacheStrategy.cache(field))
// {
//
// }
return translator;
}
else if (relationshipStrategy.key(field))
{
return keyFieldTranslator;
}
else if (storageStrategy.embed(field))
{
if (storageStrategy.polymorphic(field))
{
return polyMorphicComponentTranslator;
}
else
{
return embedTranslator;
}
}
else
{
return defaultTranslator;
}
}
/**
* @return The translator which is used if no others are configured
*/
protected PropertyTranslator getFallbackTranslator()
{
return getIndependantTranslator();
}
protected TypeConverter createTypeConverter()
{
return new DefaultTypeConverter();
}
/**
* @return The translator that is used for single items by default
*/
protected ChainedTranslator createValueTranslatorChain()
{
ChainedTranslator result = new ChainedTranslator();
result.append(new NativeDirectTranslator());
result.append(new CoreStringTypesTranslator());
result.append(new EnumTranslator());
return result;
}
// TODO put this in a class meta data object
private static final Map<Class<?>, Field> keyFields = new ConcurrentHashMap<Class<?>, Field>();
// null values are not permitted in a concurrent hash map so need a "missing" value
private static final Field NO_KEY_FIELD;
static
{
try
{
NO_KEY_FIELD = StrategyObjectDatastore.class.getDeclaredField("NO_KEY_FIELD");
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
/**
* Potentially store an entity in the datastore.
*/
protected Key entityToKey(Entity entity)
{
// we could be just pretending to store to process the instance to get its key
if (associating)
{
// do not save the entity because we just want the key
Key key = entity.getKey();
if (!key.isComplete())
{
// incomplete keys are no good to us
throw new IllegalArgumentException("Associating entity does not have complete key: " + entity);
}
return key;
}
else if (batched != null)
{
// don't store anything yet if we are batching writes
Key key = entity.getKey();
// referenced entities must have a full key without being stored
if (!encodeKeySpec.isComplete())
{
// incomplete keys are no good to us - we need a key now
throw new IllegalArgumentException("Must have complete key in batched mode for entity " + entity);
}
// we will get the key after put
return key;
}
else
{
// actually put the entity in the datastore
return servicePut(entity);
}
}
protected List<Key> entitiesToKeys(Iterable<Entity> entities)
{
// TODO do some of the same stuff as above
return servicePut(entities);
}
@SuppressWarnings("unchecked")
final <T> T entityToInstance(Entity entity, Predicate<Property> filter)
{
T instance = (T) keyCache.getInstance(entity.getKey());
if (instance == null)
{
// push a new context
Key existingDecodeKey = decodeKey;
decodeKey = entity.getKey();
Type type = fieldStrategy.kindToType(entity.getKind());
Set<Property> properties = PropertySets.create(entity.getProperties(), indexed);
// filter out unwanted properties at the lowest level
if (filter != null)
{
properties = Sets.filter(properties, filter);
}
// order the properties for efficient separation by field
properties = new TreeSet<Property>(properties);
instance = (T) decoder(entity).propertiesToTypesafe(properties, Path.EMPTY_PATH, type);
if (instance == null)
{
throw new IllegalStateException("Could not translate entity " + entity);
}
// pop the context
decodeKey = existingDecodeKey;
}
return instance;
}
final <T> Iterator<T> entitiesToInstances(final Iterator<Entity> entities, final Predicate<Property> filter)
{
return new Iterator<T>()
{
@Override
public boolean hasNext()
{
return entities.hasNext();
}
@SuppressWarnings("unchecked")
@Override
public T next()
{
return (T) entityToInstance(entities.next(), filter);
}
@Override
public void remove()
{
entities.remove();
}
};
}
@SuppressWarnings("unchecked")
<T> T keyToInstance(Key key, Predicate<Property> filter)
{
T instance = (T) keyCache.getInstance(key);
if (instance == null)
{
Entity entity = keyToEntity(key);
if (entity == null)
{
instance = null;
}
else
{
instance = (T) entityToInstance(entity, filter);
}
}
return instance;
}
@SuppressWarnings("unchecked")
final <T> Map<Key, T> keysToInstances(List<Key> keys, Predicate<Property> filter)
{
Map<Key, T> result = new HashMap<Key, T>(keys.size());
List<Key> missing = null;
for (Key key : keys)
{
T instance = (T) keyCache.getInstance(key);
if (instance != null)
{
result.put(key, instance);
}
else
{
if (missing == null)
{
missing = new ArrayList<Key>(keys.size());
}
missing.add(key);
}
}
if (!missing.isEmpty())
{
Map<Key, Entity> entities = keysToEntities(missing);
if (!entities.isEmpty())
{
Set<Entry<Key, Entity>> entries = entities.entrySet();
for (Entry<Key, Entity> entry : entries)
{
T instance = (T) entityToInstance(entry.getValue(), filter);
result.put(entry.getKey(), instance);
}
}
}
return result;
}
// TODO make private once cache strategy working
protected Entity keyToEntity(Key key)
{
if (getActivationDepth() > 0)
{
try
{
return serviceGet(key);
}
catch (EntityNotFoundException e)
{
return null;
}
}
else
{
// don't load entity if it will not be activated - but need one for key
return new Entity(key);
}
}
protected Map<Key, Entity> keysToEntities(Collection<Key> keys)
{
// only load entity if we will activate instance
if (getActivationDepth() > 0)
{
return serviceGet(keys);
}
else
{
// we must return empty entities with the correct kind to instantiate
HashMap<Key, Entity> result = new HashMap<Key, Entity>();
for (Key key : keys)
{
result.put(key, new Entity(key));
}
return result;
}
}
// TODO make almost every method private once commands contain no logic
final Entity createEntity()
{
if (encodeKeySpec.isComplete())
{
// we have a complete key with id specified
return new Entity(encodeKeySpec.toKey());
}
else
{
// we have no id specified so must create entity for auto-generated id
ObjectReference<Key> parentKeyReference = encodeKeySpec.getParentKeyReference();
Key parentKey = parentKeyReference == null ? null : parentKeyReference.get();
return Entities.createEntity(encodeKeySpec.getKind(), null, parentKey);
}
}
protected boolean propertiesIndexedByDefault()
{
return true;
}
@Override
public final void disassociate(Object reference)
{
keyCache.evictInstance(reference);
}
@Override
public final void disassociateAll()
{
keyCache.clear();
}
@Override
public final void associate(Object instance, Key key)
{
keyCache.cache(key, instance);
}
@Override
public final void associate(Object instance)
{
// convert the instance so we can get its key and children
associating = true;
store(instance);
associating = false;
}
@Override
public final Key associatedKey(Object instance)
{
return keyCache.getKey(instance);
}
@Override
public final <T> T load(Class<T> type, Object id, Object parent)
{
Object converted;
if (Number.class.isAssignableFrom(id.getClass()))
{
converted = converter.convert(id, Long.class);
}
else
{
converted = converter.convert(id, String.class);
}
Key parentKey = null;
if (parent != null)
{
parentKey = keyCache.getKey(parent);
}
return internalLoad(type, converted, parentKey);
}
@Override
public final <I, T> Map<I, T> loadAll(Class<? extends T> type, Collection<I> ids)
{
Map<I, T> result = new HashMap<I, T>(ids.size());
for (I id : ids)
{
// TODO optimise this
T loaded = load(type, id);
result.put(id, loaded);
}
return result;
}
@Override
public final void update(Object instance)
{
Key key = keyCache.getKey(instance);
if (key == null)
{
throw new IllegalArgumentException("Can only update instances loaded from this session");
}
internalUpdate(instance, key);
}
@Override
public final void storeOrUpdate(Object instance)
{
if (associatedKey(instance) != null)
{
update(instance);
}
else
{
store(instance);
}
}
@Override
public final void storeOrUpdate(Object instance, Object parent)
{
if (associatedKey(instance) != null)
{
update(instance);
}
else
{
store(instance, parent);
}
}
@Override
public final void delete(Object instance)
{
Key key= keyCache.getKey(instance);
if (key == null)
{
throw new IllegalArgumentException("Instance " + instance + " is not associated");
}
deleteKeys(Collections.singleton(key));
}
@Override
public final void deleteAll(Collection<?> instances)
{
deleteKeys(Collections2.transform(instances, cachedInstanceToKeyFunction));
}
/**
* Either gets exiting key from cache or first stores the instance then returns the key
*/
Key instanceToKey(Object instance, Key parentKey)
{
Key key = keyCache.getKey(instance);
if (key == null)
{
key = internalStore(instance, parentKey);
}
return key;
}
<T> Map<T, Key> instancesToKeys(Collection<T> instances, Object parent)
{
Map<T, Key> result = new HashMap<T, Key>(instances.size());
List<T> missed = new ArrayList<T>(instances.size());
for (T instance : instances)
{
Key key = keyCache.getKey(instance);
if (key == null)
{
missed.add(instance);
}
else
{
result.put(instance, key);
}
}
if (!missed.isEmpty())
{
result.putAll(storeAll(missed, parent));
}
return result;
}
@Override
public final Key store(Object instance, Object parent)
{
Key parentKey = null;
if (parent != null)
{
parentKey = keyCache.getKey(parent);
}
return internalStore(instance, parentKey);
}
final Key internalStore(Object instance, Key parentKey)
{
// cache the empty key details now in case a child references back to us
if (keyCache.getKey(instance) != null)
{
throw new IllegalStateException("Cannot store same instance twice: " + instance);
}
Entity entity = instanceToEntity(instance, parentKey);
Key key = entityToKey(entity);
// replace the temp key ObjRef with the full key for this instance
keyCache.cache(key, instance);
setInstanceId(instance, key);
return key;
}
@SuppressWarnings("deprecation")
private void setInstanceId(Object instance, Key key)
{
// TODO share fields with ObjectFieldTranslator
Field idField = null;
if (keyFields.containsKey(instance.getClass()))
{
idField = keyFields.get(instance.getClass());
}
else
{
List<Field> fields = Reflection.getAccessibleFields(instance.getClass());
for (Field field : fields)
{
if (field.isAnnotationPresent(com.vercer.engine.persist.annotation.Key.class) ||
field.isAnnotationPresent(Id.class))
{
idField = field;
break;
}
}
if (idField == null)
{
idField = NO_KEY_FIELD;
}
keyFields.put(instance.getClass(), idField);
}
try
{
// if there is a key field
if (idField != NO_KEY_FIELD)
{
// see if its current value is null or 0
Object current = idField.get(instance);
if (current == null || current instanceof Number && ((Number) current).longValue() == 0)
{
Class<?> type = idField.getType();
Object idOrName = key.getId();
// the key name could have been set explicitly when storing
if (idOrName == null)
{
idOrName = key.getName();
}
// convert the long or String to the declared key type
Object converted = converter.convert(idOrName, type);
idField.set(instance, converted);
}
}
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
@Override
public final <T> Map<T, Key> storeAll(Collection<? extends T> instances)
{
return storeAll(instances, (Key) null);
}
@Override
public final <T> Map<T, Key> storeAll(Collection<? extends T> instances, Object parent)
{
// encode the instances to entities
final Map<T, Entity> entities = instancesToEntities(instances, parent, false);
// actually put them in the datastore and get their keys
final List<Key> keys = entitiesToKeys(entities.values());
LinkedHashMap<T, Key> result = Maps.newLinkedHashMap();
Iterator<T> instanceItr = entities.keySet().iterator();
Iterator<Key> keyItr = keys.iterator();
while (instanceItr.hasNext())
{
// iterate instances and keys in parallel
T instance = instanceItr.next();
Key key = keyItr.next();
// replace the temp key ObjRef with the full key for this instance
keyCache.cache(key, instance);
result.put(instance, key);
}
return result;
}
@Override
public final void refresh(Object instance)
{
Key key = associatedKey(instance);
if (key == null)
{
throw new IllegalStateException("Instance not associated with session");
}
// so it is not loaded from the cache
disassociate(instance);
// load will use this instance instead of creating new
refresh = instance;
// load from datastore into the refresh instance
Object loaded = load(key);
if (loaded == null)
{
throw new IllegalStateException("Instance to be refreshed could not be found");
}
}
@Override
public void refreshAll(Collection<?> instances)
{
// TODO optimise!
for (Object instance : instances)
{
refresh(instance);
}
}
@Override
public final int getActivationDepth()
{
return activationDepthDeque.peek();
}
@Override
public final void setActivationDepth(int depth)
{
activationDepthDeque.pop();
activationDepthDeque.push(depth);
}
protected final PropertyTranslator getIndependantTranslator()
{
return independantTranslator;
}
protected final PropertyTranslator getChildTranslator()
{
return childTranslator;
}
protected final PropertyTranslator getParentTranslator()
{
return parentTranslator;
}
protected final PropertyTranslator getPolyMorphicComponentTranslator()
{
return polyMorphicComponentTranslator;
}
protected final PropertyTranslator getEmbedTranslator()
{
return embedTranslator;
}
protected final PropertyTranslator getKeyFieldTranslator()
{
return keyFieldTranslator;
}
protected final PropertyTranslator getDefaultTranslator()
{
return defaultTranslator;
}
protected final KeyCache getKeyCache()
{
return keyCache;
}
private final Function<Object, Key> cachedInstanceToKeyFunction = new Function<Object, Key>()
{
public Key apply(Object instance)
{
return keyCache.getKey(instance);
}
};
@Override
public final FindCommand find()
{
return new StandardFindCommand(this);
}
@Override
public final StoreCommand store()
{
return new StandardStoreCommand(this);
}
@Override
public void activate(Object... instances)
{
activateAll(Arrays.asList(instances));
}
@Override
public void activateAll(Collection<?> instances)
{
// TODO optimise this
for (Object instance : instances)
{
refresh(instance);
}
}
protected final void setIndexed(boolean indexed)
{
this.indexed = indexed;
}
final Entity instanceToEntity(Object instance, Key parentKey)
{
String kind = fieldStrategy.typeToKind(instance.getClass());
// push a new encode context
KeySpecification existingEncodeKeySpec = encodeKeySpec;
encodeKeySpec = new KeySpecification(kind, parentKey, null);
keyCache.cacheKeyReferenceForInstance(instance, encodeKeySpec.toObjectReference());
// translate fields to properties - sets parent and id on key
PropertyTranslator encoder = encoder(instance);
Set<Property> properties = encoder.typesafeToProperties(instance, Path.EMPTY_PATH, indexed);
if (properties == null)
{
throw new IllegalStateException("Could not translate instance: " + instance);
}
// the key will now be set with id and parent
Entity entity = createEntity();
transferProperties(entity, properties);
// we can store all entities for a single batch put
if (batched != null)
{
batched.put(instance, entity);
}
// pop the encode context
encodeKeySpec = existingEncodeKeySpec;
return entity;
}
@SuppressWarnings("unchecked")
final <T> Map<T, Entity> instancesToEntities(Collection<? extends T> instances, Object parent, boolean batch)
{
Key parentKey = null;
if (parent != null)
{
parentKey= keyCache.getKey(parent);
}
Map<T, Entity> entities = new LinkedHashMap<T, Entity>(instances.size());
if (batch)
{
batched = (Map<Object, Entity>) entities;
}
// TODO optimise
for (T instance : instances)
{
// cannot define a key name
Entity entity = instanceToEntity(instance, parentKey);
entities.put(instance, entity);
}
if (batch)
{
batched = null;
}
return entities;
}
private void transferProperties(Entity entity, Collection<Property> properties)
{
for (Property property : properties)
{
// dereference object references
Object value = property.getValue();
value = dereferencePropertyValue(value);
if (property.isIndexed())
{
entity.setProperty(property.getPath().toString(), value);
}
else
{
entity.setUnindexedProperty(property.getPath().toString(), value);
}
}
}
public static Object dereferencePropertyValue(Object value)
{
if (value instanceof ObjectReference<?>)
{
value = ((ObjectReference<?>)value).get();
}
else if (value instanceof List<?>)
{
// we know the value is a mutable list from ListTranslator
@SuppressWarnings("unchecked")
List<Object> values = (List<Object>) value;
for (int i = 0; i < values.size(); i++)
{
Object item = values.get(i);
if (item instanceof ObjectReference<?>)
{
// dereference the value and set it in-place
Object dereferenced = ((ObjectReference<?>) item).get();
values.set(i, dereferenced); // replace the reference
}
}
}
return value;
}
@Override
public final Key store(Object instance)
{
return store(instance, null);
}
@Override
public final <T> T load(Class<T> type, Object key)
{
return load(type, key, null);
}
protected final <T> T internalLoad(Class<T> type, Object converted, Key parent)
{
assert activationDepthDeque.size() == 1;
String kind = fieldStrategy.typeToKind(type);
Key key;
if (parent == null)
{
if (converted instanceof Long)
{
key = KeyFactory.createKey(kind, (Long) converted);
}
else
{
key = KeyFactory.createKey(kind, (String) converted);
}
}
else
{
if (converted instanceof Long)
{
key = KeyFactory.createKey(parent, kind, (Long) converted);
}
else
{
key = KeyFactory.createKey(parent, kind, (String) converted);
}
}
// needed to avoid sun generics bug "no unique maximal instance exists..."
@SuppressWarnings("unchecked")
T result = (T) keyToInstance(key, null);
return result;
}
public final <T> QueryResultIterator<T> find(Class<T> type)
{
return find().type(type).returnResultsNow();
}
public final <T> QueryResultIterator<T> find(Class<T> type, Object ancestor)
{
return find().type(type).ancestor(ancestor).returnResultsNow();
}
final Query createQuery(Type type)
{
return new Query(fieldStrategy.typeToKind(type));
}
public final <T> T load(Key key)
{
@SuppressWarnings("unchecked")
T result = (T) keyToInstance(key, null);
return result;
}
final void internalUpdate(Object instance, Key key)
{
Entity entity = new Entity(key);
// push a new encode context just to double check values and stop NPEs
assert encodeKeySpec == null;
encodeKeySpec = new KeySpecification();
// translate fields to properties - sets parent and id on key
Set<Property> properties = encoder(instance).typesafeToProperties(instance, Path.EMPTY_PATH, indexed);
if (properties == null)
{
throw new IllegalStateException("Could not translate instance: " + instance);
}
transferProperties(entity, properties);
// we can store all entities for a single batch put
if (batched != null)
{
batched.put(instance, entity);
}
// pop the encode context
encodeKeySpec = null;
Key putKey = entityToKey(entity);
assert putKey.equals(key);
}
public final void deleteAll(Type type)
{
Query query = createQuery(type);
query.setKeysOnly();
FetchOptions options = FetchOptions.Builder.withChunkSize(100);
Iterator<Entity> entities = servicePrepare(query).asIterator(options);
Iterator<Key> keys = Iterators.transform(entities, entityToKeyFunction);
Iterator<List<Key>> partitioned = Iterators.partition(keys, 100);
while (partitioned.hasNext())
{
deleteKeys(partitioned.next());
}
}
protected void deleteKeys(Collection<Key> keys)
{
serviceDelete(keys);
for (Key key : keys)
{
if (keyCache.containsKey(key))
{
keyCache.evictKey(key);
}
}
}
private final class StrategyObjectFieldTranslator extends ObjectFieldTranslator
{
private StrategyObjectFieldTranslator(TypeConverter converters)
{
super(converters);
}
@Override
protected boolean indexed(Field field)
{
return StrategyObjectDatastore.this.storageStrategy.index(field);
}
@Override
protected boolean stored(Field field)
{
return StrategyObjectDatastore.this.storageStrategy.store(field);
}
@Override
protected Type typeFromField(Field field)
{
return StrategyObjectDatastore.this.fieldStrategy.typeOf(field);
}
@Override
protected String fieldToPartName(Field field)
{
return StrategyObjectDatastore.this.fieldStrategy.name(field);
}
@Override
protected PropertyTranslator encoder(Field field, Object instance)
{
return StrategyObjectDatastore.this.encoder(field, instance);
}
@Override
protected PropertyTranslator decoder(Field field, Set<Property> properties)
{
return StrategyObjectDatastore.this.decoder(field, properties);
}
@Override
protected Object createInstance(Class<?> clazz)
{
// if we are refreshing an instance do not create a new one
Object instance = refresh;
if (instance == null)
{
instance = super.createInstance(clazz);
}
refresh = null;
// need to cache the instance immediately so instances can reference it
if (keyCache.getInstance(decodeKey) == null)
{
// only cache first time - not for embedded components
keyCache.cache(decodeKey, instance);
}
return instance;
}
@Override
protected void onBeforeTranslate(Field field, Set<Property> childProperties)
{
if (activationDepthDeque.peek() > 0)
{
activationDepthDeque.push(StrategyObjectDatastore.this.activationStrategy.activationDepth(field, activationDepthDeque.peek() - 1));
}
}
@Override
protected void onAfterTranslate(Field field, Object value)
{
activationDepthDeque.pop();
}
@Override
protected void activate(Set<Property> properties, Object instance, Path path)
{
if (getActivationDepth() > 0)
{
super.activate(properties, instance, path);
}
}
}
private static final Function<Entity, Key> entityToKeyFunction = new Function<Entity, Key>()
{
public Key apply(Entity arg0)
{
return arg0.getKey();
}
};
@Override
public LoadCommand load()
{
throw new UnsupportedOperationException("Not yet implemented");
}
}
| Java |
package com.vercer.engine.persist.standard;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.Future;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.utils.FutureWrapper;
import com.google.common.collect.Iterables;
import com.vercer.engine.persist.StoreCommand.SingleStoreCommand;
final class StandardSingleStoreCommand<T> extends StandardBaseStoreCommand<T, SingleStoreCommand<T>> implements SingleStoreCommand<T>
{
public StandardSingleStoreCommand(StandardStoreCommand command, T instance)
{
super(command);
instances = Collections.singletonList(instance);
}
public Future<Key> returnKeyLater()
{
Future<Map<T, Key>> resultsLater = storeResultsLater();
return new FutureWrapper<Map<T, Key>, Key>(resultsLater)
{
@Override
protected Throwable convertException(Throwable arg0)
{
return arg0;
}
@Override
protected Key wrap(Map<T, Key> keys) throws Exception
{
return Iterables.getOnlyElement(keys.values());
}
};
}
public Key returnKeyNow()
{
T instance = Iterables.getOnlyElement(instances);
// cannot just call store because we may need to check the key
Key parentKey = null;
if (parent != null)
{
parentKey = command.datastore.associatedKey(parent);
}
Entity entity = command.datastore.instanceToEntity(instance, parentKey);
if (unique)
{
checkUniqueKeys(Collections.singleton(entity));
}
return command.datastore.entityToKey(entity);
}
}
| Java |
package com.vercer.engine.persist.standard;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.appengine.api.datastore.QueryResultList;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.vercer.engine.persist.FindCommand.RootFindCommand;
final class StandardRootFindCommand<T> extends StandardTypedFindCommand<T, RootFindCommand<T>> implements RootFindCommand<T>
{
private final Type type;
private FetchOptions options;
private Object ancestor;
List<Sort> sorts;
private boolean keysOnly;
class Sort
{
public Sort(String field, SortDirection direction)
{
super();
this.direction = direction;
this.field = field;
}
SortDirection direction;
String field;
}
StandardRootFindCommand(Type type, StrategyObjectDatastore datastore)
{
super(datastore);
this.type = type;
}
@Override
StandardRootFindCommand<T> getRootCommand()
{
return this;
}
@Override
public RootFindCommand<T> ancestor(Object ancestor)
{
this.ancestor = ancestor;
return this;
}
@Override
public RootFindCommand<T> fetchNoFields()
{
keysOnly = true;
return this;
}
@Override
public RootFindCommand<T> addSort(String field)
{
return addSort(field, SortDirection.ASCENDING);
}
@Override
public RootFindCommand<T> addSort(String field, SortDirection direction)
{
if (this.sorts == null)
{
this.sorts = new ArrayList<Sort>(2);
}
this.sorts.add(new Sort(field, direction));
return this;
}
@Override
public RootFindCommand<T> continueFrom(Cursor cursor)
{
if (this.options == null)
{
this.options = FetchOptions.Builder.withDefaults();
}
this.options.startCursor(cursor);
return this;
}
@Override
public RootFindCommand<T> finishAt(Cursor cursor)
{
if (this.options == null)
{
this.options = FetchOptions.Builder.withDefaults();
}
this.options.endCursor(cursor);
return this;
}
@Override
public RootFindCommand<T> fetchNextBy(int size)
{
if (this.options == null)
{
this.options = FetchOptions.Builder.withChunkSize(size);
}
else
{
this.options.chunkSize(size);
}
return this;
}
@Override
public RootFindCommand<T> fetchFirst(int size)
{
if (this.options == null)
{
this.options = FetchOptions.Builder.withPrefetchSize(size);
}
else
{
this.options.prefetchSize(size);
}
return this;
}
@Override
public RootFindCommand<T> startFrom(int offset)
{
if (this.options == null)
{
this.options = FetchOptions.Builder.withOffset(offset);
}
else
{
this.options.offset(offset);
}
return this;
}
@Override
public RootFindCommand<T> maximumResults(int limit)
{
if (this.options == null)
{
this.options = FetchOptions.Builder.withLimit(limit);
}
else
{
this.options.limit(limit);
}
return this;
}
@Override
public Future<QueryResultIterator<T>> returnResultsLater()
{
return futureSingleQueryInstanceIterator();
}
@Override
public int countResultsNow()
{
Collection<Query> queries = getValidatedQueries();
if (queries.size() > 1)
{
throw new IllegalStateException("Too many queries");
}
Query query = queries.iterator().next();
PreparedQuery prepared = this.datastore.servicePrepare(query);
return prepared.countEntities();
}
@Override
public QueryResultList<T> returnAllResultsNow()
{
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public Future<QueryResultList<T>> returnAllResultsLater()
{
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public QueryResultIterator<T> returnResultsNow()
{
if (children == null)
{
return nowSingleQueryInstanceIterator();
}
else
{
try
{
final Iterator<T> result = this.<T>futureMultiQueryInstanceIterator().get();
return new QueryResultIterator<T>()
{
public Cursor getCursor()
{
throw new IllegalStateException("Cannot use cursor with merged queries");
}
public boolean hasNext()
{
return result.hasNext();
}
public T next()
{
return result.next();
}
public void remove()
{
result.remove();
}
};
}
catch (Exception e)
{
if (e instanceof RuntimeException)
{
throw (RuntimeException) e;
}
else
{
throw (RuntimeException) e.getCause();
}
}
}
}
@Override
protected Query newQuery()
{
if (this.ancestor == null && this.datastore.getTransaction() != null)
{
throw new IllegalStateException("You must set an ancestor if you run a find this in a transaction");
}
Query query = new Query(datastore.fieldStrategy.typeToKind(type));
applyFilters(query);
if (sorts != null)
{
for (Sort sort : sorts)
{
query.addSort(sort.field, sort.direction);
}
}
if (ancestor != null)
{
Key key = datastore.associatedKey(ancestor);
if (key == null)
{
throw new IllegalArgumentException("Ancestor must be loaded in same session");
}
query.setAncestor(key);
}
if (keysOnly)
{
query.setKeysOnly();
}
return query;
}
public FetchOptions getFetchOptions()
{
return options;
}
public boolean isKeysOnly()
{
return keysOnly;
}
}
| Java |
/**
*
*/
package com.vercer.engine.persist.standard;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.conversion.TypeConverter;
import com.vercer.engine.persist.translator.DecoratingTranslator;
final class KeyFieldTranslator extends DecoratingTranslator
{
private final StrategyObjectDatastore datastore;
private final TypeConverter converters;
KeyFieldTranslator(StrategyObjectDatastore datastore, PropertyTranslator chained, TypeConverter converters)
{
super(chained);
this.datastore = datastore;
this.converters = converters;
}
public Set<Property> typesafeToProperties(Object instance, Path path, boolean indexed)
{
assert path.getParts().size() == 1 : "Key field must be in root Entity";
// key spec may be null if we are in an update as we already have the key
if (datastore.encodeKeySpec != null)
{
if (instance != null)
{
// treat 0 the same as null
if (!instance.equals(0))
{
// the key name is not stored in the fields but only in key
if (Number.class.isAssignableFrom(instance.getClass()))
{
Long converted = converters.convert(instance, Long.class);
datastore.encodeKeySpec.setId(converted);
}
else
{
String keyName = converters.convert(instance, String.class);
datastore.encodeKeySpec.setName(keyName);
}
}
}
}
return Collections.emptySet();
}
public Object propertiesToTypesafe(Set<Property> properties, Path prefix, Type type)
{
assert properties.isEmpty();
// the key value is not stored in the properties but in the key
Object keyValue = datastore.decodeKey.getName();
if (keyValue == null)
{
keyValue = datastore.decodeKey.getId();
}
return converters.convert(keyValue, type);
}
} | Java |
package com.vercer.engine.persist.standard;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.appengine.api.datastore.AsyncPreparedQuery;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortPredicate;
import com.google.appengine.api.utils.FutureWrapper;
import com.google.common.base.Predicate;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.ForwardingIterator;
import com.vercer.engine.persist.FindCommand;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.FindCommand.BranchFindCommand;
import com.vercer.engine.persist.FindCommand.ChildFindCommand;
import com.vercer.engine.persist.FindCommand.MergeOperator;
import com.vercer.engine.persist.FindCommand.ParentsCommand;
import com.vercer.engine.persist.FindCommand.TypedFindCommand;
import com.vercer.engine.persist.util.RestrictionToPredicateAdaptor;
public abstract class StandardTypedFindCommand<T, C extends TypedFindCommand<T, C>> extends StandardBaseFindCommand<T, C> implements TypedFindCommand<T, C>, BranchFindCommand<T>
{
protected List<StandardBranchFindCommand<T>> children;
protected List<Filter> filters;
private MergeOperator operator;
private static class Filter implements Serializable
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
private Filter()
{
}
public Filter(String field, FilterOperator operator, Object value)
{
this.field = field;
this.operator = operator;
this.value = value;
}
String field;
FilterOperator operator;
Object value;
}
public StandardTypedFindCommand(StrategyObjectDatastore datastore)
{
super(datastore);
}
protected abstract Query newQuery();
abstract StandardRootFindCommand<T> getRootCommand();
@SuppressWarnings("unchecked")
public C addFilter(String field, FilterOperator operator, Object value)
{
if (filters == null)
{
filters = new ArrayList<Filter>(2);
}
filters.add(new Filter(field, operator, value));
return (C) this;
}
@SuppressWarnings("unchecked")
public C addRangeFilter(String field, Object from, Object to)
{
addFilter(field, FilterOperator.GREATER_THAN_OR_EQUAL, from);
addFilter(field, FilterOperator.LESS_THAN, to);
return (C) this;
}
public BranchFindCommand<T> branch(FindCommand.MergeOperator operator)
{
if (operator != null)
{
throw new IllegalStateException("Can only branch a command once");
}
this.operator = operator;
return this;
}
public ChildFindCommand<T> addChildCommand()
{
StandardBranchFindCommand<T> child = new StandardBranchFindCommand<T>(this);
if (children == null)
{
children = new ArrayList<StandardBranchFindCommand<T>>(2);
}
children.add(child);
return child;
}
protected Collection<Query> queries()
{
if (children == null)
{
return Collections.singleton(newQuery());
}
else
{
List<Query> queries = new ArrayList<Query>(children.size() * 2);
for (StandardBranchFindCommand<T> child : children)
{
queries.addAll(child.queries());
}
return queries;
}
}
protected Collection<Query> getValidatedQueries()
{
Collection<Query> queries = queries();
if (queries.iterator().next().isKeysOnly() && (entityPredicate != null || propertyPredicate != null))
{
throw new IllegalStateException("Cannot set filters for a keysOnly query");
}
return queries;
}
void applyFilters(Query query)
{
if (filters != null)
{
for (Filter filter : filters)
{
query.addFilter(filter.field, filter.operator, filter.value);
}
}
}
public <P> Iterator<P> returnParentsNow()
{
return this.<P>returnParentsCommandNow().returnParentsNow();
}
public <P> ParentsCommand<P> returnParentsCommandNow()
{
Collection<Query> queries = queries();
if (queries.size() == 1)
{
Iterator<Entity> childEntities = nowSingleQueryEntities(queries.iterator().next());
childEntities = applyEntityFilter(childEntities);
return new StandardSingleParentsCommand<P>(this, childEntities);
}
else
{
try
{
List<Iterator<Entity>> childIterators = new ArrayList<Iterator<Entity>>(queries.size());
List<Future<QueryResultIterator<Entity>>> futures = multiQueriesToFutureEntityIterators(queries);
for (Future<QueryResultIterator<Entity>> future : futures)
{
childIterators.add(future.get());
}
Query query = queries.iterator().next();
List<SortPredicate> sorts = query.getSortPredicates();
if (query.isKeysOnly() == false)
{
// we should have the property values from the sort to merge
Iterator<Entity> childEntities = mergeEntities(childIterators, sorts);
childEntities = applyEntityFilter(childEntities);
return new StandardSingleParentsCommand<P>(this, childEntities);
}
else
{
return new StandardMergeParentsCommand<P>(this, childIterators, sorts);
}
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
}
@SuppressWarnings("unchecked")
public <P> Future<ParentsCommand<P>> returnParentsCommandLater()
{
Future<Iterator<Entity>> futureEntityIterator = (Future<Iterator<Entity>>) futureEntityIterator();
return new FutureWrapper<Iterator<Entity>, ParentsCommand<P>>(futureEntityIterator)
{
@Override
protected Throwable convertException(Throwable arg0)
{
return arg0;
}
@Override
protected ParentsCommand<P> wrap(Iterator<Entity> childEntities) throws Exception
{
return new StandardSingleParentsCommand(StandardTypedFindCommand.this, childEntities);
}
};
}
Future<? extends Iterator<Entity>> futureEntityIterator()
{
Collection<Query> queries = queries();
if (queries.size() == 1)
{
return futureSingleQueryEntities(queries.iterator().next());
}
else
{
assert queries.isEmpty() == false;
return futureMergedEntities(queries);
}
}
// TODO get rid of this
<R> QueryResultIterator<R> nowSingleQueryInstanceIterator()
{
Collection<Query> queries = getValidatedQueries();
if (queries.size() > 1)
{
throw new IllegalStateException("Too many queries");
}
Query query = queries.iterator().next();
QueryResultIterator<Entity> entities = nowSingleQueryEntities(query);
Iterator<Entity> iterator = applyEntityFilter(entities);
Iterator<R> instances = entityToInstanceIterator(iterator, query.isKeysOnly());
return new BasicQueryResultIterator<R>(instances, entities);
}
private QueryResultIterator<Entity> nowSingleQueryEntities(Query query)
{
final QueryResultIterator<Entity> entities;
PreparedQuery prepared = this.datastore.servicePrepare(query);
FetchOptions fetchOptions = getRootCommand().getFetchOptions();
if (fetchOptions == null)
{
entities = prepared.asQueryResultIterator();
}
else
{
entities = prepared.asQueryResultIterator(fetchOptions);
}
return entities;
}
<R> Future<QueryResultIterator<R>> futureSingleQueryInstanceIterator()
{
Collection<Query> queries = getValidatedQueries();
if (queries.size() > 1)
{
throw new IllegalStateException("Multiple queries defined");
}
final Query query = queries.iterator().next();
final Future<QueryResultIterator<Entity>> futureEntities = futureSingleQueryEntities(query);
return new Future<QueryResultIterator<R>>()
{
private QueryResultIterator<R> doGet(QueryResultIterator<Entity> entities)
{
Iterator<Entity> iterator = applyEntityFilter(entities);
Iterator<R> instances = entityToInstanceIterator(iterator, query.isKeysOnly());
return new BasicQueryResultIterator<R>(instances, entities);
}
public QueryResultIterator<R> get() throws InterruptedException,
ExecutionException
{
return doGet(futureEntities.get());
}
public QueryResultIterator<R> get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException,
TimeoutException
{
return doGet(futureEntities.get(timeout, unit));
}
public boolean isCancelled()
{
return futureEntities.isCancelled();
}
public boolean isDone()
{
return futureEntities.isDone();
}
public boolean cancel(boolean mayInterruptIfRunning)
{
return futureEntities.cancel(mayInterruptIfRunning);
}
};
}
private Future<QueryResultIterator<Entity>> futureSingleQueryEntities(Query query)
{
Transaction txn = this.datastore.getTransaction();
Future<QueryResultIterator<Entity>> futureEntities;
AsyncPreparedQuery prepared = new AsyncPreparedQuery(query, txn);
FetchOptions fetchOptions = getRootCommand().getFetchOptions();
if (fetchOptions == null)
{
futureEntities = prepared.asFutureQueryResultIterator();
}
else
{
futureEntities = prepared.asFutureQueryResultIterator(fetchOptions);
}
return futureEntities;
}
//
// private boolean isInternalIncompatability(Throwable t)
// {
// return t instanceof Error ||
// t instanceof SecurityException ||
// t instanceof ClassNotFoundException ||
// t instanceof NoSuchMethodException;
// }
protected Iterator<Entity> nowMultipleQueryEntities(Collection<Query> queries)
{
List<Iterator<Entity>> iterators = new ArrayList<Iterator<Entity>>(queries.size());
for (Query query : queries)
{
PreparedQuery prepared = this.datastore.servicePrepare(query);
Iterator<Entity> entities;
FetchOptions fetchOptions = getRootCommand().getFetchOptions();
if (fetchOptions == null)
{
entities = prepared.asIterator();
}
else
{
entities = prepared.asIterator(fetchOptions);
}
// apply filters etc
entities = applyEntityFilter(entities);
iterators.add(entities);
}
// all queries have the same sorts
Query query = queries.iterator().next();
List<SortPredicate> sorts = query.getSortPredicates();
Iterator<Entity> merged = mergeEntities(iterators, sorts);
return merged;
}
<R> Future<Iterator<R>> futureMultiQueryInstanceIterator()
{
Collection<Query> queries = getValidatedQueries();
return futureMultipleQueriesInstanceIterator(queries);
}
protected <R> Iterator<R> nowMultiQueryInstanceIterator()
{
try
{
Collection<Query> queries = getValidatedQueries();
Iterator<Entity> entities = nowMultipleQueryEntities(queries);
return entityToInstanceIterator(entities, false);
}
catch (Exception e)
{
// only unchecked exceptions thrown from datastore service
throw (RuntimeException) e.getCause();
}
}
private <R> Future<Iterator<R>> futureMultipleQueriesInstanceIterator(Collection<Query> queries)
{
final Future<Iterator<Entity>> futureMerged = futureMergedEntities(queries);
final boolean keysOnly = queries.iterator().next().isKeysOnly();
return new Future<Iterator<R>>()
{
public boolean cancel(boolean mayInterruptIfRunning)
{
return futureMerged.cancel(mayInterruptIfRunning);
}
public Iterator<R> get() throws InterruptedException, ExecutionException
{
return entityToInstanceIterator(futureMerged.get(), keysOnly);
}
public Iterator<R> get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException
{
return entityToInstanceIterator(futureMerged.get(timeout, unit), keysOnly);
}
public boolean isCancelled()
{
return futureMerged.isCancelled();
}
public boolean isDone()
{
return futureMerged.isDone();
}
};
}
private Future<Iterator<Entity>> futureMergedEntities(Collection<Query> queries)
{
List<Future<QueryResultIterator<Entity>>> futures = multiQueriesToFutureEntityIterators(queries);
Query query = queries.iterator().next();
List<SortPredicate> sorts = query.getSortPredicates();
return futureEntityIteratorsToFutureMergedIterator(futures, sorts);
}
private List<Future<QueryResultIterator<Entity>>> multiQueriesToFutureEntityIterators(
Collection<Query> queries)
{
final List<Future<QueryResultIterator<Entity>>> futures = new ArrayList<Future<QueryResultIterator<Entity>>>(queries.size());
Transaction txn = datastore.getTransaction();
for (Query query : queries)
{
AsyncPreparedQuery prepared = new AsyncPreparedQuery(query, txn);
Future<QueryResultIterator<Entity>> futureEntities;
FetchOptions fetchOptions = getRootCommand().getFetchOptions();
if (fetchOptions == null)
{
futureEntities = prepared.asFutureQueryResultIterator();
}
else
{
futureEntities = prepared.asFutureQueryResultIterator(fetchOptions);
}
futures.add(futureEntities);
}
return futures;
}
private Future<Iterator<Entity>> futureEntityIteratorsToFutureMergedIterator(
final List<Future<QueryResultIterator<Entity>>> futures, final List<SortPredicate> sorts)
{
return new Future<Iterator<Entity>>()
{
public boolean cancel(boolean mayInterruptIfRunning)
{
boolean success = true;
for (Future<QueryResultIterator<Entity>> future : futures)
{
if (future.cancel(mayInterruptIfRunning) == false)
{
success = false;
}
}
return success;
}
public Iterator<Entity> get() throws InterruptedException, ExecutionException
{
return futureQueriesToEntities(futures);
}
public Iterator<Entity> get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException
{
return futureQueriesToEntities(futures);
}
private Iterator<Entity> futureQueriesToEntities(
List<Future<QueryResultIterator<Entity>>> futures)
throws InterruptedException, ExecutionException
{
List<Iterator<Entity>> iterators = new ArrayList<Iterator<Entity>>(futures.size());
for (Future<QueryResultIterator<Entity>> future : futures)
{
Iterator<Entity> entities = future.get();
entities = applyEntityFilter(entities);
iterators.add(entities);
}
return mergeEntities(iterators, sorts);
}
public boolean isCancelled()
{
// only if all are canceled
for (Future<QueryResultIterator<Entity>> future : futures)
{
if (!future.isCancelled())
{
return false;
}
}
return true;
}
public boolean isDone()
{
// only if all are done
for (Future<QueryResultIterator<Entity>> future : futures)
{
if (!future.isDone())
{
return false;
}
}
return true;
}
};
}
// private final class KeyToInstanceFunction<T> implements Function<Entity, T>
// {
// private final Predicate<String> propertyPredicate;
//
// public KeyToInstanceFunction(Predicate<String> propertyPredicate)
// {
// this.propertyPredicate = propertyPredicate;
// }
//
// public T apply(Entity entity)
// {
// @SuppressWarnings("unchecked")
// T result = (T) datastore.keyToInstance(entity.getKey(), propertyPredicate);
// return result;
// }
// }
//
// private final class ParentKeyToInstanceFunction<T> implements Function<Entity, T>
// {
// private final Predicate<String> propertyPredicate;
//
// public ParentKeyToInstanceFunction(Predicate<String> propertyPredicate)
// {
// this.propertyPredicate = propertyPredicate;
// }
//
// public T apply(Entity entity)
// {
// @SuppressWarnings("unchecked")
// T result = (T) datastore.keyToInstance(entity.getKey().getParent(), propertyPredicate);
// return result;
// }
// }
public class FilteredIterator<V> extends AbstractIterator<V>
{
private final Iterator<V> unfiltered;
private final Predicate<V> predicate;
public FilteredIterator(Iterator<V> unfiltered, Predicate<V> predicate)
{
this.unfiltered = unfiltered;
this.predicate = predicate;
}
@Override
protected V computeNext()
{
while (unfiltered.hasNext())
{
V next = unfiltered.next();
if (predicate.apply(next))
{
return next;
}
}
return endOfData();
}
}
private class BasicQueryResultIterator<V> extends ForwardingIterator<V> implements QueryResultIterator<V>
{
private final Iterator<V> instances;
private final QueryResultIterator<Entity> entities;
public BasicQueryResultIterator(Iterator<V> instances, QueryResultIterator<Entity> entities)
{
this.instances = instances;
this.entities = entities;
}
@Override
protected Iterator<V> delegate()
{
return instances;
}
public Cursor getCursor()
{
return entities.getCursor();
}
}
public class ParentEntityIterator implements Iterator<Entity>
{
private final Iterator<Entity> children;
public ParentEntityIterator(Iterator<Entity> entities)
{
this.children = entities;
}
public boolean hasNext()
{
return children.hasNext();
}
public Entity next()
{
return datastore.keyToInstance(children.next().getKey(), new RestrictionToPredicateAdaptor<Property>(propertyPredicate));
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
| Java |
/**
*
*/
package com.vercer.engine.persist.standard;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.google.appengine.api.datastore.Key;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.engine.persist.util.SinglePropertySet;
import com.vercer.util.reference.ObjectReference;
import com.vercer.util.reference.ReadOnlyObjectReference;
class EntityTranslator implements PropertyTranslator
{
protected final StrategyObjectDatastore datastore;
private static final Logger logger = Logger.getLogger(EntityTranslator.class.getName());
/**
* @param strategyObjectDatastore
*/
EntityTranslator(StrategyObjectDatastore strategyObjectDatastore)
{
this.datastore = strategyObjectDatastore;
}
public Object propertiesToTypesafe(Set<Property> properties, Path prefix, Type type)
{
if (properties.isEmpty())
{
return NULL_VALUE;
}
Object value = PropertySets.firstValue(properties);
if (value instanceof Collection<?>)
{
@SuppressWarnings("unchecked")
List<Key> keys = (List<Key>) value;
Map<Key, Object> keysToInstances = this.datastore.keysToInstances(keys, null);
List<Object> result = new ArrayList<Object>();
// keep order the same as keys
Iterator<Key> iterator = keys.iterator();
while(iterator.hasNext())
{
Key key = iterator.next();
Object instance = keysToInstances.get(key);
if (instance != null)
{
result.add(instance);
iterator.remove();
}
else
{
logger.warning("No entity found for referenced key " + key);
}
}
return result;
}
else
{
Key key = (Key) value;
Object result = this.datastore.keyToInstance(key, null);
if (result == null)
{
result = NULL_VALUE;
logger.warning("No entity found for referenced key " + key);
}
return result;
}
}
public Set<Property> typesafeToProperties(final Object instance, final Path path, final boolean indexed)
{
if (instance== null)
{
return Collections.emptySet();
}
ObjectReference<?> item;
if (instance instanceof Collection<?>)
{
item = new ReadOnlyObjectReference<List<Key>>()
{
@Override
public List<Key> get()
{
// get keys for each item
List<?> instances = (List<?>) instance;
Map<?, Key> instancesToKeys = datastore.instancesToKeys(instances, getParentKey());
// need to make sure keys are in same order as original instances
List<Key> keys = new ArrayList<Key>(instances.size());
for (Object instance : instances)
{
keys.add(instancesToKeys.get(instance));
}
return keys;
}
};
}
else
{
// delay creating actual entity until all current fields have been encoded
item = new ReadOnlyObjectReference<Key>()
{
public Key get()
{
return datastore.instanceToKey(instance, getParentKey());
}
};
}
return new SinglePropertySet(path, item, indexed);
}
protected Key getParentKey()
{
return null;
}
} | Java |
package com.vercer.engine.persist.standard;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.vercer.engine.persist.FindCommand.ParentsCommand;
public abstract class StandardBaseParentsCommand<P> extends StandardBaseFindCommand<P, ParentsCommand<P>> implements ParentsCommand<P>
{
protected final StandardTypedFindCommand<?, ?> childCommand;
public StandardBaseParentsCommand(StandardTypedFindCommand<?, ?> command)
{
super(command.datastore);
this.childCommand = command;
}
public Future<Iterator<P>> returnParentsLater()
{
// TODO depends on async get being implemented
throw new UnsupportedOperationException("Not implemented yet - depends on async get");
}
/**
* @param childEntities
* @param source Allows a cache to be used to
* @return
*/
Iterator<Entity> childEntitiesToParentEntities(Iterator<Entity> childEntities, final Map<Key, Entity> cache)
{
childEntities = childCommand.applyEntityFilter(childEntities);
return new PrefetchParentIterator(childEntities, datastore, getFetchSize())
{
@Override
protected Map<Key, Entity> keysToEntities(List<Key> keys)
{
if (cache == null)
{
return super.keysToEntities(keys);
}
else
{
Map<Key, Entity> result = new HashMap<Key, Entity>(keys.size());
List<Key> missing = null;
for (Key key : keys)
{
Entity entity = cache.get(key);
if (entity != null)
{
result.put(key, entity);
}
else
{
if (missing == null)
{
missing = new ArrayList<Key>(keys.size());
}
missing.add(key);
}
}
if (missing != null)
{
Map<Key, Entity> entities = super.keysToEntities(missing);
Set<Entry<Key,Entity>> entrySet = entities.entrySet();
for (Entry<Key, Entity> entry : entrySet)
{
cache.put(entry.getKey(), entry.getValue());
}
result.putAll(entities);
}
return result;
}
}
};
}
protected int getFetchSize()
{
@SuppressWarnings("deprecation")
int fetch = FetchOptions.DEFAULT_CHUNK_SIZE;
FetchOptions fetchOptions = childCommand.getRootCommand().getFetchOptions();
if (fetchOptions != null)
{
if (fetchOptions.getChunkSize() != fetchOptions.getPrefetchSize())
{
throw new IllegalArgumentException("Must have same fetchFirst and fetchNextBy to get parents");
}
fetch = fetchOptions.getChunkSize();
}
return fetch;
}
} | Java |
package com.vercer.engine.persist.standard;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
import com.vercer.engine.persist.ObjectDatastore;
public abstract class BaseObjectDatastore implements ObjectDatastore
{
private DatastoreService service;
private Transaction transaction;
public BaseObjectDatastore()
{
this(DatastoreServiceConfig.Builder.withDefaults());
}
public BaseObjectDatastore(DatastoreServiceConfig config)
{
setConfiguration(config);
}
public void setConfiguration(DatastoreServiceConfig config)
{
this.service = newDatastoreService(config);
}
protected DatastoreService newDatastoreService(DatastoreServiceConfig config)
{
return DatastoreServiceFactory.getDatastoreService(config);
}
protected final Key servicePut(Entity entity)
{
if (transaction == null)
{
return service.put(entity);
}
else
{
return service.put(transaction, entity);
}
}
protected final List<Key> servicePut(Iterable<Entity> entities)
{
if (transaction == null)
{
return service.put(entities);
}
else
{
return service.put(transaction, entities);
}
}
protected final PreparedQuery servicePrepare(Query query)
{
if (transaction == null)
{
return service.prepare(query);
}
else
{
return service.prepare(transaction, query);
}
}
protected final void serviceDelete(Collection<Key> keys)
{
if (transaction == null)
{
service.delete(keys);
}
else
{
service.delete(transaction, keys);
}
}
protected final Entity serviceGet(Key key) throws EntityNotFoundException
{
if (transaction == null)
{
return service.get(key);
}
else
{
return service.get(transaction, key);
}
}
protected final Map<Key, Entity> serviceGet(Iterable<Key> keys)
{
if (transaction == null)
{
return service.get(keys);
}
else
{
return service.get(transaction, keys);
}
}
public final Transaction getTransaction()
{
return transaction;
}
public final Transaction beginTransaction()
{
if (getTransaction() != null && getTransaction().isActive())
{
throw new IllegalStateException("Already in active transaction");
}
transaction = service.beginTransaction();
return transaction;
}
public final void removeTransaction()
{
transaction = null;
}
}
| Java |
package com.vercer.engine.persist.standard;
import com.vercer.engine.persist.strategy.CombinedStrategy;
public class StandardObjectDatastore extends StrategyObjectDatastore
{
public StandardObjectDatastore(CombinedStrategy strategy)
{
super(strategy);
}
}
| Java |
package com.vercer.engine.persist.standard;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.vercer.util.reference.ObjectReference;
import com.vercer.util.reference.ReadOnlyObjectReference;
import com.vercer.util.reference.SimpleObjectReference;
public class KeySpecification
{
private String kind;
private ObjectReference<Key> parentKeyReference;
private String name;
private Long id;
public KeySpecification()
{
}
public KeySpecification(String kind, Key parentKey, String name)
{
this.kind = kind;
this.name = name;
this.parentKeyReference = parentKey == null ? null : new SimpleObjectReference<Key>(parentKey);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Long getId()
{
return id;
}
public String getKind()
{
return kind;
}
public void setKind(String kind)
{
this.kind = kind;
}
public void setParentKeyReference(ObjectReference<Key> parentKeyReference)
{
this.parentKeyReference = parentKeyReference;
}
public ObjectReference<Key> getParentKeyReference()
{
return parentKeyReference;
}
public boolean isComplete()
{
return kind != null && (name != null || id != null);
}
public Key toKey()
{
if (isComplete())
{
if (parentKeyReference == null)
{
if (id == null)
{
return KeyFactory.createKey(kind, name);
}
else
{
return KeyFactory.createKey(kind, id);
}
}
else
{
if (id == null)
{
return KeyFactory.createKey(parentKeyReference.get(), kind, name);
}
else
{
return KeyFactory.createKey(parentKeyReference.get(), kind, id);
}
}
}
else
{
throw new IllegalStateException("Key specification is incomplete. "
+ " You may need to define a key name for this or its parent instance");
}
}
public ObjectReference<Key> toObjectReference()
{
return new ReadOnlyObjectReference<Key>()
{
public Key get()
{
return toKey();
}
};
}
public void merge(KeySpecification specification)
{
// fill in any blanks with info we have gathered from the instance
// fields
if (parentKeyReference == null)
{
parentKeyReference = specification.parentKeyReference;
}
if (name == null)
{
name = specification.name;
}
if (id == null)
{
id = specification.id;
}
if (kind == null)
{
kind = specification.kind;
}
}
public void setId(Long id)
{
this.id = id;
}
}
| Java |
package com.vercer.engine.persist;
import java.util.Collection;
public interface Activator
{
void activate(Object... instances);
void activateAll(Collection<?> instances);
}
| Java |
/**
*
*/
package com.vercer.engine.persist;
public interface Property extends Comparable<Property>
{
Path getPath();
Object getValue();
boolean isIndexed();
} | Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.engine.persist.util.SinglePropertySet;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
public abstract class AbstractTypeTranslator<T> implements PropertyTranslator
{
private final Class<T> clazz;
public AbstractTypeTranslator(Class<T> clazz)
{
this.clazz = clazz;
}
protected abstract T decode(Object value);
protected abstract Object encode(T value);
public final Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
if (GenericTypeReflector.erase(type) == clazz)
{
return decode(PropertySets.firstValue(properties));
}
else
{
return null;
}
}
@SuppressWarnings("unchecked")
public final Set<Property> typesafeToProperties(Object instance, Path path, boolean indexed)
{
if (clazz.isInstance(instance))
{
return new SinglePropertySet(path, encode((T) instance), indexed);
}
else
{
return null;
}
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.util.SimpleProperty;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
public class EnumTranslator implements PropertyTranslator
{
@SuppressWarnings("unchecked")
public Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
Class<?> clazz = GenericTypeReflector.erase(type);
if (clazz.isEnum())
{
Property property = properties.iterator().next();
String name = (String) property.getValue();
Class<? extends Enum> ce = (Class<? extends Enum>) clazz;
return Enum.valueOf(ce, name);
}
else
{
return null;
}
}
public Set<Property> typesafeToProperties(Object object, Path path, boolean indexed)
{
if (object instanceof Enum<?>)
{
String name = ((Enum<?>) object).name();
Property property = new SimpleProperty(path, name, indexed);
return Collections.singleton(property);
}
else
{
return null;
}
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.engine.persist.util.SinglePropertySet;
public class DirectTranslator implements PropertyTranslator
{
public Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
if (isDirectType(type))
{
if (properties.isEmpty())
{
return NULL_VALUE;
}
return PropertySets.firstValue(properties);
}
else
{
return null;
}
}
protected boolean isDirectType(Type type)
{
return true;
}
public Set<Property> typesafeToProperties(Object object, Path path, boolean indexed)
{
if (isDirectType(object.getClass()))
{
return new SinglePropertySet(path, object, indexed);
}
else
{
return null;
}
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;
import com.google.appengine.api.datastore.Blob;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.conversion.DefaultTypeConverter;
import com.vercer.engine.persist.conversion.DefaultTypeConverter.BlobToAnything;
import com.vercer.engine.persist.conversion.DefaultTypeConverter.SerializableToBlob;
import com.vercer.engine.persist.util.SimpleProperty;
public class SerializingTranslator implements PropertyTranslator
{
private final BlobToAnything blobToSerializable = new DefaultTypeConverter.BlobToAnything();
private final SerializableToBlob serializableToBlob = new DefaultTypeConverter.SerializableToBlob();
public final Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
try
{
Property property = properties.iterator().next();
if (property.getValue() instanceof Blob)
{
Blob blob = (Blob) property.getValue();
return blobToSerializable.convert(blob);
}
else
{
return null;
}
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
public final Set<Property> typesafeToProperties(Object object, Path path, boolean indexed)
{
try
{
if (object instanceof Serializable)
{
Blob blob = serializableToBlob.convert((Serializable) object);
return Collections.singleton((Property) new SimpleProperty(path, blob, indexed));
}
else
{
return null;
}
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.Path.Part;
import com.vercer.engine.persist.conversion.TypeConverter;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.engine.persist.util.PropertySets.PrefixPropertySet;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
import com.vercer.util.collections.MergeSet;
public class MapTranslator extends DecoratingTranslator
{
private final TypeConverter converter;
public MapTranslator(PropertyTranslator delegate, TypeConverter converter)
{
super(delegate);
this.converter = converter;
}
@Override
public Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
// only try if we can set a map to the field
if (!GenericTypeReflector.erase(type).isAssignableFrom(HashMap.class))
{
// pass on all other types down the chain
return chained.propertiesToTypesafe(properties, path, type);
}
if (properties.isEmpty())
{
return NULL_VALUE;
}
// group the properties by prefix to create each item
Collection<PrefixPropertySet> ppss = PropertySets.prefixPropertySets(properties, path);
// find the types of the key and value from the generic parameters
Type exact = GenericTypeReflector.getExactSuperType(type, Map.class);
Type keyType = ((ParameterizedType) exact).getActualTypeArguments()[0];
Type valueType = ((ParameterizedType) exact).getActualTypeArguments()[1];
// type erasure means we can use object as the generic parameters
Map<Object, Object> result = new HashMap<Object, Object>(ppss.size());
for (PrefixPropertySet pps : ppss)
{
// the key must be converted from a String
Part partAfterPrefix = pps.getPrefix().firstPartAfterPrefix(path);
Object key = converter.convert(partAfterPrefix.getName(), keyType);
// decode the value properties using the generic type info
Object value = chained.propertiesToTypesafe(pps.getProperties(), pps.getPrefix(), valueType);
result.put(key, value);
}
return result;
}
@Override
public Set<Property> typesafeToProperties(Object instance, Path path, boolean indexed)
{
if (instance instanceof Map<?, ?> == false)
{
// pass it on down the line
return chained.typesafeToProperties(instance, path, indexed);
}
Map<?, ?> map = (Map<?, ?>) instance;
Set<?> keys = map.keySet();
Set<Property> merged = new MergeSet<Property>(map.size());
for (Object key: keys)
{
Object value = map.get(key);
String keyString = converter.convert(key, String.class);
Path childPath = Path.builder(path).field(keyString).build();
Set<Property> properties = chained.typesafeToProperties(value, childPath, indexed);
if (properties == null)
{
// we could not handle a value so pass the whole map down the chain
return chained.typesafeToProperties(instance, path, indexed);
}
merged.addAll(properties);
}
return merged;
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.Set;
import com.google.common.base.Predicates;
import com.google.common.collect.Sets;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.strategy.FieldStrategy;
import com.vercer.engine.persist.util.PathPrefixPredicate;
import com.vercer.engine.persist.util.SimpleProperty;
import com.vercer.util.collections.PrependSet;
public class PolymorphicTranslator extends DecoratingTranslator
{
private static final String CLASS_NAME = "class";
private final FieldStrategy strategy;
public PolymorphicTranslator(PropertyTranslator chained, FieldStrategy strategy)
{
super(chained);
this.strategy = strategy;
}
public Object propertiesToTypesafe(Set<Property> properties, final Path prefix, Type type)
{
String kindName = null;
Path kindNamePath = new Path.Builder(prefix).meta(CLASS_NAME).build();
for (Property property : properties)
{
if (property.getPath().equals(kindNamePath))
{
kindName = (String) property.getValue();
break;
}
}
// there may be no polymorphic field
if (kindName != null)
{
// filter out the class name
properties = Sets.filter(properties, Predicates.not(new PathPrefixPredicate(kindNamePath)));
type = strategy.kindToType(kindName);
}
return chained.propertiesToTypesafe(properties, prefix, type);
}
//
// protected Type className(Set<Property> properties, Path prefix)
// {
// Path classNamePath = new Path.Builder(prefix).field(CLASS_NAME).build();
// for (Property property : properties)
// {
// if (property.getPath().equals(classNamePath))
// {
// String className = (String) property.getValue();
// try
// {
// return Class.forName(className);
// }
// catch (ClassNotFoundException e)
// {
// throw new IllegalStateException(e);
// }
// }
// }
// throw new IllegalStateException("Could not find class name");
// }
public Set<Property> typesafeToProperties(Object object, Path prefix, boolean indexed)
{
Set<Property> properties = chained.typesafeToProperties(object, prefix, indexed);
String className = object.getClass().getName();
Path classNamePath = new Path.Builder(prefix).meta(CLASS_NAME).build();
Property property = new SimpleProperty(classNamePath, className, true);
return new PrependSet<Property>(property, properties);
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import com.google.appengine.api.datastore.Blob;
import com.google.common.collect.Lists;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.Path.Part;
import com.vercer.engine.persist.conversion.DefaultTypeConverter.BlobToAnything;
import com.vercer.engine.persist.conversion.DefaultTypeConverter.SerializableToBlob;
import com.vercer.engine.persist.standard.StrategyObjectDatastore;
import com.vercer.engine.persist.util.SimpleProperty;
import com.vercer.engine.persist.util.SinglePropertySet;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
public class ListTranslator extends DecoratingTranslator
{
public ListTranslator(PropertyTranslator chained)
{
super(chained);
}
public Object propertiesToTypesafe(final Set<Property> properties, final Path path, Type type)
{
// only handle lists
if (!GenericTypeReflector.erase(type).isAssignableFrom(ArrayList.class))
{
// pass on all other types down the chain
return chained.propertiesToTypesafe(properties, path, type);
}
if (properties.isEmpty())
{
return NULL_VALUE;
}
// need to adapt a set of property lists into a list of property sets
List<Set<Property>> propertySets = Lists.newArrayList();
boolean complete = false;
for (int index = 0; !complete; index++)
{
complete = true;
Set<Property> result = new HashSet<Property>(properties.size());
for (Property property : properties)
{
List<?> values;
Path itemPath = property.getPath();
Object list = property.getValue();
// every property should be of the same type but just repeat check
if (list instanceof List<?>)
{
// we have a list of property values
values = (List<?>) list;
}
else
{
// we could not handle this value so pass the whole thing down the line
return chained.propertiesToTypesafe(properties, path, type);
}
if (values.size() > index)
{
Object value = values.get(index);
// null values are place holders for missing properties
if (value != null)
{
result.add(new SimpleProperty(itemPath, value, true));
}
// at least one property has items so we are not done yet
complete = false;
}
}
if (complete == false)
{
propertySets.add(result);
}
}
// handles the tricky task of finding what type of list we have
Type exact = GenericTypeReflector.getExactSuperType(type, List.class);
Type componentType = ((ParameterizedType) exact).getActualTypeArguments()[0];
// decode each item of the list
List<Object> objects = new ArrayList<Object>();
for (Set<Property> itemProperties : propertySets)
{
Object convertedChild = chained.propertiesToTypesafe(itemProperties, path, componentType);
// if we cannot convert every member of the list we fail
if (convertedChild == null)
{
return null;
}
objects.add(convertedChild);
}
// result will be converted to actual collection or array type
return objects;
}
public Set<Property> typesafeToProperties(Object object, Path path, final boolean indexed)
{
if (object instanceof List<?>)
{
List<?> list = (List<?>) object;
if (list.isEmpty())
{
return Collections.emptySet();
}
final Map<Path, List<Object>> lists = new HashMap<Path, List<Object>>(8);
int count = 0;
for (Object item : list)
{
if (item != null)
{
Set<Property> properties = chained.typesafeToProperties(item, path, indexed);
if (properties == null)
{
// we could not handle so continue up the chain
return chained.typesafeToProperties(object, path, indexed);
}
for (Property property : properties)
{
Object value = property.getValue();
Path itemPath = property.getPath();
List<Object> values = lists.get(itemPath);
if (values == null)
{
values = new ArrayList<Object>(4);
lists.put(itemPath, values);
}
// need to pad the list with nulls if any values are missing
while (values.size() < count)
{
values.add(null);
}
values.add(value);
}
}
else
{
Collection<List<Object>> values = lists.values();
for (List<Object> value : values)
{
value.add(null);
}
}
count++;
}
// optimise for case of single properties
if (lists.size() == 1)
{
Path childPath = lists.keySet().iterator().next();
List<?> values = lists.get(childPath);
return new SinglePropertySet(childPath, values, indexed);
}
else
{
return new AbstractSet<Property>()
{
@Override
public Iterator<Property> iterator()
{
return new Iterator<Property>()
{
Iterator<Entry<Path, List<Object>>> iterator = lists.entrySet().iterator();
public boolean hasNext()
{
return iterator.hasNext();
}
public Property next()
{
Entry<Path, List<Object>> next = iterator.next();
return new SimpleProperty(next.getKey(), next.getValue(), indexed);
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public int size()
{
return lists.size();
}
};
}
}
else
{
// we could not handle value as a collection so continue up the chain
return chained.typesafeToProperties(object, path, indexed);
}
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Currency;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.engine.persist.util.SinglePropertySet;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
public class CoreStringTypesTranslator implements PropertyTranslator
{
public Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
if (properties.isEmpty())
{
return NULL_VALUE;
}
Class<?> erased = GenericTypeReflector.erase(type);
if (erased == Locale.class)
{
String locale = PropertySets.firstValue(properties);
String[] parts = locale.split("_", -1);
return new Locale(parts[0], parts[1], parts[2]);
}
else if (Class.class.isAssignableFrom(erased))
{
String name = PropertySets.firstValue(properties);
try
{
return Class.forName(name);
}
catch (ClassNotFoundException e)
{
throw new IllegalStateException(e);
}
}
else if (Currency.class == erased)
{
String name = PropertySets.firstValue(properties);
return Currency.getInstance(name);
}
else if (URI.class == erased)
{
String name = PropertySets.firstValue(properties);
try
{
return new URI(name);
}
catch (URISyntaxException e)
{
throw new IllegalStateException(e);
}
}
else if (URL.class == erased)
{
String name = PropertySets.firstValue(properties);
try
{
return new URL(name);
}
catch (MalformedURLException e)
{
throw new IllegalStateException(e);
}
}
return null;
}
public Set<Property> typesafeToProperties(Object instance, Path path, boolean indexed)
{
if (instance instanceof Locale)
{
Locale locale = (Locale) instance;
String text = locale.getLanguage() + "_" + locale.getCountry() + "_" + locale.getVariant();
return new SinglePropertySet(path, text, indexed);
}
else if (instance instanceof Class<?>)
{
String name = ((Class<?>) instance).getName();
return new SinglePropertySet(path, name, indexed);
}
else if (instance instanceof Currency)
{
String name = ((Currency) instance).getCurrencyCode();
return new SinglePropertySet(path, name, indexed);
}
else if (instance instanceof URI)
{
String name = ((URI) instance).toString();
return new SinglePropertySet(path, name, indexed);
}
else if (instance instanceof URL)
{
String name = ((URL) instance).toString();
return new SinglePropertySet(path, name, indexed);
}
return null;
}
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.util.SinglePropertySet;
import com.vercer.util.reference.ObjectReference;
import com.vercer.util.reference.ReadOnlyObjectReference;
public class DelayedTranslator extends DecoratingTranslator
{
public DelayedTranslator(PropertyTranslator chained)
{
super(chained);
}
public Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
return chained.propertiesToTypesafe(properties, path, type);
}
public Set<Property> typesafeToProperties(final Object object, final Path path, final boolean indexed)
{
ObjectReference<Object> reference = new ReadOnlyObjectReference<Object>()
{
public Object get()
{
Set<Property> properties = chained.typesafeToProperties(object, path, indexed);
return properties.iterator().next().getValue();
}
};
return new SinglePropertySet(path, reference, indexed);
}
}
| Java |
package com.vercer.engine.persist.translator;
import com.vercer.engine.persist.PropertyTranslator;
public abstract class DecoratingTranslator implements PropertyTranslator
{
protected final PropertyTranslator chained;
public DecoratingTranslator(PropertyTranslator chained)
{
this.chained = chained;
}
} | Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
import com.vercer.engine.persist.conversion.TypeConverter;
import com.vercer.engine.persist.util.PropertySets;
import com.vercer.engine.persist.util.SimpleProperty;
import com.vercer.engine.persist.util.PropertySets.PrefixPropertySet;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
import com.vercer.util.Reflection;
import com.vercer.util.collections.MergeSet;
/**
* @author John Patterson <john@vercer.com>
*
*/
public abstract class ObjectFieldTranslator implements PropertyTranslator
{
private static final Comparator<Field> comparator = new Comparator<Field>()
{
public int compare(Field o1, Field o2)
{
return o1.getName().compareTo(o2.getName());
}
};
private final TypeConverter converters;
// permanent cache of class fields to reduce reflection
private static Map<Class<?>, List<Field>> classFields = new ConcurrentHashMap<Class<?>, List<Field>>();
private static Map<Class<?>, Constructor<?>> constructors = new ConcurrentHashMap<Class<?>, Constructor<?>>();
public ObjectFieldTranslator(TypeConverter converters)
{
this.converters = converters;
}
public final Object propertiesToTypesafe(Set<Property> properties, Path path, Type type)
{
Class<?> clazz = GenericTypeReflector.erase(type);
Object instance = createInstance(clazz);
activate(properties, instance, path);
return instance;
}
protected void activate(Set<Property> properties, Object instance, Path path)
{
// ensure the properties are sorted
if (properties instanceof SortedSet<?> == false)
{
properties = new TreeSet<Property>(properties);
}
// both fields and properties are sorted by name
List<Field> fields = getSortedFields(instance);
Iterator<PrefixPropertySet> ppss = PropertySets.prefixPropertySets(properties, path).iterator();
PrefixPropertySet pps = null;
for (Field field : fields)
{
if (stored(field))
{
String name = fieldToPartName(field);
Path fieldPath = new Path.Builder(path).field(name).build();
// handle missing class fields by ignoring the properties
while (ppss.hasNext() && (pps == null || pps.getPrefix().compareTo(fieldPath) < 0))
{
pps = ppss.next();
}
// if there are no properties for the field we must still
// run a translator because some translators do not require
// any fields to set a field value e.g. KeyTranslator
Set<Property> childProperties;
if (pps == null || !fieldPath.equals(pps.getPrefix()))
{
// there were no properties for this field
childProperties = Collections.emptySet();
}
else
{
childProperties = pps.getProperties();
}
// get the correct translator for this field
PropertyTranslator translator = decoder(field, childProperties);
// get the type that we need to store
Type type = typeFromField(field);
onBeforeTranslate(field, childProperties);
// create instance
Object value;
try
{
value = translator.propertiesToTypesafe(childProperties, fieldPath, type);
}
catch (Exception e)
{
// add a bit of context to the trace
throw new IllegalStateException("Problem translating field " + field, e);
}
onAfterTranslate(field, value);
if (value == null)
{
throw new IllegalStateException("Could not translate path " + fieldPath);
}
if (value == NULL_VALUE)
{
value = null;
}
setFieldValue(instance, field, value);
}
}
}
private void setFieldValue(Object instance, Field field, Object value)
{
// check for a default implementations of collections and reuse
if (Collection.class.isAssignableFrom(field.getType()))
{
try
{
// see if there is a default value
Collection<?> existing = (Collection<?>) field.get(instance);
if (existing != null && value!= null && existing.getClass() != value.getClass())
{
// make sure the value is a list - could be a blob
value = converters.convert(value, ArrayList.class);
existing.clear();
typesafeAddAll((Collection<?>) value, existing);
return;
}
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
else if (Map.class.isAssignableFrom(field.getType()))
{
try
{
// see if there is a default value
Map<?, ?> existing = (Map<?, ?>) field.get(instance);
if (existing != null && value!= null && existing.getClass() != value.getClass())
{
// make sure the value is a map - could be a blob
value = converters.convert(value, HashMap.class);
existing.clear();
typesafePutAll((Map<?, ?>) value, existing);
return;
}
}
catch (Exception e)
{
throw new IllegalStateException(e);
}
}
// the stored type may not be the same as the declared type
// due to the ability to define what type to store an instance
// as using FieldTypeStrategy.type(Field) or @Type annotation
// convert value to actual field type before setting
value = converters.convert(value, field.getGenericType());
try
{
field.set(instance, value);
}
catch (Exception e)
{
throw new IllegalStateException("Could not set value " + value + " to field " + field, e);
}
}
@SuppressWarnings("unchecked")
private <K, V> void typesafePutAll(Map<?, ?> value, Map<?, ?> existing)
{
((Map<K, V>) existing).putAll((Map<K, V>) value);
}
@SuppressWarnings("unchecked")
private <T> void typesafeAddAll(Collection<?> value, Collection<?> existing)
{
((Collection<T>) existing).addAll((Collection<T>) value);
}
protected void onAfterTranslate(Field field, Object value)
{
}
protected void onBeforeTranslate(Field field, Set<Property> childProperties)
{
}
protected String fieldToPartName(Field field)
{
return field.getName();
}
protected Type typeFromField(Field field)
{
return field.getType();
}
protected Object createInstance(Class<?> clazz)
{
try
{
Constructor<?> constructor = getNoArgsConstructor(clazz);
return constructor.newInstance();
}
catch (NoSuchMethodException e)
{
throw new IllegalArgumentException("Could not find no args constructor in " + clazz, e);
}
catch (Exception e)
{
throw new IllegalArgumentException("Could not construct instance of " + clazz, e);
}
}
private Constructor<?> getNoArgsConstructor(Class<?> clazz) throws NoSuchMethodException
{
Constructor<?> constructor = constructors.get(clazz);
if (constructor == null)
{
// use no-args constructor
constructor = clazz.getDeclaredConstructor();
// allow access to private constructor
if (!constructor.isAccessible())
{
constructor.setAccessible(true);
}
constructors.put(clazz, constructor);
}
return constructor;
}
public final Set<Property> typesafeToProperties(Object object, Path path, boolean indexed)
{
if (object == null)
{
return Collections.emptySet();
}
try
{
List<Field> fields = getSortedFields(object);
MergeSet<Property> merged = new MergeSet<Property>(fields.size());
for (Field field : fields)
{
if (stored(field))
{
// get the type that we need to store
Type type = typeFromField(field);
// we may need to convert the object if it is not assignable
Object value = field.get(object);
if (value == null)
{
if (isNullStored())
{
merged.add(new SimpleProperty(path, null, indexed));
}
continue;
}
value = converters.convert(value, type);
Path childPath = new Path.Builder(path).field(fieldToPartName(field)).build();
PropertyTranslator translator = encoder(field, value);
Set<Property> properties = translator.typesafeToProperties(value, childPath, indexed(field));
if (properties == null)
{
throw new IllegalStateException("Could not translate value to properties: " + value);
}
merged.addAll(properties);
}
}
return merged;
}
catch (IllegalAccessException e)
{
throw new IllegalStateException(e);
}
}
private List<Field> getSortedFields(Object object)
{
// fields are cached and stored as a map because reading more common than writing
List<Field> fields = classFields.get(object.getClass());
if (fields == null)
{
fields = Reflection.getAccessibleFields(object.getClass());
// sort the fields by name
Collections.sort(fields, comparator);
// cache because reflection is costly
classFields.put(object.getClass(), fields);
}
return fields;
}
protected boolean isNullStored()
{
return false;
}
protected abstract boolean indexed(Field field);
protected abstract boolean stored(Field field);
protected abstract PropertyTranslator encoder(Field field, Object instance);
protected abstract PropertyTranslator decoder(Field field, Set<Property> properties);
}
| Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
public abstract class InstanceTranslator implements PropertyTranslator
{
public Object propertiesToTypesafe(Set<Property> properties, Path prefix, Type type)
{
return getInstance();
}
protected abstract Object getInstance();
public Set<Property> typesafeToProperties(Object object, Path prefix, boolean indexed)
{
return Collections.singleton(getProperty());
}
protected abstract Property getProperty();
}
| Java |
/**
*
*/
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import com.google.appengine.api.datastore.DataTypeUtils;
import com.vercer.engine.persist.util.generic.GenericTypeReflector;
public final class NativeDirectTranslator extends DirectTranslator
{
@Override
protected boolean isDirectType(Type type)
{
// get the non-parameterised class
Class<?> clazz = GenericTypeReflector.erase(type);
return clazz.isPrimitive() || DataTypeUtils.isSupportedType(clazz);
}
} | Java |
package com.vercer.engine.persist.translator;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.PropertyTranslator;
public class ChainedTranslator implements PropertyTranslator
{
private final List<PropertyTranslator> translators;
public ChainedTranslator(PropertyTranslator... translators)
{
this.translators = new ArrayList<PropertyTranslator>(Arrays.asList(translators));
}
public ChainedTranslator()
{
this.translators = new ArrayList<PropertyTranslator>(4);
}
public PropertyTranslator append(PropertyTranslator translator)
{
this.translators.add(translator);
return this;
}
public PropertyTranslator prepend(PropertyTranslator translator)
{
this.translators.add(0, translator);
return this;
}
public Iterator<PropertyTranslator> translators()
{
return translators.iterator();
}
public Set<Property> typesafeToProperties(Object object, Path prefix, boolean indexed)
{
for (PropertyTranslator translator : translators)
{
Set<Property> result = translator.typesafeToProperties(object, prefix, indexed);
if (result != null)
{
return result;
}
}
return null;
}
public Object propertiesToTypesafe(Set<Property> properties, Path prefix, Type type)
{
for (PropertyTranslator translator: translators)
{
Object result = translator.propertiesToTypesafe(properties, prefix, type);
if (result != null)
{
return result;
}
}
return null;
}
} | Java |
package com.vercer.engine.persist;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Future;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.SortDirection;
public interface FindCommand
{
enum MergeOperator { OR, AND };
<T> RootFindCommand<T> type(Class<T> type);
interface BaseFindCommand<C extends BaseFindCommand<C>>
{
C restrictEntities(Restriction<Entity> restriction);
C restrictProperties(Restriction<Property> restriction);
}
interface TypedFindCommand<T, C extends TypedFindCommand<T, C>> extends BaseFindCommand<C>
{
C addFilter(String field, FilterOperator operator, Object value);
C addRangeFilter(String field, Object from, Object to);
BranchFindCommand<T> branch(MergeOperator operator);
}
interface BranchFindCommand<T>
{
ChildFindCommand<T> addChildCommand();
}
interface ChildFindCommand<T> extends TypedFindCommand<T, ChildFindCommand<T>>
{
}
/**
* @author John Patterson <john@vercer.com>
*
* @param <T>
*/
interface RootFindCommand<T> extends TypedFindCommand<T, RootFindCommand<T>>
{
// methods that have side effects
/**
* Passed to {@link Query#addSort(String)}
* @param field The name of the class field to sort on
* @return <code>this</code> for method chaining
*/
RootFindCommand<T> addSort(String field);
/**
* Passed to {@link Query#addSort(String, SortDirection)}
* @param field The name of the class field to sort on
* @param sort Direction of sort
* @return <code>this</code> for method chaining
*/
RootFindCommand<T> addSort(String field, SortDirection sort);
/**
* @param ancestor Passed to {@link Query#setAncestor(com.google.appengine.api.datastore.Key)}
* @return <code>this</code> for method chaining
*/
RootFindCommand<T> ancestor(Object ancestor);
/**
* @param offset Set as {@link FetchOptions#offset(int)}
* @return <code>this</code> for method chaining
*/
RootFindCommand<T> startFrom(int offset);
/**
* @param cursor Set as {@link FetchOptions#startCursor(Cursor)}
* @return <code>this</code> for method chaining
*/
RootFindCommand<T> continueFrom(Cursor cursor);
/**
* @param cursor set as {@link FetchOptions#endCursor(Cursor)}
* @return <code>this</code> for method chaining
*/
RootFindCommand<T> finishAt(Cursor cursor);
RootFindCommand<T> maximumResults(int limit);
RootFindCommand<T> fetchNoFields();
RootFindCommand<T> fetchNextBy(int size);
RootFindCommand<T> fetchFirst(int size);
// terminating methods
int countResultsNow();
QueryResultIterator<T> returnResultsNow();
List<T> returnAllResultsNow();
Future<QueryResultIterator<T>> returnResultsLater();
Future<? extends List<T>> returnAllResultsLater();
<P> Iterator<P> returnParentsNow();
<P> ParentsCommand<P> returnParentsCommandNow();
<P> Future<ParentsCommand<P>> returnParentsCommandLater();
}
interface ParentsCommand<P> extends BaseFindCommand<ParentsCommand<P>>
{
Iterator<P> returnParentsNow();
// Future<Iterator<P>> returnParentsLater();
}
}
| Java |
/**
*
*/
package com.vercer.engine.persist.util;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
public final class PropertyMapToSet extends AbstractSet<Property>
{
private final Map<String, Object> properties;
private final boolean indexed;
public PropertyMapToSet(Map<String, Object> properties, boolean indexed)
{
this.properties = properties;
this.indexed = indexed;
}
@Override
public Iterator<Property> iterator()
{
final Iterator<Entry<String, Object>> iterator = properties.entrySet().iterator();
return new Iterator<Property>()
{
public boolean hasNext()
{
return iterator.hasNext();
}
public Property next()
{
Entry<String, Object> next = iterator.next();
return new SimpleProperty(new Path(next.getKey()), next.getValue(), indexed);
}
public void remove()
{
iterator.remove();
}
};
}
@Override
public int size()
{
return properties.size();
}
} | Java |
package com.vercer.engine.persist.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
import com.google.common.collect.PeekingIterator;
public class SortedMergeIterator<T> extends AbstractIterator<T>
{
private final Comparator<T> comparator;
private LinkedList<PeekingIterator<T>> peekings;
private final boolean dedup;
public SortedMergeIterator(Comparator<T> comparator, Collection<Iterator<T>> iterators, boolean ignoreDuplicates)
{
this.comparator = comparator;
this.dedup = ignoreDuplicates;
peekings = new LinkedList<PeekingIterator<T>>();
for (Iterator<T> iterator : iterators)
{
if (iterator.hasNext())
{
PeekingIterator<T> peeking = Iterators.peekingIterator(iterator);
peekings.add(peeking);
}
}
Collections.sort(peekings, pc);
}
@Override
protected T computeNext()
{
if (peekings.isEmpty())
{
return endOfData();
}
T next = removeTop();
// discard duplicates
if (dedup)
{
while (peekings.size() > 0 && peekings.getFirst().peek().equals(next))
{
removeTop();
}
}
return next;
}
private T removeTop()
{
PeekingIterator<T> top = peekings.getFirst();
T next = top.next(); // step forward the top iterator
if (!top.hasNext())
{
peekings.removeFirst();
}
Collections.sort(peekings, pc);
return next;
}
Comparator<PeekingIterator<T>> pc = new Comparator<PeekingIterator<T>>()
{
public int compare(PeekingIterator<T> o1, PeekingIterator<T> o2)
{
int compare = comparator.compare(o1.peek(), o2.peek());
return compare;
}
};
}
| Java |
package com.vercer.engine.persist.util;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Set;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterators;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
public class PrefixFilteringPropertySet extends AbstractSet<Property>
{
private final Set<Property> properties;
private final Path prefix;
public PrefixFilteringPropertySet(Path prefix, Set<Property> properties)
{
this.prefix = prefix;
this.properties = properties;
}
@Override
public Iterator<Property> iterator()
{
return Iterators.filter(properties.iterator(), new Predicate<Property>()
{
public boolean apply(Property source)
{
Path path = source.getPath();
return path.equals(prefix) || path.hasPrefix(prefix);
}
});
}
@Override
public int size()
{
return Iterators.size(iterator());
}
@Override
public boolean isEmpty()
{
return !iterator().hasNext();
}
}
| Java |
package com.vercer.engine.persist.util;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.util.Reflection;
public class SimpleProperty implements Property
{
protected Object value;
private final Path path;
private final boolean indexed;
public SimpleProperty(Path path, Object value, boolean indexed)
{
this.path = path;
this.value = value;
this.indexed = indexed;
}
public Path getPath()
{
return this.path;
}
public Object getValue()
{
return this.value;
}
public boolean isIndexed()
{
return indexed;
}
@Override
public String toString()
{
return Reflection.toString(this);
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (indexed ? 1231 : 1237);
result = prime * result + ((path == null) ? 0 : path.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (!(obj instanceof SimpleProperty))
{
return false;
}
SimpleProperty other = (SimpleProperty) obj;
if (indexed != other.indexed)
{
return false;
}
if (path == null)
{
if (other.path != null)
{
return false;
}
}
else if (!path.equals(other.path))
{
return false;
}
if (value == null)
{
if (other.value != null)
{
return false;
}
}
else if (!value.equals(other.value))
{
return false;
}
return true;
}
@SuppressWarnings("unchecked")
public int compareTo(Property o)
{
int pathComparison = path.compareTo(o.getPath());
if (pathComparison != 0)
{
return pathComparison;
}
else if (value instanceof Comparable<?>)
{
return ((Comparable) value).compareTo(o.getValue());
}
else
{
throw new IllegalArgumentException("Cannot compare " + o);
}
}
}
| Java |
package com.vercer.engine.persist.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
import com.vercer.engine.persist.Path.Part;
import com.vercer.util.collections.ArraySortedSet;
public class PropertySets
{
@SuppressWarnings("unchecked")
public static <T> T firstValue(Set<Property> properties)
{
if (properties instanceof SinglePropertySet)
{
// optimised case for our own implementation
return (T) ((SinglePropertySet) properties).getValue();
}
else
{
Iterator<Property> iterator = properties.iterator();
Property property = iterator.next();
if (property == null)
{
return null;
}
else
{
return (T) property.getValue();
}
}
}
public static class PrefixPropertySet
{
private Path prefix;
private Set<Property> properties;
public PrefixPropertySet(Path prefix, Set<Property> properties)
{
super();
this.prefix = prefix;
this.properties = properties;
}
public Path getPrefix()
{
return prefix;
}
public Set<Property> getProperties()
{
return properties;
}
}
public static Collection<PrefixPropertySet> prefixPropertySets(Set<Property> properties, Path prefix)
{
Collection<PrefixPropertySet> result = new ArrayList<PrefixPropertySet>();
Property[] array = (Property[]) properties.toArray(new Property[properties.size()]);
Part part = null;
int start = 0;
for (int i = 0; i < array.length; i++)
{
Part firstPartAfterPrefix = array[i].getPath().firstPartAfterPrefix(prefix);
if (part != null && !firstPartAfterPrefix.equals(part))
{
// if the first part has changed then add a new set
PrefixPropertySet ppf = createPrefixSubset(prefix, array, part, start, i);
result.add(ppf);
start = i;
}
part = firstPartAfterPrefix;
}
// add the last set
if (array.length > 0)
{
PrefixPropertySet ppf = createPrefixSubset(prefix, array, part, start, array.length);
result.add(ppf);
}
return result;
}
private static PrefixPropertySet createPrefixSubset(Path prefix, Property[] array, Part part,
int start, int i)
{
Set<Property> subset = new ArraySortedSet<Property>(array, start, i - start);
PrefixPropertySet ppf = new PrefixPropertySet(Path.builder(prefix).append(part).build(), subset);
return ppf;
}
public static Set<Property> create(Map<String, Object> properties, boolean indexed)
{
return new PropertyMapToSet(properties, indexed);
}
}
| Java |
package com.vercer.engine.persist.util;
import com.google.common.base.Predicate;
import com.vercer.engine.persist.Restriction;
public class RestrictionToPredicateAdaptor<T> implements Predicate<T>
{
private final Restriction<T> restriction;
public RestrictionToPredicateAdaptor(Restriction<T> restriction)
{
this.restriction = restriction;
}
public boolean apply(T input)
{
return restriction.allow(input);
}
}
| Java |
package com.vercer.engine.persist.util;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
public final class Entities
{
public static Entity changeKind(Entity entity, String kind)
{
Key key;
if (entity.getKey().getName() == null)
{
if (entity.getParent() == null)
{
key = KeyFactory.createKey(kind, entity.getKey().getId());
}
else
{
key = KeyFactory.createKey(entity.getParent(), kind, entity.getKey().getId());
}
}
else
{
if (entity.getParent() == null)
{
key = KeyFactory.createKey(kind, entity.getKey().getName());
}
else
{
key = KeyFactory.createKey(entity.getParent(), kind, entity.getKey().getName());
}
}
Entity changed = new Entity(key);
changed.setPropertiesFrom(entity);
return changed;
}
public static Entity createEntity(String kind, String name, Key parent)
{
if (parent == null)
{
if (name == null)
{
return new Entity(kind);
}
else
{
return new Entity(kind, name);
}
}
else
{
if (name == null)
{
return new Entity(kind, parent);
}
else
{
return new Entity(kind, name, parent);
}
}
}
}
| Java |
package com.vercer.engine.persist.util;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
public class SinglePropertySet extends AbstractSet<Property>
{
private final Path path;
private final Object value;
private final boolean indexed;
public SinglePropertySet(Path path, Object value, boolean indexed)
{
this.path = path;
this.value = value;
this.indexed = indexed;
}
@Override
public Iterator<Property> iterator()
{
return new Iterator<Property>()
{
boolean complete;
public boolean hasNext()
{
return !complete;
}
public Property next()
{
if (hasNext())
{
complete = true;
return new SimpleProperty(path, value, indexed);
}
else
{
throw new NoSuchElementException();
}
}
public void remove()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public int size()
{
return 1;
}
public Object getValue()
{
return value;
}
public Path getPath()
{
return path;
}
public boolean isIndexed()
{
return indexed;
}
}
| Java |
package com.vercer.engine.persist.util;
import com.google.common.base.Predicate;
import com.vercer.engine.persist.Restriction;
public class PredicateToRestrictionAdaptor<T> implements Restriction<T>
{
private final Predicate<T> predicate;
public PredicateToRestrictionAdaptor(Predicate<T> predicate)
{
this.predicate = predicate;
}
@Override
public boolean allow(T candidate)
{
return predicate.apply(candidate);
}
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
class ParameterizedTypeImpl implements ParameterizedType
{
private final Class<?> rawType;
private final Type[] actualTypeArguments;
private final Type ownerType;
public ParameterizedTypeImpl(Class<?> rawType, Type[] actualTypeArguments, Type ownerType)
{
this.rawType = rawType;
this.actualTypeArguments = actualTypeArguments;
this.ownerType = ownerType;
}
public Type getRawType()
{
return rawType;
}
public Type[] getActualTypeArguments()
{
return actualTypeArguments;
}
public Type getOwnerType()
{
return ownerType;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof ParameterizedType))
return false;
ParameterizedType other = (ParameterizedType) obj;
return rawType.equals(other.getRawType())
&& Arrays.equals(actualTypeArguments, other.getActualTypeArguments())
&& (ownerType == null ? other.getOwnerType() == null : ownerType.equals(other
.getOwnerType()));
}
@Override
public int hashCode()
{
int result = rawType.hashCode() ^ Arrays.hashCode(actualTypeArguments);
if (ownerType != null)
result ^= ownerType.hashCode();
return result;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
String clazz = rawType.getName();
if (ownerType != null)
{
sb.append(GenericTypeReflector.getTypeName(ownerType)).append('.');
String prefix = (ownerType instanceof ParameterizedType) ? ((Class<?>) ((ParameterizedType) ownerType)
.getRawType()).getName() + '$'
: ((Class<?>) ownerType).getName() + '$';
if (clazz.startsWith(prefix))
clazz = clazz.substring(prefix.length());
}
sb.append(clazz);
if (actualTypeArguments.length != 0)
{
sb.append('<');
for (int i = 0; i < actualTypeArguments.length; i++)
{
Type arg = actualTypeArguments[i];
if (i != 0)
sb.append(", ");
sb.append(GenericTypeReflector.getTypeName(arg));
}
sb.append('>');
}
return sb.toString();
}
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Code was reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Type;
class GenericArrayTypeImpl implements GenericArrayType
{
private Type componentType;
static Class<?> createArrayType(Class<?> componentType)
{
// there's no (clean) other way to create a array class, then create an
// instance of it
return Array.newInstance(componentType, 0).getClass();
}
static Type createArrayType(Type componentType)
{
if (componentType instanceof Class<?>)
{
return createArrayType((Class<?>) componentType);
}
else
{
return new GenericArrayTypeImpl(componentType);
}
}
private GenericArrayTypeImpl(Type componentType)
{
super();
this.componentType = componentType;
}
public Type getGenericComponentType()
{
return componentType;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof GenericArrayType))
return false;
return componentType.equals(((GenericArrayType) obj).getGenericComponentType());
}
@Override
public int hashCode()
{
return componentType.hashCode() * 7;
}
@Override
public String toString()
{
return componentType + "[]";
}
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Utility class for doing reflection on types.
*
* @author Wouter Coekaerts <wouter@coekaerts.be>
*/
public class GenericTypeReflector
{
private static final Type UNBOUND_WILDCARD = new WildcardTypeImpl(new Type[] { Object.class },
new Type[] {});
/**
* Returns the erasure of the given type.
*/
public static Class<?> erase(Type type)
{
if (type instanceof Class<?>)
{
return (Class<?>) type;
}
else if (type instanceof ParameterizedType)
{
return (Class<?>) ((ParameterizedType) type).getRawType();
}
else if (type instanceof TypeVariable<?>)
{
TypeVariable<?> tv = (TypeVariable<?>) type;
if (tv.getBounds().length == 0)
return Object.class;
else
return erase(tv.getBounds()[0]);
}
else if (type instanceof GenericArrayType)
{
GenericArrayType aType = (GenericArrayType) type;
return GenericArrayTypeImpl.createArrayType(erase(aType.getGenericComponentType()));
}
else
{
// TODO at least support CaptureType here
throw new RuntimeException("not supported: " + type.getClass());
}
}
/**
* Maps type parameters in a type to their values.
*
* @param toMapType
* Type possibly containing type arguments
* @param typeAndParams
* must be either ParameterizedType, or (in case there are no
* type arguments, or it's a raw type) Class
* @return toMapType, but with type parameters from typeAndParams replaced.
*/
private static Type mapTypeParameters(Type toMapType, Type typeAndParams)
{
if (isMissingTypeParameters(typeAndParams))
{
return erase(toMapType);
}
else
{
VarMap varMap = new VarMap();
Type handlingTypeAndParams = typeAndParams;
while (handlingTypeAndParams instanceof ParameterizedType)
{
ParameterizedType pType = (ParameterizedType) handlingTypeAndParams;
Class<?> clazz = (Class<?>) pType.getRawType(); // getRawType
// should always
// be Class
varMap.addAll(clazz.getTypeParameters(), pType.getActualTypeArguments());
handlingTypeAndParams = pType.getOwnerType();
}
return varMap.map(toMapType);
}
}
/**
* Checks if the given type is a class that is supposed to have type
* parameters, but doesn't. In other words, if it's a really raw type.
*/
private static boolean isMissingTypeParameters(Type type)
{
if (type instanceof Class<?>)
{
for (Class<?> clazz = (Class<?>) type; clazz != null; clazz = clazz.getEnclosingClass())
{
if (clazz.getTypeParameters().length != 0)
return true;
}
return false;
}
else if (type instanceof ParameterizedType)
{
return false;
}
else
{
throw new AssertionError("Unexpected type " + type.getClass());
}
}
/**
* Returns a type representing the class, with all type parameters the
* unbound wildcard ("?"). For example,
* <tt>addWildcardParameters(Map.class)</tt> returns a type representing
* <tt>Map<?,?></tt>.
*
* @return <ul>
* <li>If clazz is a class or interface without type parameters,
* clazz itself is returned.</li>
* <li>If clazz is a class or interface with type parameters, an
* instance of ParameterizedType is returned.</li>
* <li>if clazz is an array type, an array type is returned with
* unbound wildcard parameters added in the the component type.
* </ul>
*/
public static Type addWildcardParameters(Class<?> clazz)
{
if (clazz.isArray())
{
return GenericArrayTypeImpl.createArrayType(addWildcardParameters(clazz
.getComponentType()));
}
else if (isMissingTypeParameters(clazz))
{
TypeVariable<?>[] vars = clazz.getTypeParameters();
Type[] arguments = new Type[vars.length];
Arrays.fill(arguments, UNBOUND_WILDCARD);
Type owner = clazz.getDeclaringClass() == null ? null : addWildcardParameters(clazz
.getDeclaringClass());
return new ParameterizedTypeImpl(clazz, arguments, owner);
}
else
{
return clazz;
}
}
/**
* With type a supertype of searchClass, returns the exact supertype of the
* given class, including type parameters. For example, with
* <tt>class StringList implements List<String></tt>,
* <tt>getExactSuperType(StringList.class, Collection.class)</tt> returns a
* {@link ParameterizedType} representing <tt>Collection<String></tt>.
* <ul>
* <li>Returns null if <tt>searchClass</tt> is not a superclass of type.</li>
* <li>Returns an instance of {@link Class} if <tt>type</tt> if it is a raw
* type, or has no type parameters</li>
* <li>Returns an instance of {@link ParameterizedType} if the type does
* have parameters</li>
* <li>Returns an instance of {@link GenericArrayType} if
* <tt>searchClass</tt> is an array type, and the actual type has type
* parameters</li>
* </ul>
*/
public static Type getExactSuperType(Type type, Class<?> searchClass)
{
if (type instanceof ParameterizedType || type instanceof Class<?>
|| type instanceof GenericArrayType)
{
Class<?> clazz = erase(type);
if (searchClass == clazz)
{
return type;
}
if (!searchClass.isAssignableFrom(clazz))
return null;
}
for (Type superType : getExactDirectSuperTypes(type))
{
Type result = getExactSuperType(superType, searchClass);
if (result != null)
return result;
}
return null;
}
/**
* Gets the type parameter for a given type that is the value for a given
* type variable. For example, with
* <tt>class StringList implements List<String></tt>,
* <tt>getTypeParameter(StringList.class, Collection.class.getTypeParameters()[0])</tt>
* returns <tt>String</tt>.
*
* @param type
* The type to inspect.
* @param variable
* The type variable to find the value for.
* @return The type parameter for the given variable. Or null if type is not
* a subtype of the type that declares the variable, or if the
* variable isn't known (because of raw types).
*/
public static Type getTypeParameter(Type type, TypeVariable<? extends Class<?>> variable)
{
Class<?> clazz = variable.getGenericDeclaration();
Type superType = getExactSuperType(type, clazz);
if (superType instanceof ParameterizedType)
{
int index = Arrays.asList(clazz.getTypeParameters()).indexOf(variable);
return ((ParameterizedType) superType).getActualTypeArguments()[index];
}
else
{
return null;
}
}
/**
* Checks if the capture of subType is a subtype of superType
*/
public static boolean isSuperType(Type superType, Type subType)
{
if (superType instanceof ParameterizedType || superType instanceof Class<?>
|| superType instanceof GenericArrayType)
{
Class<?> superClass = erase(superType);
Type mappedSubType = getExactSuperType(capture(subType), superClass);
if (mappedSubType == null)
{
return false;
}
else if (superType instanceof Class<?>)
{
return true;
}
else if (mappedSubType instanceof Class<?>)
{
// TODO treat supertype by being raw type differently
// ("supertype, but with warnings")
return true; // class has no parameters, or it's a raw type
}
else if (mappedSubType instanceof GenericArrayType)
{
Type superComponentType = getArrayComponentType(superType);
assert superComponentType != null;
Type mappedSubComponentType = getArrayComponentType(mappedSubType);
assert mappedSubComponentType != null;
return isSuperType(superComponentType, mappedSubComponentType);
}
else
{
assert mappedSubType instanceof ParameterizedType;
ParameterizedType pMappedSubType = (ParameterizedType) mappedSubType;
assert pMappedSubType.getRawType() == superClass;
ParameterizedType pSuperType = (ParameterizedType) superType;
Type[] superTypeArgs = pSuperType.getActualTypeArguments();
Type[] subTypeArgs = pMappedSubType.getActualTypeArguments();
assert superTypeArgs.length == subTypeArgs.length;
for (int i = 0; i < superTypeArgs.length; i++)
{
if (!contains(superTypeArgs[i], subTypeArgs[i]))
{
return false;
}
}
// params of the class itself match, so if the owner types are
// supertypes too, it's a supertype.
return pSuperType.getOwnerType() == null
|| isSuperType(pSuperType.getOwnerType(), pMappedSubType.getOwnerType());
}
}
else if (superType instanceof CaptureType)
{
if (superType.equals(subType))
return true;
for (Type lowerBound : ((CaptureType) superType).getLowerBounds())
{
if (isSuperType(lowerBound, subType))
{
return true;
}
}
return false;
}
else if (superType instanceof GenericArrayType)
{
return isArraySupertype(superType, subType);
}
else
{
throw new RuntimeException("not implemented: " + superType.getClass());
}
}
private static boolean isArraySupertype(Type arraySuperType, Type subType)
{
Type superTypeComponent = getArrayComponentType(arraySuperType);
assert superTypeComponent != null;
Type subTypeComponent = getArrayComponentType(subType);
if (subTypeComponent == null)
{ // subType is not an array type
return false;
}
else
{
return isSuperType(superTypeComponent, subTypeComponent);
}
}
/**
* If type is an array type, returns the type of the component of the array.
* Otherwise, returns null.
*/
public static Type getArrayComponentType(Type type)
{
if (type instanceof Class<?>)
{
Class<?> clazz = (Class<?>) type;
return clazz.getComponentType();
}
else if (type instanceof GenericArrayType)
{
GenericArrayType aType = (GenericArrayType) type;
return aType.getGenericComponentType();
}
else
{
return null;
}
}
private static boolean contains(Type containingType, Type containedType)
{
if (containingType instanceof WildcardType)
{
WildcardType wContainingType = (WildcardType) containingType;
for (Type upperBound : wContainingType.getUpperBounds())
{
if (!isSuperType(upperBound, containedType))
{
return false;
}
}
for (Type lowerBound : wContainingType.getLowerBounds())
{
if (!isSuperType(containedType, lowerBound))
{
return false;
}
}
return true;
}
else
{
return containingType.equals(containedType);
}
}
/**
* Returns the direct supertypes of the given type. Resolves type
* parameters.
*/
public static Type[] getExactDirectSuperTypes(Type type)
{
if (type instanceof ParameterizedType || type instanceof Class<?>)
{
Class<?> clazz;
if (type instanceof ParameterizedType)
{
clazz = (Class<?>) ((ParameterizedType) type).getRawType();
}
else
{
// TODO primitive types?
clazz = (Class<?>) type;
if (clazz.isArray())
return getArrayExactDirectSuperTypes(clazz);
}
Type[] superInterfaces = clazz.getGenericInterfaces();
Type superClass = clazz.getGenericSuperclass();
Type[] result;
int resultIndex;
if (superClass == null)
{
result = new Type[superInterfaces.length];
resultIndex = 0;
}
else
{
result = new Type[superInterfaces.length + 1];
resultIndex = 1;
result[0] = mapTypeParameters(superClass, type);
}
for (Type superInterface : superInterfaces)
{
result[resultIndex++] = mapTypeParameters(superInterface, type);
}
return result;
}
else if (type instanceof TypeVariable<?>)
{
TypeVariable<?> tv = (TypeVariable<?>) type;
return tv.getBounds();
}
else if (type instanceof WildcardType)
{
// This should be a rare case: normally this wildcard is already
// captured.
// But it does happen if the upper bound of a type variable contains
// a wildcard
// TODO shouldn't upper bound of type variable have been captured
// too? (making this case impossible?)
return ((WildcardType) type).getUpperBounds();
}
else if (type instanceof CaptureType)
{
return ((CaptureType) type).getUpperBounds();
}
else if (type instanceof GenericArrayType)
{
return getArrayExactDirectSuperTypes(type);
}
else
{
throw new RuntimeException("not implemented type: " + type);
}
}
private static Type[] getArrayExactDirectSuperTypes(Type arrayType)
{
// see
// http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.10.3
Type typeComponent = getArrayComponentType(arrayType);
Type[] result;
int resultIndex;
if (typeComponent instanceof Class<?> && ((Class<?>) typeComponent).isPrimitive())
{
resultIndex = 0;
result = new Type[3];
}
else
{
Type[] componentSupertypes = getExactDirectSuperTypes(typeComponent);
result = new Type[componentSupertypes.length + 3];
for (resultIndex = 0; resultIndex < componentSupertypes.length; resultIndex++)
{
result[resultIndex] = GenericArrayTypeImpl
.createArrayType(componentSupertypes[resultIndex]);
}
}
result[resultIndex++] = Object.class;
result[resultIndex++] = Cloneable.class;
result[resultIndex++] = Serializable.class;
return result;
}
/**
* Returns the exact return type of the given method in the given type. This
* may be different from <tt>m.getGenericReturnType()</tt> when the method
* was declared in a superclass, of <tt>type</tt> is a raw type.
*/
public static Type getExactReturnType(Method m, Type type)
{
Type returnType = m.getGenericReturnType();
Type exactDeclaringType = getExactSuperType(capture(type), m.getDeclaringClass());
return mapTypeParameters(returnType, exactDeclaringType);
}
/**
* Returns the exact type of the given field in the given type. This may be
* different from <tt>f.getGenericType()</tt> when the field was declared in
* a superclass, of <tt>type</tt> is a raw type.
*/
public static Type getExactFieldType(Field f, Type type)
{
Type returnType = f.getGenericType();
Type exactDeclaringType = getExactSuperType(capture(type), f.getDeclaringClass());
return mapTypeParameters(returnType, exactDeclaringType);
}
/**
* Applies capture conversion to the given type.
*/
public static Type capture(Type type)
{
VarMap varMap = new VarMap();
List<CaptureTypeImpl> toInit = new ArrayList<CaptureTypeImpl>();
if (type instanceof ParameterizedType)
{
ParameterizedType pType = (ParameterizedType) type;
Class<?> clazz = (Class<?>) pType.getRawType();
Type[] arguments = pType.getActualTypeArguments();
TypeVariable<?>[] vars = clazz.getTypeParameters();
Type[] capturedArguments = new Type[arguments.length];
assert arguments.length == vars.length;
for (int i = 0; i < arguments.length; i++)
{
Type argument = arguments[i];
if (argument instanceof WildcardType)
{
CaptureTypeImpl captured = new CaptureTypeImpl((WildcardType) argument, vars[i]);
argument = captured;
toInit.add(captured);
}
capturedArguments[i] = argument;
varMap.add(vars[i], argument);
}
for (CaptureTypeImpl captured : toInit)
{
captured.init(varMap);
}
Type ownerType = (pType.getOwnerType() == null) ? null : capture(pType.getOwnerType());
return new ParameterizedTypeImpl(clazz, capturedArguments, ownerType);
}
else
{
return type;
}
}
/**
* Returns the display name of a Type.
*/
public static String getTypeName(Type type)
{
if (type instanceof Class<?>)
{
Class<?> clazz = (Class<?>) type;
return clazz.isArray() ? (getTypeName(clazz.getComponentType()) + "[]") : clazz.getName();
}
else
{
return type.toString();
}
}
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
class WildcardTypeImpl implements WildcardType
{
private final Type[] upperBounds;
private final Type[] lowerBounds;
public WildcardTypeImpl(Type[] upperBounds, Type[] lowerBounds)
{
if (upperBounds.length == 0)
throw new IllegalArgumentException(
"There must be at least one upper bound. For an unbound wildcard, the upper bound must be Object");
this.upperBounds = upperBounds;
this.lowerBounds = lowerBounds;
}
public Type[] getUpperBounds()
{
return upperBounds;
}
public Type[] getLowerBounds()
{
return lowerBounds;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof WildcardType))
return false;
WildcardType other = (WildcardType) obj;
return Arrays.equals(lowerBounds, other.getLowerBounds())
&& Arrays.equals(upperBounds, other.getUpperBounds());
}
@Override
public int hashCode()
{
return Arrays.hashCode(lowerBounds) ^ Arrays.hashCode(upperBounds);
}
@Override
public String toString()
{
if (lowerBounds.length > 0)
{
return "? super " + GenericTypeReflector.getTypeName(lowerBounds[0]);
}
else if (upperBounds[0] == Object.class)
{
return "?";
}
else
{
return "? extends " + GenericTypeReflector.getTypeName(upperBounds[0]);
}
}
} | Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
/**
* CaptureType represents a wildcard that has gone through capture conversion.
* It is a custom subinterface of Type, not part of the java builtin Type
* hierarchy.
*
* @author Wouter Coekaerts <wouter@coekaerts.be>
*/
public interface CaptureType extends Type
{
/**
* Returns an array of <tt>Type</tt> objects representing the upper bound(s)
* of this capture. This includes both the upper bound of a
* <tt>? extends</tt> wildcard, and the bounds declared with the type
* variable. References to other (or the same) type variables in bounds
* coming from the type variable are replaced by their matching capture.
*/
Type[] getUpperBounds();
/**
* Returns an array of <tt>Type</tt> objects representing the lower bound(s)
* of this type variable. This is the bound of a <tt>? super</tt> wildcard.
* This normally contains only one or no types; it is an array for
* consistency with {@link WildcardType#getLowerBounds()}.
*/
Type[] getLowerBounds();
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;
class CaptureTypeImpl implements CaptureType
{
private final WildcardType wildcard;
private final TypeVariable<?> variable;
private final Type[] lowerBounds;
private Type[] upperBounds;
/**
* Creates an uninitialized CaptureTypeImpl. Before using this type,
* {@link #init(VarMap)} must be called.
*
* @param wildcard
* The wildcard this is a capture of
* @param variable
* The type variable where the wildcard is a parameter for.
*/
public CaptureTypeImpl(WildcardType wildcard, TypeVariable<?> variable)
{
this.wildcard = wildcard;
this.variable = variable;
this.lowerBounds = wildcard.getLowerBounds();
}
/**
* Initialize this CaptureTypeImpl. This is needed for type variable bounds
* referring to each other: we need the capture of the argument.
*/
void init(VarMap varMap)
{
ArrayList<Type> upperBoundsList = new ArrayList<Type>();
upperBoundsList.addAll(Arrays.asList(varMap.map(variable.getBounds())));
upperBoundsList.addAll(Arrays.asList(wildcard.getUpperBounds()));
upperBounds = new Type[upperBoundsList.size()];
upperBoundsList.toArray(upperBounds);
}
/*
* @see com.googlecode.gentyref.CaptureType#getLowerBounds()
*/
public Type[] getLowerBounds()
{
return lowerBounds.clone();
}
/*
* @see com.googlecode.gentyref.CaptureType#getUpperBounds()
*/
public Type[] getUpperBounds()
{
assert upperBounds != null;
return upperBounds.clone();
}
@Override
public String toString()
{
return "capture of " + wildcard;
}
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Wrapper around {@link Type}.
*
* You can use this to create instances of Type for a type known at compile
* time.
*
* For example, to get the Type that represents List<String>:
* <code>Type listOfString = new TypeToken<List<String>>(){}.getType();</code>
*
* @author Wouter Coekaerts <wouter@coekaerts.be>
*
* @param <T>
* The type represented by this TypeToken.
*/
public abstract class TypeToken<T>
{
private final Type type;
/**
* Constructs a type token.
*/
protected TypeToken()
{
this.type = extractType();
}
private TypeToken(Type type)
{
this.type = type;
}
public Type getType()
{
return type;
}
private Type extractType()
{
Type t = getClass().getGenericSuperclass();
if (!(t instanceof ParameterizedType))
{
throw new RuntimeException("Invalid TypeToken; must specify type parameters");
}
ParameterizedType pt = (ParameterizedType) t;
if (pt.getRawType() != TypeToken.class)
{
throw new RuntimeException("Invalid TypeToken; must directly extend TypeToken");
}
return pt.getActualTypeArguments()[0];
}
/**
* Gets type token for the given {@code Class} instance.
*/
public static <T> TypeToken<T> get(Class<T> type)
{
return new SimpleTypeToken<T>(type);
}
/**
* Gets type token for the given {@code Type} instance.
*/
public static TypeToken<?> get(Type type)
{
return new SimpleTypeToken<Object>(type);
}
private static class SimpleTypeToken<T> extends TypeToken<T>
{
public SimpleTypeToken(Type type)
{
super(type);
}
}
@Override
public boolean equals(Object obj)
{
return (obj instanceof TypeToken<?>) && type.equals(((TypeToken<?>) obj).type);
}
@Override
public int hashCode()
{
return type.hashCode();
}
}
| Java |
/*
* Copied from Gentyref project http://code.google.com/p/gentyref/
* Reformatted and moved to fit package structure
*/
package com.vercer.engine.persist.util.generic;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.HashMap;
import java.util.Map;
/**
* Mapping between type variables and actual parameters.
*
* @author Wouter Coekaerts <wouter@coekaerts.be>
*/
class VarMap
{
private final Map<TypeVariable<?>, Type> map = new HashMap<TypeVariable<?>, Type>();
/**
* Creates an empty VarMap
*/
VarMap()
{
}
void add(TypeVariable<?> variable, Type value)
{
map.put(variable, value);
}
void addAll(TypeVariable<?>[] variables, Type[] values)
{
assert variables.length == values.length;
for (int i = 0; i < variables.length; i++)
{
map.put(variables[i], values[i]);
}
}
VarMap(TypeVariable<?>[] variables, Type[] values)
{
addAll(variables, values);
}
Type map(Type type)
{
if (type instanceof Class<?>)
{
return type;
}
else if (type instanceof TypeVariable<?>)
{
assert map.containsKey(type);
return map.get(type);
}
else if (type instanceof ParameterizedType)
{
ParameterizedType pType = (ParameterizedType) type;
return new ParameterizedTypeImpl((Class<?>) pType.getRawType(), map(pType
.getActualTypeArguments()), pType.getOwnerType() == null ? pType.getOwnerType()
: map(pType.getOwnerType()));
}
else if (type instanceof WildcardType)
{
WildcardType wType = (WildcardType) type;
return new WildcardTypeImpl(map(wType.getUpperBounds()), map(wType.getLowerBounds()));
}
else if (type instanceof GenericArrayType)
{
return GenericArrayTypeImpl.createArrayType(map(((GenericArrayType) type)
.getGenericComponentType()));
}
else
{
throw new RuntimeException("not implemented: mapping " + type.getClass() + " (" + type
+ ")");
}
}
Type[] map(Type[] types)
{
Type[] result = new Type[types.length];
for (int i = 0; i < types.length; i++)
{
result[i] = map(types[i]);
}
return result;
}
} | Java |
package com.vercer.engine.persist.util.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
public class NoDescriptorObjectInputStream extends ObjectInputStream
{
public NoDescriptorObjectInputStream(InputStream in) throws IOException
{
super(in);
}
@Override
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException
{
String name = readUTF();
ObjectStreamClass lookup = ObjectStreamClass.lookup(Class.forName(name));
return lookup;
}
} | Java |
package com.vercer.engine.persist.util.io;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
public class NoDescriptorObjectOutputStream extends ObjectOutputStream
{
public NoDescriptorObjectOutputStream(OutputStream out) throws IOException
{
super(out);
}
@Override
protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException
{
writeUTF(desc.getName());
}
} | Java |
/**
*
*/
package com.vercer.engine.persist.util;
import com.google.common.base.Predicate;
import com.vercer.engine.persist.Path;
import com.vercer.engine.persist.Property;
public final class PathPrefixPredicate implements Predicate<Property>
{
private final Path prefix;
public PathPrefixPredicate(Path prefix)
{
this.prefix = prefix;
}
public boolean apply(Property property)
{
return property.getPath().hasPrefix(prefix);
}
} | Java |
package com.vercer.engine.persist;
import java.util.Map;
import java.util.Collection;
import java.util.concurrent.Future;
import com.google.appengine.api.datastore.Entity;
public interface LoadCommand
{
interface TypedLoadCommand<T>
{
SingleTypedLoadCommand<T> id(Object id);
<K> MultipleTypedLoadCommand<T, K> ids(Collection<? extends K> ids);
<K> MultipleTypedLoadCommand<T, K> ids(K... ids);
}
interface BaseTypedLoadCommand<T, C extends BaseTypedLoadCommand<T, C>>
{
C restrictEntities(Restriction<Entity> restriction);
C restrictProperties(Restriction<Property> restriction);
}
interface SingleTypedLoadCommand<T> extends BaseTypedLoadCommand<T, SingleTypedLoadCommand<T>>
{
T returnResultNow();
Future<T> returnResultLater();
}
interface MultipleTypedLoadCommand<T, K> extends BaseTypedLoadCommand<T, MultipleTypedLoadCommand<T, K>>
{
Map<? super K, ? super T> returnResultsNow();
Future<Map<? super K, ? super T>> returnResultsLater();
}
<T> TypedLoadCommand<T> type(Class<T> type);
}
| Java |
package com.google.appengine.api.datastore;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.appengine.api.utils.FutureWrapper;
import com.google.apphosting.api.ApiBasePb;
import com.google.apphosting.api.DatastorePb;
import com.google.apphosting.api.ApiProxy.ApiConfig;
public class AsyncPreparedQuery extends BasePreparedQuery
{
private final Query query;
private final Transaction txn;
public AsyncPreparedQuery(Query query, Transaction txn)
{
this.query = query;
this.txn = txn;
}
public Future<QueryResultIterator<Entity>> asFutureQueryResultIterator()
{
return asFutureQueryResultIterator(FetchOptions.Builder.withDefaults());
}
public Future<QueryResultIterator<Entity>> asFutureQueryResultIterator(FetchOptions fetchOptions)
{
if (fetchOptions.getCompile() == null)
{
fetchOptions = new FetchOptions(fetchOptions).compile(true);
}
return runAsyncQuery(this.query, fetchOptions);
}
public Future<Integer> countEntitiesAsync()
{
DatastorePb.Query queryProto = convertToPb(this.query, FetchOptions.Builder.withDefaults());
Future<byte[]> fb = AsyncDatastoreHelper.makeAsyncCall("Count", queryProto);
return new FutureWrapper<byte[], Integer>(fb)
{
@Override
protected Throwable convertException(Throwable e)
{
return e;
}
@Override
protected Integer wrap(byte[] bytes) throws Exception
{
ApiBasePb.Integer64Proto resp = new ApiBasePb.Integer64Proto();
resp.mergeFrom(bytes);
return (int) resp.getValue();
}
};
}
private Future<QueryResultIterator<Entity>> runAsyncQuery(Query q, final FetchOptions fetchOptions)
{
DatastorePb.Query queryProto = convertToPb(q, fetchOptions);
final Future<byte[]> future;
future = AsyncDatastoreHelper.makeAsyncCall("RunQuery", queryProto);
return new Future<QueryResultIterator<Entity>>()
{
public boolean isDone()
{
return future.isDone();
}
public boolean isCancelled()
{
return future.isCancelled();
}
public QueryResultIterator<Entity> get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException
{
byte[] bs = future.get(timeout, unit);
return makeResult(bs);
}
private QueryResultIterator<Entity> makeResult(byte[] bs)
{
DatastorePb.QueryResult result = new DatastorePb.QueryResult();
if (bs != null)
{
result.mergeFrom(bs);
}
QueryResultsSourceImpl src = new QueryResultsSourceImpl(null, fetchOptions, txn);
List<Entity> prefetchedEntities = src.loadFromPb(result);
return new QueryResultIteratorImpl(AsyncPreparedQuery.this, prefetchedEntities,
src, fetchOptions, txn);
}
public QueryResultIterator<Entity> get() throws InterruptedException,
ExecutionException
{
byte[] bs = future.get();
return makeResult(bs);
}
public boolean cancel(boolean mayInterruptIfRunning)
{
return future.cancel(mayInterruptIfRunning);
}
};
}
private DatastorePb.Query convertToPb(Query q, FetchOptions fetchOptions)
{
DatastorePb.Query queryProto = QueryTranslator.convertToPb(q, fetchOptions);
if (this.txn != null)
{
TransactionImpl.ensureTxnActive(this.txn);
queryProto.setTransaction(DatastoreServiceImpl.localTxnToRemoteTxn(this.txn));
}
return queryProto;
}
@Override
public String toString()
{
return this.query.toString() + ((this.txn != null) ? " IN " + this.txn : "");
}
public Iterator<Entity> asIterator(FetchOptions fetchOptions)
{
throw new UnsupportedOperationException();
}
public List<Entity> asList(FetchOptions fetchOptions)
{
throw new UnsupportedOperationException();
}
public QueryResultList<Entity> asQueryResultList(FetchOptions fetchOptions)
{
throw new UnsupportedOperationException();
}
public Entity asSingleEntity() throws TooManyResultsException
{
throw new UnsupportedOperationException();
}
public QueryResultIterator<Entity> asQueryResultIterator(FetchOptions fetchOptions)
{
throw new UnsupportedOperationException();
}
public int countEntities()
{
// TODO Auto-generated method stub
return 0;
}
} | Java |
package com.google.appengine.api.datastore;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.google.appengine.api.datastore.Query.SortPredicate;
import com.google.appengine.repackaged.com.google.io.protocol.ProtocolMessage;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.DatastorePb;
import com.google.storage.onestore.v3.OnestoreEntity;
import com.google.storage.onestore.v3.OnestoreEntity.Reference;
import com.vercer.util.reference.SimpleObjectReference;
/**
* This class has access to package private internals that are essential to async operations
* but has the danger that if the internal code is updated this may break without warning.
*
* Use at your own risk.
*
* @author John Patterson <john@vercer.com>
*/
public class AsyncDatastoreHelper
{
public static Future<List<Key>> put(final Transaction txn, final Iterable<Entity> entities)
{
final DatastorePb.PutRequest req = new DatastorePb.PutRequest();
final SimpleObjectReference<Future<byte[]>> futureBytes = new SimpleObjectReference<Future<byte[]>>();
new TransactionRunner(txn, false) // never auto-commit
{
@Override
protected void run()
{
if (txn != null)
{
req.setTransaction(DatastoreServiceImpl.localTxnToRemoteTxn(txn));
}
for (Entity entity : entities)
{
OnestoreEntity.EntityProto proto = EntityTranslator.convertToPb(entity);
req.addEntity(proto);
}
futureBytes.set(makeAsyncCall("Put", req));
}
}.runInTransaction();
return new Future<List<Key>>()
{
public boolean isDone()
{
return futureBytes.get().isDone();
}
public boolean isCancelled()
{
return futureBytes.get().isCancelled();
}
public List<Key> get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException
{
return doGet(futureBytes.get().get(timeout, unit));
}
public List<Key> get() throws InterruptedException, ExecutionException
{
return doGet(futureBytes.get().get());
}
private List<Key> doGet(byte[] bytes)
{
DatastorePb.PutResponse response = new DatastorePb.PutResponse();
if (bytes != null)
{
response.mergeFrom(bytes);
}
Iterator<Entity> entitiesIterator = entities.iterator();
Iterator<Reference> referenceIterator = response.keys().iterator();
List<Key> keysInOrder = new ArrayList<Key>(response.keySize());
while (entitiesIterator.hasNext())
{
Entity entity = entitiesIterator.next();
OnestoreEntity.Reference reference = referenceIterator.next();
KeyTranslator.updateKey(reference, entity.getKey());
keysInOrder.add(entity.getKey());
}
return keysInOrder;
}
public boolean cancel(boolean mayInterruptIfRunning)
{
return futureBytes.get().cancel(mayInterruptIfRunning);
}
};
}
static Future<byte[]> makeAsyncCall(String method, ProtocolMessage<?> request)
{
try
{
return ApiProxy.makeAsyncCall("datastore_v3", method, request.toByteArray());
}
catch (ApiProxy.ApplicationException exception)
{
throw DatastoreApiHelper.translateError(exception);
}
}
public static Comparator<Entity> newEntityComparator(List<SortPredicate> sorts)
{
return new PreparedMultiQuery.EntityComparator(sorts);
}
}
| Java |
package org.sshtunnel.db;
import java.sql.SQLException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
/**
* Database helper class used to manage the creation and upgrading of your
* database. This class also usually provides the DAOs used by the other
* classes.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something
// appropriate for your app
private static final String DATABASE_NAME = "sshtunnel.db";
// any time you make changes to your database objects, you may have to
// increase the database version
private static final int DATABASE_VERSION = 5;
// the DAO object we use to access the SimpleData table
private Dao<Profile, Integer> profileDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Close the database connections and clear any cached DAOs.
*/
@Override
public void close() {
super.close();
profileDao = null;
}
/**
* Returns the Database Access Object (DAO) for our SimpleData class. It
* will create it or just give the cached value.
*/
public Dao<Profile, Integer> getProfileDao() throws SQLException {
if (profileDao == null) {
profileDao = getDao(Profile.class);
}
return profileDao;
}
/**
* This is called when the database is first created. Usually you should
* call createTable statements here to create the tables that will store
* your data.
*/
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Profile.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* This is called when your application is upgraded and it has a higher
* version number. This allows you to adjust the various data to match the
* new version number.
*/
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL("ALTER TABLE Profile ADD COLUMN isDNSProxy BOOLEAN");
db.execSQL("UPDATE Profile SET isDNSProxy=1");
case 2:
db.execSQL("ALTER TABLE Profile ADD COLUMN isActive BOOLEAN");
db.execSQL("UPDATE Profile SET isActive=0");
case 3:
db.execSQL("ALTER TABLE Profile ADD COLUMN isUpstreamProxy BOOLEAN");
db.execSQL("UPDATE Profile SET isUpstreamProxy=0");
db.execSQL("ALTER TABLE Profile ADD COLUMN upstreamProxy VARCHAR");
db.execSQL("UPDATE Profile SET upstreamProxy=''");
case 4:
db.execSQL("ALTER TABLE Profile ADD COLUMN fingerPrint VARCHAR");
db.execSQL("UPDATE Profile SET fingerPrint=''");
db.execSQL("ALTER TABLE Profile ADD COLUMN fingerPrintType VARCHAR");
db.execSQL("UPDATE Profile SET fingerPrintType=''");
break;
default:
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, Profile.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
}
}
| Java |
package org.sshtunnel.db;
import java.util.List;
import org.sshtunnel.SSHTunnelContext;
import org.sshtunnel.utils.Constraints;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
public class ProfileFactory {
private static Profile profile;
private static final String TAG = "SSHTunnelDB";
private static DatabaseHelper helper;
static {
OpenHelperManager.setOpenHelperClass(DatabaseHelper.class);
if (helper == null) {
helper = ((DatabaseHelper) OpenHelperManager
.getHelper(SSHTunnelContext.getAppContext()));
}
}
public static boolean delFromDao() {
try {
// try to remove profile from dao
Dao<Profile, Integer> profileDao = helper.getProfileDao();
int result = profileDao.delete(profile);
if (result != 1)
return false;
// reload the current profile
profile = getActiveProfile();
// ensure current profile is active
profile.setActive(true);
saveToDao();
return true;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
return false;
}
}
public static Profile getProfile() {
if (profile == null) {
initProfile();
}
return profile;
}
private static Profile getActiveProfile() {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
List<Profile> list = profileDao.queryForAll();
if (list == null || list.size() == 0)
return null;
Profile tmp = list.get(0);
for (Profile p : list) {
if (p.isActive) {
tmp = p;
break;
}
}
return tmp;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
return null;
}
}
private static void initProfile() {
profile = getActiveProfile();
if (profile == null) {
profile = new Profile();
profile.setActive(true);
saveToPreference();
saveToDao();
}
}
public static List<Profile> loadAllProfilesFromDao() {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
List<Profile> list = profileDao.queryForAll();
return list;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
return null;
}
public static void switchToProfile(int profileId) {
// current profile should not be null
if (profile == null)
return;
// first save any changes to dao
saveToDao();
// deactive all profiles
deactiveAllProfiles();
// query for new profile
Profile tmp = loadProfileFromDao(profileId);
if (tmp != null) {
profile = tmp;
saveToPreference();
}
profile.setActive(true);
saveToDao();
}
private static void deactiveAllProfiles() {
List<Profile> list = loadAllProfilesFromDao();
for (Profile p : list) {
p.setActive(false);
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
profileDao.createOrUpdate(p);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
}
}
public static void loadFromPreference() {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnelContext.getAppContext());
profile.name = settings.getString(Constraints.NAME, "");
profile.host = settings.getString(Constraints.HOST, "");
profile.user = settings.getString(Constraints.USER, "");
profile.password = settings.getString(Constraints.PASSWORD, "");
profile.remoteAddress = settings.getString(Constraints.REMOTE_ADDRESS,
Constraints.DEFAULT_REMOTE_ADDRESS);
profile.ssid = settings.getString(Constraints.SSID, "");
profile.proxyedApps = settings.getString(Constraints.PROXYED_APPS, "");
profile.keyPath = settings.getString(Constraints.KEY_PATH,
Constraints.DEFAULT_KEY_PATH);
profile.upstreamProxy = settings.getString(Constraints.UPSTREAM_PROXY, "");
profile.isAutoConnect = settings.getBoolean(
Constraints.IS_AUTO_CONNECT, false);
profile.isAutoReconnect = settings.getBoolean(
Constraints.IS_AUTO_RECONNECT, false);
profile.isAutoSetProxy = settings.getBoolean(
Constraints.IS_AUTO_SETPROXY, false);
profile.isSocks = settings.getBoolean(Constraints.IS_SOCKS, false);
profile.isGFWList = settings.getBoolean(Constraints.IS_GFW_LIST, false);
profile.isDNSProxy = settings
.getBoolean(Constraints.IS_DNS_PROXY, true);
profile.isUpstreamProxy = settings.getBoolean(Constraints.IS_UPSTREAM_PROXY, false);
try {
profile.port = Integer.valueOf(settings.getString(Constraints.PORT,
"22"));
profile.localPort = Integer.valueOf(settings.getString(
Constraints.LOCAL_PORT, "1984"));
profile.remotePort = Integer.valueOf(settings.getString(
Constraints.REMOTE_PORT, "3128"));
} catch (NumberFormatException e) {
Log.e(TAG, "Exception when get preferences");
profile = null;
return;
}
saveToDao();
}
public static Profile loadProfileFromDao(int profileId) {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
Profile mProfile = profileDao.queryForId(profileId);
return mProfile;
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
return null;
}
public static void newProfile() {
profile = new Profile();
saveToDao();
}
public static void saveToDao() {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
profileDao.createOrUpdate(profile);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
}
public static void saveToDao(Profile mProfile) {
try {
Dao<Profile, Integer> profileDao = helper.getProfileDao();
profileDao.createOrUpdate(mProfile);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO");
}
}
public static void saveToPreference() {
if (profile == null)
return;
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnelContext.getAppContext());
Editor ed = settings.edit();
ed = settings.edit();
ed.putString(Constraints.NAME, profile.name);
ed.putString(Constraints.HOST, profile.host);
ed.putString(Constraints.USER, profile.user);
ed.putString(Constraints.PASSWORD, profile.password);
ed.putString(Constraints.REMOTE_ADDRESS, profile.remoteAddress);
ed.putString(Constraints.SSID, profile.ssid);
ed.putString(Constraints.KEY_PATH, profile.proxyedApps);
ed.putString(Constraints.KEY_PATH, profile.keyPath);
ed.putString(Constraints.UPSTREAM_PROXY, profile.upstreamProxy);
ed.putString(Constraints.PORT, Integer.toString(profile.port));
ed.putString(Constraints.LOCAL_PORT,
Integer.toString(profile.localPort));
ed.putString(Constraints.REMOTE_PORT,
Integer.toString(profile.remotePort));
ed.putBoolean(Constraints.IS_AUTO_CONNECT, profile.isAutoConnect);
ed.putBoolean(Constraints.IS_AUTO_RECONNECT, profile.isAutoReconnect);
ed.putBoolean(Constraints.IS_AUTO_SETPROXY, profile.isAutoSetProxy);
ed.putBoolean(Constraints.IS_SOCKS, profile.isSocks);
ed.putBoolean(Constraints.IS_GFW_LIST, profile.isGFWList);
ed.putBoolean(Constraints.IS_DNS_PROXY, profile.isDNSProxy);
ed.putBoolean(Constraints.IS_UPSTREAM_PROXY, profile.isUpstreamProxy);
ed.commit();
}
}
| Java |
package org.sshtunnel;
import java.io.IOException;
public interface WrapServer extends Runnable {
public abstract void close() throws IOException;
public abstract int getServPort();
public abstract boolean isClosed();
public abstract void setProxyHost(String host);
public abstract void setProxyPort(int port);
/**
* 设置此服务的目的地址
*
* @param target
*/
public abstract void setTarget(String target);
}
| Java |
/* Copyright (c) 2009, Nathan Freitas, Orbot / The Guardian Project - http://openideals.com/guardian */
/* See LICENSE for licensing information */
package org.sshtunnel;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.ProxyedApp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AppManager extends Activity implements OnCheckedChangeListener,
OnClickListener {
private static class ListEntry {
private CheckBox box;
private TextView text;
private ImageView icon;
}
public static ProxyedApp[] getProxyedApps(Context context,
String tordAppString) {
String[] tordApps;
StringTokenizer st = new StringTokenizer(tordAppString, "|");
tordApps = new String[st.countTokens()];
int tordIdx = 0;
while (st.hasMoreTokens()) {
tordApps[tordIdx++] = st.nextToken();
}
Arrays.sort(tordApps);
// else load the apps up
PackageManager pMgr = context.getPackageManager();
List<ApplicationInfo> lAppInfo = pMgr.getInstalledApplications(0);
Iterator<ApplicationInfo> itAppInfo = lAppInfo.iterator();
ProxyedApp[] apps = new ProxyedApp[lAppInfo.size()];
ApplicationInfo aInfo = null;
int appIdx = 0;
while (itAppInfo.hasNext()) {
aInfo = itAppInfo.next();
apps[appIdx] = new ProxyedApp();
apps[appIdx].setUid(aInfo.uid);
apps[appIdx].setUsername(pMgr.getNameForUid(apps[appIdx].getUid()));
// check if this application is allowed
if (Arrays.binarySearch(tordApps, apps[appIdx].getUsername()) >= 0) {
apps[appIdx].setProxyed(true);
} else {
apps[appIdx].setProxyed(false);
}
appIdx++;
}
return apps;
}
private ProxyedApp[] apps = null;
private ListView listApps;
private AppManager mAppManager;
private TextView overlay;
private ProgressDialog pd = null;
private ListAdapter adapter;
private ImageLoader dm;
private static final int MSG_LOAD_START = 1;
private static final int MSG_LOAD_FINISH = 2;
private boolean appsLoaded = false;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_LOAD_START:
pd = ProgressDialog.show(AppManager.this, "",
getString(R.string.loading), true, true);
break;
case MSG_LOAD_FINISH:
listApps.setAdapter(adapter);
listApps.setOnScrollListener(new OnScrollListener() {
boolean visible;
@Override
public void onScroll(AbsListView view,
int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (visible) {
String name = apps[firstVisibleItem].getName();
if (name != null && name.length() > 1)
overlay.setText(apps[firstVisibleItem]
.getName().substring(0, 1));
else
overlay.setText("*");
overlay.setVisibility(View.VISIBLE);
}
}
@Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
visible = true;
if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) {
overlay.setVisibility(View.INVISIBLE);
}
}
});
if (pd != null) {
pd.dismiss();
pd = null;
}
break;
}
super.handleMessage(msg);
}
};
public void getApps(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
String tordAppString = prefs.getString(Constraints.PROXYED_APPS, "");
String[] tordApps;
StringTokenizer st = new StringTokenizer(tordAppString, "|");
tordApps = new String[st.countTokens()];
int tordIdx = 0;
while (st.hasMoreTokens()) {
tordApps[tordIdx++] = st.nextToken();
}
Arrays.sort(tordApps);
Vector<ProxyedApp> vectorApps = new Vector<ProxyedApp>();
// else load the apps up
PackageManager pMgr = context.getPackageManager();
List<ApplicationInfo> lAppInfo = pMgr.getInstalledApplications(0);
Iterator<ApplicationInfo> itAppInfo = lAppInfo.iterator();
ApplicationInfo aInfo = null;
while (itAppInfo.hasNext()) {
aInfo = itAppInfo.next();
if (aInfo.processName == null)
continue;
if (pMgr.getApplicationLabel(aInfo) == null
|| pMgr.getApplicationLabel(aInfo).toString().equals(""))
continue;
if (pMgr.getApplicationIcon(aInfo) == null)
continue;
ProxyedApp tApp = new ProxyedApp();
tApp.setEnabled(aInfo.enabled);
tApp.setUid(aInfo.uid);
tApp.setUsername(pMgr.getNameForUid(tApp.getUid()));
tApp.setProcname(aInfo.processName);
tApp.setName(pMgr.getApplicationLabel(aInfo).toString());
// check if this application is allowed
if (Arrays.binarySearch(tordApps, tApp.getUsername()) >= 0) {
tApp.setProxyed(true);
} else {
tApp.setProxyed(false);
}
vectorApps.add(tApp);
}
apps = new ProxyedApp[lAppInfo.size()];
vectorApps.toArray(apps);
}
private void loadApps() {
getApps(this);
Arrays.sort(apps, new Comparator<ProxyedApp>() {
@Override
public int compare(ProxyedApp o1, ProxyedApp o2) {
if (o1 == null || o2 == null)
return 1;
if (o1.isProxyed() == o2.isProxyed())
return o1.getName().compareTo(o2.getName());
if (o1.isProxyed())
return -1;
return 1;
}
});
final LayoutInflater inflater = getLayoutInflater();
adapter = new ArrayAdapter<ProxyedApp>(this, R.layout.layout_apps_item,
R.id.itemtext, apps) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ListEntry entry;
if (convertView == null) {
// Inflate a new view
convertView = inflater.inflate(R.layout.layout_apps_item,
parent, false);
entry = new ListEntry();
entry.icon = (ImageView) convertView
.findViewById(R.id.itemicon);
entry.box = (CheckBox) convertView
.findViewById(R.id.itemcheck);
entry.text = (TextView) convertView
.findViewById(R.id.itemtext);
entry.text.setOnClickListener(mAppManager);
convertView.setTag(entry);
entry.box.setOnCheckedChangeListener(mAppManager);
} else {
// Convert an existing view
entry = (ListEntry) convertView.getTag();
}
final ProxyedApp app = apps[position];
entry.icon.setTag(app.getUid());
dm.DisplayImage(app.getUid(),
(Activity) convertView.getContext(), entry.icon);
entry.text.setText(app.getName());
final CheckBox box = entry.box;
box.setTag(app);
box.setChecked(app.isProxyed());
entry.text.setTag(box);
return convertView;
}
};
appsLoaded = true;
}
/**
* Called an application is check/unchecked
*/
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final ProxyedApp app = (ProxyedApp) buttonView.getTag();
if (app != null) {
app.setProxyed(isChecked);
}
saveAppSettings(this);
}
@Override
public void onClick(View v) {
CheckBox cbox = (CheckBox) v.getTag();
final ProxyedApp app = (ProxyedApp) cbox.getTag();
if (app != null) {
app.setProxyed(!app.isProxyed());
cbox.setChecked(app.isProxyed());
}
saveAppSettings(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.layout_apps);
dm = ImageLoaderFactory.getImageLoader(this);
this.overlay = (TextView) View.inflate(this, R.layout.overlay, null);
getWindowManager()
.addView(
overlay,
new WindowManager.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
PixelFormat.TRANSLUCENT));
mAppManager = this;
}
@Override
protected void onResume() {
super.onResume();
new Thread() {
@Override
public void run() {
handler.sendEmptyMessage(MSG_LOAD_START);
listApps = (ListView) findViewById(R.id.applistview);
if (!appsLoaded)
loadApps();
handler.sendEmptyMessage(MSG_LOAD_FINISH);
}
}.start();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
// Log.d(getClass().getName(),"Exiting Preferences");
}
public void saveAppSettings(Context context) {
if (apps == null)
return;
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
StringBuilder tordApps = new StringBuilder();
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
tordApps.append(apps[i].getUsername());
tordApps.append("|");
}
}
Editor edit = prefs.edit();
edit.putString(Constraints.PROXYED_APPS, tordApps.toString());
edit.commit();
}
}
| Java |
// dbartists - Douban artists client for Android
// Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
//
// ___====-_ _-====___
// _--^^^#####// \\#####^^^--_
// _-^##########// ( ) \\##########^-_
// -############// |\^^/| \\############-
// _/############// (@::@) \\############\_
// /#############(( \\// ))#############\
// -###############\\ (oo) //###############-
// -#################\\ / VV \ //#################-
// -###################\\/ \//###################-
// _#/|##########/\######( /\ )######/\##########|\#_
// |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
// ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
// ` ` ` ` / | | | | \ ' ' ' '
// ( | | | | )
// __\ | | | | /__
// (vvv(VVV)(VVV)vvv)
//
// HERE BE DRAGONS
package org.sshtunnel;
import android.content.Context;
public class ImageLoaderFactory {
private static ImageLoader il = null;
public static ImageLoader getImageLoader(Context context) {
if (il == null) {
il = new ImageLoader(context);
}
return il;
}
}
| Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.Utils;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.flurry.android.FlurryAgent;
import com.ksmaze.android.preference.ListPreferenceMultiSelect;
public class SSHTunnel extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
private static final String TAG = "SSHTunnel";
public static boolean runCommand(String command) {
Process process = null;
try {
process = Runtime.getRuntime().exec(command);
process.waitFor();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
} finally {
try {
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
private BroadcastReceiver ssidReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.w(TAG, "onReceived() called uncorrectly");
return;
}
loadNetworkList();
}
};
private ProgressDialog pd = null;
private static boolean isRoot = false;
private List<Profile> profileList;
private CheckBoxPreference isAutoConnectCheck;
private CheckBoxPreference isAutoReconnectCheck;
private CheckBoxPreference isAutoSetProxyCheck;
private CheckBoxPreference isSocksCheck;
private CheckBoxPreference isGFWListCheck;
private CheckBoxPreference isDNSProxyCheck;
private CheckBoxPreference isUpstreamProxyCheck;
private ListPreference profileListPreference;
private EditTextPreference hostText;
private EditTextPreference portText;
private EditTextPreference userText;
private EditTextPreference passwordText;
private EditTextPreference localPortText;
private EditTextPreference remotePortText;
private EditTextPreference remoteAddressText;
private EditTextPreference upstreamProxyText;
private CheckBoxPreference isRunningCheck;
private Preference proxyedApps;
private ListPreferenceMultiSelect ssidListPreference;
private static final int MSG_UPDATE_FINISHED = 0;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_FINISHED:
Toast.makeText(SSHTunnel.this,
getString(R.string.update_finished), Toast.LENGTH_LONG)
.show();
break;
}
super.handleMessage(msg);
}
};
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
for (int i = 0; i < files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
// if (!(new File("/data/data/org.sshtunnel/" +
// files[i])).exists()) {
in = assetManager.open(files[i]);
out = new FileOutputStream("/data/data/org.sshtunnel/"
+ files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
// }
} catch (Exception e) {
Log.e(TAG, "Assets error", e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
private void delProfile() {
if (profileList.size() > 1) {
// del current profile
boolean result = ProfileFactory.delFromDao();
if (result == false)
Log.e(TAG, "del profile error");
// refresh profile list
loadProfileList();
// save the next profile to preference
ProfileFactory.saveToPreference();
// switch to the last profile
Profile profile = ProfileFactory.getProfile();
int id = profile.getId();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor ed = settings.edit();
ed.putString(Constraints.ID, Integer.toString(id));
ed.commit();
// change the profile list value
profileListPreference.setValue(Integer.toString(id));
}
}
public boolean detectRoot() {
try {
Process proc = Runtime.getRuntime().exec("su");
if (proc == null)
return false;
proc.destroy();
} catch (Exception e) {
return false;
}
return true;
}
private void disableAll() {
hostText.setEnabled(false);
portText.setEnabled(false);
userText.setEnabled(false);
passwordText.setEnabled(false);
localPortText.setEnabled(false);
remotePortText.setEnabled(false);
remoteAddressText.setEnabled(false);
proxyedApps.setEnabled(false);
profileListPreference.setEnabled(false);
ssidListPreference.setEnabled(false);
upstreamProxyText.setEnabled(false);
isSocksCheck.setEnabled(false);
isAutoSetProxyCheck.setEnabled(false);
isAutoConnectCheck.setEnabled(false);
isAutoReconnectCheck.setEnabled(false);
isGFWListCheck.setEnabled(false);
isDNSProxyCheck.setEnabled(false);
isUpstreamProxyCheck.setEnabled(false);
}
private void enableAll() {
hostText.setEnabled(true);
portText.setEnabled(true);
userText.setEnabled(true);
passwordText.setEnabled(true);
localPortText.setEnabled(true);
if (!isSocksCheck.isChecked()) {
remotePortText.setEnabled(true);
remoteAddressText.setEnabled(true);
}
if (!isGFWListCheck.isChecked()) {
isAutoSetProxyCheck.setEnabled(true);
if (!isAutoSetProxyCheck.isChecked())
proxyedApps.setEnabled(true);
}
if (isAutoConnectCheck.isChecked()) {
ssidListPreference.setEnabled(true);
}
if (isUpstreamProxyCheck.isChecked()) {
upstreamProxyText.setEnabled(true);
}
profileListPreference.setEnabled(true);
isGFWListCheck.setEnabled(true);
isSocksCheck.setEnabled(true);
isAutoConnectCheck.setEnabled(true);
isAutoReconnectCheck.setEnabled(true);
isDNSProxyCheck.setEnabled(true);
isUpstreamProxyCheck.setEnabled(true);
}
private String getVersionName() {
try {
return getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
return "NONE";
}
}
private void initProfileList() {
profileList = ProfileFactory.loadAllProfilesFromDao();
if (profileList == null || profileList.size() == 0) {
ProfileFactory.newProfile();
Profile profile = ProfileFactory.getProfile();
profile.setName(getString(R.string.profile_default));
ProfileFactory.saveToDao();
ProfileFactory.saveToPreference();
}
loadProfileList();
}
private boolean isTextEmpty(String s, String msg) {
if (s == null || s.length() <= 0) {
showAToast(msg);
return true;
}
return false;
}
private void loadNetworkList() {
WifiManager wm = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> wcs = wm.getConfiguredNetworks();
String[] ssidEntries = new String[wcs.size() + 3];
ssidEntries[0] = Constraints.WIFI_AND_3G;
ssidEntries[1] = Constraints.ONLY_WIFI;
ssidEntries[2] = Constraints.ONLY_3G;
int n = 3;
for (WifiConfiguration wc : wcs) {
if (wc != null && wc.SSID != null)
ssidEntries[n++] = wc.SSID.replace("\"", "");
else
ssidEntries[n++] = "unknown";
}
ssidListPreference.setEntries(ssidEntries);
ssidListPreference.setEntryValues(ssidEntries);
}
private void loadProfileList() {
profileList = ProfileFactory.loadAllProfilesFromDao();
String[] profileEntries = new String[profileList.size() + 1];
String[] profileValues = new String[profileList.size() + 1];
int index = 0;
for (Profile profile : profileList) {
profileEntries[index] = Utils.getProfileName(profile);
profileValues[index] = Integer.toString(profile.getId());
index++;
}
profileEntries[index] = getString(R.string.profile_new);
profileValues[index] = Integer.toString(-1);
profileListPreference.setEntries(profileEntries);
profileListPreference.setEntryValues(profileValues);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.main_pre);
hostText = (EditTextPreference) findPreference("host");
portText = (EditTextPreference) findPreference("port");
userText = (EditTextPreference) findPreference("user");
passwordText = (EditTextPreference) findPreference("password");
localPortText = (EditTextPreference) findPreference("localPort");
remotePortText = (EditTextPreference) findPreference("remotePort");
remoteAddressText = (EditTextPreference) findPreference("remoteAddress");
upstreamProxyText = (EditTextPreference) findPreference("upstreamProxy");
proxyedApps = findPreference("proxyedApps");
profileListPreference = (ListPreference) findPreference("profile_id");
ssidListPreference = (ListPreferenceMultiSelect) findPreference("ssid");
isRunningCheck = (CheckBoxPreference) findPreference("isRunning");
isAutoSetProxyCheck = (CheckBoxPreference) findPreference("isAutoSetProxy");
isSocksCheck = (CheckBoxPreference) findPreference("isSocks");
isAutoConnectCheck = (CheckBoxPreference) findPreference("isAutoConnect");
isAutoReconnectCheck = (CheckBoxPreference) findPreference("isAutoReconnect");
isGFWListCheck = (CheckBoxPreference) findPreference("isGFWList");
isDNSProxyCheck = (CheckBoxPreference) findPreference("isDNSProxy");
isUpstreamProxyCheck = (CheckBoxPreference) findPreference("isUpstreamProxy");
registerReceiver(ssidReceiver, new IntentFilter(
android.net.ConnectivityManager.CONNECTIVITY_ACTION));
loadNetworkList();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor edit = settings.edit();
if (Utils.isWorked()) {
edit.putBoolean("isRunning", true);
} else {
if (settings.getBoolean("isRunning", false)) {
// showAToast(getString(R.string.crash_alert));
recovery();
}
edit.putBoolean("isRunning", false);
}
edit.commit();
if (settings.getBoolean("isRunning", false)) {
isRunningCheck.setChecked(true);
disableAll();
} else {
isRunningCheck.setChecked(false);
enableAll();
}
if (!detectRoot()) {
isRoot = false;
} else {
isRoot = true;
}
if (!isRoot) {
isAutoSetProxyCheck.setChecked(false);
isAutoSetProxyCheck.setEnabled(false);
proxyedApps.setEnabled(false);
showAToast(getString(R.string.require_root_alert));
}
initProfileList();
if (!settings.getBoolean(getVersionName(), false)) {
new Thread() {
@Override
public void run() {
CopyAssets();
runCommand("chmod 755 /data/data/org.sshtunnel/iptables");
runCommand("chmod 755 /data/data/org.sshtunnel/redsocks");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_http.sh");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_socks.sh");
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnel.this);
String versionName = getVersionName();
Editor edit = settings.edit();
edit = settings.edit();
edit.putBoolean(versionName, true);
edit.commit();
handler.sendEmptyMessage(MSG_UPDATE_FINISHED);
}
}.start();
}
}
// 点击Menu时,系统调用当前Activity的onCreateOptionsMenu方法,并传一个实现了一个Menu接口的menu对象供你使用
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/*
* add()方法的四个参数,依次是: 1、组别,如果不分组的话就写Menu.NONE,
* 2、Id,这个很重要,Android根据这个Id来确定不同的菜单 3、顺序,那个菜单现在在前面由这个参数的大小决定
* 4、文本,菜单的显示文本
*/
menu.add(Menu.NONE, Menu.FIRST + 3, 1, getString(R.string.about))
.setIcon(android.R.drawable.ic_menu_info_details);
menu.add(Menu.NONE, Menu.FIRST + 4, 2, getString(R.string.key_manager))
.setIcon(android.R.drawable.ic_menu_manage);
menu.add(Menu.NONE, Menu.FIRST + 1, 3, getString(R.string.recovery))
.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
menu.add(Menu.NONE, Menu.FIRST + 5, 4, getString(R.string.change_name))
.setIcon(android.R.drawable.ic_menu_edit);
menu.add(Menu.NONE, Menu.FIRST + 2, 5, getString(R.string.profile_del))
.setIcon(android.R.drawable.ic_menu_delete);
// return true才会起作用
return true;
}
/** Called when the activity is closed. */
@Override
public void onDestroy() {
unregisterReceiver(ssidReceiver);
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK,同时没有重复
try {
finish();
} catch (Exception ignore) {
// Nothing
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// 菜单项被选择事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu.FIRST + 1:
CopyAssets();
runCommand("chmod 755 /data/data/org.sshtunnel/iptables");
runCommand("chmod 755 /data/data/org.sshtunnel/redsocks");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_http.sh");
runCommand("chmod 755 /data/data/org.sshtunnel/proxy_socks.sh");
recovery();
break;
case Menu.FIRST + 2:
delProfile();
break;
case Menu.FIRST + 3:
String versionName = "";
try {
versionName = getPackageManager().getPackageInfo(
getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
versionName = "";
}
showAToast(getString(R.string.about) + " (" + versionName + ")"
+ getString(R.string.copy_rights));
break;
case Menu.FIRST + 4:
Intent intent = new Intent(this, FileChooser.class);
startActivity(intent);
break;
case Menu.FIRST + 5:
rename();
break;
}
return true;
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
if (preference.getKey() != null
&& preference.getKey().equals("proxyedApps")) {
Intent intent = new Intent(this, AppManager.class);
startActivity(intent);
} else if (preference.getKey() != null
&& preference.getKey().equals("isRunning")) {
if (!serviceStart()) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnel.this);
Editor edit = settings.edit();
edit.putBoolean("isRunning", false);
edit.commit();
enableAll();
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
if (settings.getBoolean("isGFWList", false)) {
isAutoSetProxyCheck.setEnabled(false);
proxyedApps.setEnabled(false);
} else {
isAutoSetProxyCheck.setEnabled(true);
if (settings.getBoolean("isAutoSetProxy", false))
proxyedApps.setEnabled(false);
else
proxyedApps.setEnabled(true);
}
if (settings.getBoolean("isSocks", false)) {
remotePortText.setEnabled(false);
remoteAddressText.setEnabled(false);
} else {
remotePortText.setEnabled(true);
remoteAddressText.setEnabled(true);
}
if (settings.getBoolean("isConnecting", false)) {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
Editor edit = settings.edit();
if (Utils.isWorked()) {
if (settings.getBoolean("isConnecting", false))
isRunningCheck.setEnabled(false);
edit.putBoolean("isRunning", true);
} else {
if (settings.getBoolean("isRunning", false)) {
showAToast(getString(R.string.crash_alert));
recovery();
}
edit.putBoolean("isRunning", false);
}
edit.commit();
if (settings.getBoolean("isAutoConnecting", false)) {
ssidListPreference.setEnabled(true);
} else {
ssidListPreference.setEnabled(false);
}
if (settings.getBoolean("isUpstreamProxy", false)) {
upstreamProxyText.setEnabled(true);
} else {
upstreamProxyText.setEnabled(false);
}
if (settings.getBoolean("isRunning", false)) {
isRunningCheck.setChecked(true);
disableAll();
} else {
isRunningCheck.setChecked(false);
enableAll();
}
// Setup the initial values
Profile profile = ProfileFactory.getProfile();
profileListPreference.setValue(Integer.toString(profile.getId()));
profileListPreference.setSummary(Utils.getProfileName(profile));
if (!settings.getString("ssid", "").equals(""))
ssidListPreference.setSummary(settings.getString("ssid", ""));
if (!settings.getString("user", "").equals(""))
userText.setSummary(settings.getString("user",
getString(R.string.user_summary)));
if (!settings.getString("port", "").equals(""))
portText.setSummary(settings.getString("port",
getString(R.string.port_summary)));
if (!settings.getString("host", "").equals(""))
hostText.setSummary(settings.getString("host",
getString(R.string.host_summary)));
if (!settings.getString("password", "").equals(""))
passwordText.setSummary("*********");
if (!settings.getString("localPort", "").equals(""))
localPortText.setSummary(settings.getString("localPort",
getString(R.string.local_port_summary)));
if (!settings.getString("remotePort", "").equals(""))
remotePortText.setSummary(settings.getString("remotePort",
getString(R.string.remote_port_summary)));
if (!settings.getString("remoteAddress", "").equals(""))
remoteAddressText.setSummary(settings.getString("remoteAddress",
getString(R.string.remote_port_summary)));
if (!settings.getString("upstreamProxy", "").equals(""))
upstreamProxyText.setSummary(settings.getString("upstreamProxy",
getString(R.string.upstream_proxy_summary)));
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
private void updateValue(Profile profile) {
hostText.setText(profile.getHost());
userText.setText(profile.getUser());
passwordText.setText(profile.getPassword());
remoteAddressText.setText(profile.getRemoteAddress());
ssidListPreference.setValue(profile.getSsid());
upstreamProxyText.setText(profile.getUpstreamProxy());
portText.setText(Integer.toString(profile.getPort()));
localPortText.setText(Integer.toString(profile.getLocalPort()));
remotePortText.setText(Integer.toString(profile.getRemotePort()));
isAutoReconnectCheck.setChecked(profile.isAutoReconnect());
isDNSProxyCheck.setChecked(profile.isDNSProxy());
}
@Override
public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
// Let's do something a preference value changes
if (key.equals(Constraints.ID)) {
ProfileFactory.loadFromPreference();
String id = settings.getString(Constraints.ID, "-1");
if (id.equals("-1")) {
// Create a new profile
ProfileFactory.newProfile();
// refresh profile list
loadProfileList();
// save the new profile to preference
ProfileFactory.saveToPreference();
// switch profile again
Profile profile = ProfileFactory.getProfile();
String profileId = Integer.toString(profile.getId());
Editor ed = settings.edit();
ed.putString(Constraints.ID, profileId);
ed.commit();
// change profile list value
profileListPreference.setValue(profileId);
} else {
int profileId;
try {
profileId = Integer.valueOf(id);
} catch (NumberFormatException e) {
profileList = ProfileFactory.loadAllProfilesFromDao();
profileId = profileList.get(0).getId();
}
ProfileFactory.switchToProfile(profileId);
Profile profile = ProfileFactory.getProfile();
profileListPreference.setSummary(Utils.getProfileName(profile));
updateValue(profile);
}
}
if (key.equals("isConnecting")) {
if (settings.getBoolean("isConnecting", false)) {
Log.d(TAG, "Connecting start");
isRunningCheck.setEnabled(false);
pd = ProgressDialog.show(this, "",
getString(R.string.connecting), true, true);
} else {
Log.d(TAG, "Connecting finish");
if (pd != null) {
pd.dismiss();
pd = null;
}
isRunningCheck.setEnabled(true);
}
}
if (key.equals("isSocks")) {
if (settings.getBoolean("isSocks", false)) {
isSocksCheck.setChecked(true);
remotePortText.setEnabled(false);
remoteAddressText.setEnabled(false);
} else {
isSocksCheck.setChecked(false);
remotePortText.setEnabled(true);
remoteAddressText.setEnabled(true);
}
}
if (key.equals("isGFWList")) {
if (settings.getBoolean("isGFWList", false)) {
isGFWListCheck.setChecked(true);
isAutoSetProxyCheck.setEnabled(false);
proxyedApps.setEnabled(false);
} else {
isGFWListCheck.setChecked(false);
isAutoSetProxyCheck.setEnabled(true);
if (settings.getBoolean("isAutoSetProxy", false))
proxyedApps.setEnabled(false);
else
proxyedApps.setEnabled(true);
}
}
if (key.equals("isAutoConnect")) {
if (settings.getBoolean("isAutoConnect", false)) {
isAutoConnectCheck.setChecked(true);
ssidListPreference.setEnabled(true);
} else {
isAutoConnectCheck.setChecked(false);
ssidListPreference.setEnabled(false);
}
}
if (key.equals("isAutoSetProxy")) {
if (!settings.getBoolean("isGFWList", false)) {
if (settings.getBoolean("isAutoSetProxy", false)) {
isAutoSetProxyCheck.setChecked(true);
proxyedApps.setEnabled(false);
} else {
isAutoSetProxyCheck.setChecked(false);
proxyedApps.setEnabled(true);
}
}
}
if (key.equals("isUpstreamProxy")) {
if (settings.getBoolean("isUpstreamProxy", false)) {
isUpstreamProxyCheck.setChecked(true);
upstreamProxyText.setEnabled(true);
} else {
isUpstreamProxyCheck.setChecked(false);
upstreamProxyText.setEnabled(false);
}
}
if (key.equals("isRunning")) {
if (settings.getBoolean("isRunning", false)) {
disableAll();
isRunningCheck.setChecked(true);
} else {
enableAll();
isRunningCheck.setChecked(false);
}
}
if (key.equals("ssid"))
if (settings.getString("ssid", "").equals(""))
ssidListPreference.setSummary(getString(R.string.ssid_summary));
else
ssidListPreference.setSummary(settings.getString("ssid", ""));
else if (key.equals("user"))
if (settings.getString("user", "").equals(""))
userText.setSummary(getString(R.string.user_summary));
else
userText.setSummary(settings.getString("user", ""));
else if (key.equals("port"))
if (settings.getString("port", "").equals(""))
portText.setSummary(getString(R.string.port_summary));
else
portText.setSummary(settings.getString("port", ""));
else if (key.equals("host"))
if (settings.getString("host", "").equals(""))
hostText.setSummary(getString(R.string.host_summary));
else
hostText.setSummary(settings.getString("host", ""));
else if (key.equals("localPort"))
if (settings.getString("localPort", "").equals(""))
localPortText
.setSummary(getString(R.string.local_port_summary));
else
localPortText.setSummary(settings.getString("localPort", ""));
else if (key.equals("remotePort"))
if (settings.getString("remotePort", "").equals(""))
remotePortText
.setSummary(getString(R.string.remote_port_summary));
else
remotePortText.setSummary(settings.getString("remotePort", ""));
else if (key.equals("remoteAddress"))
if (settings.getString("remoteAddress", "").equals(""))
remoteAddressText
.setSummary(getString(R.string.remote_port_summary));
else
remoteAddressText.setSummary(settings.getString(
"remoteAddress", ""));
else if (key.equals("password"))
if (!settings.getString("password", "").equals(""))
passwordText.setSummary("*********");
else
passwordText.setSummary(getString(R.string.password_summary));
else if (key.equals("upstreamProxy"))
if (settings.getString("upstreamProxy", "").equals(""))
upstreamProxyText
.setSummary(getString(R.string.upstream_proxy_summary));
else
upstreamProxyText.setSummary(settings.getString(
"upstreamProxy", ""));
}
@Override
public void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, "MBY4JL18FQK1DPEJ5Y39");
}
@Override
public void onStop() {
super.onStop();
FlurryAgent.onEndSession(this);
}
private void recovery() {
new Thread() {
@Override
public void run() {
try {
stopService(new Intent(SSHTunnel.this,
SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
try {
File cache = new File(SSHTunnelService.BASE
+ "cache/dnscache");
if (cache.exists())
cache.delete();
} catch (Exception ignore) {
// Nothing
}
runRootCommand(SSHTunnelService.BASE
+ "iptables -t nat -F OUTPUT");
runRootCommand(SSHTunnelService.BASE + "proxy_http.sh stop");
}
}.start();
}
private void rename() {
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(
R.layout.alert_dialog_text_entry, null);
final EditText profileName = (EditText) textEntryView
.findViewById(R.id.profile_name_edit);
final Profile profile = ProfileFactory.getProfile();
profileName.setText(Utils.getProfileName(profile));
AlertDialog ad = new AlertDialog.Builder(this)
.setTitle(R.string.change_name)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
EditText profileName = (EditText) textEntryView
.findViewById(R.id.profile_name_edit);
String name = profileName.getText().toString();
if (name == null)
return;
name = name.replace("|", "");
if (name.length() <= 0)
return;
profile.setName(name);
ProfileFactory.saveToDao();
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(SSHTunnel.this);
Editor ed = settings.edit();
ed.putString(Constraints.NAME,
profile.getName());
ed.commit();
profileListPreference.setSummary(Utils
.getProfileName(profile));
loadProfileList();
}
})
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
/* User clicked cancel so do some stuff */
}
}).create();
ad.show();
}
/** Called when connect button is clicked. */
public boolean serviceStart() {
if (Utils.isWorked()) {
try {
stopService(new Intent(SSHTunnel.this, SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
return false;
}
Profile profile = ProfileFactory.getProfile();
ProfileFactory.loadFromPreference();
if (isTextEmpty(profile.getHost(), getString(R.string.host_empty)))
return false;
if (isTextEmpty(profile.getUser(), getString(R.string.user_empty)))
return false;
try {
if (isTextEmpty(Integer.toString(profile.getPort()),
getString(R.string.port_empty)))
return false;
if (isTextEmpty(Integer.toString(profile.getLocalPort()),
getString(R.string.local_port_empty)))
return false;
if (profile.getLocalPort() <= 1024)
this.showAToast(getString(R.string.port_alert));
if (!profile.isSocks()) {
if (isTextEmpty(Integer.toString(profile.getRemotePort()),
getString(R.string.remote_port_empty)))
return false;
}
} catch (NullPointerException e) {
showAToast(getString(R.string.number_alert));
Log.e(TAG, "wrong number", e);
return false;
}
try {
Intent it = new Intent(SSHTunnel.this, SSHTunnelService.class);
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profile.getId());
it.putExtras(bundle);
startService(it);
} catch (Exception ignore) {
// Nothing
return false;
}
return true;
}
private void showAToast(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setNegativeButton(getString(R.string.ok_iknow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
} | Java |
package org.sshtunnel;
import android.app.Application;
import android.content.Context;
public class SSHTunnelContext extends Application {
private static Context context;
public void onCreate() {
SSHTunnelContext.context = getApplicationContext();
}
public static Context getAppContext() {
return context;
}
}
| Java |
package org.sshtunnel;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.sshtunnel.utils.Constraints;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class FileChooser extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
private void fill(File f) {
File[] dirs = f.listFiles();
this.setTitle(getString(R.string.current_dir) + ": " + f.getName());
List<Option> dir = new ArrayList<Option>();
List<Option> fls = new ArrayList<Option>();
try {
for (File ff : dirs) {
if (ff.isDirectory())
dir.add(new Option(ff.getName(),
getString(R.string.folder), ff.getAbsolutePath()));
else {
fls.add(new Option(ff.getName(),
getString(R.string.file_size) + ff.length(), ff
.getAbsolutePath()));
}
}
} catch (Exception e) {
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if (!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,
new Option("..", getString(R.string.parent_dir), f
.getParent()));
adapter = new FileArrayAdapter(FileChooser.this, R.layout.file_view,
dir);
this.setListAdapter(adapter);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentDir = new File("/sdcard/");
fill(currentDir);
}
private void onFileClick(Option o) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
Editor ed = settings.edit();
ed.putString(Constraints.KEY_PATH, o.getPath());
ed.commit();
Toast.makeText(this, getString(R.string.file_toast) + o.getPath(),
Toast.LENGTH_SHORT).show();
finish();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Option o = adapter.getItem(position);
if (o.getData().equalsIgnoreCase(getString(R.string.folder))
|| o.getData().equalsIgnoreCase(getString(R.string.parent_dir))) {
currentDir = new File(o.getPath());
fill(currentDir);
} else {
onFileClick(o);
}
}
} | Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.ProxyedApp;
import org.sshtunnel.utils.Utils;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.flurry.android.FlurryAgent;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.DynamicPortForwarder;
import com.trilead.ssh2.HTTPProxyData;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.LocalPortForwarder;
import com.trilead.ssh2.ServerHostKeyVerifier;
public class SSHTunnelService extends Service implements ServerHostKeyVerifier,
InteractiveCallback, ConnectionMonitor {
// ConnectivityBroadcastReceiver stateChanged = null;
private Notification notification;
private NotificationManager notificationManager;
private Intent intent;
private PendingIntent pendIntent;
private static final String TAG = "SSHTunnel";
private static final int MSG_CONNECT_START = 0;
private static final int MSG_CONNECT_FINISH = 1;
private static final int MSG_CONNECT_SUCCESS = 2;
private static final int MSG_CONNECT_FAIL = 3;
private static final int MSG_DISCONNECT_FINISH = 4;
private static final String AUTH_PUBLICKEY = "publickey",
AUTH_PASSWORD = "password",
AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive";
// Global settings
private SharedPreferences settings = null;
// Current profile
private Profile profile;
// Host IP address
private String hostAddress = null;
// Upstream proxy
private HTTPProxyData proxyData = null;
// DNS proxy option
private boolean enableDNSProxy = true;
// DNS proxy
private DNSServer dnsServer = null;
private int dnsPort = 0;
// Fingerprint Checker
private boolean fingerPrintChecker = false;
private Object fingerPrintLock = new Object();
// Port forwarding
private LocalPortForwarder lpf = null;
private LocalPortForwarder dnspf = null;
private DynamicPortForwarder dpf = null;
// Connecting / Stopping lock
public volatile static boolean isConnecting = false;
public volatile static boolean isStopping = false;
private final static int AUTH_TRIES = 1;
private final static int RECONNECT_TRIES = 2;
private Connection connection;
private volatile boolean connected = false;
private ProxyedApp apps[] = null;
public final static String BASE = "/data/data/org.sshtunnel/";
final static String CMD_IPTABLES_REDIRECT_ADD = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 80 -j REDIRECT --to 8123\n"
+ BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 443 -j REDIRECT --to 8124\n";
final static String CMD_IPTABLES_DNAT_ADD = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 80 -j DNAT --to-destination 127.0.0.1:8123\n"
+ BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp --dport 443 -j DNAT --to-destination 127.0.0.1:8124\n";
final static String CMD_IPTABLES_REDIRECT_ADD_SOCKS = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp -j REDIRECT --to 8123\n";
final static String CMD_IPTABLES_DNAT_ADD_SOCKS = BASE
+ "iptables -t nat -A SSHTUNNEL -p tcp -j DNAT --to-destination 127.0.0.1:8123\n";
final static String CMD_IPTABLES_RETURN = BASE
+ "iptables -t nat -A OUTPUT -p tcp -d 0.0.0.0 -j RETURN\n";
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
Log.d(TAG, command);
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
/*
* This is a hack see
* http://www.mail-archive.com/android-developers@googlegroups
* .com/msg18298.html we are not really able to decide if the service was
* started. So we remember a week reference to it. We set it if we are
* running and clear it if we are stopped. If anything goes wrong, the
* reference will hopefully vanish
*/
private static WeakReference<SSHTunnelService> sRunningInstance = null;
public final static boolean isServiceStarted() {
final boolean isServiceStarted;
if (sRunningInstance == null) {
isServiceStarted = false;
} else if (sRunningInstance.get() == null) {
isServiceStarted = false;
sRunningInstance = null;
} else {
isServiceStarted = true;
}
return isServiceStarted;
}
private void markServiceStarted() {
sRunningInstance = new WeakReference<SSHTunnelService>(this);
}
private void markServiceStopped() {
sRunningInstance = null;
}
// Flag indicating if this is an ARMv6 device (-1: unknown, 0: no, 1: yes)
private boolean hasRedirectSupport = true;
private String reason = null;
private static final Class<?>[] mStartForegroundSignature = new Class[] {
int.class, Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Editor ed = settings.edit();
switch (msg.what) {
case MSG_CONNECT_START:
ed.putBoolean("isConnecting", true);
break;
case MSG_CONNECT_FINISH:
ed.putBoolean("isConnecting", false);
ed.putBoolean("isSwitching", false);
break;
case MSG_CONNECT_SUCCESS:
ed.putBoolean("isRunning", true);
// stateChanged = new ConnectivityBroadcastReceiver();
// registerReceiver(stateChanged, new IntentFilter(
// ConnectivityManager.CONNECTIVITY_ACTION));
break;
case MSG_CONNECT_FAIL:
ed.putBoolean("isRunning", false);
break;
case MSG_DISCONNECT_FINISH:
ed.putBoolean("isRunning", false);
ed.putBoolean("isSwitching", false);
try {
notificationManager.cancel(0);
notificationManager.cancel(1);
} catch (Exception ignore) {
// Nothing
}
// for widget, maybe exception here
try {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.sshtunnel_appwidget);
views.setImageViewResource(R.id.serviceToggle,
R.drawable.off);
AppWidgetManager awm = AppWidgetManager
.getInstance(SSHTunnelService.this);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(
SSHTunnelService.this,
SSHTunnelWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
break;
}
ed.commit();
super.handleMessage(msg);
}
};
final BroadcastReceiver hostKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Constraints.FINGER_PRINT_ACTION)) {
if (intent.getBooleanExtra(
Constraints.FINGER_PRINT_ACTION_ACCEPT, false)) {
fingerPrintChecker = true;
synchronized (fingerPrintLock) {
fingerPrintLock.notifyAll();
}
} else {
fingerPrintChecker = false;
synchronized (fingerPrintLock) {
fingerPrintLock.notifyAll();
}
}
}
unregisterReceiver(hostKeyReceiver);
}
};
final Handler hostKeyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
Intent i = new Intent(SSHTunnelService.this,
FingerPrintDialog.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtras(bundle);
startActivity(i);
IntentFilter filter = new IntentFilter(
Constraints.FINGER_PRINT_ACTION);
registerReceiver(hostKeyReceiver, filter);
}
};
private void authenticate() {
try {
if (connection.authenticateWithNone(profile.getUser())) {
Log.d(TAG, "Authenticate with none");
return;
}
} catch (Exception e) {
Log.d(TAG, "Host does not support 'none' authentication.");
}
try {
if (connection.isAuthMethodAvailable(profile.getUser(),
AUTH_PUBLICKEY)) {
File f = new File(profile.getKeyPath());
if (f.exists())
if (profile.getPassword().equals(""))
profile.setPassword(null);
if (connection.authenticateWithPublicKey(profile.getUser(), f,
profile.getPassword())) {
Log.d(TAG, "Authenticate with public key");
return;
}
}
} catch (Exception e) {
Log.d(TAG, "Host does not support 'Public key' authentication.");
}
try {
if (connection.isAuthMethodAvailable(profile.getUser(),
AUTH_PASSWORD)) {
if (connection.authenticateWithPassword(profile.getUser(),
profile.getPassword())) {
Log.d(TAG, "Authenticate with password");
return;
}
}
} catch (IllegalStateException e) {
Log.e(TAG,
"Connection went away while we were trying to authenticate",
e);
} catch (Exception e) {
Log.e(TAG, "Problem during handleAuthentication()", e);
}
// TODO: Need verification
try {
if (connection.isAuthMethodAvailable(profile.getUser(),
AUTH_KEYBOARDINTERACTIVE)) {
if (connection.authenticateWithKeyboardInteractive(
profile.getUser(), this))
return;
}
} catch (Exception e) {
Log.d(TAG,
"Host does not support 'Keyboard-Interactive' authentication.");
}
}
public boolean connect() {
// try {
//
// connection.setCompression(true);
// connection.setTCPNoDelay(true);
//
// } catch (IOException e) {
// Log.e(TAG, "Could not enable compression!", e);
// }
// initialize the upstream proxy
if (profile.isUpstreamProxy()) {
try {
if (profile.getUpstreamProxy() == null
|| profile.getUpstreamProxy().equals(""))
throw new Exception();
String[] proxyInfo = profile.getUpstreamProxy().split("@");
if (proxyInfo.length == 1) {
String[] hostInfo = proxyInfo[0].split(":");
if (hostInfo.length != 2)
throw new Exception();
proxyData = new HTTPProxyData(hostInfo[0],
Integer.valueOf(hostInfo[1]));
} else if (proxyInfo.length == 2) {
String[] userInfo = proxyInfo[0].split(":");
if (userInfo.length != 2)
throw new Exception();
String[] hostInfo = proxyInfo[1].split(":");
if (hostInfo.length != 2)
throw new Exception();
proxyData = new HTTPProxyData(hostInfo[0],
Integer.valueOf(hostInfo[1]), userInfo[0],
userInfo[1]);
} else {
throw new Exception();
}
} catch (Exception e) {
if (reason == null)
reason = getString(R.string.upstream_format_error);
return false;
}
}
// get the host ip address
if (proxyData != null) {
try {
hostAddress = InetAddress.getByName(proxyData.proxyHost)
.getHostAddress();
} catch (UnknownHostException e) {
hostAddress = null;
}
} else {
try {
hostAddress = InetAddress.getByName(profile.getHost())
.getHostAddress();
} catch (UnknownHostException e) {
hostAddress = null;
}
}
// fail to connect if the dns lookup failed
if (hostAddress == null) {
if (reason == null)
reason = getString(R.string.fail_to_connect);
return false;
}
// begin to connect
try {
connection = new Connection(profile.getHost(), profile.getPort());
if (proxyData != null)
connection.setProxyData(proxyData);
connection.addConnectionMonitor(this);
/*
* Uncomment when debugging SSH protocol:
*/
/*
* DebugLogger logger = new DebugLogger() {
*
* public void log(int level, String className, String message) {
* Log.d("SSH", message); }
*
* };
*
* Logger.enabled = true; Logger.logger = logger;
*/
connection.connect(this, 10 * 1000, 20 * 1000);
connected = true;
} catch (Exception e) {
Log.e(TAG, "Problem in SSH connection thread during connecting", e);
// Display the reason in the text.
if (reason == null)
reason = getString(R.string.fail_to_connect);
return false;
}
try {
// enter a loop to keep trying until authentication
int tries = 0;
while (connected && !connection.isAuthenticationComplete()
&& tries++ < AUTH_TRIES) {
authenticate();
// sleep to make sure we dont kill system
Thread.sleep(1000);
}
} catch (Exception e) {
Log.e(TAG,
"Problem in SSH connection thread during authentication", e);
if (reason == null)
reason = getString(R.string.fail_to_authenticate);
return false;
}
try {
if (connection.isAuthenticationComplete()) {
return enablePortForward();
}
} catch (Exception e) {
Log.e(TAG, "Problem in SSH connection thread during enabling port",
e);
if (reason == null)
reason = getString(R.string.fail_to_connect);
return false;
}
if (reason == null)
reason = getString(R.string.fail_to_authenticate);
Log.e(TAG, "Cannot authenticate");
return false;
}
@Override
public void connectionLost(Throwable reason) {
Log.d(TAG, "Connection Lost");
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
if (isConnecting || isStopping) {
return;
}
if (!isOnline()) {
stopReconnect(df);
return;
}
if (reason != null) {
if (reason.getMessage().contains(
"There was a problem during connect")) {
Log.e(TAG, "connection lost", reason);
return;
} else if (reason.getMessage().contains(
"Closed due to user request")) {
Log.e(TAG, "connection lost", reason);
return;
} else if (reason.getMessage().contains(
"The connect timeout expired")) {
stopReconnect(df);
return;
}
Log.e(TAG, "connection lost: " + reason.getMessage());
} else {
stopReconnect(df);
return;
}
if (profile.isAutoReconnect() && connected) {
for (int reconNum = 1; reconNum <= RECONNECT_TRIES; reconNum++) {
Log.d(TAG, "Reconnect tries: " + reconNum);
onDisconnect();
if (!connect()) {
try {
Thread.sleep(2000 * reconNum);
} catch (Exception ignore) {
// Nothing
}
continue;
}
notifyAlert(
getString(R.string.reconnect_success) + " "
+ df.format(new Date()),
getString(R.string.reconnect_success));
return;
}
}
stopReconnect(df);
}
public boolean enablePortForward() {
/*
* DynamicPortForwarder dpf = null;
*
* try { dpf = connection.createDynamicPortForwarder(new
* InetSocketAddress( InetAddress.getLocalHost(), 1984)); } catch
* (Exception e) { Log.e(TAG, "Could not create dynamic port forward",
* e); return false; }
*/
// LocalPortForwarder lpf1 = null;
try {
dnspf = connection.createLocalPortForwarder(8053, "www.google.com",
80);
if (profile.isSocks()) {
dpf = connection.createDynamicPortForwarder(profile
.getLocalPort());
} else {
lpf = connection.createLocalPortForwarder(
profile.getLocalPort(), profile.getRemoteAddress(),
profile.getRemotePort());
}
} catch (Exception e) {
Log.e(TAG, "Could not create local port forward", e);
if (reason == null)
reason = getString(R.string.fail_to_forward);
return false;
}
return true;
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
private void finishConnection() {
Log.e(TAG, "Forward Successful");
if (profile.isSocks())
runRootCommand(BASE + "proxy_socks.sh start "
+ profile.getLocalPort());
else
runRootCommand(BASE + "proxy_http.sh start "
+ profile.getLocalPort());
StringBuffer cmd = new StringBuffer();
cmd.append(BASE + "iptables -t nat -N SSHTUNNEL\n");
cmd.append(BASE + "iptables -t nat -F SSHTUNNEL\n");
if (enableDNSProxy) {
cmd.append(BASE + "iptables -t nat -N SSHTUNNELDNS\n");
cmd.append(BASE + "iptables -t nat -F SSHTUNNELDNS\n");
if (hasRedirectSupport)
cmd.append(BASE
+ "iptables "
+ "-t nat -A SSHTUNNELDNS -p udp --dport 53 -j REDIRECT --to "
+ dnsPort + "\n");
else
cmd.append(BASE
+ "iptables "
+ "-t nat -A SSHTUNNELDNS -p udp --dport 53 -j DNAT --to-destination 127.0.0.1:"
+ dnsPort + "\n");
cmd.append(BASE
+ "iptables -t nat -A OUTPUT -p udp -j SSHTUNNELDNS\n");
}
if (profile.isSocks())
cmd.append(hasRedirectSupport ? CMD_IPTABLES_REDIRECT_ADD_SOCKS
: CMD_IPTABLES_DNAT_ADD_SOCKS);
else
cmd.append(hasRedirectSupport ? CMD_IPTABLES_REDIRECT_ADD
: CMD_IPTABLES_DNAT_ADD);
cmd.append(CMD_IPTABLES_RETURN.replace("0.0.0.0", hostAddress));
if (profile.isGFWList()) {
String[] gfw_list = getResources().getStringArray(R.array.gfw_list);
for (String item : gfw_list) {
cmd.append(BASE + "iptables -t nat -A OUTPUT -p tcp -d " + item
+ " -j SSHTUNNEL\n");
}
} else if (profile.isAutoSetProxy()) {
cmd.append(BASE + "iptables -t nat -A OUTPUT -p tcp -j SSHTUNNEL\n");
} else {
// for proxy specified apps
if (apps == null || apps.length <= 0)
apps = AppManager
.getProxyedApps(this, profile.getProxyedApps());
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
cmd.append(BASE + "iptables "
+ "-t nat -m owner --uid-owner " + apps[i].getUid()
+ " -A OUTPUT -p tcp -j SSHTUNNEL\n");
}
}
}
String rules = cmd.toString();
if (hostAddress != null)
rules = rules.replace("--dport 443",
"! -d " + hostAddress + " --dport 443").replace(
"--dport 80", "! -d " + hostAddress + " --dport 80");
if (profile.isSocks())
runRootCommand(rules.replace("8124", "8123"));
else
runRootCommand(rules);
}
private void flushIptables() {
StringBuffer cmd = new StringBuffer();
cmd.append(BASE + "iptables -t nat -F SSHTUNNEL\n");
cmd.append(BASE + "iptables -t nat -X SSHTUNNEL\n");
cmd.append((CMD_IPTABLES_RETURN.replace("0.0.0.0", hostAddress))
.replace("-A", "-D"));
if (enableDNSProxy) {
cmd.append(BASE + "iptables -t nat -F SSHTUNNELDNS\n");
cmd.append(BASE + "iptables -t nat -X SSHTUNNELDNS\n");
cmd.append(BASE
+ "iptables -t nat -D OUTPUT -p udp -j SSHTUNNELDNS\n");
}
if (profile.isGFWList()) {
String[] gfw_list = getResources().getStringArray(R.array.gfw_list);
for (String item : gfw_list) {
cmd.append(BASE + "iptables -t nat -D OUTPUT -p tcp -d " + item
+ " -j SSHTUNNEL\n");
}
} else if (profile.isAutoSetProxy()) {
cmd.append(BASE + "iptables -t nat -D OUTPUT -p tcp -j SSHTUNNEL\n");
} else {
// for proxy specified apps
if (apps == null || apps.length <= 0)
apps = AppManager
.getProxyedApps(this, profile.getProxyedApps());
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
cmd.append(BASE + "iptables "
+ "-t nat -m owner --uid-owner " + apps[i].getUid()
+ " -D OUTPUT -p tcp -j SSHTUNNEL\n");
}
}
}
String rules = cmd.toString();
runRootCommand(rules);
if (profile.isSocks())
runRootCommand(BASE + "proxy_socks.sh stop");
else
runRootCommand(BASE + "proxy_http.sh stop");
}
private void initHasRedirectSupported() {
Process process = null;
DataOutputStream os = null;
DataInputStream es = null;
String command;
String line = null;
command = BASE
+ "iptables -t nat -A OUTPUT -p udp --dport 54 -j REDIRECT --to 8154";
try {
process = Runtime.getRuntime().exec("su");
es = new DataInputStream(process.getErrorStream());
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
while (null != (line = es.readLine())) {
Log.d(TAG, line);
if (line.contains("No chain/target/match")) {
this.hasRedirectSupport = false;
break;
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
} finally {
try {
if (os != null) {
os.close();
}
if (es != null)
es.close();
process.destroy();
} catch (Exception e) {
// nothing
}
}
// flush the check command
runRootCommand(command.replace("-A", "-D"));
}
private void initSoundVibrateLights(Notification notification) {
final String ringtone = settings.getString(
"settings_key_notif_ringtone", null);
AudioManager audioManager = (AudioManager) this
.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_RING) == 0) {
notification.sound = null;
} else if (ringtone != null)
notification.sound = Uri.parse(ringtone);
else
notification.defaults |= Notification.DEFAULT_SOUND;
if (settings.getBoolean("settings_key_notif_icon", true)) {
notification.icon = R.drawable.ic_stat;
} else {
notification.icon = R.drawable.ic_stat_trans;
}
if (settings.getBoolean("settings_key_notif_vibrate", false)) {
long[] vibrate = { 0, 1000, 500, 1000, 500, 1000 };
notification.vibrate = vibrate;
}
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
void invokeMethod(Method method, Object[] args) {
try {
method.invoke(this, mStartForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke method", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke method", e);
}
}
public boolean isOnline() {
ConnectivityManager manager = (ConnectivityManager) this
.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null) {
if (reason == null)
reason = getString(R.string.fail_to_online);
return false;
}
return true;
}
private void notifyAlert(String title, String info) {
notification.tickerText = title;
notification.flags = Notification.FLAG_ONGOING_EVENT;
// notification.defaults = Notification.DEFAULT_SOUND;
initSoundVibrateLights(notification);
notification.setLatestEventInfo(this, getString(R.string.app_name)
+ " | " + Utils.getProfileName(profile), info, pendIntent);
notificationManager.cancel(1);
startForegroundCompat(1, notification);
}
private void notifyAlert(String title, String info, int flags) {
notification.tickerText = title;
notification.flags = flags;
initSoundVibrateLights(notification);
notification.setLatestEventInfo(this, getString(R.string.app_name)
+ " | " + Utils.getProfileName(profile), info, pendIntent);
notificationManager.cancel(0);
notificationManager.notify(0, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
settings = PreferenceManager.getDefaultSharedPreferences(this);
notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(this, SSHTunnel.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new Notification();
try {
mStartForeground = getClass().getMethod("startForeground",
mStartForegroundSignature);
mStopForeground = getClass().getMethod("stopForeground",
mStopForegroundSignature);
} catch (NoSuchMethodException e) {
// Running on an older platform.
mStartForeground = mStopForeground = null;
}
if (reason == null)
reason = getString(R.string.fail_to_connect);
}
/** Called when the activity is closed. */
@Override
public void onDestroy() {
if (profile == null) {
return;
}
isStopping = true;
stopForegroundCompat(1);
FlurryAgent.onEndSession(this);
if (connected) {
notifyAlert(getString(R.string.forward_stop),
getString(R.string.service_stopped),
Notification.FLAG_AUTO_CANCEL);
}
if (enableDNSProxy) {
try {
if (dnsServer != null) {
dnsServer.close();
dnsServer = null;
}
} catch (Exception e) {
Log.e(TAG, "DNS Server close unexpected");
}
}
new Thread() {
@Override
public void run() {
// Make sure the connection is closed, important here
onDisconnect();
isStopping = false;
handler.sendEmptyMessage(MSG_DISCONNECT_FINISH);
}
}.start();
flushIptables();
super.onDestroy();
markServiceStopped();
}
private void onDisconnect() {
connected = false;
try {
if (lpf != null) {
lpf.close();
lpf = null;
}
} catch (IOException ignore) {
// Nothing
}
try {
if (dpf != null) {
dpf.close();
dpf = null;
}
} catch (IOException ignore) {
// Nothing
}
try {
if (dnspf != null) {
dnspf.close();
dnspf = null;
}
} catch (IOException ignore) {
// Nothing
}
if (connection != null) {
connection.close();
connection = null;
}
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
FlurryAgent.onStartSession(this, "MBY4JL18FQK1DPEJ5Y39");
Log.d(TAG, "Service Start");
Bundle bundle = intent.getExtras();
int id = bundle.getInt(Constraints.ID);
profile = ProfileFactory.loadProfileFromDao(id);
Log.d(TAG, profile.toString());
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(MSG_CONNECT_START);
isConnecting = true;
enableDNSProxy = profile.isDNSProxy();
try {
URL url = new URL("http://gae-ip-country.appspot.com/");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setConnectTimeout(2000);
conn.setReadTimeout(5000);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader input = new BufferedReader(
new InputStreamReader(is));
String code = input.readLine();
if (code != null && code.length() > 0 && code.length() < 3) {
Log.d(TAG, "Location: " + code);
if (!code.contains("CN") && !code.contains("ZZ"))
enableDNSProxy = false;
}
} catch (Exception e) {
Log.d(TAG, "Cannot get country code");
// Nothing
}
if (enableDNSProxy) {
if (dnsServer == null) {
// dnsServer = new DNSServer("DNS Server", "8.8.4.4",
// 53,
// SSHTunnelService.this);
dnsServer = new DNSServer("DNS Server", "127.0.0.1",
8053, SSHTunnelService.this);
dnsServer.setBasePath("/data/data/org.sshtunnel");
dnsPort = dnsServer.init();
}
}
// Test for Redirect Support
initHasRedirectSupported();
if (isOnline() && connect()) {
// Connection and forward successful
finishConnection();
if (enableDNSProxy) {
// Start DNS Proxy
Thread dnsThread = new Thread(dnsServer);
dnsThread.setDaemon(true);
dnsThread.start();
}
notifyAlert(getString(R.string.forward_success),
getString(R.string.service_running));
handler.sendEmptyMessage(MSG_CONNECT_FINISH);
handler.sendEmptyMessage(MSG_CONNECT_SUCCESS);
// for widget, maybe exception here
try {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.sshtunnel_appwidget);
views.setImageViewResource(R.id.serviceToggle,
R.drawable.on);
AppWidgetManager awm = AppWidgetManager
.getInstance(SSHTunnelService.this);
awm.updateAppWidget(awm
.getAppWidgetIds(new ComponentName(
SSHTunnelService.this,
SSHTunnelWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
} else {
// Connection or forward unsuccessful
notifyAlert(getString(R.string.forward_fail) + ": "
+ reason, getString(R.string.service_failed),
Notification.FLAG_AUTO_CANCEL);
handler.sendEmptyMessage(MSG_CONNECT_FINISH);
handler.sendEmptyMessage(MSG_CONNECT_FAIL);
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
// Nothing
}
connected = false;
stopSelf();
}
isConnecting = false;
}
}).start();
markServiceStarted();
}
// XXX: Is it right?
@Override
public String[] replyToChallenge(String name, String instruction,
int numPrompts, String[] prompt, boolean[] echo) throws Exception {
String[] responses = new String[numPrompts];
for (int i = 0; i < numPrompts; i++) {
// request response from user for each prompt
if (prompt[i].toLowerCase().contains("password"))
responses[i] = profile.getPassword();
}
return responses;
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod(mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
setForeground(true);
notificationManager.notify(id, notification);
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat(int id) {
// If we have the new stopForeground API, then use it.
if (mStopForeground != null) {
mStopForegroundArgs[0] = Boolean.TRUE;
try {
mStopForeground.invoke(this, mStopForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke stopForeground", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w("ApiDemos", "Unable to invoke stopForeground", e);
}
return;
}
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
notificationManager.cancel(id);
setForeground(false);
}
public void stopReconnect(SimpleDateFormat df) {
connected = false;
notifyAlert(
getString(R.string.reconnect_fail) + " "
+ df.format(new Date()),
getString(R.string.reconnect_fail),
Notification.FLAG_AUTO_CANCEL);
stopSelf();
}
@Override
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey)
throws Exception {
String fingerPrint = KnownHosts.createHexFingerprint(
serverHostKeyAlgorithm, serverHostKey);
int fingerPrintStatus = Constraints.FINGER_PRINT_CHANGED;
if (profile.getFingerPrintType() == null
|| profile.getFingerPrintType().equals("")) {
fingerPrintStatus = Constraints.FINGER_PRINT_INIITIALIZE;
reason = getString(R.string.finger_print_unknown);
} else {
if (profile.getFingerPrintType().equals(serverHostKeyAlgorithm)
&& profile.getFingerPrint() != null
&& profile.getFingerPrint().equals(fingerPrint)) {
return true;
} else {
fingerPrintStatus = Constraints.FINGER_PRINT_CHANGED;
reason = getString(R.string.finger_print_mismatch);
}
}
Log.d(TAG, "Finger Print: " + profile.getFingerPrint());
Log.d(TAG, "Finger Print Type: " + profile.getFingerPrintType());
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profile.getId());
bundle.putInt(Constraints.FINGER_PRINT_STATUS, fingerPrintStatus);
bundle.putString(Constraints.FINGER_PRINT, fingerPrint);
bundle.putString(Constraints.FINGER_PRINT_TYPE, serverHostKeyAlgorithm);
Message msg = new Message();
msg.setData(bundle);
hostKeyHandler.sendMessage(msg);
synchronized (fingerPrintLock) {
fingerPrintLock.wait();
}
return fingerPrintChecker;
}
}
| Java |
package org.sshtunnel;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Random;
import org.sshtunnel.utils.Base64;
import org.sshtunnel.utils.DomainValidator;
import org.sshtunnel.utils.InnerSocketBuilder;
import org.sshtunnel.utils.Utils;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* 此类封装了一个Dns回应
*
* @author biaji
*
*/
class DnsResponse implements Serializable {
private static final long serialVersionUID = -6693216674221293274L;
private String request = null;
private long timestamp = System.currentTimeMillis();;
private int reqTimes = 0;
private byte[] dnsResponse = null;
public DnsResponse(String request) {
this.request = request;
}
/**
* @return the dnsResponse
*/
public byte[] getDnsResponse() {
this.reqTimes++;
return dnsResponse;
}
/**
* @return IP string
*/
public String getIPString() {
String ip = null;
int i;
if (dnsResponse == null) {
return null;
}
i = dnsResponse.length - 4;
if (i < 0) {
return null;
}
ip = "" + (dnsResponse[i] & 0xFF); /* Unsigned byte to int */
for (i++; i < dnsResponse.length; i++) {
ip += "." + (dnsResponse[i] & 0xFF);
}
return ip;
}
/**
* @return the reqTimes
*/
public int getReqTimes() {
return reqTimes;
}
public String getRequest() {
return this.request;
}
/**
* @return the timestamp
*/
public long getTimestamp() {
return timestamp;
}
/**
* @param dnsResponse
* the dnsResponse to set
*/
public void setDnsResponse(byte[] dnsResponse) {
this.dnsResponse = dnsResponse;
}
}
/**
* 此类实现了DNS代理
*
* @author biaji
*
*/
public class DNSServer implements WrapServer {
public static byte[] int2byte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);// 最低位
targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
return targets;
}
private final String TAG = "SSHTunnel";
private String homePath;
private final String CACHE_PATH = "/cache";
private final String CACHE_FILE = "/dnscache";
private DatagramSocket srvSocket;
private int srvPort = 0;
private String name;
protected String dnsHost;
protected int dnsPort;
protected Context context;
private volatile int threadNum = 0;
private final static int MAX_THREAD_NUM = 5;
public HashSet<String> domains;
final protected int DNS_PKG_HEADER_LEN = 12;
final private int[] DNS_HEADERS = { 0, 0, 0x81, 0x80, 0, 0, 0, 0, 0, 0, 0,
0 };
final private int[] DNS_PAYLOAD = { 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01,
0x00, 0x00, 0x00, 0x3c, 0x00, 0x04 };
final private int IP_SECTION_LEN = 4;
private boolean inService = false;
private Hashtable<String, DnsResponse> dnsCache = new Hashtable<String, DnsResponse>();
/**
* 内建自定义缓存
*
*/
private Hashtable<String, String> orgCache = new Hashtable<String, String>();
private String target = "8.8.8.8:53";
private static final String CANT_RESOLVE = "Error";
public DNSServer(String name, String dnsHost, int dnsPort, Context context) {
this.name = name;
this.dnsHost = dnsHost;
this.dnsPort = dnsPort;
this.context = context;
domains = new HashSet<String>();
if (dnsHost != null && !dnsHost.equals(""))
target = dnsHost + ":" + dnsPort;
}
/**
* 在缓存中添加一个域名解析
*
* @param questDomainName
* 域名
* @param answer
* 解析结果
*/
private synchronized void addToCache(String questDomainName, byte[] answer) {
DnsResponse response = new DnsResponse(questDomainName);
response.setDnsResponse(answer);
dnsCache.put(questDomainName, response);
saveCache();
}
@Override
public void close() throws IOException {
inService = false;
if (srvSocket != null) {
srvSocket.close();
srvSocket = null;
}
saveCache();
Log.i(TAG, "DNS服务关闭");
}
/*
* Create a DNS response packet, which will send back to application.
*
* @author yanghong
*
* Reference to:
*
* Mini Fake DNS server (Python)
* http://code.activestate.com/recipes/491264-mini-fake-dns-server/
*
* DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION
* http://www.ietf.org/rfc/rfc1035.txt
*/
protected byte[] createDNSResponse(byte[] quest, byte[] ips) {
byte[] response = null;
int start = 0;
response = new byte[128];
for (int val : DNS_HEADERS) {
response[start] = (byte) val;
start++;
}
System.arraycopy(quest, 0, response, 0, 2); /* 0:2 */
System.arraycopy(quest, 4, response, 4, 2); /* 4:6 -> 4:6 */
System.arraycopy(quest, 4, response, 6, 2); /* 4:6 -> 7:9 */
System.arraycopy(quest, DNS_PKG_HEADER_LEN, response, start,
quest.length - DNS_PKG_HEADER_LEN); /* 12:~ -> 15:~ */
start += quest.length - DNS_PKG_HEADER_LEN;
for (int val : DNS_PAYLOAD) {
response[start] = (byte) val;
start++;
}
/* IP address in response */
for (byte ip : ips) {
response[start] = ip;
start++;
}
byte[] result = new byte[start];
System.arraycopy(response, 0, result, 0, start);
Log.d(TAG, "DNS Response package size: " + start);
return result;
}
/**
* 由上级DNS通过TCP取得解析
*
* @param quest
* 原始DNS请求
* @return
*/
protected byte[] fetchAnswer(byte[] quest) {
Socket innerSocket = new InnerSocketBuilder("8.8.4.4", 53, "8.8.4.4:53")
.getSocket();
DataInputStream in;
DataOutputStream out;
byte[] result = null;
try {
if (innerSocket != null && innerSocket.isConnected()) {
// 构造TCP DNS包
int dnsqLength = quest.length;
byte[] tcpdnsq = new byte[dnsqLength + 2];
System.arraycopy(int2byte(dnsqLength), 0, tcpdnsq, 1, 1);
System.arraycopy(quest, 0, tcpdnsq, 2, dnsqLength);
// 转发DNS
in = new DataInputStream(innerSocket.getInputStream());
out = new DataOutputStream(innerSocket.getOutputStream());
out.write(tcpdnsq);
out.flush();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int b = -1;
while ((b = in.read()) != -1) {
bout.write(b);
}
byte[] tcpdnsr = bout.toByteArray();
if (tcpdnsr != null && tcpdnsr.length > 2) {
result = new byte[tcpdnsr.length - 2];
System.arraycopy(tcpdnsr, 2, result, 0, tcpdnsr.length - 2);
}
innerSocket.close();
}
} catch (IOException e) {
Log.e(TAG, "", e);
}
return result;
}
public byte[] fetchAnswerHTTP(byte[] quest) {
byte[] result = null;
String domain = getRequestDomain(quest);
String ip = null;
DomainValidator dv = DomainValidator.getInstance();
/* Not support reverse domain name query */
if (domain.endsWith("in-addr.arpa") || !dv.isValid(domain)) {
return createDNSResponse(quest, parseIPString("127.0.0.1"));
// return null;
}
ip = resolveDomainName(domain);
if (ip == null) {
Log.e(TAG, "Failed to resolve domain name: " + domain);
return null;
}
if (ip.equals(CANT_RESOLVE)) {
return null;
}
byte[] ips = parseIPString(ip);
if (ips != null) {
result = createDNSResponse(quest, ips);
}
return result;
}
/**
* 获取UDP DNS请求的域名
*
* @param request
* dns udp包
* @return 请求的域名
*/
protected String getRequestDomain(byte[] request) {
String requestDomain = "";
int reqLength = request.length;
if (reqLength > 13) { // 包含包体
byte[] question = new byte[reqLength - 12];
System.arraycopy(request, 12, question, 0, reqLength - 12);
requestDomain = parseDomain(question);
if (requestDomain.length() > 1)
requestDomain = requestDomain.substring(0,
requestDomain.length() - 1);
}
return requestDomain;
}
@Override
public int getServPort() {
return this.srvPort;
}
public int init() {
try {
srvSocket = new DatagramSocket(0,
InetAddress.getByName("127.0.0.1"));
inService = true;
srvPort = srvSocket.getLocalPort();
Log.e(TAG, this.name + "启动于端口: " + srvPort);
} catch (SocketException e) {
Log.e(TAG, "DNSServer初始化错误,端口号" + srvPort, e);
} catch (UnknownHostException e) {
Log.e(TAG, "DNSServer初始化错误,端口号" + srvPort, e);
}
return srvPort;
}
@Override
public boolean isClosed() {
return srvSocket.isClosed();
}
public boolean isInService() {
return inService;
}
/**
* 由缓存载入域名解析缓存
*/
private void loadCache() {
ObjectInputStream ois = null;
File cache = new File(homePath + CACHE_PATH + CACHE_FILE);
try {
if (!cache.exists())
return;
ois = new ObjectInputStream(new FileInputStream(cache));
dnsCache = (Hashtable<String, DnsResponse>) ois.readObject();
ois.close();
ois = null;
Hashtable<String, DnsResponse> tmpCache = (Hashtable<String, DnsResponse>) dnsCache
.clone();
for (DnsResponse resp : dnsCache.values()) {
// 检查缓存时效(五天)
if ((System.currentTimeMillis() - resp.getTimestamp()) > 432000000L) {
Log.d(TAG, "删除" + resp.getRequest() + "记录");
tmpCache.remove(resp.getRequest());
}
}
dnsCache = tmpCache;
tmpCache = null;
} catch (ClassCastException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (FileNotFoundException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (ClassNotFoundException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} finally {
try {
if (ois != null)
ois.close();
} catch (IOException e) {
}
}
}
/**
* 解析域名
*
* @param request
* @return
*/
private String parseDomain(byte[] request) {
String result = "";
int length = request.length;
int partLength = request[0];
if (partLength == 0)
return result;
try {
byte[] left = new byte[length - partLength - 1];
System.arraycopy(request, partLength + 1, left, 0, length
- partLength - 1);
result = new String(request, 1, partLength) + ".";
result += parseDomain(left);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
}
return result;
}
/*
* Parse IP string into byte, do validation.
*
* @param ip IP string
*
* @return IP in byte array
*/
protected byte[] parseIPString(String ip) {
byte[] result = null;
int value;
int i = 0;
String[] ips = null;
ips = ip.split("\\.");
Log.d(TAG, "Start parse ip string: " + ip + ", Sectons: " + ips.length);
if (ips.length != IP_SECTION_LEN) {
Log.e(TAG, "Malformed IP string number of sections is: "
+ ips.length);
return null;
}
result = new byte[IP_SECTION_LEN];
for (String section : ips) {
try {
value = Integer.parseInt(section);
/* 0.*.*.* and *.*.*.0 is invalid */
if ((i == 0 || i == 3) && value == 0) {
return null;
}
result[i] = (byte) value;
i++;
} catch (NumberFormatException e) {
Log.e(TAG, "Malformed IP string section: " + section);
return null;
}
}
return result;
}
/*
* Resolve host name by access a DNSRelay running on GAE:
*
* Example:
*
* http://www.hosts.dotcloud.com/lookup.php?(domain name encoded)
* http://gaednsproxy.appspot.com/?d=(domain name encoded)
*/
private String resolveDomainName(String domain) {
String ip = null;
InputStream is;
String encode_host = URLEncoder.encode(Base64.encodeBytes(Base64
.encodeBytesToBytes(domain.getBytes())));
String url = "http://gaednsproxy.appspot.com:" + dnsPort + "/?d="
+ encode_host;
Random random = new Random(System.currentTimeMillis());
int n = random.nextInt(2);
if (n == 1)
url = "http://gaednsproxy1.appspot.com:" + dnsPort + "/?d="
+ encode_host;
Log.d(TAG, "DNS Relay URL: " + url);
try {
URL aURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.setConnectTimeout(2000);
conn.setConnectTimeout(5000);
conn.connect();
is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
ip = br.readLine();
} catch (SocketException e) {
Log.e(TAG, "Failed to request URI: " + url, e);
} catch (IOException e) {
Log.e(TAG, "Failed to request URI: " + url, e);
} catch (NullPointerException e) {
Log.e(TAG, "Failed to request URI: " + url, e);
}
return ip;
}
/*
* Implement with http based DNS.
*/
@Override
public void run() {
loadCache();
byte[] qbuffer = new byte[576];
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
threadNum = 0;
while (true) {
try {
final DatagramPacket dnsq = new DatagramPacket(qbuffer,
qbuffer.length);
if (!settings.getBoolean("isRunning", false))
break;
srvSocket.receive(dnsq);
// 连接外部DNS进行解析。
byte[] data = dnsq.getData();
int dnsqLength = dnsq.getLength();
final byte[] udpreq = new byte[dnsqLength];
System.arraycopy(data, 0, udpreq, 0, dnsqLength);
// 尝试从缓存读取域名解析
final String questDomain = getRequestDomain(udpreq);
Log.d(TAG, "解析" + questDomain);
if (dnsCache.containsKey(questDomain)) {
sendDns(dnsCache.get(questDomain).getDnsResponse(), dnsq,
srvSocket);
Log.d(TAG, "命中缓存");
} else if (orgCache.containsKey(questDomain)) { // 如果为自定义域名解析
byte[] ips = parseIPString(orgCache.get(questDomain));
byte[] answer = createDNSResponse(udpreq, ips);
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "自定义解析" + orgCache);
} else if (questDomain.toLowerCase().contains("appspot.com")) { // for
// gaednsproxy.appspot.com
byte[] ips = parseIPString("127.0.0.1");
byte[] answer = createDNSResponse(udpreq, ips);
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "Custom DNS resolver gaednsproxy.appspot.com");
} else {
synchronized (this) {
if (domains.contains(questDomain))
continue;
else
domains.add(questDomain);
}
while (threadNum >= MAX_THREAD_NUM) {
Thread.sleep(2000);
}
threadNum++;
new Thread() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
try {
byte[] answer;
answer = fetchAnswerHTTP(udpreq);
if (answer != null && answer.length != 0) {
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG,
"正确返回DNS解析,长度:"
+ answer.length
+ " 耗时:"
+ (System
.currentTimeMillis() - startTime)
/ 1000 + "s");
} else {
Log.e(TAG, "返回DNS包长为0");
}
} catch (Exception e) {
// Nothing
}
synchronized (DNSServer.this) {
domains.remove(questDomain);
}
threadNum--;
}
}.start();
}
/* For test, validate dnsCache */
/*
* if (dnsCache.size() > 0) { Log.d(TAG, "Domains in cache:");
*
* Enumeration<String> enu = dnsCache.keys(); while
* (enu.hasMoreElements()) { String domain = (String)
* enu.nextElement(); DnsResponse resp = dnsCache.get(domain);
*
* Log.d(TAG, domain + " : " + resp.getIPString()); } }
*/
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
} catch (NullPointerException e) {
Log.e(TAG, "Srvsocket wrong", e);
break;
} catch (InterruptedException e) {
Log.e(TAG, "Interuppted");
break;
}
}
if (srvSocket != null) {
srvSocket.close();
srvSocket = null;
}
if (Utils.isWorked()) {
try {
context.stopService(new Intent(context, SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
}
}
/**
* 保存域名解析内容缓存
*/
private void saveCache() {
ObjectOutputStream oos = null;
File cache = new File(homePath + CACHE_PATH + CACHE_FILE);
try {
if (!cache.exists()) {
File cacheDir = new File(homePath + CACHE_PATH);
if (!cacheDir.exists()) { // android的createNewFile这个方法真够恶心的啊
cacheDir.mkdir();
}
cache.createNewFile();
}
oos = new ObjectOutputStream(new FileOutputStream(cache));
oos.writeObject(dnsCache);
oos.flush();
oos.close();
oos = null;
} catch (FileNotFoundException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} finally {
try {
if (oos != null)
oos.close();
} catch (IOException e) {
}
}
}
/**
* 向来源发送dns应答
*
* @param response
* 应答包
* @param dnsq
* 请求包
* @param srvSocket
* 侦听Socket
*/
private void sendDns(byte[] response, DatagramPacket dnsq,
DatagramSocket srvSocket) {
// 同步identifier
System.arraycopy(dnsq.getData(), 0, response, 0, 2);
DatagramPacket resp = new DatagramPacket(response, 0, response.length);
resp.setPort(dnsq.getPort());
resp.setAddress(dnsq.getAddress());
try {
srvSocket.send(resp);
} catch (IOException e) {
Log.e(TAG, "", e);
}
}
public void setBasePath(String path) {
this.homePath = path;
}
@Override
public void setProxyHost(String host) {
// TODO Auto-generated method stub
}
@Override
public void setProxyPort(int port) {
// TODO Auto-generated method stub
}
@Override
public void setTarget(String target) {
this.target = target;
}
public boolean test(String domain, String ip) {
boolean ret = true;
// TODO: Implement test case
return ret;
}
}
| Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.Utils;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class SSHTunnelReceiver {
private static final String TAG = "SSHTunnelReceiver";
public void onReceive(Context context, Intent intent, boolean enable) {
Profile profile = ProfileFactory.getProfile();
ProfileFactory.loadFromPreference();
if (profile == null) {
Log.e(TAG, "Exception when get preferences");
return;
}
if (profile.isAutoConnect() || enable) {
Utils.notifyConnect();
Intent it = new Intent(context, SSHTunnelService.class);
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profile.getId());
it.putExtras(bundle);
context.startService(it);
}
}
}
| Java |
package org.sshtunnel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Stack;
import org.sshtunnel.utils.Utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;
public class ImageLoader {
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i) {
bitmap = b;
imageView = i;
}
@Override
public void run() {
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
class PhotosLoader extends Thread {
@Override
public void run() {
try {
while (true) {
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.uid);
cache.put(photoToLoad.uid, bmp);
Object tag = photoToLoad.imageView.getTag();
if (tag != null
&& ((Integer) tag) == photoToLoad.uid) {
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
// Task for the queue
private class PhotoToLoad {
public int uid;
public ImageView imageView;
public PhotoToLoad(int u, ImageView i) {
uid = u;
imageView = i;
}
}
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<Integer, Bitmap> cache = new HashMap<Integer, Bitmap>();
private File cacheDir;
private Context context;
final int stub_id = R.drawable.sym_def_app_icon;
PhotosQueue photosQueue = new PhotosQueue();
PhotosLoader photoLoaderThread = new PhotosLoader();
public ImageLoader(Context c) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
context = c;
// Find the dir to save cached images
cacheDir = context.getCacheDir();
}
public void clearCache() {
// clear memory cache
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
public void DisplayImage(int uid, Activity activity, ImageView imageView) {
if (cache.containsKey(uid))
imageView.setImageBitmap(cache.get(uid));
else {
queuePhoto(uid, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private Bitmap getBitmap(int uid) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(uid);
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
BitmapDrawable icon = (BitmapDrawable) Utils.getAppIcon(context,
uid);
return icon.getBitmap();
} catch (Exception ex) {
return null;
}
}
private void queuePhoto(int uid, Activity activity, ImageView imageView) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(uid, imageView);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
public void stopThread() {
photoLoaderThread.interrupt();
}
}
| Java |
package org.sshtunnel;
public class Option implements Comparable<Option>{
private String name;
private String data;
private String path;
public Option(String n,String d,String p)
{
name = n;
data = d;
path = p;
}
@Override
public int compareTo(Option o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
public String getData()
{
return data;
}
public String getName()
{
return name;
}
public String getPath()
{
return path;
}
}
| Java |
package org.sshtunnel.utils;
import java.io.IOException;
import java.net.Socket;
import android.util.Log;
public class InnerSocketBuilder {
private String proxyHost = "127.0.0.1";
private int proxyPort = 1053;
private Socket innerSocket = null;
private boolean isConnected = false;
private final String TAG = "CMWRAP->InnerSocketBuilder";
/**
* 建立经由代理服务器至目标服务器的连接
*
* @param proxyHost
* 代理服务器地址
* @param proxyPort
* 代理服务器端口
* @param target
* 目标服务器
*/
public InnerSocketBuilder(String proxyHost, int proxyPort, String target) {
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
connect();
}
private void connect() {
// starTime = System.currentTimeMillis();
Log.v(TAG, "建立通道");
try {
innerSocket = new Socket(proxyHost, proxyPort);
// innerSocket.setKeepAlive(true);
innerSocket.setTcpNoDelay(true);
innerSocket.setSoTimeout(60 * 1000);
isConnected = true;
} catch (IOException e) {
Log.e(TAG, "建立隧道失败:" + e.getLocalizedMessage());
}
}
public Socket getSocket() {
return innerSocket;
}
public boolean isConnected() {
return this.isConnected;
}
}
| Java |
package org.sshtunnel.utils;
public class Constraints {
public static final String ID = "profile_id";
public static final String NAME = "name";
public static final String USER = "user";
public static final String PASSWORD = "password";
public static final String HOST = "host";
public static final String SSID = "ssid";
public static final String REMOTE_ADDRESS = "remoteAddress";
public static final String KEY_PATH = "keyPath";
public static final String PROXYED_APPS = "proxyedApps";
public static final String UPSTREAM_PROXY = "upstreamProxy";
public static final String IS_AUTO_RECONNECT = "isAutoReconnect";
public static final String IS_AUTO_CONNECT = "isAutoConnect";
public static final String IS_AUTO_SETPROXY = "isAutoSetProxy";
public static final String IS_GFW_LIST = "isGFWList";
public static final String IS_SOCKS = "isSocks";
public static final String IS_DNS_PROXY = "isDNSProxy";
public static final String IS_ACTIVE = "isActive";
public static final String IS_UPSTREAM_PROXY = "isUpstreamProxy";
public static final String PORT = "port";
public static final String REMOTE_PORT = "remotePort";
public static final String LOCAL_PORT = "localPort";
public static final String DEFAULT_KEY_PATH = "/sdcard/sshtunnel/key";
public static final String DEFAULT_REMOTE_ADDRESS = "127.0.0.1";
public static final String ONLY_3G = "3G";
public static final String ONLY_WIFI = "WIFI";
public static final String WIFI_AND_3G = "WIFI/3G";
public static final String FINGER_PRINT_STATUS = "fingerPrintStatus";
public static final String FINGER_PRINT_TYPE = "fingerPrintType";
public static final String FINGER_PRINT = "fingerPrint";
public static final int FINGER_PRINT_INIITIALIZE = 1;
public static final int FINGER_PRINT_CHANGED = 2;
public static final int FINGER_PRINT_ACCEPT = 3;
public static final int FINGER_PRINT_DENY = 4;
public static final String FINGER_PRINT_ACTION_ACCEPT = "org.sshtunnel.fingerprint.ACCEPT";
public static final String FINGER_PRINT_ACTION_DENY = "org.sshtunnel.fingerprint.DENY";
public static final String FINGER_PRINT_ACTION = "org.sshtunnel.fingerprint.ACTION";
}
| Java |
package org.sshtunnel.utils;
import android.graphics.drawable.Drawable;
public class ProxyedApp {
private boolean enabled;
private int uid;
private String username;
private String procname;
private String name;
private boolean proxyed = false;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the procname
*/
public String getProcname() {
return procname;
}
/**
* @return the uid
*/
public int getUid() {
return uid;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @return the proxyed
*/
public boolean isProxyed() {
return proxyed;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @param procname the procname to set
*/
public void setProcname(String procname) {
this.procname = procname;
}
/**
* @param proxyed the proxyed to set
*/
public void setProxyed(boolean proxyed) {
this.proxyed = proxyed;
}
/**
* @param uid the uid to set
*/
public void setUid(int uid) {
this.uid = uid;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
} | Java |
/*
* 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.sshtunnel.utils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* <p><b>Domain name</b> validation routines.</p>
*
* <p>
* This validator provides methods for validating Internet domain names
* and top-level domains.
* </p>
*
* <p>Domain names are evaluated according
* to the standards <a href="http://www.ietf.org/rfc/rfc1034.txt">RFC1034</a>,
* section 3, and <a href="http://www.ietf.org/rfc/rfc1123.txt">RFC1123</a>,
* section 2.1. No accomodation is provided for the specialized needs of
* other applications; if the domain name has been URL-encoded, for example,
* validation will fail even though the equivalent plaintext version of the
* same name would have passed.
* </p>
*
* <p>
* Validation is also provided for top-level domains (TLDs) as defined and
* maintained by the Internet Assigned Numbers Authority (IANA):
* </p>
*
* <ul>
* <li>{@link #isValidInfrastructureTld} - validates infrastructure TLDs
* (<code>.arpa</code>, etc.)</li>
* <li>{@link #isValidGenericTld} - validates generic TLDs
* (<code>.com, .org</code>, etc.)</li>
* <li>{@link #isValidCountryCodeTld} - validates country code TLDs
* (<code>.us, .uk, .cn</code>, etc.)</li>
* </ul>
*
* <p>
* (<b>NOTE</b>: This class does not provide IP address lookup for domain names or
* methods to ensure that a given domain name matches a specific IP; see
* {@link java.net.InetAddress} for that functionality.)
* </p>
*
* @version $Revision$ $Date$
* @since Validator 1.4
*/
public class DomainValidator implements Serializable {
// Regular expression strings for hostnames (derived from RFC2396 and RFC 1123)
private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?>[\\p{Alnum}-]*\\p{Alnum})*";
private static final String TOP_LABEL_REGEX = "\\p{Alpha}{2,}";
private static final String DOMAIN_NAME_REGEX =
"^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")$";
/**
* Singleton instance of this validator.
*/
private static final DomainValidator DOMAIN_VALIDATOR = new DomainValidator();
private static final String[] INFRASTRUCTURE_TLDS = new String[] {
"arpa", // internet infrastructure
"root" // diagnostic marker for non-truncated root zone
};
private static final String[] GENERIC_TLDS = new String[] {
"aero", // air transport industry
"asia", // Pan-Asia/Asia Pacific
"biz", // businesses
"cat", // Catalan linguistic/cultural community
"com", // commercial enterprises
"coop", // cooperative associations
"info", // informational sites
"jobs", // Human Resource managers
"mobi", // mobile products and services
"museum", // museums, surprisingly enough
"name", // individuals' sites
"net", // internet support infrastructure/business
"org", // noncommercial organizations
"pro", // credentialed professionals and entities
"tel", // contact data for businesses and individuals
"travel", // entities in the travel industry
"gov", // United States Government
"edu", // accredited postsecondary US education entities
"mil", // United States Military
"int" // organizations established by international treaty
};
private static final String[] COUNTRY_CODE_TLDS = new String[] {
"ac", // Ascension Island
"ad", // Andorra
"ae", // United Arab Emirates
"af", // Afghanistan
"ag", // Antigua and Barbuda
"ai", // Anguilla
"al", // Albania
"am", // Armenia
"an", // Netherlands Antilles
"ao", // Angola
"aq", // Antarctica
"ar", // Argentina
"as", // American Samoa
"at", // Austria
"au", // Australia (includes Ashmore and Cartier Islands and Coral Sea Islands)
"aw", // Aruba
"ax", // 脙鈥and
"az", // Azerbaijan
"ba", // Bosnia and Herzegovina
"bb", // Barbados
"bd", // Bangladesh
"be", // Belgium
"bf", // Burkina Faso
"bg", // Bulgaria
"bh", // Bahrain
"bi", // Burundi
"bj", // Benin
"bm", // Bermuda
"bn", // Brunei Darussalam
"bo", // Bolivia
"br", // Brazil
"bs", // Bahamas
"bt", // Bhutan
"bv", // Bouvet Island
"bw", // Botswana
"by", // Belarus
"bz", // Belize
"ca", // Canada
"cc", // Cocos (Keeling) Islands
"cd", // Democratic Republic of the Congo (formerly Zaire)
"cf", // Central African Republic
"cg", // Republic of the Congo
"ch", // Switzerland
"ci", // C脙麓te d'Ivoire
"ck", // Cook Islands
"cl", // Chile
"cm", // Cameroon
"cn", // China, mainland
"co", // Colombia
"cr", // Costa Rica
"cu", // Cuba
"cv", // Cape Verde
"cx", // Christmas Island
"cy", // Cyprus
"cz", // Czech Republic
"de", // Germany
"dj", // Djibouti
"dk", // Denmark
"dm", // Dominica
"do", // Dominican Republic
"dz", // Algeria
"ec", // Ecuador
"ee", // Estonia
"eg", // Egypt
"er", // Eritrea
"es", // Spain
"et", // Ethiopia
"eu", // European Union
"fi", // Finland
"fj", // Fiji
"fk", // Falkland Islands
"fm", // Federated States of Micronesia
"fo", // Faroe Islands
"fr", // France
"ga", // Gabon
"gb", // Great Britain (United Kingdom)
"gd", // Grenada
"ge", // Georgia
"gf", // French Guiana
"gg", // Guernsey
"gh", // Ghana
"gi", // Gibraltar
"gl", // Greenland
"gm", // The Gambia
"gn", // Guinea
"gp", // Guadeloupe
"gq", // Equatorial Guinea
"gr", // Greece
"gs", // South Georgia and the South Sandwich Islands
"gt", // Guatemala
"gu", // Guam
"gw", // Guinea-Bissau
"gy", // Guyana
"hk", // Hong Kong
"hm", // Heard Island and McDonald Islands
"hn", // Honduras
"hr", // Croatia (Hrvatska)
"ht", // Haiti
"hu", // Hungary
"id", // Indonesia
"ie", // Ireland (脙鈥癷re)
"il", // Israel
"im", // Isle of Man
"in", // India
"io", // British Indian Ocean Territory
"iq", // Iraq
"ir", // Iran
"is", // Iceland
"it", // Italy
"je", // Jersey
"jm", // Jamaica
"jo", // Jordan
"jp", // Japan
"ke", // Kenya
"kg", // Kyrgyzstan
"kh", // Cambodia (Khmer)
"ki", // Kiribati
"km", // Comoros
"kn", // Saint Kitts and Nevis
"kp", // North Korea
"kr", // South Korea
"kw", // Kuwait
"ky", // Cayman Islands
"kz", // Kazakhstan
"la", // Laos (currently being marketed as the official domain for Los Angeles)
"lb", // Lebanon
"lc", // Saint Lucia
"li", // Liechtenstein
"lk", // Sri Lanka
"lr", // Liberia
"ls", // Lesotho
"lt", // Lithuania
"lu", // Luxembourg
"lv", // Latvia
"ly", // Libya
"ma", // Morocco
"mc", // Monaco
"md", // Moldova
"me", // Montenegro
"mg", // Madagascar
"mh", // Marshall Islands
"mk", // Republic of Macedonia
"ml", // Mali
"mm", // Myanmar
"mn", // Mongolia
"mo", // Macau
"mp", // Northern Mariana Islands
"mq", // Martinique
"mr", // Mauritania
"ms", // Montserrat
"mt", // Malta
"mu", // Mauritius
"mv", // Maldives
"mw", // Malawi
"mx", // Mexico
"my", // Malaysia
"mz", // Mozambique
"na", // Namibia
"nc", // New Caledonia
"ne", // Niger
"nf", // Norfolk Island
"ng", // Nigeria
"ni", // Nicaragua
"nl", // Netherlands
"no", // Norway
"np", // Nepal
"nr", // Nauru
"nu", // Niue
"nz", // New Zealand
"om", // Oman
"pa", // Panama
"pe", // Peru
"pf", // French Polynesia With Clipperton Island
"pg", // Papua New Guinea
"ph", // Philippines
"pk", // Pakistan
"pl", // Poland
"pm", // Saint-Pierre and Miquelon
"pn", // Pitcairn Islands
"pr", // Puerto Rico
"ps", // Palestinian territories (PA-controlled West Bank and Gaza Strip)
"pt", // Portugal
"pw", // Palau
"py", // Paraguay
"qa", // Qatar
"re", // R脙漏union
"ro", // Romania
"rs", // Serbia
"ru", // Russia
"rw", // Rwanda
"sa", // Saudi Arabia
"sb", // Solomon Islands
"sc", // Seychelles
"sd", // Sudan
"se", // Sweden
"sg", // Singapore
"sh", // Saint Helena
"si", // Slovenia
"sj", // Svalbard and Jan Mayen Islands Not in use (Norwegian dependencies; see .no)
"sk", // Slovakia
"sl", // Sierra Leone
"sm", // San Marino
"sn", // Senegal
"so", // Somalia
"sr", // Suriname
"st", // S脙拢o Tom脙漏 and Pr脙颅ncipe
"su", // Soviet Union (deprecated)
"sv", // El Salvador
"sy", // Syria
"sz", // Swaziland
"tc", // Turks and Caicos Islands
"td", // Chad
"tf", // French Southern and Antarctic Lands
"tg", // Togo
"th", // Thailand
"tj", // Tajikistan
"tk", // Tokelau
"tl", // East Timor (deprecated old code)
"tm", // Turkmenistan
"tn", // Tunisia
"to", // Tonga
"tp", // East Timor
"tr", // Turkey
"tt", // Trinidad and Tobago
"tv", // Tuvalu
"tw", // Taiwan, Republic of China
"tz", // Tanzania
"ua", // Ukraine
"ug", // Uganda
"uk", // United Kingdom
"um", // United States Minor Outlying Islands
"us", // United States of America
"uy", // Uruguay
"uz", // Uzbekistan
"va", // Vatican City State
"vc", // Saint Vincent and the Grenadines
"ve", // Venezuela
"vg", // British Virgin Islands
"vi", // U.S. Virgin Islands
"vn", // Vietnam
"vu", // Vanuatu
"wf", // Wallis and Futuna
"ws", // Samoa (formerly Western Samoa)
"ye", // Yemen
"yt", // Mayotte
"yu", // Serbia and Montenegro (originally Yugoslavia)
"za", // South Africa
"zm", // Zambia
"zw", // Zimbabwe
};
private static final List INFRASTRUCTURE_TLD_LIST = Arrays.asList(INFRASTRUCTURE_TLDS);
private static final List GENERIC_TLD_LIST = Arrays.asList(GENERIC_TLDS);
private static final List COUNTRY_CODE_TLD_LIST = Arrays.asList(COUNTRY_CODE_TLDS);
/**
* Returns the singleton instance of this validator.
* @return the singleton instance of this validator
*/
public static DomainValidator getInstance() {
return DOMAIN_VALIDATOR;
}
/**
* RegexValidator for matching domains.
*/
private final RegexValidator domainRegex =
new RegexValidator(DOMAIN_NAME_REGEX);
/** Private constructor. */
private DomainValidator() {}
// ---------------------------------------------
// ----- TLDs defined by IANA
// ----- Authoritative and comprehensive list at:
// ----- http://data.iana.org/TLD/tlds-alpha-by-domain.txt
private String chompLeadingDot(String str) {
if (str.startsWith(".")) {
return str.substring(1);
} else {
return str;
}
}
/**
* Returns true if the specified <code>String</code> parses
* as a valid domain name with a recognized top-level domain.
* The parsing is case-sensitive.
* @param domain the parameter to check for domain name syntax
* @return true if the parameter is a valid domain name
*/
public boolean isValid(String domain) {
String[] groups = domainRegex.match(domain);
if (groups != null && groups.length > 0) {
return isValidTld(groups[0]);
} else {
return false;
}
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined country code top-level domain. Leading dots are
* ignored if present. The search is case-sensitive.
* @param ccTld the parameter to check for country code TLD status
* @return true if the parameter is a country code TLD
*/
public boolean isValidCountryCodeTld(String ccTld) {
return COUNTRY_CODE_TLD_LIST.contains(chompLeadingDot(ccTld.toLowerCase()));
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined generic top-level domain. Leading dots are ignored
* if present. The search is case-sensitive.
* @param gTld the parameter to check for generic TLD status
* @return true if the parameter is a generic TLD
*/
public boolean isValidGenericTld(String gTld) {
return GENERIC_TLD_LIST.contains(chompLeadingDot(gTld.toLowerCase()));
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined infrastructure top-level domain. Leading dots are
* ignored if present. The search is case-sensitive.
* @param iTld the parameter to check for infrastructure TLD status
* @return true if the parameter is an infrastructure TLD
*/
public boolean isValidInfrastructureTld(String iTld) {
return INFRASTRUCTURE_TLD_LIST.contains(chompLeadingDot(iTld.toLowerCase()));
}
/**
* Returns true if the specified <code>String</code> matches any
* IANA-defined top-level domain. Leading dots are ignored if present.
* The search is case-sensitive.
* @param tld the parameter to check for TLD status
* @return true if the parameter is a TLD
*/
public boolean isValidTld(String tld) {
return isValidInfrastructureTld(tld)
|| isValidGenericTld(tld)
|| isValidCountryCodeTld(tld);
}
}
| Java |
package org.sshtunnel.utils;
/**
* <p>Encodes and decodes to and from Base64 notation.</p>
* <p>Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.</p>
*
* <p>Example:</p>
*
* <code>String encoded = Base64.encode( myByteArray );</code>
* <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
* <p>The <tt>options</tt> parameter, which appears in a few places, is used to pass
* several pieces of information to the encoder. In the "higher level" methods such as
* encodeBytes( bytes, options ) the options parameter can be used to indicate such
* things as first gzipping the bytes before encoding them, not inserting linefeeds,
* and encoding using the URL-safe and Ordered dialects.</p>
*
* <p>Note, according to <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>,
* Section 2.1, implementations should not add line feeds unless explicitly told
* to do so. I've got Base64 set to this behavior now, although earlier versions
* broke lines by default.</p>
*
* <p>The constants defined in Base64 can be OR-ed together to combine options, so you
* might make a call like this:</p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>to compress the data before encoding it and then making the output have newline characters.</p>
* <p>Also...</p>
* <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
*
*
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the
* value 01111111, which is an invalid base 64 character but should not
* throw an ArrayIndexOutOfBoundsException either. Led to discovery of
* mishandling (or potential for better handling) of other bad input
* characters. You should now get an IOException if you try decoding
* something that has bad characters in it.</li>
* <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded
* string ended in the last column; the buffer was not properly shrunk and
* contained an extra (null) byte that made it into the string.</li>
* <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size
* was wrong for files of size 31, 34, and 37 bytes.</li>
* <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing
* the Base64.OutputStream closed the Base64 encoding (by padding with equals
* signs) too soon. Also added an option to suppress the automatic decoding
* of gzipped streams. Also added experimental support for specifying a
* class loader when using the
* {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)}
* method.</li>
* <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the internal Java
* footprint with its CharEncoders and so forth. Fixed some javadocs that were
* inconsistent. Removed imports and specified things like java.io.IOException
* explicitly inline.</li>
* <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how big the
* final encoded data will be so that the code doesn't have to create two output
* arrays: an oversized initial one and then a final, exact-sized one. Big win
* when using the {@link #encodeBytesToBytes(byte[])} family of methods (and not
* using the gzip options which uses a different mechanism with streams and stuff).</li>
* <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and some
* similar helper methods to be more efficient with memory by not returning a
* String but just a byte array.</li>
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two years of comments
* and bug fixes queued up and finally executed. Thanks to everyone who sent
* me stuff, and I'm sorry I wasn't able to distribute your fixes to everyone else.
* Much bad coding was cleaned up including throwing exceptions where necessary
* instead of returning null values or something similar. Here are some changes
* that may affect you:
* <ul>
* <li><em>Does not break lines, by default.</em> This is to keep in compliance with
* <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
* <li><em>Throws exceptions instead of returning null values.</em> Because some operations
* (especially those that may permit the GZIP option) use IO streams, there
* is a possiblity of an java.io.IOException being thrown. After some discussion and
* thought, I've changed the behavior of the methods to throw java.io.IOExceptions
* rather than return null if ever there's an error. I think this is more
* appropriate, though it will require some changes to your code. Sorry,
* it should have been done this way to begin with.</li>
* <li><em>Removed all references to System.out, System.err, and the like.</em>
* Shame on me. All I can say is sorry they were ever there.</li>
* <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as needed
* such as when passed arrays are null or offsets are invalid.</li>
* <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings.
* This was especially annoying before for people who were thorough in their
* own projects and then had gobs of javadoc warnings on this file.</li>
* </ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug
* when using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from
* one file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64 dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as described
* in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a>
* for contributing the new Base64 dialects.
* </li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.3.7
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in ) {
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options ) {
super( in );
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if( position < 0 ) {
if( encode ) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ ) {
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 ) {
b3[i] = (byte)b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if( numBinaryBytes > 0 ) {
encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ ) {
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 ) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 ) {
numSigBytes = decode4to3( b4, 0, buffer, 0, options );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 ) {
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes ){
return -1;
} // end if: got data
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength ) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read( byte[] dest, int off, int len )
throws java.io.IOException {
int i;
int b;
for( i = 0; i < len; i++ ) {
b = read();
if( b >= 0 ) {
dest[off + i] = (byte) b;
}
else if( i == 0 ) {
return -1;
}
else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out ) {
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options ) {
super( out );
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
* @throws java.io.IOException if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if( position > 0 ) {
if( encode ) {
out.write( encode3to4( b4, buffer, position, options ) );
position = 0;
} // end if: encoding
else {
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base64-encoded data in a stream.
*
* @throws java.io.IOException if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
@Override
public void write( byte[] theBytes, int off, int len )
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ ) {
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
@Override
public void write(int theByte)
throws java.io.IOException {
// Encoding suspended?
if( suspendEncoding ) {
this.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to encode.
this.out.write( encode3to4( b4, buffer, bufferLength, options ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
this.out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) {
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) { // Enough to output.
int len = Base64.decode4to3( buffer, 0, b4, 0, options );
out.write( b4, 0, len );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) {
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
} // end inner class OutputStream
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/** Specify that gzipped data should <em>not</em> be automatically gunzipped. */
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/* ******** P R I V A T E F I E L D S ******** */
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode( byte[] source )
throws java.io.IOException {
byte[] decoded = null;
// try {
decoded = decode( source, 0, source.length, Base64.NO_OPTIONS );
// } catch( java.io.IOException ex ) {
// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
// }
return decoded;
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @param options Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len, int options )
throws java.io.IOException {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
} // end if
if( off < 0 || off + len > source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
} // end if
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for( i = off; i < off+len; i++ ) { // Loop through source
sbiDecode = DECODABET[ source[i]&0xFF ];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = source[i]; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( source[i] == EQUALS_SIGN ) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException( String.format(
"Bad Base64 input character decimal %d in array position %d", source[i]&0xFF, i ) );
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @throws java.io.IOException If there is a problem
* @since 1.4
*/
public static byte[] decode( String s ) throws java.io.IOException {
return decode( s, NO_OPTIONS );
}
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @param options encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode( String s, int options ) throws java.io.IOException {
if( s == null ){
throw new NullPointerException( "Input string was null." );
} // end if
byte[] bytes;
try {
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee ) {
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length, options );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) {
int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 ) {
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e ) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
} // end decodeToBytes
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void decodeFileToFile( String infile, String outfile )
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( decoded );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end decodeFileToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." );
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for decoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static void decodeToFile( String dataToDecode, String filename )
throws java.io.IOException {
Base64.OutputStream bos = null;
try{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end decodeToFile
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject,NO_OPTIONS,null);
}
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
* If <tt>loader</tt> is not null, it will be the class loader
* used when deserializing.
*
* @param encodedObject The Base64 data to decode
* @param options Various parameters related to decoding
* @param loader Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException if encodedObject is null
* @throws java.io.IOException if there is a general error
* @throws ClassNotFoundException if the decoded object is of a
* class that cannot be found by the JVM
* @since 2.3.4
*/
public static Object decodeToObject(
String encodedObject, int options, final ClassLoader loader )
throws java.io.IOException, java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject, options );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream( objBytes );
// If no custom class loader is provided, use Java's builtin OIS.
if( loader == null ){
ois = new java.io.ObjectInputStream( bais );
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais){
@Override
public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class c = Class.forName(streamClass.getName(), false, loader);
if( c == null ){
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch( java.lang.ClassNotFoundException e ) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> ByteBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer,
* writing it to the <code>encoded</code> CharBuffer.
* This is an experimental feature. Currently it does not
* pass along any options (such as {@link #DO_BREAK_LINES}
* or {@link #GZIP}.
*
* @param raw input buffer
* @param encoded output buffer
* @since 2.3
*/
public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while( raw.hasRemaining() ){
int rem = Math.min(3,raw.remaining());
raw.get(raw3,0,rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS );
for( int i = 0; i < 4; i++ ){
encoded.put( (char)(enc4[i] & 0xFF) );
}
} // end input remaining
}
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) {
encode3to4( threeBytes, 0, numSigBytes, b4, 0, options );
return b4;
} // end encode3to4
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException if source array is null
* @since 1.4
*/
public static String encodeBytes( byte[] source ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException {
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* <p>As of v 2.3, if there is an error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len ) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes( source, off, len, NO_OPTIONS );
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>As of v 2.3, if there is an error with the GZIP stream,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
byte[] encoded = encodeBytesToBytes( source, off, len, options );
// Return value according to relevant encoding.
try {
return new String( encoded, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String( encoded );
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source ) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS );
} catch( java.io.IOException ex ) {
assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns
* a byte array instead of instantiating a String. This is more efficient
* if you're working with I/O streams and have large data sets to encode.
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException {
if( source == null ){
throw new NullPointerException( "Cannot serialize a null array." );
} // end if: null
if( off < 0 ){
throw new IllegalArgumentException( "Cannot have negative offset: " + off );
} // end if: off < 0
if( len < 0 ){
throw new IllegalArgumentException( "Cannot have length offset: " + len );
} // end if: len < 0
if( off + len > source.length ){
throw new IllegalArgumentException(
String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
} // end if: off < 0
// Compress?
if( (options & GZIP) != 0 ) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) != 0;
//int len43 = len * 4 / 3;
//byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
if( breakLines ){
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[ encLen ];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 ) {
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len ) {
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if( e <= outBuff.length - 1 ){
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff,0, finalOut,0,e);
//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
//System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile Input file
* @param outfile Output file
* @throws java.io.IOException if there is an error
* @since 2.2
*/
public static void encodeFileToFile( String infile, String outfile )
throws java.io.IOException {
String encoded = Base64.encodeFromFile( infile );
java.io.OutputStream out = null;
try{
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream( outfile ) );
out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output.
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try { out.close(); }
catch( Exception ex ){}
} // end finally
} // end encodeFileToFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param filename Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException if there is an error
* @since 2.1
*/
public static String encodeFromFile( String filename )
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException if there is an error
* @throws NullPointerException if serializedObject is null
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
throws java.io.IOException {
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object.
*
* <p>As of v 2.3, if the object
* cannot be serialized or there is another error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned a null value, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
throws java.io.IOException {
if( serializableObject == null ){
throw new NullPointerException( "Cannot serialize a null object." );
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | options );
if( (options & GZIP) != 0 ){
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream( gzos );
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream( b64os );
}
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e ) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try {
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue){
// Fall back to some Java default
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Convenience method for encoding data to a file.
*
* <p>As of v 2.3, if there is a error,
* the method will throw an java.io.IOException. <b>This is new to v2.3!</b>
* In earlier versions, it just returned false, but
* in retrospect that's a pretty poor way to handle it.</p>
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @throws java.io.IOException if there is an error
* @throws NullPointerException if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile( byte[] dataToEncode, String filename )
throws java.io.IOException {
if( dataToEncode == null ){
throw new NullPointerException( "Data to encode was null." );
} // end iff
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
} // end try
catch( java.io.IOException e ) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try{ bos.close(); } catch( Exception e ){}
} // end finally
} // end encodeToFile
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/** Defeats instantiation. */
private Base64(){}
} // end class Base64
| Java |
package org.sshtunnel.utils;
import org.sshtunnel.R;
import org.sshtunnel.SSHTunnel;
import org.sshtunnel.SSHTunnelContext;
import org.sshtunnel.SSHTunnelService;
import org.sshtunnel.db.Profile;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Utils {
public static final String SERVICE_NAME = "org.sshtunnel.SSHTunnelService";
public static final String TAG = "SSHTunnelUtils";
public static String getProfileName(Profile profile) {
if (profile.getName() == null || profile.getName().equals("")) {
return SSHTunnelContext.getAppContext().getString(R.string.profile_base) + " "
+ profile.getId();
}
return profile.getName();
}
public static Drawable getAppIcon(Context c, int uid) {
PackageManager pm = c.getPackageManager();
Drawable appIcon = c.getResources().getDrawable(R.drawable.sym_def_app_icon);
String[] packages = pm.getPackagesForUid(uid);
if (packages != null) {
if (packages.length == 1) {
try {
ApplicationInfo appInfo = pm.getApplicationInfo(packages[0], 0);
appIcon = pm.getApplicationIcon(appInfo);
} catch (NameNotFoundException e) {
Log.e(TAG, "No package found matching with the uid " + uid);
}
}
} else {
Log.e(TAG, "Package not found for uid " + uid);
}
return appIcon;
}
public static boolean isWorked() {
return SSHTunnelService.isServiceStarted();
}
public static void notifyConnect() {
Context context = SSHTunnelContext.getAppContext();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
Intent intent = new Intent(context, SSHTunnel.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(context, 0,
intent, 0);
notification.icon = R.drawable.ic_stat;
notification.tickerText = context.getString(R.string.auto_connecting);
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(context,
context.getString(R.string.app_name),
context.getString(R.string.auto_connecting), pendIntent);
notificationManager.notify(1, notification);
}
} | Java |
/*
* 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.sshtunnel.utils;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <b>Regular Expression</b> validation (using JDK 1.4+ regex support).
* <p>
* Construct the validator either for a single regular expression or a set (array) of
* regular expressions. By default validation is <i>case sensitive</i> but constructors
* are provided to allow <i>case in-sensitive</i> validation. For example to create
* a validator which does <i>case in-sensitive</i> validation for a set of regular
* expressions:
* <pre>
* String[] regexs = new String[] {...};
* RegexValidator validator = new RegexValidator(regexs, false);
* </pre>
* <p>
* <ul>
* <li>Validate <code>true</code> or <code>false</code>:</li>
* <ul>
* <li><code>boolean valid = validator.isValid(value);</code></li>
* </ul>
* <li>Validate returning an aggregated String of the matched groups:</li>
* <ul>
* <li><code>String result = validator.validate(value);</code></li>
* </ul>
* <li>Validate returning the matched groups:</li>
* <ul>
* <li><code>String[] result = validator.match(value);</code></li>
* </ul>
* </ul>
* <p>
* Cached instances pre-compile and re-use {@link Pattern}(s) - which according
* to the {@link Pattern} API are safe to use in a multi-threaded environment.
*
* @version $Revision$ $Date$
* @since Validator 1.4
*/
public class RegexValidator implements Serializable {
private final Pattern[] patterns;
/**
* Construct a <i>case sensitive</i> validator for a single
* regular expression.
*
* @param regex The regular expression this validator will
* validate against
*/
public RegexValidator(String regex) {
this(regex, true);
}
/**
* Construct a validator for a single regular expression
* with the specified case sensitivity.
*
* @param regex The regular expression this validator will
* validate against
* @param caseSensitive when <code>true</code> matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String regex, boolean caseSensitive) {
this(new String[] {regex}, caseSensitive);
}
/**
* Construct a <i>case sensitive</i> validator that matches any one
* of the set of regular expressions.
*
* @param regexs The set of regular expressions this validator will
* validate against
*/
public RegexValidator(String[] regexs) {
this(regexs, true);
}
/**
* Construct a validator that matches any one of the set of regular
* expressions with the specified case sensitivity.
*
* @param regexs The set of regular expressions this validator will
* validate against
* @param caseSensitive when <code>true</code> matching is <i>case
* sensitive</i>, otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String[] regexs, boolean caseSensitive) {
if (regexs == null || regexs.length == 0) {
throw new IllegalArgumentException("Regular expressions are missing");
}
patterns = new Pattern[regexs.length];
int flags = (caseSensitive ? 0: Pattern.CASE_INSENSITIVE);
for (int i = 0; i < regexs.length; i++) {
if (regexs[i] == null || regexs[i].length() == 0) {
throw new IllegalArgumentException("Regular expression[" + i + "] is missing");
}
patterns[i] = Pattern.compile(regexs[i], flags);
}
}
/**
* Validate a value against the set of regular expressions.
*
* @param value The value to validate.
* @return <code>true</code> if the value is valid
* otherwise <code>false</code>.
*/
public boolean isValid(String value) {
if (value == null) {
return false;
}
for (int i = 0; i < patterns.length; i++) {
if (patterns[i].matcher(value).matches()) {
return true;
}
}
return false;
}
/**
* Validate a value against the set of regular expressions
* returning the array of matched groups.
*
* @param value The value to validate.
* @return String array of the <i>groups</i> matched if
* valid or <code>null</code> if invalid
*/
public String[] match(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
String[] groups = new String[count];
for (int j = 0; j < count; j++) {
groups[j] = matcher.group(j+1);
}
return groups;
}
}
return null;
}
/**
* Provide a String representation of this validator.
* @return A String representation of this validator
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("RegexValidator{");
for (int i = 0; i < patterns.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(patterns[i].pattern());
}
buffer.append("}");
return buffer.toString();
}
/**
* Validate a value against the set of regular expressions
* returning a String value of the aggregated groups.
*
* @param value The value to validate.
* @return Aggregated String value comprised of the
* <i>groups</i> matched if valid or <code>null</code> if invalid
*/
public String validate(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
if (count == 1) {
return matcher.group(1);
}
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < count; j++) {
String component = matcher.group(j+1);
if (component != null) {
buffer.append(component);
}
}
return buffer.toString();
}
}
return null;
}
} | Java |
package org.sshtunnel;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class FingerPrintDialog extends Activity {
private Profile profile = null;
private String fingerPrint = "";
private String fingerPrintType = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.layout_finger_print_dialog);
Bundle bundle = getIntent().getExtras();
int status = bundle.getInt(Constraints.FINGER_PRINT_STATUS);
fingerPrint = bundle.getString(Constraints.FINGER_PRINT);
fingerPrintType = bundle.getString(Constraints.FINGER_PRINT_TYPE);
int profileId = bundle.getInt(Constraints.ID);
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
String id = settings.getString(Constraints.ID, "-1");
if (id.equals(Integer.toString(profileId))) {
profile = ProfileFactory.getProfile();
} else {
profile = ProfileFactory.loadProfileFromDao(profileId);
}
TextView warningText = (TextView) findViewById(R.id.warning_text);
Button acceptButton = (Button) findViewById(R.id.accept);
Button denyButton = (Button) findViewById(R.id.deny);
acceptButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
accept();
}
});
denyButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deny();
}
});
StringBuffer sb = new StringBuffer();
switch (status) {
case Constraints.FINGER_PRINT_INIITIALIZE:
sb.append(getString(R.string.finger_print_first) + "\n\n");
break;
case Constraints.FINGER_PRINT_CHANGED:
sb.append(getString(R.string.finger_print_changed) + "\n\n");
break;
}
sb.append(fingerPrintType + " " + getString(R.string.finger_print)
+ "\n" + fingerPrint);
warningText.setText(sb.toString());
}
private void accept() {
if (profile != null) {
profile.setFingerPrintType(fingerPrintType);
profile.setFingerPrint(fingerPrint);
ProfileFactory.saveToDao(profile);
}
Intent intent = new Intent(
Constraints.FINGER_PRINT_ACTION);
intent.putExtra(Constraints.FINGER_PRINT_ACTION_ACCEPT, true);
sendBroadcast(intent);
finish();
}
private void deny() {
Intent intent = new Intent(
Constraints.FINGER_PRINT_ACTION);
intent.putExtra(Constraints.FINGER_PRINT_ACTION_ACCEPT, false);
sendBroadcast(intent);
finish();
}
}
| Java |
package org.sshtunnel;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class FileArrayAdapter extends ArrayAdapter<Option>{
private Context c;
private int id;
private List<Option>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Option> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
@Override
public Option getItem(int i)
{
return items.get(i);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
}
return v;
}
}
| Java |
package org.sshtunnel;
import java.util.List;
import org.sshtunnel.db.Profile;
import org.sshtunnel.db.ProfileFactory;
import org.sshtunnel.utils.Constraints;
import org.sshtunnel.utils.Utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.ksmaze.android.preference.ListPreferenceMultiSelect;
public class ConnectivityBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectivityBroadcastReceiver";
public String onlineSSID(Context context, String ssid) {
String ssids[] = ListPreferenceMultiSelect.parseStoredValue(ssid);
if (ssids == null)
return null;
if (ssids.length < 1)
return null;
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null)
return null;
if (!networkInfo.getTypeName().equals("WIFI")) {
for (String item : ssids) {
if (item.equals(Constraints.WIFI_AND_3G))
return item;
if (item.equals(Constraints.ONLY_3G))
return item;
}
return null;
}
WifiManager wm = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wm.getConnectionInfo();
if (wInfo == null)
return null;
String current = wInfo.getSSID();
if (current == null || current.equals(""))
return null;
for (String item : ssids) {
if (item.equals(Constraints.WIFI_AND_3G))
return item;
if (item.equals(Constraints.ONLY_WIFI))
return item;
if (item.equals(current))
return item;
}
return null;
}
@Override
public synchronized void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.w(TAG, "onReceived() called uncorrectly");
return;
}
Log.d(TAG, "Connection Test");
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
if (SSHTunnelService.isConnecting)
return;
// only switching profiles when needed
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null) {
if (Utils.isWorked()) {
context.stopService(new Intent(context, SSHTunnelService.class));
}
}
// Save current settings first
ProfileFactory.getProfile();
ProfileFactory.loadFromPreference();
String curSSID = null;
List<Profile> profileList = ProfileFactory.loadAllProfilesFromDao();
int profileId = -1;
if (profileList == null)
return;
// Test on each profile
for (Profile profile : profileList) {
curSSID = onlineSSID(context, profile.getSsid());
if (profile.isAutoConnect() && curSSID != null) {
// Then switch profile values
profileId = profile.getId();
break;
}
}
if (curSSID != null && profileId != -1) {
if (!Utils.isWorked()) {
Editor ed = settings.edit();
ed.putString("lastSSID", curSSID);
ed.commit();
while (SSHTunnelService.isStopping) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
Utils.notifyConnect();
Intent it = new Intent(context, SSHTunnelService.class);
Bundle bundle = new Bundle();
bundle.putInt(Constraints.ID, profileId);
it.putExtras(bundle);
context.startService(it);
}
}
}
} | Java |
/* sshtunnel - SSH Tunnel App for Android
* Copyright (C) 2011 Max Lv <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.sshtunnel;
import java.util.ArrayList;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
public class SSHTunnelWidgetProvider extends AppWidgetProvider {
public static final String PROXY_SWITCH_ACTION = "org.sshtunnel.SSHTunnelWidgetProvider.PROXY_SWITCH_ACTION";
public static final String SERVICE_NAME = "org.sshtunnel.SSHTunnelService";
public static final String TAG = "SSHTunnelWidgetProvider";
public boolean isWorked(Context context, String service) {
ActivityManager myManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
.getRunningServices(30);
for (int i = 0; i < runningService.size(); i++) {
if (runningService.get(i).service.getClassName().toString()
.equals(service)) {
return true;
}
}
return false;
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(PROXY_SWITCH_ACTION)) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (settings.getBoolean("isSwitching", false))
return;
Editor ed = settings.edit();
ed.putBoolean("isSwitching", true);
ed.commit();
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.sshtunnel_appwidget);
try {
views.setImageViewResource(R.id.serviceToggle, R.drawable.ing);
AppWidgetManager awm = AppWidgetManager.getInstance(context);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(
context, SSHTunnelWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
Log.d(TAG, "Proxy switch action");
// do some really cool stuff here
if (isWorked(context, SERVICE_NAME)) {
// Service is working, so stop it
try {
context.stopService(new Intent(context,
SSHTunnelService.class));
} catch (Exception e) {
// Nothing
}
} else {
SSHTunnelReceiver sshr = new SSHTunnelReceiver();
sshr.onReceive(context, intent, true);
}
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, SSHTunnelWidgetProvider.class);
intent.setAction(PROXY_SWITCH_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.sshtunnel_appwidget);
views.setOnClickPendingIntent(R.id.serviceToggle, pendingIntent);
if (isWorked(context, SERVICE_NAME)) {
views.setImageViewResource(R.id.serviceToggle, R.drawable.on);
Log.d(TAG, "Service running");
} else {
views.setImageViewResource(R.id.serviceToggle, R.drawable.off);
Log.d(TAG, "Service stopped");
}
// Tell the AppWidgetManager to perform an update on the current App
// Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
| Java |
package com.trilead.ssh2;
import java.util.Map;
/**
* AuthAgentCallback.
*
* @author Kenny Root
* @version $Id$
*/
public interface AuthAgentCallback {
/**
* @param key
* A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of the user in Trilead
* object format.
* @param comment
* comment associated with this key
* @param confirmUse
* whether to prompt before using this key
* @param lifetime
* lifetime in seconds for key to be remembered
* @return success or failure
*/
boolean addIdentity(Object key, String comment, boolean confirmUse,
int lifetime);
/**
* @param publicKey
* byte blob containing the OpenSSH-format encoded public key
* @return A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of the user in Trilead object
* format.
*/
Object getPrivateKey(byte[] publicKey);
/**
* @return
*/
boolean isAgentLocked();
/**
* @return success or failure
*/
boolean removeAllIdentities();
/**
* @param publicKey
* byte blob containing the OpenSSH-format encoded public key
* @return success or failure
*/
boolean removeIdentity(byte[] publicKey);
/**
* @param unlockPassphrase
* @return
*/
boolean requestAgentUnlock(String unlockPassphrase);
/**
* @return array of blobs containing the OpenSSH-format encoded public keys
*/
Map<String, byte[]> retrieveIdentities();
/**
* @param lockPassphrase
*/
boolean setAgentLock(String lockPassphrase);
}
| Java |
package com.trilead.ssh2;
/**
* An abstract marker interface implemented by all proxy data implementations.
*
* @see HTTPProxyData
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ProxyData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public abstract interface ProxyData {
}
| Java |
package com.trilead.ssh2;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.digest.Digest;
import com.trilead.ssh2.crypto.digest.HMAC;
import com.trilead.ssh2.crypto.digest.MD5;
import com.trilead.ssh2.crypto.digest.SHA1;
import com.trilead.ssh2.signature.DSAPublicKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.RSAPublicKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
/**
* The <code>KnownHosts</code> class is a handy tool to verify received server
* hostkeys based on the information in <code>known_hosts</code> files (the ones
* used by OpenSSH).
* <p>
* It offers basically an in-memory database for known_hosts entries, as well as
* some helper functions. Entries from a <code>known_hosts</code> file can be
* loaded at construction time. It is also possible to add more keys later
* (e.g., one can parse different <code>known_hosts<code> files).
* <p>
* It is a thread safe implementation, therefore, you need only to instantiate one
* <code>KnownHosts</code> for your whole application.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KnownHosts.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class KnownHosts {
private class KnownHostsEntry {
String[] patterns;
Object key;
KnownHostsEntry(String[] patterns, Object key) {
this.patterns = patterns;
this.key = key;
}
}
public static final int HOSTKEY_IS_OK = 0;
public static final int HOSTKEY_IS_NEW = 1;
public static final int HOSTKEY_HAS_CHANGED = 2;
/**
* Adds a single public key entry to the a known_hosts file. This method is
* designed to be used in a {@link ServerHostKeyVerifier}.
*
* @param knownHosts
* the file where the publickey entry will be appended.
* @param hostnames
* a list of hostname patterns - at least one most be specified.
* Check out the OpenSSH sshd man page for a description of the
* pattern matching algorithm.
* @param serverHostKeyAlgorithm
* as passed to the {@link ServerHostKeyVerifier}.
* @param serverHostKey
* as passed to the {@link ServerHostKeyVerifier}.
* @throws IOException
*/
public final static void addHostkeyToFile(File knownHosts,
String[] hostnames, String serverHostKeyAlgorithm,
byte[] serverHostKey) throws IOException {
if ((hostnames == null) || (hostnames.length == 0))
throw new IllegalArgumentException(
"Need at least one hostname specification");
if ((serverHostKeyAlgorithm == null) || (serverHostKey == null))
throw new IllegalArgumentException();
CharArrayWriter writer = new CharArrayWriter();
for (int i = 0; i < hostnames.length; i++) {
if (i != 0)
writer.write(',');
writer.write(hostnames[i]);
}
writer.write(' ');
writer.write(serverHostKeyAlgorithm);
writer.write(' ');
writer.write(Base64.encode(serverHostKey));
writer.write("\n");
char[] entry = writer.toCharArray();
RandomAccessFile raf = new RandomAccessFile(knownHosts, "rw");
long len = raf.length();
if (len > 0) {
raf.seek(len - 1);
int last = raf.read();
if (last != '\n')
raf.write('\n');
}
raf.write(new String(entry).getBytes("ISO-8859-1"));
raf.close();
}
/**
* Convert a ssh2 key-blob into a human readable bubblebabble fingerprint.
* The used bubblebabble algorithm (taken from OpenSSH) generates
* fingerprints that are easier to remember for humans.
* <p>
* Example fingerprint:
* xofoc-bubuz-cazin-zufyl-pivuk-biduk-tacib-pybur-gonar-hotat-lyxux.
*
* @param keytype
* either "ssh-rsa" or "ssh-dss"
* @param publickey
* key data
* @return Bubblebabble fingerprint
*/
public final static String createBubblebabbleFingerprint(String keytype,
byte[] publickey) {
byte[] raw = rawFingerPrint("sha1", keytype, publickey);
return rawToBubblebabbleFingerprint(raw);
}
/**
* Generate the hashed representation of the given hostname. Useful for
* adding entries with hashed hostnames to a known_hosts file. (see -H
* option of OpenSSH key-gen).
*
* @param hostname
* @return the hashed representation, e.g.,
* "|1|cDhrv7zwEUV3k71CEPHnhHZezhA=|Xo+2y6rUXo2OIWRAYhBOIijbJMA="
*/
public static final String createHashedHostname(String hostname) {
SHA1 sha1 = new SHA1();
byte[] salt = new byte[sha1.getDigestLength()];
new SecureRandom().nextBytes(salt);
byte[] hash = hmacSha1Hash(salt, hostname);
String base64_salt = new String(Base64.encode(salt));
String base64_hash = new String(Base64.encode(hash));
return new String("|1|" + base64_salt + "|" + base64_hash);
}
/**
* Convert a ssh2 key-blob into a human readable hex fingerprint. Generated
* fingerprints are identical to those generated by OpenSSH.
* <p>
* Example fingerprint: d0:cb:76:19:99:5a:03:fc:73:10:70:93:f2:44:63:47.
*
* @param keytype
* either "ssh-rsa" or "ssh-dss"
* @param publickey
* key blob
* @return Hex fingerprint
*/
public final static String createHexFingerprint(String keytype,
byte[] publickey) {
byte[] raw = rawFingerPrint("md5", keytype, publickey);
return rawToHexFingerprint(raw);
}
private static final byte[] hmacSha1Hash(byte[] salt, String hostname) {
SHA1 sha1 = new SHA1();
if (salt.length != sha1.getDigestLength())
throw new IllegalArgumentException("Salt has wrong length ("
+ salt.length + ")");
HMAC hmac = new HMAC(sha1, salt, salt.length);
try {
hmac.update(hostname.getBytes("ISO-8859-1"));
} catch (UnsupportedEncodingException ignore) {
/*
* Actually, ISO-8859-1 is supported by all correct Java
* implementations. But... you never know.
*/
hmac.update(hostname.getBytes());
}
byte[] dig = new byte[hmac.getDigestLength()];
hmac.digest(dig);
return dig;
}
/**
* Generates a "raw" fingerprint of a hostkey.
*
* @param type
* either "md5" or "sha1"
* @param keyType
* either "ssh-rsa" or "ssh-dss"
* @param hostkey
* the hostkey
* @return the raw fingerprint
*/
static final private byte[] rawFingerPrint(String type, String keyType,
byte[] hostkey) {
Digest dig = null;
if ("md5".equals(type)) {
dig = new MD5();
} else if ("sha1".equals(type)) {
dig = new SHA1();
} else
throw new IllegalArgumentException("Unknown hash type " + type);
if ("ssh-rsa".equals(keyType)) {
} else if ("ssh-dss".equals(keyType)) {
} else
throw new IllegalArgumentException("Unknown key type " + keyType);
if (hostkey == null)
throw new IllegalArgumentException("hostkey is null");
dig.update(hostkey);
byte[] res = new byte[dig.getDigestLength()];
dig.digest(res);
return res;
}
/**
* Convert a raw fingerprint to bubblebabble representation.
*
* @param raw
* raw fingerprint
* @return the bubblebabble representation
*/
static final private String rawToBubblebabbleFingerprint(byte[] raw) {
final char[] v = "aeiouy".toCharArray();
final char[] c = "bcdfghklmnprstvzx".toCharArray();
StringBuffer sb = new StringBuffer();
int seed = 1;
int rounds = (raw.length / 2) + 1;
sb.append('x');
for (int i = 0; i < rounds; i++) {
if (((i + 1) < rounds) || ((raw.length) % 2 != 0)) {
sb.append(v[(((raw[2 * i] >> 6) & 3) + seed) % 6]);
sb.append(c[(raw[2 * i] >> 2) & 15]);
sb.append(v[((raw[2 * i] & 3) + (seed / 6)) % 6]);
if ((i + 1) < rounds) {
sb.append(c[(((raw[(2 * i) + 1])) >> 4) & 15]);
sb.append('-');
sb.append(c[(((raw[(2 * i) + 1]))) & 15]);
// As long as seed >= 0, seed will be >= 0 afterwards
seed = ((seed * 5) + (((raw[2 * i] & 0xff) * 7) + (raw[(2 * i) + 1] & 0xff))) % 36;
}
} else {
sb.append(v[seed % 6]); // seed >= 0, therefore index positive
sb.append('x');
sb.append(v[seed / 6]);
}
}
sb.append('x');
return sb.toString();
}
/**
* Convert a raw fingerprint to hex representation (XX:YY:ZZ...).
*
* @param fingerprint
* raw fingerprint
* @return the hex representation
*/
static final private String rawToHexFingerprint(byte[] fingerprint) {
final char[] alpha = "0123456789abcdef".toCharArray();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < fingerprint.length; i++) {
if (i != 0)
sb.append(':');
int b = fingerprint[i] & 0xff;
sb.append(alpha[b >> 4]);
sb.append(alpha[b & 15]);
}
return sb.toString();
}
private LinkedList publicKeys = new LinkedList();
public KnownHosts() {
}
public KnownHosts(char[] knownHostsData) throws IOException {
initialize(knownHostsData);
}
public KnownHosts(File knownHosts) throws IOException {
initialize(knownHosts);
}
/**
* Adds a single public key entry to the database. Note: this will NOT add
* the public key to any physical file (e.g., "~/.ssh/known_hosts") - use
* <code>addHostkeyToFile()</code> for that purpose. This method is designed
* to be used in a {@link ServerHostKeyVerifier}.
*
* @param hostnames
* a list of hostname patterns - at least one most be specified.
* Check out the OpenSSH sshd man page for a description of the
* pattern matching algorithm.
* @param serverHostKeyAlgorithm
* as passed to the {@link ServerHostKeyVerifier}.
* @param serverHostKey
* as passed to the {@link ServerHostKeyVerifier}.
* @throws IOException
*/
public void addHostkey(String hostnames[], String serverHostKeyAlgorithm,
byte[] serverHostKey) throws IOException {
if (hostnames == null)
throw new IllegalArgumentException("hostnames may not be null");
if ("ssh-rsa".equals(serverHostKeyAlgorithm)) {
RSAPublicKey rpk = RSASHA1Verify
.decodeSSHRSAPublicKey(serverHostKey);
synchronized (publicKeys) {
publicKeys.add(new KnownHostsEntry(hostnames, rpk));
}
} else if ("ssh-dss".equals(serverHostKeyAlgorithm)) {
DSAPublicKey dpk = DSASHA1Verify
.decodeSSHDSAPublicKey(serverHostKey);
synchronized (publicKeys) {
publicKeys.add(new KnownHostsEntry(hostnames, dpk));
}
} else
throw new IOException("Unknwon host key type ("
+ serverHostKeyAlgorithm + ")");
}
/**
* Parses the given known_hosts data and adds entries to the database.
*
* @param knownHostsData
* @throws IOException
*/
public void addHostkeys(char[] knownHostsData) throws IOException {
initialize(knownHostsData);
}
/**
* Parses the given known_hosts file and adds entries to the database.
*
* @param knownHosts
* @throws IOException
*/
public void addHostkeys(File knownHosts) throws IOException {
initialize(knownHosts);
}
private final boolean checkHashed(String entry, String hostname) {
if (entry.startsWith("|1|") == false)
return false;
int delim_idx = entry.indexOf('|', 3);
if (delim_idx == -1)
return false;
String salt_base64 = entry.substring(3, delim_idx);
String hash_base64 = entry.substring(delim_idx + 1);
byte[] salt = null;
byte[] hash = null;
try {
salt = Base64.decode(salt_base64.toCharArray());
hash = Base64.decode(hash_base64.toCharArray());
} catch (IOException e) {
return false;
}
SHA1 sha1 = new SHA1();
if (salt.length != sha1.getDigestLength())
return false;
byte[] dig = hmacSha1Hash(salt, hostname);
for (int i = 0; i < dig.length; i++)
if (dig[i] != hash[i])
return false;
return true;
}
private int checkKey(String remoteHostname, Object remoteKey) {
int result = HOSTKEY_IS_NEW;
synchronized (publicKeys) {
Iterator i = publicKeys.iterator();
while (i.hasNext()) {
KnownHostsEntry ke = (KnownHostsEntry) i.next();
if (hostnameMatches(ke.patterns, remoteHostname) == false)
continue;
boolean res = matchKeys(ke.key, remoteKey);
if (res == true)
return HOSTKEY_IS_OK;
result = HOSTKEY_HAS_CHANGED;
}
}
return result;
}
private Vector getAllKeys(String hostname) {
Vector keys = new Vector();
synchronized (publicKeys) {
Iterator i = publicKeys.iterator();
while (i.hasNext()) {
KnownHostsEntry ke = (KnownHostsEntry) i.next();
if (hostnameMatches(ke.patterns, hostname) == false)
continue;
keys.addElement(ke.key);
}
}
return keys;
}
/**
* Try to find the preferred order of hostkey algorithms for the given
* hostname. Based on the type of hostkey that is present in the internal
* database (i.e., either <code>ssh-rsa</code> or <code>ssh-dss</code>) an
* ordered list of hostkey algorithms is returned which can be passed to
* <code>Connection.setServerHostKeyAlgorithms</code>.
*
* @param hostname
* @return <code>null</code> if no key for the given hostname is present or
* there are keys of multiple types present for the given hostname.
* Otherwise, an array with hostkey algorithms is returned (i.e., an
* array of length 2).
*/
public String[] getPreferredServerHostkeyAlgorithmOrder(String hostname) {
String[] algos = recommendHostkeyAlgorithms(hostname);
if (algos != null)
return algos;
InetAddress[] ipAdresses = null;
try {
ipAdresses = InetAddress.getAllByName(hostname);
} catch (UnknownHostException e) {
return null;
}
for (int i = 0; i < ipAdresses.length; i++) {
algos = recommendHostkeyAlgorithms(ipAdresses[i].getHostAddress());
if (algos != null)
return algos;
}
return null;
}
private final boolean hostnameMatches(String[] hostpatterns, String hostname) {
boolean isMatch = false;
boolean negate = false;
hostname = hostname.toLowerCase();
for (int k = 0; k < hostpatterns.length; k++) {
if (hostpatterns[k] == null)
continue;
String pattern = null;
/*
* In contrast to OpenSSH we also allow negated hash entries (as
* well as hashed entries in lines with multiple entries).
*/
if ((hostpatterns[k].length() > 0)
&& (hostpatterns[k].charAt(0) == '!')) {
pattern = hostpatterns[k].substring(1);
negate = true;
} else {
pattern = hostpatterns[k];
negate = false;
}
/* Optimize, no need to check this entry */
if ((isMatch) && (negate == false))
continue;
/* Now compare */
if (pattern.charAt(0) == '|') {
if (checkHashed(pattern, hostname)) {
if (negate)
return false;
isMatch = true;
}
} else {
pattern = pattern.toLowerCase();
if ((pattern.indexOf('?') != -1)
|| (pattern.indexOf('*') != -1)) {
if (pseudoRegex(pattern.toCharArray(), 0,
hostname.toCharArray(), 0)) {
if (negate)
return false;
isMatch = true;
}
} else if (pattern.compareTo(hostname) == 0) {
if (negate)
return false;
isMatch = true;
}
}
}
return isMatch;
}
private void initialize(char[] knownHostsData) throws IOException {
BufferedReader br = new BufferedReader(new CharArrayReader(
knownHostsData));
while (true) {
String line = br.readLine();
if (line == null)
break;
line = line.trim();
if (line.startsWith("#"))
continue;
String[] arr = line.split(" ");
if (arr.length >= 3) {
if ((arr[1].compareTo("ssh-rsa") == 0)
|| (arr[1].compareTo("ssh-dss") == 0)) {
String[] hostnames = arr[0].split(",");
byte[] msg = Base64.decode(arr[2].toCharArray());
addHostkey(hostnames, arr[1], msg);
}
}
}
}
private void initialize(File knownHosts) throws IOException {
char[] buff = new char[512];
CharArrayWriter cw = new CharArrayWriter();
knownHosts.createNewFile();
FileReader fr = new FileReader(knownHosts);
while (true) {
int len = fr.read(buff);
if (len < 0)
break;
cw.write(buff, 0, len);
}
fr.close();
initialize(cw.toCharArray());
}
private final boolean matchKeys(Object key1, Object key2) {
if ((key1 instanceof RSAPublicKey) && (key2 instanceof RSAPublicKey)) {
RSAPublicKey savedRSAKey = (RSAPublicKey) key1;
RSAPublicKey remoteRSAKey = (RSAPublicKey) key2;
if (savedRSAKey.getE().equals(remoteRSAKey.getE()) == false)
return false;
if (savedRSAKey.getN().equals(remoteRSAKey.getN()) == false)
return false;
return true;
}
if ((key1 instanceof DSAPublicKey) && (key2 instanceof DSAPublicKey)) {
DSAPublicKey savedDSAKey = (DSAPublicKey) key1;
DSAPublicKey remoteDSAKey = (DSAPublicKey) key2;
if (savedDSAKey.getG().equals(remoteDSAKey.getG()) == false)
return false;
if (savedDSAKey.getP().equals(remoteDSAKey.getP()) == false)
return false;
if (savedDSAKey.getQ().equals(remoteDSAKey.getQ()) == false)
return false;
if (savedDSAKey.getY().equals(remoteDSAKey.getY()) == false)
return false;
return true;
}
return false;
}
private final boolean pseudoRegex(char[] pattern, int i, char[] match, int j) {
/* This matching logic is equivalent to the one present in OpenSSH 4.1 */
while (true) {
/* Are we at the end of the pattern? */
if (pattern.length == i)
return (match.length == j);
if (pattern[i] == '*') {
i++;
if (pattern.length == i)
return true;
if ((pattern[i] != '*') && (pattern[i] != '?')) {
while (true) {
if ((pattern[i] == match[j])
&& pseudoRegex(pattern, i + 1, match, j + 1))
return true;
j++;
if (match.length == j)
return false;
}
}
while (true) {
if (pseudoRegex(pattern, i, match, j))
return true;
j++;
if (match.length == j)
return false;
}
}
if (match.length == j)
return false;
if ((pattern[i] != '?') && (pattern[i] != match[j]))
return false;
i++;
j++;
}
}
private String[] recommendHostkeyAlgorithms(String hostname) {
String preferredAlgo = null;
Vector keys = getAllKeys(hostname);
for (int i = 0; i < keys.size(); i++) {
String thisAlgo = null;
if (keys.elementAt(i) instanceof RSAPublicKey)
thisAlgo = "ssh-rsa";
else if (keys.elementAt(i) instanceof DSAPublicKey)
thisAlgo = "ssh-dss";
else
continue;
if (preferredAlgo != null) {
/* If we find different key types, then return null */
if (preferredAlgo.compareTo(thisAlgo) != 0)
return null;
/* OK, we found the same algo again, optimize */
continue;
}
}
/* If we did not find anything that we know of, return null */
if (preferredAlgo == null)
return null;
/*
* Now put the preferred algo to the start of the array. You may ask
* yourself why we do it that way - basically, we could just return only
* the preferred algorithm: since we have a saved key of that type (sent
* earlier from the remote host), then that should work out. However,
* imagine that the server is (for whatever reasons) not offering that
* type of hostkey anymore (e.g., "ssh-rsa" was disabled and now
* "ssh-dss" is being used). If we then do not let the server send us a
* fresh key of the new type, then we shoot ourself into the foot: the
* connection cannot be established and hence the user cannot decide if
* he/she wants to accept the new key.
*/
if (preferredAlgo.equals("ssh-rsa"))
return new String[] { "ssh-rsa", "ssh-dss" };
return new String[] { "ssh-dss", "ssh-rsa" };
}
/**
* Checks the internal hostkey database for the given hostkey. If no
* matching key can be found, then the hostname is resolved to an IP address
* and the search is repeated using that IP address.
*
* @param hostname
* the server's hostname, will be matched with all hostname
* patterns
* @param serverHostKeyAlgorithm
* type of hostkey, either <code>ssh-rsa</code> or
* <code>ssh-dss</code>
* @param serverHostKey
* the key blob
* @return <ul>
* <li><code>HOSTKEY_IS_OK</code>: the given hostkey matches an
* entry for the given hostname</li>
* <li><code>HOSTKEY_IS_NEW</code>: no entries found for this
* hostname and this type of hostkey</li>
* <li><code>HOSTKEY_HAS_CHANGED</code>: hostname is known, but with
* another key of the same type (man-in-the-middle attack?)</li>
* </ul>
* @throws IOException
* if the supplied key blob cannot be parsed or does not match
* the given hostkey type.
*/
public int verifyHostkey(String hostname, String serverHostKeyAlgorithm,
byte[] serverHostKey) throws IOException {
Object remoteKey = null;
if ("ssh-rsa".equals(serverHostKeyAlgorithm)) {
remoteKey = RSASHA1Verify.decodeSSHRSAPublicKey(serverHostKey);
} else if ("ssh-dss".equals(serverHostKeyAlgorithm)) {
remoteKey = DSASHA1Verify.decodeSSHDSAPublicKey(serverHostKey);
} else
throw new IllegalArgumentException("Unknown hostkey type "
+ serverHostKeyAlgorithm);
int result = checkKey(hostname, remoteKey);
if (result == HOSTKEY_IS_OK)
return result;
InetAddress[] ipAdresses = null;
try {
ipAdresses = InetAddress.getAllByName(hostname);
} catch (UnknownHostException e) {
return result;
}
for (int i = 0; i < ipAdresses.length; i++) {
int newresult = checkKey(ipAdresses[i].getHostAddress(), remoteKey);
if (newresult == HOSTKEY_IS_OK)
return newresult;
if (newresult == HOSTKEY_HAS_CHANGED)
result = HOSTKEY_HAS_CHANGED;
}
return result;
}
}
| Java |
package com.trilead.ssh2;
/**
* An <code>InteractiveCallback</code> is used to respond to challenges sent by
* the server if authentication mode "keyboard-interactive" is selected.
*
* @see Connection#authenticateWithKeyboardInteractive(String, String[],
* InteractiveCallback)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: InteractiveCallback.java,v 1.1 2007/10/15 12:49:56 cplattne Exp
* $
*/
public interface InteractiveCallback {
/**
* This callback interface is used during a "keyboard-interactive"
* authentication. Every time the server sends a set of challenges (however,
* most often just one challenge at a time), this callback function will be
* called to give your application a chance to talk to the user and to
* determine the response(s).
* <p>
* Some copy-paste information from the standard: a command line interface
* (CLI) client SHOULD print the name and instruction (if non-empty), adding
* newlines. Then for each prompt in turn, the client SHOULD display the
* prompt and read the user input. The name and instruction fields MAY be
* empty strings, the client MUST be prepared to handle this correctly. The
* prompt field(s) MUST NOT be empty strings.
* <p>
* Please refer to draft-ietf-secsh-auth-kbdinteract-XX.txt for the details.
* <p>
* Note: clients SHOULD use control character filtering as discussed in
* RFC4251 to avoid attacks by including terminal control characters in the
* fields to be displayed.
*
* @param name
* the name String sent by the server.
* @param instruction
* the instruction String sent by the server.
* @param numPrompts
* number of prompts - may be zero (in this case, you should just
* return a String array of length zero).
* @param prompt
* an array (length <code>numPrompts</code>) of Strings
* @param echo
* an array (length <code>numPrompts</code>) of booleans. For
* each prompt, the corresponding echo field indicates whether or
* not the user input should be echoed as characters are typed.
* @return an array of reponses - the array size must match the parameter
* <code>numPrompts</code>.
*/
public String[] replyToChallenge(String name, String instruction,
int numPrompts, String[] prompt, boolean[] echo) throws Exception;
}
| Java |
package com.trilead.ssh2;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.util.Vector;
import com.trilead.ssh2.auth.AuthenticationManager;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.crypto.CryptoWishList;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.log.Logger;
import com.trilead.ssh2.packets.PacketIgnore;
import com.trilead.ssh2.transport.KexManager;
import com.trilead.ssh2.transport.TransportManager;
import com.trilead.ssh2.util.TimeoutService;
import com.trilead.ssh2.util.TimeoutService.TimeoutToken;
/**
* A <code>Connection</code> is used to establish an encrypted TCP/IP connection
* to a SSH-2 server.
* <p>
* Typically, one
* <ol>
* <li>creates a {@link #Connection(String) Connection} object.</li>
* <li>calls the {@link #connect() connect()} method.</li>
* <li>calls some of the authentication methods (e.g.,
* {@link #authenticateWithPublicKey(String, File, String)
* authenticateWithPublicKey()}).</li>
* <li>calls one or several times the {@link #openSession() openSession()}
* method.</li>
* <li>finally, one must close the connection and release resources with the
* {@link #close() close()} method.</li>
* </ol>
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Connection.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
*/
public class Connection {
/**
* The identifier presented to the SSH-2 server.
*/
public final static String identification = "TrileadSSH2Java_213";
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported cipher algorithms by this implementation.
*/
public static synchronized String[] getAvailableCiphers() {
return BlockCipherFactory.getDefaultCipherList();
}
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported MAC algorthims by this implementation.
*/
public static synchronized String[] getAvailableMACs() {
return MAC.getMacList();
}
/**
* Unless you know what you are doing, you will never need this.
*
* @return The list of supported server host key algorthims by this
* implementation.
*/
public static synchronized String[] getAvailableServerHostKeyAlgorithms() {
return KexManager.getDefaultServerHostkeyAlgorithmList();
}
/**
* Will be used to generate all random data needed for the current
* connection. Note: SecureRandom.nextBytes() is thread safe.
*/
private SecureRandom generator;
private AuthenticationManager am;
private boolean authenticated = false;
private boolean compression = false;
private ChannelManager cm;
private CryptoWishList cryptoWishList = new CryptoWishList();
private DHGexParameters dhgexpara = new DHGexParameters();
private final String hostname;
private final int port;
private TransportManager tm;
private boolean tcpNoDelay = false;
private ProxyData proxyData = null;
private Vector<ConnectionMonitor> connectionMonitors = new Vector<ConnectionMonitor>();
/**
* Prepares a fresh <code>Connection</code> object which can then be used to
* establish a connection to the specified SSH-2 server.
* <p>
* Same as {@link #Connection(String, int) Connection(hostname, 22)}.
*
* @param hostname
* the hostname of the SSH-2 server.
*/
public Connection(String hostname) {
this(hostname, 22);
}
/**
* Prepares a fresh <code>Connection</code> object which can then be used to
* establish a connection to the specified SSH-2 server.
*
* @param hostname
* the host where we later want to connect to.
* @param port
* port on the server, normally 22.
*/
public Connection(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
/**
* Add a {@link ConnectionMonitor} to this connection. Can be invoked at any
* time, but it is best to add connection monitors before invoking
* <code>connect()</code> to avoid glitches (e.g., you add a connection
* monitor after a successful connect(), but the connection has died in the
* mean time. Then, your connection monitor won't be notified.)
* <p>
* You can add as many monitors as you like.
*
* @see ConnectionMonitor
*
* @param cmon
* An object implementing the <code>ConnectionMonitor</code>
* interface.
*/
public synchronized void addConnectionMonitor(ConnectionMonitor cmon) {
if (cmon == null)
throw new IllegalArgumentException("cmon argument is null");
connectionMonitors.addElement(cmon);
if (tm != null)
tm.setConnectionMonitors(connectionMonitors);
}
/**
* After a successful connect, one has to authenticate oneself. This method
* is based on DSA (it uses DSA to sign a challenge sent by the server).
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and one
* can retry either by using this or any other authentication method (use
* the <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
*
* @param user
* A <code>String</code> holding the username.
* @param pem
* A <code>String</code> containing the DSA private key of the
* user in OpenSSH key format (PEM, you can't miss the
* "-----BEGIN DSA PRIVATE KEY-----" tag). The string may contain
* linefeeds.
* @param password
* If the PEM string is 3DES encrypted ("DES-EDE3-CBC"), then you
* must specify the password. Otherwise, this argument will be
* ignored and can be set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*
* @deprecated You should use one of the
* {@link #authenticateWithPublicKey(String, File, String)
* authenticateWithPublicKey()} methods, this method is just a
* wrapper for it and will disappear in future builds.
*
*/
@Deprecated
public synchronized boolean authenticateWithDSA(String user, String pem,
String password) throws IOException {
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (pem == null)
throw new IllegalArgumentException("pem argument is null");
authenticated = am.authenticatePublicKey(user, pem.toCharArray(),
password, getOrCreateSecureRND());
return authenticated;
}
/**
* A wrapper that calls
* {@link #authenticateWithKeyboardInteractive(String, String[], InteractiveCallback)
* authenticateWithKeyboardInteractivewith} a <code>null</code> submethod
* list.
*
* @param user
* A <code>String</code> holding the username.
* @param cb
* An <code>InteractiveCallback</code> which will be used to
* determine the responses to the questions asked by the server.
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithKeyboardInteractive(
String user, InteractiveCallback cb) throws IOException {
return authenticateWithKeyboardInteractive(user, null, cb);
}
/**
* After a successful connect, one has to authenticate oneself. This method
* is based on "keyboard-interactive", specified in
* draft-ietf-secsh-auth-kbdinteract-XX. Basically, you have to define a
* callback object which will be feeded with challenges generated by the
* server. Answers are then sent back to the server. It is possible that the
* callback will be called several times during the invocation of this
* method (e.g., if the server replies to the callback's answer(s) with
* another challenge...)
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and one
* can retry either by using this or any other authentication method (use
* the <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
* <p>
* Note: some SSH servers advertise "keyboard-interactive", however, any
* interactive request will be denied (without having sent any challenge to
* the client).
*
* @param user
* A <code>String</code> holding the username.
* @param submethods
* An array of submethod names, see
* draft-ietf-secsh-auth-kbdinteract-XX. May be <code>null</code>
* to indicate an empty list.
* @param cb
* An <code>InteractiveCallback</code> which will be used to
* determine the responses to the questions asked by the server.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithKeyboardInteractive(
String user, String[] submethods, InteractiveCallback cb)
throws IOException {
if (cb == null)
throw new IllegalArgumentException("Callback may not ne NULL!");
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
authenticated = am.authenticateInteractive(user, submethods, cb);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* can be used to explicitly use the special "none" authentication method
* (where only a username has to be specified).
* <p>
* Note 1: The "none" method may always be tried by clients, however as by
* the specs, the server will not explicitly announce it. In other words,
* the "none" token will never show up in the list returned by
* {@link #getRemainingAuthMethods(String)}.
* <p>
* Note 2: no matter which one of the authenticateWithXXX() methods you
* call, the library will always issue exactly one initial "none"
* authentication request to retrieve the initially allowed list of
* authentication methods by the server. Please read RFC 4252 for the
* details.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If further authentication steps are needed, <code>false</code>
* is returned and one can retry by any other authentication method (use the
* <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
*
* @param user
* @return if the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithNone(String user)
throws IOException {
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
/* Trigger the sending of the PacketUserauthRequestNone packet */
/* (if not already done) */
authenticated = am.authenticateNone(user);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* sends username and password to the server.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and one
* can retry either by using this or any other authentication method (use
* the <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
* <p>
* Note: if this method fails, then please double-check that it is actually
* offered by the server (use {@link #getRemainingAuthMethods(String)
* getRemainingAuthMethods()}.
* <p>
* Often, password authentication is disabled, but users are not aware of
* it. Many servers only offer "publickey" and "keyboard-interactive".
* However, even though "keyboard-interactive" *feels* like password
* authentication (e.g., when using the putty or openssh clients) it is
* *not* the same mechanism.
*
* @param user
* @param password
* @return if the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPassword(String user,
String password) throws IOException {
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (password == null)
throw new IllegalArgumentException("password argument is null");
authenticated = am.authenticatePassword(user, password);
return authenticated;
}
/**
* After a successful connect, one has to authenticate oneself. The
* authentication method "publickey" works by signing a challenge sent by
* the server. The signature is either DSA or RSA based - it just depends on
* the type of private key you specify, either a DSA or RSA private key in
* PEM format. And yes, this is may seem to be a little confusing, the
* method is called "publickey" in the SSH-2 protocol specification, however
* since we need to generate a signature, you actually have to supply a
* private key =).
* <p>
* The private key contained in the PEM file may also be encrypted
* ("Proc-Type: 4,ENCRYPTED"). The library supports DES-CBC and DES-EDE3-CBC
* encryption, as well as the more exotic PEM encrpytions AES-128-CBC,
* AES-192-CBC and AES-256-CBC.
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and one
* can retry either by using this or any other authentication method (use
* the <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
* <p>
* NOTE PUTTY USERS: Event though your key file may start with
* "-----BEGIN..." it is not in the expected format. You have to convert it
* to the OpenSSH key format by using the "puttygen" tool (can be downloaded
* from the Putty website). Simply load your key and then use the
* "Conversions/Export OpenSSH key" functionality to get a proper PEM file.
*
* @param user
* A <code>String</code> holding the username.
* @param pemPrivateKey
* A <code>char[]</code> containing a DSA or RSA private key of
* the user in OpenSSH key format (PEM, you can't miss the
* "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE
* KEY-----" tag). The char array may contain
* linebreaks/linefeeds.
* @param password
* If the PEM structure is encrypted ("Proc-Type: 4,ENCRYPTED")
* then you must specify a password. Otherwise, this argument
* will be ignored and can be set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user,
char[] pemPrivateKey, String password) throws IOException {
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (pemPrivateKey == null)
throw new IllegalArgumentException("pemPrivateKey argument is null");
authenticated = am.authenticatePublicKey(user, pemPrivateKey, password,
getOrCreateSecureRND());
return authenticated;
}
/**
* A convenience wrapper function which reads in a private key (PEM format,
* either DSA or RSA) and then calls
* <code>authenticateWithPublicKey(String, char[], String)</code>.
* <p>
* NOTE PUTTY USERS: Event though your key file may start with
* "-----BEGIN..." it is not in the expected format. You have to convert it
* to the OpenSSH key format by using the "puttygen" tool (can be downloaded
* from the Putty website). Simply load your key and then use the
* "Conversions/Export OpenSSH key" functionality to get a proper PEM file.
*
* @param user
* A <code>String</code> holding the username.
* @param pemFile
* A <code>File</code> object pointing to a file containing a DSA
* or RSA private key of the user in OpenSSH key format (PEM, you
* can't miss the "-----BEGIN DSA PRIVATE KEY-----" or
* "-----BEGIN RSA PRIVATE KEY-----" tag).
* @param password
* If the PEM file is encrypted then you must specify the
* password. Otherwise, this argument will be ignored and can be
* set to <code>null</code>.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user,
File pemFile, String password) throws IOException {
if (pemFile == null)
throw new IllegalArgumentException("pemFile argument is null");
char[] buff = new char[256];
CharArrayWriter cw = new CharArrayWriter();
FileReader fr = new FileReader(pemFile);
while (true) {
int len = fr.read(buff);
if (len < 0)
break;
cw.write(buff, 0, len);
}
fr.close();
return authenticateWithPublicKey(user, cw.toCharArray(), password);
}
/**
* After a successful connect, one has to authenticate oneself. The
* authentication method "publickey" works by signing a challenge sent by
* the server. The signature is either DSA or RSA based - it just depends on
* the type of private key you specify, either a DSA or RSA private key in
* PEM format. And yes, this is may seem to be a little confusing, the
* method is called "publickey" in the SSH-2 protocol specification, however
* since we need to generate a signature, you actually have to supply a
* private key =).
* <p>
* If the authentication phase is complete, <code>true</code> will be
* returned. If the server does not accept the request (or if further
* authentication steps are needed), <code>false</code> is returned and one
* can retry either by using this or any other authentication method (use
* the <code>getRemainingAuthMethods</code> method to get a list of the
* remaining possible methods).
*
* @param user
* A <code>String</code> holding the username.
* @param key
* A <code>RSAPrivateKey</code> or <code>DSAPrivateKey</code>
* containing a DSA or RSA private key of the user in Trilead
* object format.
*
* @return whether the connection is now authenticated.
* @throws IOException
*/
public synchronized boolean authenticateWithPublicKey(String user,
Object key) throws IOException {
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
if (user == null)
throw new IllegalArgumentException("user argument is null");
if (key == null)
throw new IllegalArgumentException("Key argument is null");
authenticated = am.authenticatePublicKey(user, key,
getOrCreateSecureRND());
return authenticated;
}
/**
* Cancel an earlier requested remote port forwarding. Currently active
* forwardings will not be affected (e.g., disrupted). Note that further
* connection forwarding requests may be received until this method has
* returned.
*
* @param bindPort
* the allocated port number on the server
* @throws IOException
* if the remote side refuses the cancel request or another low
* level error occurs (e.g., the underlying connection is
* closed)
*/
public synchronized void cancelRemotePortForwarding(int bindPort)
throws IOException {
if (tm == null)
throw new IllegalStateException(
"You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"The connection is not authenticated.");
cm.requestCancelGlobalForward(bindPort);
}
/**
* Close the connection to the SSH-2 server. All assigned sessions will be
* closed, too. Can be called at any time. Don't forget to call this once
* you don't need a connection anymore - otherwise the receiver thread may
* run forever.
*/
public synchronized void close() {
Throwable t = new Throwable("Closed due to user request.");
close(t, false);
}
private void close(Throwable t, boolean hard) {
if (cm != null)
cm.closeAllChannels();
if (tm != null) {
tm.close(t, hard == false);
tm = null;
}
am = null;
cm = null;
authenticated = false;
}
/**
* Same as {@link #connect(ServerHostKeyVerifier, int, int) connect(null, 0,
* 0)}.
*
* @return see comments for the
* {@link #connect(ServerHostKeyVerifier, int, int)
* connect(ServerHostKeyVerifier, int, int)} method.
* @throws IOException
*/
public synchronized ConnectionInfo connect() throws IOException {
return connect(null, 0, 0);
}
/**
* Same as {@link #connect(ServerHostKeyVerifier, int, int)
* connect(verifier, 0, 0)}.
*
* @return see comments for the
* {@link #connect(ServerHostKeyVerifier, int, int)
* connect(ServerHostKeyVerifier, int, int)} method.
* @throws IOException
*/
public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier)
throws IOException {
return connect(verifier, 0, 0);
}
/**
* Connect to the SSH-2 server and, as soon as the server has presented its
* host key, use the
* {@link ServerHostKeyVerifier#verifyServerHostKey(String, int, String, byte[])
* ServerHostKeyVerifier.verifyServerHostKey()} method of the
* <code>verifier</code> to ask for permission to proceed. If
* <code>verifier</code> is <code>null</code>, then any host key will be
* accepted - this is NOT recommended, since it makes man-in-the-middle
* attackes VERY easy (somebody could put a proxy SSH server between you and
* the real server).
* <p>
* Note: The verifier will be called before doing any crypto calculations
* (i.e., diffie-hellman). Therefore, if you don't like the presented host
* key then no CPU cycles are wasted (and the evil server has less
* information about us).
* <p>
* However, it is still possible that the server presented a fake host key:
* the server cheated (typically a sign for a man-in-the-middle attack) and
* is not able to generate a signature that matches its host key. Don't
* worry, the library will detect such a scenario later when checking the
* signature (the signature cannot be checked before having completed the
* diffie-hellman exchange).
* <p>
* Note 2: The
* {@link ServerHostKeyVerifier#verifyServerHostKey(String, int, String, byte[])
* ServerHostKeyVerifier.verifyServerHostKey()} method will *NOT* be called
* from the current thread, the call is being made from a background thread
* (there is a background dispatcher thread for every established
* connection).
* <p>
* Note 3: This method will block as long as the key exchange of the
* underlying connection has not been completed (and you have not specified
* any timeouts).
* <p>
* Note 4: If you want to re-use a connection object that was successfully
* connected, then you must call the {@link #close()} method before invoking
* <code>connect()</code> again.
*
* @param verifier
* An object that implements the {@link ServerHostKeyVerifier}
* interface. Pass <code>null</code> to accept any server host
* key - NOT recommended.
*
* @param connectTimeout
* Connect the underlying TCP socket to the server with the given
* timeout value (non-negative, in milliseconds). Zero means no
* timeout. If a proxy is being used (see
* {@link #setProxyData(ProxyData)}), then this timeout is used
* for the connection establishment to the proxy.
*
* @param kexTimeout
* Timeout for complete connection establishment (non-negative,
* in milliseconds). Zero means no timeout. The timeout counts
* from the moment you invoke the connect() method and is
* cancelled as soon as the first key-exchange round has
* finished. It is possible that the timeout event will be fired
* during the invocation of the <code>verifier</code> callback,
* but it will only have an effect after the
* <code>verifier</code> returns.
*
* @return A {@link ConnectionInfo} object containing the details of the
* established connection.
*
* @throws IOException
* If any problem occurs, e.g., the server's host key is not
* accepted by the <code>verifier</code> or there is problem
* during the initial crypto setup (e.g., the signature sent by
* the server is wrong).
* <p>
* In case of a timeout (either connectTimeout or kexTimeout) a
* SocketTimeoutException is thrown.
* <p>
* An exception may also be thrown if the connection was already
* successfully connected (no matter if the connection broke in
* the mean time) and you invoke <code>connect()</code> again
* without having called {@link #close()} first.
* <p>
* If a HTTP proxy is being used and the proxy refuses the
* connection, then a {@link HTTPProxyException} may be thrown,
* which contains the details returned by the proxy. If the
* proxy is buggy and does not return a proper HTTP response,
* then a normal IOException is thrown instead.
*/
public synchronized ConnectionInfo connect(ServerHostKeyVerifier verifier,
int connectTimeout, int kexTimeout) throws IOException {
final class TimeoutState {
boolean isCancelled = false;
boolean timeoutSocketClosed = false;
}
if (tm != null)
throw new IOException("Connection to " + hostname
+ " is already in connected state!");
if (connectTimeout < 0)
throw new IllegalArgumentException(
"connectTimeout must be non-negative!");
if (kexTimeout < 0)
throw new IllegalArgumentException(
"kexTimeout must be non-negative!");
final TimeoutState state = new TimeoutState();
tm = new TransportManager(hostname, port);
tm.setConnectionMonitors(connectionMonitors);
// Don't offer compression if not requested
if (!compression) {
cryptoWishList.c2s_comp_algos = new String[] { "none" };
cryptoWishList.s2c_comp_algos = new String[] { "none" };
}
/*
* Make sure that the runnable below will observe the new value of "tm"
* and "state" (the runnable will be executed in a different thread,
* which may be already running, that is why we need a memory barrier
* here). See also the comment in Channel.java if you are interested in
* the details.
*
* OKOK, this is paranoid since adding the runnable to the todo list of
* the TimeoutService will ensure that all writes have been flushed
* before the Runnable reads anything (there is a synchronized block in
* TimeoutService.addTimeoutHandler).
*/
synchronized (tm) {
/* We could actually synchronize on anything. */
}
try {
TimeoutToken token = null;
if (kexTimeout > 0) {
final Runnable timeoutHandler = new Runnable() {
@Override
public void run() {
synchronized (state) {
if (state.isCancelled)
return;
state.timeoutSocketClosed = true;
tm.close(new SocketTimeoutException(
"The connect timeout expired"), false);
}
}
};
long timeoutHorizont = System.currentTimeMillis() + kexTimeout;
token = TimeoutService.addTimeoutHandler(timeoutHorizont,
timeoutHandler);
}
try {
tm.initialize(cryptoWishList, verifier, dhgexpara,
connectTimeout, getOrCreateSecureRND(), proxyData);
} catch (SocketTimeoutException se) {
throw (SocketTimeoutException) new SocketTimeoutException(
"The connect() operation on the socket timed out.")
.initCause(se);
}
tm.setTcpNoDelay(tcpNoDelay);
/* Wait until first KEX has finished */
ConnectionInfo ci = tm.getConnectionInfo(1);
/* Now try to cancel the timeout, if needed */
if (token != null) {
TimeoutService.cancelTimeoutHandler(token);
/* Were we too late? */
synchronized (state) {
if (state.timeoutSocketClosed)
throw new IOException(
"This exception will be replaced by the one below =)");
/*
* Just in case the "cancelTimeoutHandler" invocation came
* just a little bit too late but the handler did not enter
* the semaphore yet - we can still stop it.
*/
state.isCancelled = true;
}
}
return ci;
} catch (SocketTimeoutException ste) {
throw ste;
} catch (IOException e1) {
/* This will also invoke any registered connection monitors */
close(new Throwable("There was a problem during connect."), false);
synchronized (state) {
/*
* Show a clean exception, not something like "the socket is
* closed!?!"
*/
if (state.timeoutSocketClosed)
throw new SocketTimeoutException("The kexTimeout ("
+ kexTimeout + " ms) expired.");
}
/* Do not wrap a HTTPProxyException */
if (e1 instanceof HTTPProxyException)
throw e1;
throw (IOException) new IOException(
"There was a problem while connecting to " + hostname + ":"
+ port).initCause(e1);
}
}
/**
* Creates a new {@link DynamicPortForwarder}. A
* <code>DynamicPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host that is chosen via
* the SOCKS protocol.
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param addr
* specifies the InetSocketAddress where the local socket shall
* be bound to.
* @return A {@link DynamicPortForwarder} object.
* @throws IOException
*/
public synchronized DynamicPortForwarder createDynamicPortForwarder(
InetSocketAddress addr) throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot forward ports, connection is not authenticated.");
return new DynamicPortForwarder(cm, addr);
}
/**
* Creates a new {@link DynamicPortForwarder}. A
* <code>DynamicPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host that is chosen via
* the SOCKS protocol.
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param local_port
* @return A {@link DynamicPortForwarder} object.
* @throws IOException
*/
public synchronized DynamicPortForwarder createDynamicPortForwarder(
int local_port) throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot forward ports, connection is not authenticated.");
return new DynamicPortForwarder(cm, local_port);
}
/**
* Creates a new {@link LocalPortForwarder}. A
* <code>LocalPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host (which may or may
* not be identical to the remote SSH-2 server).
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param addr
* specifies the InetSocketAddress where the local socket shall
* be bound to.
* @param host_to_connect
* target address (IP or hostname)
* @param port_to_connect
* target port
* @return A {@link LocalPortForwarder} object.
* @throws IOException
*/
public synchronized LocalPortForwarder createLocalPortForwarder(
InetSocketAddress addr, String host_to_connect, int port_to_connect)
throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot forward ports, connection is not authenticated.");
return new LocalPortForwarder(cm, addr, host_to_connect,
port_to_connect);
}
/**
* Creates a new {@link LocalPortForwarder}. A
* <code>LocalPortForwarder</code> forwards TCP/IP connections that arrive
* at a local port via the secure tunnel to another host (which may or may
* not be identical to the remote SSH-2 server).
* <p>
* This method must only be called after one has passed successfully the
* authentication step. There is no limit on the number of concurrent
* forwardings.
*
* @param local_port
* the local port the LocalPortForwarder shall bind to.
* @param host_to_connect
* target address (IP or hostname)
* @param port_to_connect
* target port
* @return A {@link LocalPortForwarder} object.
* @throws IOException
*/
public synchronized LocalPortForwarder createLocalPortForwarder(
int local_port, String host_to_connect, int port_to_connect)
throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot forward ports, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot forward ports, connection is not authenticated.");
return new LocalPortForwarder(cm, local_port, host_to_connect,
port_to_connect);
}
/**
* Creates a new {@link LocalStreamForwarder}. A
* <code>LocalStreamForwarder</code> manages an Input/Outputstream pair that
* is being forwarded via the secure tunnel into a TCP/IP connection to
* another host (which may or may not be identical to the remote SSH-2
* server).
*
* @param host_to_connect
* @param port_to_connect
* @return A {@link LocalStreamForwarder} object.
* @throws IOException
*/
public synchronized LocalStreamForwarder createLocalStreamForwarder(
String host_to_connect, int port_to_connect) throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot forward, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot forward, connection is not authenticated.");
return new LocalStreamForwarder(cm, host_to_connect, port_to_connect);
}
/**
* Create a very basic {@link SCPClient} that can be used to copy files
* from/to the SSH-2 server.
* <p>
* Works only after one has passed successfully the authentication step.
* There is no limit on the number of concurrent SCP clients.
* <p>
* Note: This factory method will probably disappear in the future.
*
* @return A {@link SCPClient} object.
* @throws IOException
*/
public synchronized SCPClient createSCPClient() throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot create SCP client, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot create SCP client, connection is not authenticated.");
return new SCPClient(this);
}
/**
* Enable/disable debug logging. <b>Only do this when requested by Trilead
* support.</b>
* <p>
* For speed reasons, some static variables used to check whether debugging
* is enabled are not protected with locks. In other words, if you
* dynamicaly enable/disable debug logging, then some threads may still use
* the old setting. To be on the safe side, enable debugging before doing
* the <code>connect()</code> call.
*
* @param enable
* on/off
* @param logger
* a {@link DebugLogger DebugLogger} instance, <code>null</code>
* means logging using the simple logger which logs all messages
* to to stderr. Ignored if enabled is <code>false</code>
*/
public synchronized void enableDebugging(boolean enable, DebugLogger logger) {
Logger.enabled = enable;
if (enable == false) {
Logger.logger = null;
} else {
if (logger == null) {
logger = new DebugLogger() {
@Override
public void log(int level, String className, String message) {
long now = System.currentTimeMillis();
System.err.println(now + " : " + className + ": "
+ message);
}
};
}
Logger.logger = logger;
}
}
/**
* Force an asynchronous key re-exchange (the call does not block). The
* latest values set for MAC, Cipher and DH group exchange parameters will
* be used. If a key exchange is currently in progress, then this method has
* the only effect that the so far specified parameters will be used for the
* next (server driven) key exchange.
* <p>
* Note: This implementation will never start a key exchange (other than the
* initial one) unless you or the SSH-2 server ask for it.
*
* @throws IOException
* In case of any failure behind the scenes.
*/
public synchronized void forceKeyExchange() throws IOException {
if (tm == null)
throw new IllegalStateException(
"You need to establish a connection first.");
tm.forceKeyExchange(cryptoWishList, dhgexpara);
}
/**
* Returns a {@link ConnectionInfo} object containing the details of the
* connection. Can be called as soon as the connection has been established
* (successfully connected).
*
* @return A {@link ConnectionInfo} object.
* @throws IOException
* In case of any failure behind the scenes.
*/
public synchronized ConnectionInfo getConnectionInfo() throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot get details of connection, you need to establish a connection first.");
return tm.getConnectionInfo(1);
}
/**
* Returns the hostname that was passed to the constructor.
*
* @return the hostname
*/
public synchronized String getHostname() {
return hostname;
}
private final SecureRandom getOrCreateSecureRND() {
if (generator == null)
generator = new SecureRandom();
return generator;
}
/**
* Returns the port that was passed to the constructor.
*
* @return the TCP port
*/
public synchronized int getPort() {
return port;
}
/**
* After a successful connect, one has to authenticate oneself. This method
* can be used to tell which authentication methods are supported by the
* server at a certain stage of the authentication process (for the given
* username).
* <p>
* Note 1: the username will only be used if no authentication step was done
* so far (it will be used to ask the server for a list of possible
* authentication methods by sending the initial "none" request). Otherwise,
* this method ignores the user name and returns a cached method list (which
* is based on the information contained in the last negative server
* response).
* <p>
* Note 2: the server may return method names that are not supported by this
* implementation.
* <p>
* After a successful authentication, this method must not be called
* anymore.
*
* @param user
* A <code>String</code> holding the username.
*
* @return a (possibly emtpy) array holding authentication method names.
* @throws IOException
*/
public synchronized String[] getRemainingAuthMethods(String user)
throws IOException {
if (user == null)
throw new IllegalArgumentException("user argument may not be NULL!");
if (tm == null)
throw new IllegalStateException("Connection is not established!");
if (authenticated)
throw new IllegalStateException(
"Connection is already authenticated!");
if (am == null)
am = new AuthenticationManager(tm);
if (cm == null)
cm = new ChannelManager(tm);
return am.getRemainingMethods(user);
}
/**
* Determines if the authentication phase is complete. Can be called at any
* time.
*
* @return <code>true</code> if no further authentication steps are needed.
*/
public synchronized boolean isAuthenticationComplete() {
return authenticated;
}
/**
* Returns true if there was at least one failed authentication request and
* the last failed authentication request was marked with "partial success"
* by the server. This is only needed in the rare case of SSH-2 server
* setups that cannot be satisfied with a single successful authentication
* request (i.e., multiple authentication steps are needed.)
* <p>
* If you are interested in the details, then have a look at RFC4252.
*
* @return if the there was a failed authentication step and the last one
* was marked as a "partial success".
*/
public synchronized boolean isAuthenticationPartialSuccess() {
if (am == null)
return false;
return am.getPartialSuccess();
}
/**
* Checks if a specified authentication method is available. This method is
* actually just a wrapper for {@link #getRemainingAuthMethods(String)
* getRemainingAuthMethods()}.
*
* @param user
* A <code>String</code> holding the username.
* @param method
* An authentication method name (e.g., "publickey", "password",
* "keyboard-interactive") as specified by the SSH-2 standard.
* @return if the specified authentication method is currently available.
* @throws IOException
*/
public synchronized boolean isAuthMethodAvailable(String user, String method)
throws IOException {
if (method == null)
throw new IllegalArgumentException(
"method argument may not be NULL!");
String methods[] = getRemainingAuthMethods(user);
for (int i = 0; i < methods.length; i++) {
if (methods[i].compareTo(method) == 0)
return true;
}
return false;
}
/**
* Open a new {@link Session} on this connection. Works only after one has
* passed successfully the authentication step. There is no limit on the
* number of concurrent sessions.
*
* @return A {@link Session} object.
* @throws IOException
*/
public synchronized Session openSession() throws IOException {
if (tm == null)
throw new IllegalStateException(
"Cannot open session, you need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"Cannot open session, connection is not authenticated.");
return new Session(cm, getOrCreateSecureRND());
}
/**
* This method can be used to perform end-to-end connection testing. It
* sends a 'ping' message to the server and waits for the 'pong' from the
* server.
* <p>
* When this method throws an exception, then you can assume that the
* connection should be abandoned.
* <p>
* Note: Works only after one has passed successfully the authentication
* step.
* <p>
* Implementation details: this method sends a SSH_MSG_GLOBAL_REQUEST
* request ('trilead-ping') to the server and waits for the
* SSH_MSG_REQUEST_FAILURE reply packet from the server.
*
* @throws IOException
* in case of any problem
*/
public synchronized void ping() throws IOException {
if (tm == null)
throw new IllegalStateException(
"You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"The connection is not authenticated.");
cm.requestGlobalTrileadPing();
}
/**
* Removes duplicates from a String array, keeps only first occurence of
* each element. Does not destroy order of elements; can handle nulls. Uses
* a very efficient O(N^2) algorithm =)
*
* @param list
* a String array.
* @return a cleaned String array.
*/
private String[] removeDuplicates(String[] list) {
if ((list == null) || (list.length < 2))
return list;
String[] list2 = new String[list.length];
int count = 0;
for (int i = 0; i < list.length; i++) {
boolean duplicate = false;
String element = list[i];
for (int j = 0; j < count; j++) {
if (((element == null) && (list2[j] == null))
|| ((element != null) && (element.equals(list2[j])))) {
duplicate = true;
break;
}
}
if (duplicate)
continue;
list2[count++] = list[i];
}
if (count == list2.length)
return list2;
String[] tmp = new String[count];
System.arraycopy(list2, 0, tmp, 0, count);
return tmp;
}
/**
* Request a remote port forwarding. If successful, then forwarded
* connections will be redirected to the given target address. You can
* cancle a requested remote port forwarding by calling
* {@link #cancelRemotePortForwarding(int) cancelRemotePortForwarding()}.
* <p>
* A call of this method will block until the peer either agreed or
* disagreed to your request-
* <p>
* Note 1: this method typically fails if you
* <ul>
* <li>pass a port number for which the used remote user has not enough
* permissions (i.e., port < 1024)</li>
* <li>or pass a port number that is already in use on the remote server</li>
* <li>or if remote port forwarding is disabled on the server.</li>
* </ul>
* <p>
* Note 2: (from the openssh man page): By default, the listening socket on
* the server will be bound to the loopback interface only. This may be
* overriden by specifying a bind address. Specifying a remote bind address
* will only succeed if the server's <b>GatewayPorts</b> option is enabled
* (see sshd_config(5)).
*
* @param bindAddress
* address to bind to on the server:
* <ul>
* <li>"" means that connections are to be accepted on all
* protocol families supported by the SSH implementation</li>
* <li>"0.0.0.0" means to listen on all IPv4 addresses</li> <li>
* "::" means to listen on all IPv6 addresses</li> <li>
* "localhost" means to listen on all protocol families supported
* by the SSH implementation on loopback addresses only,
* [RFC3330] and RFC3513]</li> <li>"127.0.0.1" and "::1" indicate
* listening on the loopback interfaces for IPv4 and IPv6
* respectively</li>
* </ul>
* @param bindPort
* port number to bind on the server (must be > 0)
* @param targetAddress
* the target address (IP or hostname)
* @param targetPort
* the target port
* @throws IOException
*/
public synchronized void requestRemotePortForwarding(String bindAddress,
int bindPort, String targetAddress, int targetPort)
throws IOException {
if (tm == null)
throw new IllegalStateException(
"You need to establish a connection first.");
if (!authenticated)
throw new IllegalStateException(
"The connection is not authenticated.");
if ((bindAddress == null) || (targetAddress == null) || (bindPort <= 0)
|| (targetPort <= 0))
throw new IllegalArgumentException();
cm.requestGlobalForward(bindAddress, bindPort, targetAddress,
targetPort);
}
/**
* Send an SSH_MSG_IGNORE packet. This method will generate a random data
* attribute (length between 0 (invlusive) and 16 (exclusive) bytes,
* contents are random bytes).
* <p>
* This method must only be called once the connection is established.
*
* @throws IOException
*/
public synchronized void sendIgnorePacket() throws IOException {
SecureRandom rnd = getOrCreateSecureRND();
byte[] data = new byte[rnd.nextInt(16)];
rnd.nextBytes(data);
sendIgnorePacket(data);
}
/**
* Send an SSH_MSG_IGNORE packet with the given data attribute.
* <p>
* This method must only be called once the connection is established.
*
* @throws IOException
*/
public synchronized void sendIgnorePacket(byte[] data) throws IOException {
if (data == null)
throw new IllegalArgumentException(
"data argument must not be null.");
if (tm == null)
throw new IllegalStateException(
"Cannot send SSH_MSG_IGNORE packet, you need to establish a connection first.");
PacketIgnore pi = new PacketIgnore();
pi.setData(data);
tm.sendMessage(pi.getPayload());
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param ciphers
*/
public synchronized void setClient2ServerCiphers(String[] ciphers) {
if ((ciphers == null) || (ciphers.length == 0))
throw new IllegalArgumentException();
ciphers = removeDuplicates(ciphers);
BlockCipherFactory.checkCipherList(ciphers);
cryptoWishList.c2s_enc_algos = ciphers;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param macs
*/
public synchronized void setClient2ServerMACs(String[] macs) {
if ((macs == null) || (macs.length == 0))
throw new IllegalArgumentException();
macs = removeDuplicates(macs);
MAC.checkMacList(macs);
cryptoWishList.c2s_mac_algos = macs;
}
/**
* Controls whether compression is used on the link or not.
* <p>
* Note: This can only be called before connect()
*
* @param enabled
* whether to enable compression
* @throws IOException
*/
public synchronized void setCompression(boolean enabled) throws IOException {
if (tm != null)
throw new IOException("Connection to " + hostname
+ " is already in connected state!");
compression = enabled;
}
/**
* Sets the parameters for the diffie-hellman group exchange. Unless you
* know what you are doing, you will never need this. Default values are
* defined in the {@link DHGexParameters} class.
*
* @param dgp
* {@link DHGexParameters}, non null.
*
*/
public synchronized void setDHGexParameters(DHGexParameters dgp) {
if (dgp == null)
throw new IllegalArgumentException();
dhgexpara = dgp;
}
/**
* Used to tell the library that the connection shall be established through
* a proxy server. It only makes sense to call this method before calling
* the {@link #connect() connect()} method.
* <p>
* At the moment, only HTTP proxies are supported.
* <p>
* Note: This method can be called any number of times. The
* {@link #connect() connect()} method will use the value set in the last
* preceding invocation of this method.
*
* @see HTTPProxyData
*
* @param proxyData
* Connection information about the proxy. If <code>null</code>,
* then no proxy will be used (non surprisingly, this is also the
* default).
*/
public synchronized void setProxyData(ProxyData proxyData) {
this.proxyData = proxyData;
}
/**
* Provide your own instance of SecureRandom. Can be used, e.g., if you want
* to seed the used SecureRandom generator manually.
* <p>
* The SecureRandom instance is used during key exchanges, public key
* authentication, x11 cookie generation and the like.
*
* @param rnd
* a SecureRandom instance
*/
public synchronized void setSecureRandom(SecureRandom rnd) {
if (rnd == null)
throw new IllegalArgumentException();
this.generator = rnd;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param ciphers
*/
public synchronized void setServer2ClientCiphers(String[] ciphers) {
if ((ciphers == null) || (ciphers.length == 0))
throw new IllegalArgumentException();
ciphers = removeDuplicates(ciphers);
BlockCipherFactory.checkCipherList(ciphers);
cryptoWishList.s2c_enc_algos = ciphers;
}
/**
* Unless you know what you are doing, you will never need this.
*
* @param macs
*/
public synchronized void setServer2ClientMACs(String[] macs) {
if ((macs == null) || (macs.length == 0))
throw new IllegalArgumentException();
macs = removeDuplicates(macs);
MAC.checkMacList(macs);
cryptoWishList.s2c_mac_algos = macs;
}
/**
* Define the set of allowed server host key algorithms to be used for the
* following key exchange operations.
* <p>
* Unless you know what you are doing, you will never need this.
*
* @param algos
* An array of allowed server host key algorithms. SSH-2 defines
* <code>ssh-dss</code> and <code>ssh-rsa</code>. The entries of
* the array must be ordered after preference, i.e., the entry at
* index 0 is the most preferred one. You must specify at least
* one entry.
*/
public synchronized void setServerHostKeyAlgorithms(String[] algos) {
if ((algos == null) || (algos.length == 0))
throw new IllegalArgumentException();
algos = removeDuplicates(algos);
KexManager.checkServerHostkeyAlgorithmsList(algos);
cryptoWishList.serverHostKeyAlgorithms = algos;
}
/**
* Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm) on the
* underlying socket.
* <p>
* Can be called at any time. If the connection has not yet been established
* then the passed value will be stored and set after the socket has been
* set up. The default value that will be used is <code>false</code>.
*
* @param enable
* the argument passed to the <code>Socket.setTCPNoDelay()</code>
* method.
* @throws IOException
*/
public synchronized void setTCPNoDelay(boolean enable) throws IOException {
tcpNoDelay = enable;
if (tm != null)
tm.setTcpNoDelay(enable);
}
}
| Java |
package com.trilead.ssh2;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Vector;
import com.trilead.ssh2.packets.TypesReader;
import com.trilead.ssh2.packets.TypesWriter;
import com.trilead.ssh2.sftp.AttribFlags;
import com.trilead.ssh2.sftp.ErrorCodes;
import com.trilead.ssh2.sftp.Packet;
/**
* A <code>SFTPv3Client</code> represents a SFTP (protocol version 3) client
* connection tunnelled over a SSH-2 connection. This is a very simple
* (synchronous) implementation.
* <p>
* Basically, most methods in this class map directly to one of the packet types
* described in draft-ietf-secsh-filexfer-02.txt.
* <p>
* Note: this is experimental code.
* <p>
* Error handling: the methods of this class throw IOExceptions. However, unless
* there is catastrophic failure, exceptions of the type {@link SFTPv3Client}
* will be thrown (a subclass of IOException). Therefore, you can implement more
* verbose behavior by checking if a thrown exception if of this type. If yes,
* then you can cast the exception and access detailed information about the
* failure.
* <p>
* Notes about file names, directory names and paths, copy-pasted from the
* specs:
* <ul>
* <li>SFTP v3 represents file names as strings. File names are assumed to use
* the slash ('/') character as a directory separator.</li>
* <li>File names starting with a slash are "absolute", and are relative to the
* root of the file system. Names starting with any other character are relative
* to the user's default directory (home directory).</li>
* <li>Servers SHOULD interpret a path name component ".." as referring to the
* parent directory, and "." as referring to the current directory. If the
* server implementation limits access to certain parts of the file system, it
* must be extra careful in parsing file names when enforcing such restrictions.
* There have been numerous reported security bugs where a ".." in a path name
* has allowed access outside the intended area.</li>
* <li>An empty path name is valid, and it refers to the user's default
* directory (usually the user's home directory).</li>
* </ul>
* <p>
* If you are still not tired then please go on and read the comment for
* {@link #setCharset(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3Client.java,v 1.3 2008/04/01 12:38:09 cplattne Exp $
*/
public class SFTPv3Client {
final Connection conn;
final Session sess;
final PrintStream debug;
boolean flag_closed = false;
InputStream is;
OutputStream os;
int protocol_version = 0;
HashMap server_extensions = new HashMap();
int next_request_id = 1000;
String charsetName = null;
/**
* Create a SFTP v3 client.
*
* @param conn
* The underlying SSH-2 connection to be used.
* @throws IOException
*/
public SFTPv3Client(Connection conn) throws IOException {
this(conn, null);
}
/**
* Create a SFTP v3 client.
*
* @param conn
* The underlying SSH-2 connection to be used.
* @param debug
* @throws IOException
*
* @deprecated this constructor (debug version) will disappear in the
* future, use {@link #SFTPv3Client(Connection)} instead.
*/
@Deprecated
public SFTPv3Client(Connection conn, PrintStream debug) throws IOException {
if (conn == null)
throw new IllegalArgumentException("Cannot accept null argument!");
this.conn = conn;
this.debug = debug;
if (debug != null)
debug.println("Opening session and starting SFTP subsystem.");
sess = conn.openSession();
sess.startSubSystem("sftp");
is = sess.getStdout();
os = new BufferedOutputStream(sess.getStdin(), 2048);
if ((is == null) || (os == null))
throw new IOException(
"There is a problem with the streams of the underlying channel.");
init();
}
/**
* Have the server canonicalize any given path name to an absolute path.
* This is useful for converting path names containing ".." components or
* relative pathnames without a leading slash into absolute paths.
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return An absolute path.
* @throws IOException
*/
public String canonicalPath(String path) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_REALPATH...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_REALPATH, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME) {
int count = tr.readUINT32();
if (count != 1)
throw new IOException(
"The server sent an invalid SSH_FXP_NAME packet.");
return tr.readString(charsetName);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private final void checkHandleValidAndOpen(SFTPv3FileHandle handle)
throws IOException {
if (handle.client != this)
throw new IOException(
"The file handle was created with another SFTPv3FileHandle instance.");
if (handle.isClosed == true)
throw new IOException("The file handle is closed.");
}
/**
* Close this SFTP session. NEVER forget to call this method to free up
* resources - even if you got an exception from one of the other methods.
* Sometimes these other methods may throw an exception, saying that the
* underlying channel is closed (this can happen, e.g., if the other server
* sent a close message.) However, as long as you have not called the
* <code>close()</code> method, you are likely wasting resources.
*
*/
public void close() {
sess.close();
}
/**
* Close a file.
*
* @param handle
* a SFTPv3FileHandle handle
* @throws IOException
*/
public void closeFile(SFTPv3FileHandle handle) throws IOException {
if (handle == null)
throw new IllegalArgumentException(
"the handle argument may not be null");
try {
if (handle.isClosed == false) {
closeHandle(handle.fileHandle);
}
} finally {
handle.isClosed = true;
}
}
private final void closeHandle(byte[] handle) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle, 0, handle.length);
sendMessage(Packet.SSH_FXP_CLOSE, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private byte[] createAttrs(SFTPv3FileAttributes attr) {
TypesWriter tw = new TypesWriter();
int attrFlags = 0;
if (attr == null) {
tw.writeUINT32(0);
} else {
if (attr.size != null)
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_SIZE;
if ((attr.uid != null) && (attr.gid != null))
attrFlags = attrFlags | AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID;
if (attr.permissions != null)
attrFlags = attrFlags
| AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS;
if ((attr.atime != null) && (attr.mtime != null))
attrFlags = attrFlags
| AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME;
tw.writeUINT32(attrFlags);
if (attr.size != null)
tw.writeUINT64(attr.size.longValue());
if ((attr.uid != null) && (attr.gid != null)) {
tw.writeUINT32(attr.uid.intValue());
tw.writeUINT32(attr.gid.intValue());
}
if (attr.permissions != null)
tw.writeUINT32(attr.permissions.intValue());
if ((attr.atime != null) && (attr.mtime != null)) {
tw.writeUINT32(attr.atime.intValue());
tw.writeUINT32(attr.mtime.intValue());
}
}
return tw.getBytes();
}
/**
* Create a file and open it for reading and writing. Same as
* {@link #createFile(String, SFTPv3FileAttributes) createFile(fileName,
* null)}.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFile(String fileName) throws IOException {
return createFile(fileName, null);
}
/**
* Create a file and open it for reading and writing. You can specify the
* default attributes of the file (the server may or may not respect your
* wishes).
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param attr
* may be <code>null</code> to use server defaults. Probably only
* the <code>uid</code>, <code>gid</code> and
* <code>permissions</code> (remember the server may apply a
* umask) entries of the {@link SFTPv3FileHandle} structure make
* sense. You need only to set those fields where you want to
* override the server's defaults.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFile(String fileName,
SFTPv3FileAttributes attr) throws IOException {
return openFile(fileName, 0x00000008 | 0x00000003, attr); // SSH_FXF_CREAT
// |
// SSH_FXF_READ
// |
// SSH_FXF_WRITE
}
/**
* Create a file (truncate it if it already exists) and open it for reading
* and writing. Same as
* {@link #createFileTruncate(String, SFTPv3FileAttributes)
* createFileTruncate(fileName, null)}.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFileTruncate(String fileName)
throws IOException {
return createFileTruncate(fileName, null);
}
/**
* reate a file (truncate it if it already exists) and open it for reading
* and writing. You can specify the default attributes of the file (the
* server may or may not respect your wishes).
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param attr
* may be <code>null</code> to use server defaults. Probably only
* the <code>uid</code>, <code>gid</code> and
* <code>permissions</code> (remember the server may apply a
* umask) entries of the {@link SFTPv3FileHandle} structure make
* sense. You need only to set those fields where you want to
* override the server's defaults.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle createFileTruncate(String fileName,
SFTPv3FileAttributes attr) throws IOException {
return openFile(fileName, 0x00000018 | 0x00000003, attr); // SSH_FXF_CREAT
// |
// SSH_FXF_TRUNC
// |
// SSH_FXF_READ
// |
// SSH_FXF_WRITE
}
/**
* Create a symbolic link on the server. Creates a link "src" that points to
* "target".
*
* @param src
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param target
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void createSymlink(String src, String target) throws IOException {
int req_id = generateNextRequestID();
/*
* Either I am too stupid to understand the SFTP draft or the OpenSSH
* guys changed the semantics of src and target.
*/
TypesWriter tw = new TypesWriter();
tw.writeString(target, charsetName);
tw.writeString(src, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_SYMLINK...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_SYMLINK, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private final String expandString(byte[] b, int off, int len) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++) {
int c = b[off + i] & 0xff;
if ((c >= 32) && (c <= 126)) {
sb.append((char) c);
} else {
sb.append("{0x" + Integer.toHexString(c) + "}");
}
}
return sb.toString();
}
private void expectStatusOKMessage(int id) throws IOException {
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != id)
throw new IOException("The server sent an invalid id field.");
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_OK)
return;
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Modify the attributes of a file. Used for operations such as changing the
* ownership, permissions or access times, as well as for truncating a file.
*
* @param handle
* a SFTPv3FileHandle handle
* @param attr
* A SFTPv3FileAttributes object. Specifies the modifications to
* be made to the attributes of the file. Empty fields will be
* ignored.
* @throws IOException
*/
public void fsetstat(SFTPv3FileHandle handle, SFTPv3FileAttributes attr)
throws IOException {
checkHandleValidAndOpen(handle);
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeBytes(createAttrs(attr));
if (debug != null) {
debug.println("Sending SSH_FXP_FSETSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_FSETSTAT, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Retrieve the file attributes of an open file.
*
* @param handle
* a SFTPv3FileHandle handle.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes fstat(SFTPv3FileHandle handle)
throws IOException {
checkHandleValidAndOpen(handle);
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
if (debug != null) {
debug.println("Sending SSH_FXP_FSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_FSTAT, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_ATTRS) {
return readAttrs(tr);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
private final int generateNextRequestID() {
synchronized (this) {
return next_request_id++;
}
}
/**
* The currently used charset for filename encoding/decoding.
*
* @see #setCharset(String)
*
* @return The name of the charset (<code>null</code> if the platform's
* default charset is being used)
*/
public String getCharset() {
return charsetName;
}
/**
* Returns the negotiated SFTP protocol version between the client and the
* server.
*
* @return SFTP protocol version, i.e., "3".
*
*/
public int getProtocolVersion() {
return protocol_version;
}
private void init() throws IOException {
/* Send SSH_FXP_INIT (version 3) */
final int client_version = 3;
if (debug != null)
debug.println("Sending SSH_FXP_INIT (" + client_version + ")...");
TypesWriter tw = new TypesWriter();
tw.writeUINT32(client_version);
sendMessage(Packet.SSH_FXP_INIT, 0, tw.getBytes());
/* Receive SSH_FXP_VERSION */
if (debug != null)
debug.println("Waiting for SSH_FXP_VERSION...");
TypesReader tr = new TypesReader(receiveMessage(34000)); /*
* Should be
* enough for
* any
* reasonable
* server
*/
int type = tr.readByte();
if (type != Packet.SSH_FXP_VERSION) {
throw new IOException(
"The server did not send a SSH_FXP_VERSION packet (got "
+ type + ")");
}
protocol_version = tr.readUINT32();
if (debug != null)
debug.println("SSH_FXP_VERSION: protocol_version = "
+ protocol_version);
if (protocol_version != 3)
throw new IOException("Server version " + protocol_version
+ " is currently not supported");
/* Read and save extensions (if any) for later use */
while (tr.remain() != 0) {
String name = tr.readString();
byte[] value = tr.readByteString();
server_extensions.put(name, value);
if (debug != null)
debug.println("SSH_FXP_VERSION: extension: " + name + " = '"
+ expandString(value, 0, value.length) + "'");
}
}
/**
* List the contents of a directory.
*
* @param dirName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return A Vector containing {@link SFTPv3DirectoryEntry} objects.
* @throws IOException
*/
public Vector ls(String dirName) throws IOException {
byte[] handle = openDirectory(dirName);
Vector result = scanDirectory(handle);
closeHandle(handle);
return result;
}
/**
* Retrieve the file attributes of a file. This method does NOT follow
* symbolic links on the server.
*
* @see #stat(String)
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes lstat(String path) throws IOException {
return statBoth(path, Packet.SSH_FXP_LSTAT);
}
/**
* Create a new directory.
*
* @param dirName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param posixPermissions
* the permissions for this directory, e.g., "0700" (remember
* that this is octal noation). The server will likely apply a
* umask.
*
* @throws IOException
*/
public void mkdir(String dirName, int posixPermissions) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(dirName, charsetName);
tw.writeUINT32(AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS);
tw.writeUINT32(posixPermissions);
sendMessage(Packet.SSH_FXP_MKDIR, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Move a file or directory.
*
* @param oldPath
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param newPath
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void mv(String oldPath, String newPath) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(oldPath, charsetName);
tw.writeString(newPath, charsetName);
sendMessage(Packet.SSH_FXP_RENAME, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private final byte[] openDirectory(String path) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_OPENDIR...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_OPENDIR, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_HANDLE) {
if (debug != null) {
debug.println("Got SSH_FXP_HANDLE.");
debug.flush();
}
byte[] handle = tr.readByteString();
return handle;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
private SFTPv3FileHandle openFile(String fileName, int flags,
SFTPv3FileAttributes attr) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(fileName, charsetName);
tw.writeUINT32(flags);
tw.writeBytes(createAttrs(attr));
if (debug != null) {
debug.println("Sending SSH_FXP_OPEN...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_OPEN, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_HANDLE) {
if (debug != null) {
debug.println("Got SSH_FXP_HANDLE.");
debug.flush();
}
return new SFTPv3FileHandle(this, tr.readByteString());
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
/**
* Open a file for reading.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle openFileRO(String fileName) throws IOException {
return openFile(fileName, 0x00000001, null); // SSH_FXF_READ
}
/**
* Open a file for reading and writing.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileHandle handle
* @throws IOException
*/
public SFTPv3FileHandle openFileRW(String fileName) throws IOException {
return openFile(fileName, 0x00000003, null); // SSH_FXF_READ |
// SSH_FXF_WRITE
}
/**
* Read bytes from a file. No more than 32768 bytes may be read at once. Be
* aware that the semantics of read() are different than for Java streams.
* <p>
* <ul>
* <li>The server will read as many bytes as it can from the file (up to
* <code>len</code>), and return them.</li>
* <li>If EOF is encountered before reading any data, <code>-1</code> is
* returned.
* <li>If an error occurs, an exception is thrown</li>.
* <li>For normal disk files, it is guaranteed that the server will return
* the specified number of bytes, or up to end of file. For, e.g., device
* files this may return fewer bytes than requested.</li>
* </ul>
*
* @param handle
* a SFTPv3FileHandle handle
* @param fileOffset
* offset (in bytes) in the file
* @param dst
* the destination byte array
* @param dstoff
* offset in the destination byte array
* @param len
* how many bytes to read, 0 < len <= 32768 bytes
* @return the number of bytes that could be read, may be less than
* requested if the end of the file is reached, -1 is returned in
* case of <code>EOF</code>
* @throws IOException
*/
public int read(SFTPv3FileHandle handle, long fileOffset, byte[] dst,
int dstoff, int len) throws IOException {
checkHandleValidAndOpen(handle);
if ((len > 32768) || (len <= 0))
throw new IllegalArgumentException("invalid len argument");
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeUINT64(fileOffset);
tw.writeUINT32(len);
if (debug != null) {
debug.println("Sending SSH_FXP_READ...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READ, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_DATA) {
if (debug != null) {
debug.println("Got SSH_FXP_DATA...");
debug.flush();
}
int readLen = tr.readUINT32();
if ((readLen < 0) || (readLen > len))
throw new IOException(
"The server sent an invalid length field.");
tr.readBytes(dst, dstoff, readLen);
return readLen;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_EOF) {
if (debug != null) {
debug.println("Got SSH_FX_EOF.");
debug.flush();
}
return -1;
}
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
private SFTPv3FileAttributes readAttrs(TypesReader tr) throws IOException {
/*
* uint32 flags uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE
* uint32 uid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID uint32
* gid present only if flag SSH_FILEXFER_ATTR_V3_UIDGID uint32
* permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS uint32
* atime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME uint32
* mtime present only if flag SSH_FILEXFER_ATTR_V3_ACMODTIME uint32
* extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED string
* extended_type string extended_data ... more extended data
* (extended_type - extended_data pairs), so that number of pairs equals
* extended_count
*/
SFTPv3FileAttributes fa = new SFTPv3FileAttributes();
int flags = tr.readUINT32();
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_SIZE) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_SIZE");
fa.size = new Long(tr.readUINT64());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_UIDGID) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_V3_UIDGID");
fa.uid = new Integer(tr.readUINT32());
fa.gid = new Integer(tr.readUINT32());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_PERMISSIONS");
fa.permissions = new Integer(tr.readUINT32());
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_V3_ACMODTIME) != 0) {
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_V3_ACMODTIME");
fa.atime = new Long(tr.readUINT32() & 0xffffffffl);
fa.mtime = new Long(tr.readUINT32() & 0xffffffffl);
}
if ((flags & AttribFlags.SSH_FILEXFER_ATTR_EXTENDED) != 0) {
int count = tr.readUINT32();
if (debug != null)
debug.println("SSH_FILEXFER_ATTR_EXTENDED (" + count + ")");
/* Read it anyway to detect corrupt packets */
while (count > 0) {
tr.readByteString();
tr.readByteString();
count--;
}
}
return fa;
}
private final void readBytes(byte[] buff, int pos, int len)
throws IOException {
while (len > 0) {
int count = is.read(buff, pos, len);
if (count < 0)
throw new IOException("Unexpected end of sftp stream.");
if ((count == 0) || (count > len))
throw new IOException(
"Underlying stream implementation is bogus!");
len -= count;
pos += count;
}
}
/**
* Read the target of a symbolic link.
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return The target of the link.
* @throws IOException
*/
public String readLink(String path) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_READLINK...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READLINK, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME) {
int count = tr.readUINT32();
if (count != 1)
throw new IOException(
"The server sent an invalid SSH_FXP_NAME packet.");
return tr.readString(charsetName);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Read a message and guarantee that the <b>contents</b> is not larger than
* <code>maxlen</code> bytes.
* <p>
* Note: receiveMessage(34000) actually means that the message may be up to
* 34004 bytes (the length attribute preceeding the contents is 4 bytes).
*
* @param maxlen
* @return the message contents
* @throws IOException
*/
private final byte[] receiveMessage(int maxlen) throws IOException {
byte[] msglen = new byte[4];
readBytes(msglen, 0, 4);
int len = (((msglen[0] & 0xff) << 24) | ((msglen[1] & 0xff) << 16)
| ((msglen[2] & 0xff) << 8) | (msglen[3] & 0xff));
if ((len > maxlen) || (len <= 0))
throw new IOException("Illegal sftp packet len: " + len);
byte[] msg = new byte[len];
readBytes(msg, 0, len);
return msg;
}
/**
* Remove a file.
*
* @param fileName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void rm(String fileName) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(fileName, charsetName);
sendMessage(Packet.SSH_FXP_REMOVE, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
// Append is broken (already in the specification, because there is no way
// to
// send a write operation (what offset to use??))
// public SFTPv3FileHandle openFileRWAppend(String fileName) throws
// IOException
// {
// return openFile(fileName, 0x00000007, null); // SSH_FXF_READ |
// SSH_FXF_WRITE | SSH_FXF_APPEND
// }
/**
* Remove an empty directory.
*
* @param dirName
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @throws IOException
*/
public void rmdir(String dirName) throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(dirName, charsetName);
sendMessage(Packet.SSH_FXP_RMDIR, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
private final Vector scanDirectory(byte[] handle) throws IOException {
Vector files = new Vector();
while (true) {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle, 0, handle.length);
if (debug != null) {
debug.println("Sending SSH_FXP_READDIR...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_READDIR, req_id, tw.getBytes());
/* Some servers send here a packet with size > 34000 */
/* To whom it may concern: please learn to read the specs. */
byte[] resp = receiveMessage(65536);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_NAME) {
int count = tr.readUINT32();
if (debug != null)
debug.println("Parsing " + count + " name entries...");
while (count > 0) {
SFTPv3DirectoryEntry dirEnt = new SFTPv3DirectoryEntry();
dirEnt.filename = tr.readString(charsetName);
dirEnt.longEntry = tr.readString(charsetName);
dirEnt.attributes = readAttrs(tr);
files.addElement(dirEnt);
if (debug != null)
debug.println("File: '" + dirEnt.filename + "'");
count--;
}
continue;
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_EOF)
return files;
throw new SFTPException(tr.readString(), errorCode);
}
}
private final void sendMessage(int type, int requestId, byte[] msg)
throws IOException {
sendMessage(type, requestId, msg, 0, msg.length);
}
private final void sendMessage(int type, int requestId, byte[] msg,
int off, int len) throws IOException {
int msglen = len + 1;
if (type != Packet.SSH_FXP_INIT)
msglen += 4;
os.write(msglen >> 24);
os.write(msglen >> 16);
os.write(msglen >> 8);
os.write(msglen);
os.write(type);
if (type != Packet.SSH_FXP_INIT) {
os.write(requestId >> 24);
os.write(requestId >> 16);
os.write(requestId >> 8);
os.write(requestId);
}
os.write(msg, off, len);
os.flush();
}
/**
* Set the charset used to convert between Java Unicode Strings and byte
* encodings used by the server for paths and file names. Unfortunately, the
* SFTP v3 draft says NOTHING about such conversions (well, with the
* exception of error messages which have to be in UTF-8). Newer drafts
* specify to use UTF-8 for file names (if I remember correctly). However, a
* quick test using OpenSSH serving a EXT-3 filesystem has shown that UTF-8
* seems to be a bad choice for SFTP v3 (tested with filenames containing
* german umlauts). "windows-1252" seems to work better for Europe. Luckily,
* "windows-1252" is the platform default in my case =).
* <p>
* If you don't set anything, then the platform default will be used (this
* is the default behavior).
*
* @see #getCharset()
*
* @param charset
* the name of the charset to be used or <code>null</code> to use
* the platform's default encoding.
* @throws IOException
*/
public void setCharset(String charset) throws IOException {
if (charset == null) {
charsetName = charset;
return;
}
try {
Charset.forName(charset);
} catch (Exception e) {
throw (IOException) new IOException("This charset is not supported")
.initCause(e);
}
charsetName = charset;
}
/**
* Modify the attributes of a file. Used for operations such as changing the
* ownership, permissions or access times, as well as for truncating a file.
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @param attr
* A SFTPv3FileAttributes object. Specifies the modifications to
* be made to the attributes of the file. Empty fields will be
* ignored.
* @throws IOException
*/
public void setstat(String path, SFTPv3FileAttributes attr)
throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
tw.writeBytes(createAttrs(attr));
if (debug != null) {
debug.println("Sending SSH_FXP_SETSTAT...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_SETSTAT, req_id, tw.getBytes());
expectStatusOKMessage(req_id);
}
/**
* Retrieve the file attributes of a file. This method follows symbolic
* links on the server.
*
* @see #lstat(String)
*
* @param path
* See the {@link SFTPv3Client comment} for the class for more
* details.
* @return a SFTPv3FileAttributes object.
* @throws IOException
*/
public SFTPv3FileAttributes stat(String path) throws IOException {
return statBoth(path, Packet.SSH_FXP_STAT);
}
private SFTPv3FileAttributes statBoth(String path, int statMethod)
throws IOException {
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(path, charsetName);
if (debug != null) {
debug.println("Sending SSH_FXP_STAT/SSH_FXP_LSTAT...");
debug.flush();
}
sendMessage(statMethod, req_id, tw.getBytes());
byte[] resp = receiveMessage(34000);
if (debug != null) {
debug.println("Got REPLY.");
debug.flush();
}
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t == Packet.SSH_FXP_ATTRS) {
return readAttrs(tr);
}
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
throw new SFTPException(tr.readString(), errorCode);
}
/**
* Write bytes to a file. If <code>len</code> > 32768, then the write
* operation will be split into multiple writes.
*
* @param handle
* a SFTPv3FileHandle handle.
* @param fileOffset
* offset (in bytes) in the file.
* @param src
* the source byte array.
* @param srcoff
* offset in the source byte array.
* @param len
* how many bytes to write.
* @throws IOException
*/
public void write(SFTPv3FileHandle handle, long fileOffset, byte[] src,
int srcoff, int len) throws IOException {
checkHandleValidAndOpen(handle);
while (len > 0) {
int writeRequestLen = len;
if (writeRequestLen > 32768)
writeRequestLen = 32768;
int req_id = generateNextRequestID();
TypesWriter tw = new TypesWriter();
tw.writeString(handle.fileHandle, 0, handle.fileHandle.length);
tw.writeUINT64(fileOffset);
tw.writeString(src, srcoff, writeRequestLen);
if (debug != null) {
debug.println("Sending SSH_FXP_WRITE...");
debug.flush();
}
sendMessage(Packet.SSH_FXP_WRITE, req_id, tw.getBytes());
fileOffset += writeRequestLen;
srcoff += writeRequestLen;
len -= writeRequestLen;
byte[] resp = receiveMessage(34000);
TypesReader tr = new TypesReader(resp);
int t = tr.readByte();
int rep_id = tr.readUINT32();
if (rep_id != req_id)
throw new IOException("The server sent an invalid id field.");
if (t != Packet.SSH_FXP_STATUS)
throw new IOException(
"The SFTP server sent an unexpected packet type (" + t
+ ")");
int errorCode = tr.readUINT32();
if (errorCode == ErrorCodes.SSH_FX_OK)
continue;
String errorMessage = tr.readString();
throw new SFTPException(errorMessage, errorCode);
}
}
}
| Java |
package com.trilead.ssh2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.trilead.ssh2.channel.Channel;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.LocalAcceptThread;
/**
* A <code>LocalStreamForwarder</code> forwards an Input- and Outputstream pair
* via the secure tunnel to another host (which may or may not be identical to
* the remote SSH-2 server).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: LocalStreamForwarder.java,v 1.1 2007/10/15 12:49:56 cplattne
* Exp $
*/
public class LocalStreamForwarder {
ChannelManager cm;
String host_to_connect;
int port_to_connect;
LocalAcceptThread lat;
Channel cn;
LocalStreamForwarder(ChannelManager cm, String host_to_connect,
int port_to_connect) throws IOException {
this.cm = cm;
this.host_to_connect = host_to_connect;
this.port_to_connect = port_to_connect;
cn = cm.openDirectTCPIPChannel(host_to_connect, port_to_connect,
"127.0.0.1", 0);
}
/**
* Close the underlying SSH forwarding channel and free up resources. You
* can also use this method to force the shutdown of the underlying
* forwarding channel. Pending output (OutputStream not flushed) will NOT be
* sent. Pending input (InputStream) can still be read. If the shutdown
* operation is already in progress (initiated from either side), then this
* call is a no-op.
*
* @throws IOException
*/
public void close() throws IOException {
cm.closeChannel(cn, "Closed due to user request.", true);
}
/**
* @return An <code>InputStream</code> object.
* @throws IOException
*/
public InputStream getInputStream() throws IOException {
return cn.getStdoutStream();
}
/**
* Get the OutputStream. Please be aware that the implementation MAY use an
* internal buffer. To make sure that the buffered data is sent over the
* tunnel, you have to call the <code>flush</code> method of the
* <code>OutputStream</code>. To signal EOF, please use the
* <code>close</code> method of the <code>OutputStream</code>.
*
* @return An <code>OutputStream</code> object.
* @throws IOException
*/
public OutputStream getOutputStream() throws IOException {
return cn.getStdinStream();
}
}
| Java |
package com.trilead.ssh2;
/**
* A <code>HTTPProxyData</code> object is used to specify the needed connection
* data to connect through a HTTP proxy.
*
* @see Connection#setProxyData(ProxyData)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HTTPProxyData.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class HTTPProxyData implements ProxyData {
public final String proxyHost;
public final int proxyPort;
public final String proxyUser;
public final String proxyPass;
public final String[] requestHeaderLines;
/**
* Same as calling {@link #HTTPProxyData(String, int, String, String)
* HTTPProxyData(proxyHost, proxyPort, <code>null</code>, <code>null</code>
* )}
*
* @param proxyHost
* Proxy hostname.
* @param proxyPort
* Proxy port.
*/
public HTTPProxyData(String proxyHost, int proxyPort) {
this(proxyHost, proxyPort, null, null);
}
/**
* Same as calling
* {@link #HTTPProxyData(String, int, String, String, String[])
* HTTPProxyData(proxyHost, proxyPort, <code>null</code>, <code>null</code>,
* <code>null</code>)}
*
* @param proxyHost
* Proxy hostname.
* @param proxyPort
* Proxy port.
* @param proxyUser
* Username for basic authentication (<code>null</code> if no
* authentication is needed).
* @param proxyPass
* Password for basic authentication (<code>null</code> if no
* authentication is needed).
*/
public HTTPProxyData(String proxyHost, int proxyPort, String proxyUser,
String proxyPass) {
this(proxyHost, proxyPort, proxyUser, proxyPass, null);
}
/**
* Connection data for a HTTP proxy. It is possible to specify a username
* and password if the proxy requires basic authentication. Also, additional
* request header lines can be specified (e.g.,
* "User-Agent: CERN-LineMode/2.15 libwww/2.17b3").
* <p>
* Please note: if you want to use basic authentication, then both
* <code>proxyUser</code> and <code>proxyPass</code> must be non-null.
* <p>
* Here is an example:
* <p>
* <code>
* new HTTPProxyData("192.168.1.1", "3128", "proxyuser", "secret", new String[] {"User-Agent: TrileadBasedClient/1.0", "X-My-Proxy-Option: something"});
* </code>
*
* @param proxyHost
* Proxy hostname.
* @param proxyPort
* Proxy port.
* @param proxyUser
* Username for basic authentication (<code>null</code> if no
* authentication is needed).
* @param proxyPass
* Password for basic authentication (<code>null</code> if no
* authentication is needed).
* @param requestHeaderLines
* An array with additional request header lines (without
* end-of-line markers) that have to be sent to the server. May
* be <code>null</code>.
*/
public HTTPProxyData(String proxyHost, int proxyPort, String proxyUser,
String proxyPass, String[] requestHeaderLines) {
if (proxyHost == null)
throw new IllegalArgumentException("proxyHost must be non-null");
if (proxyPort < 0)
throw new IllegalArgumentException("proxyPort must be non-negative");
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.proxyUser = proxyUser;
this.proxyPass = proxyPass;
this.requestHeaderLines = requestHeaderLines;
}
}
| Java |
package com.trilead.ssh2;
/**
* A callback interface used to implement a client specific method of checking
* server host keys.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: ServerHostKeyVerifier.java,v 1.1 2007/10/15 12:49:56 cplattne
* Exp $
*/
public interface ServerHostKeyVerifier {
/**
* The actual verifier method, it will be called by the key exchange code on
* EVERY key exchange - this can happen several times during the lifetime of
* a connection.
* <p>
* Note: SSH-2 servers are allowed to change their hostkey at ANY time.
*
* @param hostname
* the hostname used to create the {@link Connection} object
* @param port
* the remote TCP port
* @param serverHostKeyAlgorithm
* the public key algorithm (<code>ssh-rsa</code> or
* <code>ssh-dss</code>)
* @param serverHostKey
* the server's public key blob
* @return if the client wants to accept the server's host key - if not, the
* connection will be closed.
* @throws Exception
* Will be wrapped with an IOException, extended version of
* returning false =)
*/
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey)
throws Exception;
}
| Java |
package com.trilead.ssh2;
/**
* A <code>SFTPv3DirectoryEntry</code> as returned by
* {@link SFTPv3Client#ls(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3DirectoryEntry.java,v 1.1 2007/10/15 12:49:56 cplattne
* Exp $
*/
public class SFTPv3DirectoryEntry {
/**
* A relative name within the directory, without any path components.
*/
public String filename;
/**
* An expanded format for the file name, similar to what is returned by
* "ls -l" on Un*x systems.
* <p>
* The format of this field is unspecified by the SFTP v3 protocol. It MUST
* be suitable for use in the output of a directory listing command (in
* fact, the recommended operation for a directory listing command is to
* simply display this data). However, clients SHOULD NOT attempt to parse
* the longname field for file attributes; they SHOULD use the attrs field
* instead.
* <p>
* The recommended format for the longname field is as follows:<br>
* <code>-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer</code>
*/
public String longEntry;
/**
* The attributes of this entry.
*/
public SFTPv3FileAttributes attributes;
}
| Java |
package com.trilead.ssh2;
import java.io.IOException;
import com.trilead.ssh2.sftp.ErrorCodes;
/**
* Used in combination with the SFTPv3Client. This exception wraps error
* messages sent by the SFTP server.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPException.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SFTPException extends IOException {
private static final long serialVersionUID = 578654644222421811L;
private static String constructMessage(String s, int errorCode) {
String[] detail = ErrorCodes.getDescription(errorCode);
if (detail == null)
return s + " (UNKNOW SFTP ERROR CODE)";
return s + " (" + detail[0] + ": " + detail[1] + ")";
}
private final String sftpErrorMessage;
private final int sftpErrorCode;
SFTPException(String msg, int errorCode) {
super(constructMessage(msg, errorCode));
sftpErrorMessage = msg;
sftpErrorCode = errorCode;
}
/**
* Get the error code sent by the server.
*
* @return an error code as defined in the SFTP specs.
*/
public int getServerErrorCode() {
return sftpErrorCode;
}
/**
* Get the symbolic name of the error code as given in the SFTP specs.
*
* @return e.g., "SSH_FX_INVALID_FILENAME".
*/
public String getServerErrorCodeSymbol() {
String[] detail = ErrorCodes.getDescription(sftpErrorCode);
if (detail == null)
return "UNKNOW SFTP ERROR CODE " + sftpErrorCode;
return detail[0];
}
/**
* Get the description of the error code as given in the SFTP specs.
*
* @return e.g., "The filename is not valid."
*/
public String getServerErrorCodeVerbose() {
String[] detail = ErrorCodes.getDescription(sftpErrorCode);
if (detail == null)
return "The error code " + sftpErrorCode + " is unknown.";
return detail[1];
}
/**
* Get the error message sent by the server. Often, this message does not
* help a lot (e.g., "failure").
*
* @return the plain string as sent by the server.
*/
public String getServerErrorMessage() {
return sftpErrorMessage;
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* 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.trilead.ssh2;
import java.io.IOException;
import java.net.InetSocketAddress;
import com.trilead.ssh2.channel.ChannelManager;
import com.trilead.ssh2.channel.DynamicAcceptThread;
/**
* A <code>DynamicPortForwarder</code> forwards TCP/IP connections to a local
* port via the secure tunnel to another host which is selected via the SOCKS
* protocol. Checkout {@link Connection#createDynamicPortForwarder(int)} on how
* to create one.
*
* @author Kenny Root
* @version $Id: $
*/
public class DynamicPortForwarder {
ChannelManager cm;
DynamicAcceptThread dat;
DynamicPortForwarder(ChannelManager cm, InetSocketAddress addr)
throws IOException {
this.cm = cm;
dat = new DynamicAcceptThread(cm, addr);
dat.setDaemon(true);
dat.start();
}
DynamicPortForwarder(ChannelManager cm, int local_port) throws IOException {
this.cm = cm;
dat = new DynamicAcceptThread(cm, local_port);
dat.setDaemon(true);
dat.start();
}
/**
* Stop TCP/IP forwarding of newly arriving connections.
*
* @throws IOException
*/
public void close() throws IOException {
dat.stopWorking();
}
}
| Java |
package com.trilead.ssh2;
/**
* An interface which needs to be implemented if you want to capture debugging
* messages.
*
* @see Connection#enableDebugging(boolean, DebugLogger)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DebugLogger.java,v 1.1 2008/03/03 07:01:36 cplattne Exp $
*/
public interface DebugLogger {
/**
* Log a debug message.
*
* @param level
* 0-99, 99 is a the most verbose level
* @param className
* the class that generated the message
* @param message
* the debug message
*/
public void log(int level, String className, String message);
}
| Java |
package com.trilead.ssh2.crypto;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.math.BigInteger;
import com.trilead.ssh2.crypto.cipher.AES;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.CBCMode;
import com.trilead.ssh2.crypto.cipher.DES;
import com.trilead.ssh2.crypto.cipher.DESede;
import com.trilead.ssh2.crypto.digest.MD5;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.RSAPrivateKey;
/**
* PEM Support.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PEMDecoder.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PEMDecoder {
public static final int PEM_RSA_PRIVATE_KEY = 1;
public static final int PEM_DSA_PRIVATE_KEY = 2;
public static Object decode(char[] pem, String password) throws IOException {
PEMStructure ps = parsePEM(pem);
if (isPEMEncrypted(ps)) {
if (password == null)
throw new IOException(
"PEM is encrypted, but no password was specified");
decryptPEM(ps, password.getBytes("ISO-8859-1"));
}
if (ps.pemType == PEM_DSA_PRIVATE_KEY) {
SimpleDERReader dr = new SimpleDERReader(ps.data);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
throw new IOException("Padding in DSA PRIVATE KEY DER stream.");
dr.resetInput(seq);
BigInteger version = dr.readInt();
if (version.compareTo(BigInteger.ZERO) != 0)
throw new IOException("Wrong version (" + version
+ ") in DSA PRIVATE KEY DER stream.");
BigInteger p = dr.readInt();
BigInteger q = dr.readInt();
BigInteger g = dr.readInt();
BigInteger y = dr.readInt();
BigInteger x = dr.readInt();
if (dr.available() != 0)
throw new IOException("Padding in DSA PRIVATE KEY DER stream.");
return new DSAPrivateKey(p, q, g, y, x);
}
if (ps.pemType == PEM_RSA_PRIVATE_KEY) {
SimpleDERReader dr = new SimpleDERReader(ps.data);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
throw new IOException("Padding in RSA PRIVATE KEY DER stream.");
dr.resetInput(seq);
BigInteger version = dr.readInt();
if ((version.compareTo(BigInteger.ZERO) != 0)
&& (version.compareTo(BigInteger.ONE) != 0))
throw new IOException("Wrong version (" + version
+ ") in RSA PRIVATE KEY DER stream.");
BigInteger n = dr.readInt();
BigInteger e = dr.readInt();
BigInteger d = dr.readInt();
return new RSAPrivateKey(d, e, n);
}
throw new IOException("PEM problem: it is of unknown type");
}
private static final void decryptPEM(PEMStructure ps, byte[] pw)
throws IOException {
if (ps.dekInfo == null)
throw new IOException(
"Broken PEM, no mode and salt given, but encryption enabled");
if (ps.dekInfo.length != 2)
throw new IOException("Broken PEM, DEK-Info is incomplete!");
String algo = ps.dekInfo[0];
byte[] salt = hexToByteArray(ps.dekInfo[1]);
BlockCipher bc = null;
if (algo.equals("DES-EDE3-CBC")) {
DESede des3 = new DESede();
des3.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24));
bc = new CBCMode(des3, salt, false);
} else if (algo.equals("DES-CBC")) {
DES des = new DES();
des.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 8));
bc = new CBCMode(des, salt, false);
} else if (algo.equals("AES-128-CBC")) {
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 16));
bc = new CBCMode(aes, salt, false);
} else if (algo.equals("AES-192-CBC")) {
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24));
bc = new CBCMode(aes, salt, false);
} else if (algo.equals("AES-256-CBC")) {
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 32));
bc = new CBCMode(aes, salt, false);
} else {
throw new IOException(
"Cannot decrypt PEM structure, unknown cipher " + algo);
}
if ((ps.data.length % bc.getBlockSize()) != 0)
throw new IOException(
"Invalid PEM structure, size of encrypted block is not a multiple of "
+ bc.getBlockSize());
/* Now decrypt the content */
byte[] dz = new byte[ps.data.length];
for (int i = 0; i < ps.data.length / bc.getBlockSize(); i++) {
bc.transformBlock(ps.data, i * bc.getBlockSize(), dz,
i * bc.getBlockSize());
}
/* Now check and remove RFC 1423/PKCS #7 padding */
dz = removePadding(dz, bc.getBlockSize());
ps.data = dz;
ps.dekInfo = null;
ps.procType = null;
}
private static byte[] generateKeyFromPasswordSaltWithMD5(byte[] password,
byte[] salt, int keyLen) throws IOException {
if (salt.length < 8)
throw new IllegalArgumentException(
"Salt needs to be at least 8 bytes for key generation.");
MD5 md5 = new MD5();
byte[] key = new byte[keyLen];
byte[] tmp = new byte[md5.getDigestLength()];
while (true) {
md5.update(password, 0, password.length);
md5.update(salt, 0, 8); // ARGH we only use the first 8 bytes of the
// salt in this step.
// This took me two hours until I got AES-xxx running.
int copy = (keyLen < tmp.length) ? keyLen : tmp.length;
md5.digest(tmp, 0);
System.arraycopy(tmp, 0, key, key.length - keyLen, copy);
keyLen -= copy;
if (keyLen == 0)
return key;
md5.update(tmp, 0, tmp.length);
}
}
private static byte[] hexToByteArray(String hex) {
if (hex == null)
throw new IllegalArgumentException("null argument");
if ((hex.length() % 2) != 0)
throw new IllegalArgumentException(
"Uneven string length in hex encoding.");
byte decoded[] = new byte[hex.length() / 2];
for (int i = 0; i < decoded.length; i++) {
int hi = hexToInt(hex.charAt(i * 2));
int lo = hexToInt(hex.charAt((i * 2) + 1));
decoded[i] = (byte) (hi * 16 + lo);
}
return decoded;
}
private static final int hexToInt(char c) {
if ((c >= 'a') && (c <= 'f')) {
return (c - 'a') + 10;
}
if ((c >= 'A') && (c <= 'F')) {
return (c - 'A') + 10;
}
if ((c >= '0') && (c <= '9')) {
return (c - '0');
}
throw new IllegalArgumentException("Need hex char");
}
public static final boolean isPEMEncrypted(PEMStructure ps)
throws IOException {
if (ps.procType == null)
return false;
if (ps.procType.length != 2)
throw new IOException("Unknown Proc-Type field.");
if ("4".equals(ps.procType[0]) == false)
throw new IOException("Unknown Proc-Type field (" + ps.procType[0]
+ ")");
if ("ENCRYPTED".equals(ps.procType[1]))
return true;
return false;
}
public static final PEMStructure parsePEM(char[] pem) throws IOException {
PEMStructure ps = new PEMStructure();
String line = null;
BufferedReader br = new BufferedReader(new CharArrayReader(pem));
String endLine = null;
while (true) {
line = br.readLine();
if (line == null)
throw new IOException(
"Invalid PEM structure, '-----BEGIN...' missing");
line = line.trim();
if (line.startsWith("-----BEGIN DSA PRIVATE KEY-----")) {
endLine = "-----END DSA PRIVATE KEY-----";
ps.pemType = PEM_DSA_PRIVATE_KEY;
break;
}
if (line.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
endLine = "-----END RSA PRIVATE KEY-----";
ps.pemType = PEM_RSA_PRIVATE_KEY;
break;
}
}
while (true) {
line = br.readLine();
if (line == null)
throw new IOException("Invalid PEM structure, " + endLine
+ " missing");
line = line.trim();
int sem_idx = line.indexOf(':');
if (sem_idx == -1)
break;
String name = line.substring(0, sem_idx + 1);
String value = line.substring(sem_idx + 1);
String values[] = value.split(",");
for (int i = 0; i < values.length; i++)
values[i] = values[i].trim();
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,579B6BE3E5C60483
if ("Proc-Type:".equals(name)) {
ps.procType = values;
continue;
}
if ("DEK-Info:".equals(name)) {
ps.dekInfo = values;
continue;
}
/* Ignore line */
}
StringBuffer keyData = new StringBuffer();
while (true) {
if (line == null)
throw new IOException("Invalid PEM structure, " + endLine
+ " missing");
line = line.trim();
if (line.startsWith(endLine))
break;
keyData.append(line);
line = br.readLine();
}
char[] pem_chars = new char[keyData.length()];
keyData.getChars(0, pem_chars.length, pem_chars, 0);
ps.data = Base64.decode(pem_chars);
if (ps.data.length == 0)
throw new IOException("Invalid PEM structure, no data available");
return ps;
}
private static byte[] removePadding(byte[] buff, int blockSize)
throws IOException {
/* Removes RFC 1423/PKCS #7 padding */
int rfc_1423_padding = buff[buff.length - 1] & 0xff;
if ((rfc_1423_padding < 1) || (rfc_1423_padding > blockSize))
throw new IOException(
"Decrypted PEM has wrong padding, did you specify the correct password?");
for (int i = 2; i <= rfc_1423_padding; i++) {
if (buff[buff.length - i] != rfc_1423_padding)
throw new IOException(
"Decrypted PEM has wrong padding, did you specify the correct password?");
}
byte[] tmp = new byte[buff.length - rfc_1423_padding];
System.arraycopy(buff, 0, tmp, 0, buff.length - rfc_1423_padding);
return tmp;
}
}
| Java |
package com.trilead.ssh2.crypto.digest;
import java.math.BigInteger;
/**
* HashForSSH2Types.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HashForSSH2Types.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class HashForSSH2Types {
Digest md;
public HashForSSH2Types(Digest md) {
this.md = md;
}
public HashForSSH2Types(String type) {
if (type.equals("SHA1")) {
md = new SHA1();
} else if (type.equals("MD5")) {
md = new MD5();
} else
throw new IllegalArgumentException("Unknown algorithm " + type);
}
public byte[] getDigest() {
byte[] tmp = new byte[md.getDigestLength()];
getDigest(tmp);
return tmp;
}
public void getDigest(byte[] out) {
getDigest(out, 0);
}
public void getDigest(byte[] out, int off) {
md.digest(out, off);
}
public int getDigestLength() {
return md.getDigestLength();
}
public void reset() {
md.reset();
}
public void updateBigInt(BigInteger b) {
updateByteString(b.toByteArray());
}
public void updateByte(byte b) {
/* HACK - to test it with J2ME */
byte[] tmp = new byte[1];
tmp[0] = b;
md.update(tmp);
}
public void updateBytes(byte[] b) {
md.update(b);
}
public void updateByteString(byte[] b) {
updateUINT32(b.length);
updateBytes(b);
}
public void updateUINT32(int v) {
md.update((byte) (v >> 24));
md.update((byte) (v >> 16));
md.update((byte) (v >> 8));
md.update((byte) (v));
}
}
| Java |
package com.trilead.ssh2.crypto.digest;
/**
* MAC.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: MAC.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public final class MAC {
public final static void checkMacList(String[] macs) {
for (int i = 0; i < macs.length; i++)
getKeyLen(macs[i]);
}
public final static int getKeyLen(String type) {
if (type.equals("hmac-sha1"))
return 20;
if (type.equals("hmac-sha1-96"))
return 20;
if (type.equals("hmac-md5"))
return 16;
if (type.equals("hmac-md5-96"))
return 16;
throw new IllegalArgumentException("Unkown algorithm " + type);
}
public final static String[] getMacList() {
/* Higher Priority First */
return new String[] { "hmac-sha1-96", "hmac-sha1", "hmac-md5-96",
"hmac-md5" };
}
Digest mac;
int size;
public MAC(String type, byte[] key) {
if (type.equals("hmac-sha1")) {
mac = new HMAC(new SHA1(), key, 20);
} else if (type.equals("hmac-sha1-96")) {
mac = new HMAC(new SHA1(), key, 12);
} else if (type.equals("hmac-md5")) {
mac = new HMAC(new MD5(), key, 16);
} else if (type.equals("hmac-md5-96")) {
mac = new HMAC(new MD5(), key, 12);
} else
throw new IllegalArgumentException("Unkown algorithm " + type);
size = mac.getDigestLength();
}
public final void getMac(byte[] out, int off) {
mac.digest(out, off);
}
public final void initMac(int seq) {
mac.reset();
mac.update((byte) (seq >> 24));
mac.update((byte) (seq >> 16));
mac.update((byte) (seq >> 8));
mac.update((byte) (seq));
}
public final int size() {
return size;
}
public final void update(byte[] packetdata, int off, int len) {
mac.update(packetdata, off, len);
}
}
| Java |
package com.trilead.ssh2.crypto.digest;
/**
* MD5. Based on the example code in RFC 1321. Optimized (...a little).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: MD5.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
/*
* The following disclaimer has been copied from RFC 1321:
*
* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All rights
* reserved.
*
* License to copy and use this software is granted provided that it is
* identified as the "RSA Data Security, Inc. MD5 Message-Digest Algorithm" in
* all material mentioning or referencing this software or this function.
*
* License is also granted to make and use derivative works provided that such
* works are identified as "derived from the RSA Data Security, Inc. MD5
* Message-Digest Algorithm" in all material mentioning or referencing the
* derived work.
*
* RSA Data Security, Inc. makes no representations concerning either the
* merchantability of this software or the suitability of this software for any
* particular purpose. It is provided "as is" without express or implied
* warranty of any kind.
*
* These notices must be retained in any copies of any part of this
* documentation and/or software.
*/
public final class MD5 implements Digest {
private static final void encode(byte[] dst, int dstoff, int word) {
dst[dstoff] = (byte) (word);
dst[dstoff + 1] = (byte) (word >> 8);
dst[dstoff + 2] = (byte) (word >> 16);
dst[dstoff + 3] = (byte) (word >> 24);
}
private static final int II(int a, int b, int c, int d, int x, int s, int ac) {
a += (c ^ (b | (~d))) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private int state0, state1, state2, state3;
private long count;
private final byte[] block = new byte[64];
private final int x[] = new int[16];
private static final byte[] padding = new byte[] { (byte) 128, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
private static final int FF(int a, int b, int c, int d, int x, int s, int ac) {
a += ((b & c) | ((~b) & d)) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private static final int GG(int a, int b, int c, int d, int x, int s, int ac) {
a += ((b & d) | (c & (~d))) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
private static final int HH(int a, int b, int c, int d, int x, int s, int ac) {
a += (b ^ c ^ d) + x + ac;
return ((a << s) | (a >>> (32 - s))) + b;
}
public MD5() {
reset();
}
@Override
public final void digest(byte[] dst) {
digest(dst, 0);
}
@Override
public final void digest(byte[] dst, int pos) {
byte[] bits = new byte[8];
encode(bits, 0, (int) (count << 3));
encode(bits, 4, (int) (count >> 29));
int idx = (int) count & 0x3f;
int padLen = (idx < 56) ? (56 - idx) : (120 - idx);
update(padding, 0, padLen);
update(bits, 0, 8);
encode(dst, pos, state0);
encode(dst, pos + 4, state1);
encode(dst, pos + 8, state2);
encode(dst, pos + 12, state3);
reset();
}
@Override
public final int getDigestLength() {
return 16;
}
@Override
public final void reset() {
count = 0;
state0 = 0x67452301;
state1 = 0xefcdab89;
state2 = 0x98badcfe;
state3 = 0x10325476;
/* Clear traces in memory... */
for (int i = 0; i < 16; i++)
x[i] = 0;
}
private final void transform(byte[] src, int pos) {
int a = state0;
int b = state1;
int c = state2;
int d = state3;
for (int i = 0; i < 16; i++, pos += 4) {
x[i] = (src[pos] & 0xff) | ((src[pos + 1] & 0xff) << 8)
| ((src[pos + 2] & 0xff) << 16)
| ((src[pos + 3] & 0xff) << 24);
}
/* Round 1 */
a = FF(a, b, c, d, x[0], 7, 0xd76aa478); /* 1 */
d = FF(d, a, b, c, x[1], 12, 0xe8c7b756); /* 2 */
c = FF(c, d, a, b, x[2], 17, 0x242070db); /* 3 */
b = FF(b, c, d, a, x[3], 22, 0xc1bdceee); /* 4 */
a = FF(a, b, c, d, x[4], 7, 0xf57c0faf); /* 5 */
d = FF(d, a, b, c, x[5], 12, 0x4787c62a); /* 6 */
c = FF(c, d, a, b, x[6], 17, 0xa8304613); /* 7 */
b = FF(b, c, d, a, x[7], 22, 0xfd469501); /* 8 */
a = FF(a, b, c, d, x[8], 7, 0x698098d8); /* 9 */
d = FF(d, a, b, c, x[9], 12, 0x8b44f7af); /* 10 */
c = FF(c, d, a, b, x[10], 17, 0xffff5bb1); /* 11 */
b = FF(b, c, d, a, x[11], 22, 0x895cd7be); /* 12 */
a = FF(a, b, c, d, x[12], 7, 0x6b901122); /* 13 */
d = FF(d, a, b, c, x[13], 12, 0xfd987193); /* 14 */
c = FF(c, d, a, b, x[14], 17, 0xa679438e); /* 15 */
b = FF(b, c, d, a, x[15], 22, 0x49b40821); /* 16 */
/* Round 2 */
a = GG(a, b, c, d, x[1], 5, 0xf61e2562); /* 17 */
d = GG(d, a, b, c, x[6], 9, 0xc040b340); /* 18 */
c = GG(c, d, a, b, x[11], 14, 0x265e5a51); /* 19 */
b = GG(b, c, d, a, x[0], 20, 0xe9b6c7aa); /* 20 */
a = GG(a, b, c, d, x[5], 5, 0xd62f105d); /* 21 */
d = GG(d, a, b, c, x[10], 9, 0x2441453); /* 22 */
c = GG(c, d, a, b, x[15], 14, 0xd8a1e681); /* 23 */
b = GG(b, c, d, a, x[4], 20, 0xe7d3fbc8); /* 24 */
a = GG(a, b, c, d, x[9], 5, 0x21e1cde6); /* 25 */
d = GG(d, a, b, c, x[14], 9, 0xc33707d6); /* 26 */
c = GG(c, d, a, b, x[3], 14, 0xf4d50d87); /* 27 */
b = GG(b, c, d, a, x[8], 20, 0x455a14ed); /* 28 */
a = GG(a, b, c, d, x[13], 5, 0xa9e3e905); /* 29 */
d = GG(d, a, b, c, x[2], 9, 0xfcefa3f8); /* 30 */
c = GG(c, d, a, b, x[7], 14, 0x676f02d9); /* 31 */
b = GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); /* 32 */
/* Round 3 */
a = HH(a, b, c, d, x[5], 4, 0xfffa3942); /* 33 */
d = HH(d, a, b, c, x[8], 11, 0x8771f681); /* 34 */
c = HH(c, d, a, b, x[11], 16, 0x6d9d6122); /* 35 */
b = HH(b, c, d, a, x[14], 23, 0xfde5380c); /* 36 */
a = HH(a, b, c, d, x[1], 4, 0xa4beea44); /* 37 */
d = HH(d, a, b, c, x[4], 11, 0x4bdecfa9); /* 38 */
c = HH(c, d, a, b, x[7], 16, 0xf6bb4b60); /* 39 */
b = HH(b, c, d, a, x[10], 23, 0xbebfbc70); /* 40 */
a = HH(a, b, c, d, x[13], 4, 0x289b7ec6); /* 41 */
d = HH(d, a, b, c, x[0], 11, 0xeaa127fa); /* 42 */
c = HH(c, d, a, b, x[3], 16, 0xd4ef3085); /* 43 */
b = HH(b, c, d, a, x[6], 23, 0x4881d05); /* 44 */
a = HH(a, b, c, d, x[9], 4, 0xd9d4d039); /* 45 */
d = HH(d, a, b, c, x[12], 11, 0xe6db99e5); /* 46 */
c = HH(c, d, a, b, x[15], 16, 0x1fa27cf8); /* 47 */
b = HH(b, c, d, a, x[2], 23, 0xc4ac5665); /* 48 */
/* Round 4 */
a = II(a, b, c, d, x[0], 6, 0xf4292244); /* 49 */
d = II(d, a, b, c, x[7], 10, 0x432aff97); /* 50 */
c = II(c, d, a, b, x[14], 15, 0xab9423a7); /* 51 */
b = II(b, c, d, a, x[5], 21, 0xfc93a039); /* 52 */
a = II(a, b, c, d, x[12], 6, 0x655b59c3); /* 53 */
d = II(d, a, b, c, x[3], 10, 0x8f0ccc92); /* 54 */
c = II(c, d, a, b, x[10], 15, 0xffeff47d); /* 55 */
b = II(b, c, d, a, x[1], 21, 0x85845dd1); /* 56 */
a = II(a, b, c, d, x[8], 6, 0x6fa87e4f); /* 57 */
d = II(d, a, b, c, x[15], 10, 0xfe2ce6e0); /* 58 */
c = II(c, d, a, b, x[6], 15, 0xa3014314); /* 59 */
b = II(b, c, d, a, x[13], 21, 0x4e0811a1); /* 60 */
a = II(a, b, c, d, x[4], 6, 0xf7537e82); /* 61 */
d = II(d, a, b, c, x[11], 10, 0xbd3af235); /* 62 */
c = II(c, d, a, b, x[2], 15, 0x2ad7d2bb); /* 63 */
b = II(b, c, d, a, x[9], 21, 0xeb86d391); /* 64 */
state0 += a;
state1 += b;
state2 += c;
state3 += d;
}
@Override
public final void update(byte b) {
final int space = 64 - ((int) (count & 0x3f));
count++;
block[64 - space] = b;
if (space == 1)
transform(block, 0);
}
@Override
public final void update(byte[] b) {
update(b, 0, b.length);
}
@Override
public final void update(byte[] buff, int pos, int len) {
int space = 64 - ((int) (count & 0x3f));
count += len;
while (len > 0) {
if (len < space) {
System.arraycopy(buff, pos, block, 64 - space, len);
break;
}
if (space == 64) {
transform(buff, pos);
} else {
System.arraycopy(buff, pos, block, 64 - space, space);
transform(block, 0);
}
pos += space;
len -= space;
space = 64;
}
}
}
| Java |
package com.trilead.ssh2.crypto.digest;
/**
* Digest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Digest.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public interface Digest {
public void digest(byte[] out);
public void digest(byte[] out, int off);
public int getDigestLength();
public void reset();
public void update(byte b);
public void update(byte b[], int off, int len);
public void update(byte[] b);
}
| Java |
package com.trilead.ssh2.crypto.digest;
/**
* HMAC.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: HMAC.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public final class HMAC implements Digest {
Digest md;
byte[] k_xor_ipad;
byte[] k_xor_opad;
byte[] tmp;
int size;
public HMAC(Digest md, byte[] key, int size) {
this.md = md;
this.size = size;
tmp = new byte[md.getDigestLength()];
final int BLOCKSIZE = 64;
k_xor_ipad = new byte[BLOCKSIZE];
k_xor_opad = new byte[BLOCKSIZE];
if (key.length > BLOCKSIZE) {
md.reset();
md.update(key);
md.digest(tmp);
key = tmp;
}
System.arraycopy(key, 0, k_xor_ipad, 0, key.length);
System.arraycopy(key, 0, k_xor_opad, 0, key.length);
for (int i = 0; i < BLOCKSIZE; i++) {
k_xor_ipad[i] ^= 0x36;
k_xor_opad[i] ^= 0x5C;
}
md.update(k_xor_ipad);
}
@Override
public final void digest(byte[] out) {
digest(out, 0);
}
@Override
public final void digest(byte[] out, int off) {
md.digest(tmp);
md.update(k_xor_opad);
md.update(tmp);
md.digest(tmp);
System.arraycopy(tmp, 0, out, off, size);
md.update(k_xor_ipad);
}
@Override
public final int getDigestLength() {
return size;
}
@Override
public final void reset() {
md.reset();
md.update(k_xor_ipad);
}
@Override
public final void update(byte b) {
md.update(b);
}
@Override
public final void update(byte[] b) {
md.update(b);
}
@Override
public final void update(byte[] b, int off, int len) {
md.update(b, off, len);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.