code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
package com.vercer.engine.persist.standard;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import com.google.appengine.api.datastore.Key;
import com.google.common.collect.MapMaker;
import com.vercer.util.reference.ObjectReference;
import com.vercer.util.reference.SimpleObjectReference;
public class KeyCache
{
private static class ActivatableKeyReference extends SimpleObjectReference<Key>
{
private static final long serialVersionUID = 1L;
private boolean activated;
public ActivatableKeyReference(Key object)
{
super(object);
}
}
private Map<Key, Object> cacheByKey = new MapMaker()
.weakValues()
.concurrencyLevel(1)
.makeMap();
private Map<Object, ObjectReference<Key>> cacheByValue = new MapMaker()
.weakKeys()
.concurrencyLevel(1)
.makeMap();
public void cache(Key key, Object object)
{
cacheByKey.put(key, object);
SimpleObjectReference<Key> reference = new ActivatableKeyReference(key);
cacheByValue.put(object, reference);
}
public void cacheKeyReferenceForInstance(Object object, ObjectReference<Key> keyReference)
{
if (cacheByValue.put(object, keyReference) != null)
{
throw new IllegalStateException("Object already existed: " + object);
}
}
public void clear()
{
this.cacheByKey.clear();
this.cacheByValue.clear();
}
public Key evictInstance(Object reference)
{
ObjectReference<Key> keyReference = cacheByValue.remove(reference);
if (keyReference != null)
{
Key key = keyReference.get();
cacheByKey.remove(key);
return key;
}
else
{
return null;
}
}
public Object evictKey(Key key)
{
Object object = cacheByKey.remove(key);
if (object == null)
{
throw new NoSuchElementException("Key " + key + " was not cached");
}
ObjectReference<Key> removed = cacheByValue.remove(object);
assert removed.get() == key;
return object;
}
@SuppressWarnings("unchecked")
public <T> T getInstance(Key key)
{
return (T) cacheByKey.get(key);
}
public Key getKey(Object instance)
{
ObjectReference<Key> reference = cacheByValue.get(instance);
if (reference != null)
{
return reference.get();
}
else
{
return null;
}
}
public ObjectReference<Key> getKeyReference(Object instance)
{
return cacheByValue.get(instance);
}
public Set<Key> getAllKeys()
{
return cacheByKey.keySet();
}
public Key getKeyAndActivate(Object instance)
{
// we are sure of the key reference type because the full key and instance must have been added
ActivatableKeyReference reference = (ActivatableKeyReference) cacheByValue.get(instance);
if (reference != null)
{
if (reference.activated)
{
throw new IllegalStateException("Instance was already activated");
}
reference.activated = true;
return reference.get();
}
else
{
return null;
}
}
public boolean containsKey(Key key)
{
return cacheByKey.containsKey(key);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/KeyCache.java | Java | asf20 | 2,938 |
package com.vercer.engine.persist.standard;
import com.google.appengine.api.datastore.Query;
import com.vercer.engine.persist.FindCommand.ChildFindCommand;
final class StandardBranchFindCommand<T> extends StandardTypedFindCommand<T, ChildFindCommand<T>> implements ChildFindCommand<T>
{
private final StandardTypedFindCommand<T, ?> parent;
StandardBranchFindCommand(StandardTypedFindCommand<T, ?> parent)
{
super(parent.datastore);
this.parent = parent;
}
@Override
protected Query newQuery()
{
Query query = parent.newQuery();
applyFilters(query);
return query;
}
@Override
public StandardRootFindCommand<T> getRootCommand()
{
return parent.getRootCommand();
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardBranchFindCommand.java | Java | asf20 | 694 |
package com.vercer.engine.persist.standard;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Query.SortPredicate;
public class StandardMergeParentsCommand<P> extends StandardBaseParentsCommand<P>
{
private final List<Iterator<Entity>> childEntityIterators;
private final List<SortPredicate> sorts;
public StandardMergeParentsCommand(StandardTypedFindCommand<?, ?> command, List<Iterator<Entity>> childEntityIterators, List<SortPredicate> sorts)
{
super(command);
this.childEntityIterators = childEntityIterators;
this.sorts = sorts;
}
public Iterator<P> returnParentsNow()
{
// keys only child queries cannot be sorted as fields are missing
if (childCommand.getRootCommand().isKeysOnly())
{
// make an entity cache with room to hold a round of fetches
final int maxSize = getFetchSize() * childEntityIterators.size() ;
LinkedHashMap<Key, Entity> keyToEntity = new LinkedHashMap<Key, Entity>((int) (maxSize / 0.75))
{
private static final long serialVersionUID = 1L;
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<Key, Entity> eldest)
{
return size() >= maxSize;
}
};
// cannot merge children so must get parent entities first
List<Iterator<Entity>> parentEntityIterators = new ArrayList<Iterator<Entity>>(childEntityIterators.size());
for (Iterator<Entity> child : childEntityIterators)
{
// convert children to parents - may be dups so use a cache
Iterator<Entity> parentEntities = childEntitiesToParentEntities(child, keyToEntity);
parentEntities = applyEntityFilter(parentEntities);
parentEntityIterators.add(parentEntities);
}
// merge all the parent iterators into a single iterator
Iterator<Entity> mergedParentEntities = mergeEntities(parentEntityIterators, sorts);
// convert the entities into instances to return
return entityToInstanceIterator(mergedParentEntities, false);
}
else
{
// we can merge the children first which gets rid of duplicates
Iterator<Entity> mergedChildEntities = mergeEntities(childEntityIterators, sorts);
mergedChildEntities = applyEntityFilter(mergedChildEntities);
// get parents for all children at the same time - no dups so no cache
Iterator<Entity> parentEntities = childEntitiesToParentEntities(mergedChildEntities, null);
return entityToInstanceIterator(parentEntities, false);
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardMergeParentsCommand.java | Java | asf20 | 2,599 |
package com.vercer.engine.persist.standard;
import com.vercer.engine.persist.FindCommand;
public class StandardFindCommand extends StandardCommand implements FindCommand
{
public StandardFindCommand(StrategyObjectDatastore datastore)
{
super(datastore);
}
public <T> RootFindCommand<T> type(Class<T> type)
{
return new StandardRootFindCommand<T>(type, datastore);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardFindCommand.java | Java | asf20 | 381 |
package com.vercer.engine.persist.standard;
import java.util.ArrayList;
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.AsyncDatastoreHelper;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.utils.FutureWrapper;
import com.google.common.collect.Maps;
import com.vercer.engine.persist.StoreCommand.CommonStoreCommand;
abstract class StandardBaseStoreCommand<T, C extends CommonStoreCommand<T, C>> implements CommonStoreCommand<T, C>
{
final StandardStoreCommand command;
Collection<T> instances;
Object parent;
boolean batch;
boolean unique;
public StandardBaseStoreCommand(StandardStoreCommand command)
{
this.command = command;
}
@SuppressWarnings("unchecked")
public C parent(Object parent)
{
return (C) this;
}
@SuppressWarnings("unchecked")
public C batch()
{
batch = true;
return (C) this;
}
@SuppressWarnings("unchecked")
public C ensureUniqueKey()
{
unique = true;
return (C) this;
}
void checkUniqueKeys(Collection<Entity> entities)
{
List<Key> keys = new ArrayList<Key>(entities.size());
for (Entity entity : entities)
{
keys.add(entity.getKey());
}
Map<Key, Entity> map = command.datastore.serviceGet(keys);
if (!map.isEmpty())
{
throw new IllegalStateException("Keys already exist: " + map);
}
}
Future<Map<T, Key>> storeResultsLater()
{
Transaction transaction = command.datastore.getTransaction();
final Map<T, Entity> entities = command.datastore.instancesToEntities(instances, parent, batch);
if (unique)
{
checkUniqueKeys(entities.values());
}
final Future<List<Key>> put = AsyncDatastoreHelper.put(transaction, entities.values());
return new FutureWrapper<List<Key>, Map<T,Key>>(put)
{
@Override
protected Throwable convertException(Throwable t)
{
return t;
}
@Override
protected Map<T, Key> wrap(List<Key> list) throws Exception
{
LinkedHashMap<T, Key> result = Maps.newLinkedHashMap();
Iterator<T> instances = entities.keySet().iterator();
Iterator<Key> keys = list.iterator();
while (instances.hasNext())
{
result.put(instances.next(), keys.next());
}
return result;
}
};
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardBaseStoreCommand.java | Java | asf20 | 2,447 |
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);
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardBaseFindCommand.java | Java | asf20 | 3,170 |
/**
*
*/
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();
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/ParentEntityTranslator.java | Java | asf20 | 1,742 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/ImmediateFuture.java | Java | asf20 | 764 |
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();
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardMultipleStoreCommand.java | Java | asf20 | 1,557 |
/**
*
*/
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();
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/ChildEntityTranslator.java | Java | asf20 | 364 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardSingleParentsCommand.java | Java | asf20 | 752 |
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);
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/PrefetchParentIterator.java | Java | asf20 | 1,755 |
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");
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StrategyObjectDatastore.java | Java | asf20 | 30,235 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardSingleStoreCommand.java | Java | asf20 | 1,545 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardRootFindCommand.java | Java | asf20 | 5,654 |
/**
*
*/
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);
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/KeyFieldTranslator.java | Java | asf20 | 1,940 |
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();
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardTypedFindCommand.java | Java | asf20 | 17,465 |
/**
*
*/
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;
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/EntityTranslator.java | Java | asf20 | 3,309 |
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;
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardBaseParentsCommand.java | Java | asf20 | 2,764 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/BaseObjectDatastore.java | Java | asf20 | 2,835 |
package com.vercer.engine.persist.standard;
import com.vercer.engine.persist.strategy.CombinedStrategy;
public class StandardObjectDatastore extends StrategyObjectDatastore
{
public StandardObjectDatastore(CombinedStrategy strategy)
{
super(strategy);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/StandardObjectDatastore.java | Java | asf20 | 267 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/standard/KeySpecification.java | Java | asf20 | 2,510 |
package com.vercer.engine.persist;
import java.util.Collection;
public interface Activator
{
void activate(Object... instances);
void activateAll(Collection<?> instances);
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/Activator.java | Java | asf20 | 178 |
/**
*
*/
package com.vercer.engine.persist;
public interface Property extends Comparable<Property>
{
Path getPath();
Object getValue();
boolean isIndexed();
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/Property.java | Java | asf20 | 165 |
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;
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/AbstractTypeTranslator.java | Java | asf20 | 1,208 |
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;
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/EnumTranslator.java | Java | asf20 | 1,200 |
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;
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/DirectTranslator.java | Java | asf20 | 966 |
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);
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/SerializingTranslator.java | Java | asf20 | 1,727 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/MapTranslator.java | Java | asf20 | 3,308 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/PolymorphicTranslator.java | Java | asf20 | 2,495 |
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);
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/ListTranslator.java | Java | asf20 | 5,960 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/CoreStringTypesTranslator.java | Java | asf20 | 2,851 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/DelayedTranslator.java | Java | asf20 | 1,123 |
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;
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/DecoratingTranslator.java | Java | asf20 | 312 |
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);
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/ObjectFieldTranslator.java | Java | asf20 | 9,429 |
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();
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/InstanceTranslator.java | Java | asf20 | 689 |
/**
*
*/
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);
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/NativeDirectTranslator.java | Java | asf20 | 506 |
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;
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/translator/ChainedTranslator.java | Java | asf20 | 1,647 |
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();
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/FindCommand.java | Java | asf20 | 3,422 |
/**
*
*/
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();
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/PropertyMapToSet.java | Java | asf20 | 1,075 |
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;
}
};
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/SortedMergeIterator.java | Java | asf20 | 1,743 |
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();
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/PrefixFilteringPropertySet.java | Java | asf20 | 1,003 |
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);
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/SimpleProperty.java | Java | asf20 | 1,950 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/PropertySets.java | Java | asf20 | 2,586 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/RestrictionToPredicateAdaptor.java | Java | asf20 | 429 |
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);
}
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/Entities.java | Java | asf20 | 1,248 |
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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/SinglePropertySet.java | Java | asf20 | 1,183 |
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);
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/PredicateToRestrictionAdaptor.java | Java | asf20 | 435 |
/*
* 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();
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/ParameterizedTypeImpl.java | Java | asf20 | 2,239 |
/*
* 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 + "[]";
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/GenericArrayTypeImpl.java | Java | asf20 | 1,342 |
/*
* 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();
}
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/GenericTypeReflector.java | Java | asf20 | 16,039 |
/*
* 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]);
}
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/WildcardTypeImpl.java | Java | asf20 | 1,518 |
/*
* 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();
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/CaptureType.java | Java | asf20 | 1,231 |
/*
* 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;
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/CaptureTypeImpl.java | Java | asf20 | 1,866 |
/*
* 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();
}
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/TypeToken.java | Java | asf20 | 2,021 |
/*
* 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;
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/generic/VarMap.java | Java | asf20 | 2,200 |
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;
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/io/NoDescriptorObjectInputStream.java | Java | asf20 | 565 |
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());
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/io/NoDescriptorObjectOutputStream.java | Java | asf20 | 467 |
/**
*
*/
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);
}
} | 0611037-nmhien | src/main/java/com/vercer/engine/persist/util/PathPrefixPredicate.java | Java | asf20 | 444 |
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);
}
| 0611037-nmhien | src/main/java/com/vercer/engine/persist/LoadCommand.java | Java | asf20 | 1,032 |
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;
}
} | 0611037-nmhien | src/main/java/com/google/appengine/api/datastore/AsyncPreparedQuery.java | Java | asf20 | 4,289 |
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);
}
}
| 0611037-nmhien | src/main/java/com/google/appengine/api/datastore/AsyncDatastoreHelper.java | Java | asf20 | 3,519 |
hl2 | 0102s-synergy-server-downloads | trunk/synergy/maps/map_select_v2.inc | C++ | oos | 3 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuanLyGaRaOTo.VatTu
{
public class DTO
{
public int MaVatTu { get; set; }
public string TenVatTu { get; set; }
public Nullable<int> SoLuongTon { get; set; }
public Nullable<int> DonGia { get; set; }
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/VatTu/DTO.cs | C# | asf20 | 364 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuanLyGaRaOTo.VatTu
{
public partial class Presentation : Form
{
private DataTable dtVatTu = new DataTable();
public Presentation()
{
InitializeComponent();
}
private void loadVatTu()
{
BUS bus = new BUS();
dtVatTu = new DataTable();
dtVatTu = bus.read();
dgv.DataSource = dtVatTu.DefaultView;
}
private void Presentation_Load(object sender, EventArgs e)
{
loadVatTu();
}
private void cbChonTatCa_CheckedChanged(object sender, EventArgs e)
{
cbTenVatTu.Checked = cbChonTatCa.Checked;
cbSoLuongTonTu.Checked = cbChonTatCa.Checked;
cbSoLuongTonDen.Checked = cbChonTatCa.Checked;
cbDonGiaTu.Checked = cbChonTatCa.Checked;
cbDonGiaDen.Checked = cbChonTatCa.Checked;
}
private void cbTenVatTu_CheckedChanged(object sender, EventArgs e)
{
txtTenVatTu.Enabled = cbTenVatTu.Checked;
}
private void cbSoLuongTonTu_CheckedChanged(object sender, EventArgs e)
{
txtSoLuongTonTu.Enabled = cbSoLuongTonTu.Checked;
}
private void cbSoLuongTonDen_CheckedChanged(object sender, EventArgs e)
{
txtSoLuongTonDen.Enabled = cbSoLuongTonDen.Checked;
}
private void cbDonGiaTu_CheckedChanged(object sender, EventArgs e)
{
txtDonGiaTu.Enabled = cbDonGiaTu.Checked;
}
private void cbDonGiaDen_CheckedChanged(object sender, EventArgs e)
{
txtDonGiaDen.Enabled = cbDonGiaDen.Checked;
}
private void btnTim_Click(object sender, EventArgs e)
{
string filter = "";
CheckValues cv = new CheckValues();
if (cbTenVatTu.Checked)
filter = string.Format("TENVATTU like '%{0}%'", txtTenVatTu.Text);
if (cbSoLuongTonTu.Checked)
{
if (!cv.checkUint(txtSoLuongTonTu.Text))
{
MessageBox.Show("'Số lượng tồn từ' phải là số nguyên dương!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtSoLuongTonTu.Focus();
txtSoLuongTonDen.SelectAll();
return;
}
if (filter != "")
filter += "and ";
filter += string.Format("SOLUONGTON >= {0}", txtSoLuongTonTu.Text);
}
if (cbSoLuongTonDen.Checked)
{
if (!cv.checkUint(txtSoLuongTonDen.Text))
{
MessageBox.Show("'Số lượng tồn đến' phải là số nguyên dương!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtSoLuongTonDen.Focus();
txtSoLuongTonDen.SelectAll();
return;
}
if (filter != "")
filter += "and ";
filter += string.Format("SOLUONGTON <= {0}", txtSoLuongTonDen.Text);
}
if (cbDonGiaTu.Checked)
{
if (!cv.checkUint(txtDonGiaTu.Text))
{
MessageBox.Show("'Đơn giá từ' phải là số nguyên dương!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtDonGiaTu.Focus();
txtDonGiaTu.SelectAll();
return;
}
if (filter != "")
filter += "and ";
filter += string.Format("DONGIA >= {0}", txtDonGiaTu.Text);
}
if (cbDonGiaDen.Checked)
{
if (!cv.checkUint(txtDonGiaDen.Text))
{
MessageBox.Show("'Đơn giá đến' phải là số nguyên dương!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtDonGiaDen.Focus();
txtDonGiaDen.SelectAll();
return;
}
if (filter != "")
filter += "and ";
filter += string.Format("DONGIA <= {0}", txtDonGiaDen.Text);
}
DataView dv = new DataView(dtVatTu);
dv.RowFilter = filter;
dgv.DataSource = dv;
}
private void tsbEdit_Click(object sender, EventArgs e)
{
btnStatus(false);
}
private void insert(DataRow row)
{
DTO dto = new DTO();
dto.TenVatTu = row["TenVatTu"].ToString();
if (row["SoLuongTon"].ToString() != "")
dto.SoLuongTon = Convert.ToInt32(row["SoLuongTon"]);
if (row["DonGia"].ToString() != "")
dto.DonGia = Convert.ToInt32(row["DonGia"]);
BUS bus = new BUS();
int i = bus.insert(dto);
if (i == -1)
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình thêm dòng dữ liệu mới!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtVatTu.RejectChanges();
btnStatus(true);
}
else
row["MaVatTu"] = i;
}
private void delete(DataRow row)
{
DTO dto = new DTO();
dto.MaVatTu = Convert.ToInt32(row["MaVatTu", DataRowVersion.Original]);
BUS bus = new BUS();
if (!bus.delete(dto))
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình xóa dòng dữ liệu mới!!!", "Xóa", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtVatTu.RejectChanges();
btnStatus(true);
}
}
private void update(DataRow row)
{
DTO dto = new DTO();
dto.MaVatTu = Convert.ToInt32(row["MaVatTu"]);
dto.TenVatTu = row["TenVatTu"].ToString();
if (row["SoLuongTon"].ToString() != "")
dto.SoLuongTon = Convert.ToInt32(row["SoLuongTon"]);
if (row["DonGia"].ToString() != "")
dto.DonGia = Convert.ToInt32(row["DonGia"]);
BUS bus = new BUS();
if (!bus.update(dto))
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình cập nhật dòng dữ liệu mới!!!", "Cập nhật", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtVatTu.RejectChanges();
btnStatus(true);
}
}
private void tsbSave_Click(object sender, EventArgs e)
{
foreach (DataRow row in dtVatTu.Rows)
switch (row.RowState)
{
case DataRowState.Added:
insert(row);
break;
case DataRowState.Modified:
update(row);
break;
case DataRowState.Deleted:
delete(row); ;
break;
default: break;
}
dtVatTu.AcceptChanges();
btnStatus(true);
}
private void tsbCancel_Click(object sender, EventArgs e)
{
dtVatTu.RejectChanges();
btnStatus(true);
}
private void tsbExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void txtSoLuongTonTu_TextChanged(object sender, EventArgs e)
{
editTextBoxX(txtSoLuongTonTu);
}
private void txtSoLuongTonDen_TextChanged(object sender, EventArgs e)
{
editTextBoxX(txtSoLuongTonDen);
}
private void txtDonGiaTu_TextChanged(object sender, EventArgs e)
{
editTextBoxX(txtDonGiaTu);
}
private void txtDonGiaDen_TextChanged(object sender, EventArgs e)
{
editTextBoxX(txtDonGiaDen);
}
private void editTextBoxX(DevComponents.DotNetBar.Controls.TextBoxX txt)
{
CheckValues cv = new CheckValues();
if (txt.Text != "" && !cv.checkUint(txt.Text))
{
MessageBox.Show(txt.Name + " phải là số nguyên dương!!!", "Tra cứu", MessageBoxButtons.OK, MessageBoxIcon.Error);
txt.SelectAll();
}
}
private void btnStatus(Boolean status)
{
try
{
grTraCuu.Enabled = status;
dgv.ReadOnly = status;
dgv.AllowUserToDeleteRows = !status;
tsbEdit.Enabled = tsbReset.Enabled = status;
tsbSave.Enabled = tsbCancel.Enabled = !status;
dgv.AllowUserToAddRows = !status;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void tsbReset_Click(object sender, EventArgs e)
{
dgv.DataSource = dtVatTu.DefaultView;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/VatTu/Presentation.cs | C# | asf20 | 9,871 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace QuanLyGaRaOTo.VatTu
{
public class BUS
{
private DAO dao = new DAO();
public DataTable read()
{
return dao.read();
}
public int insert(DTO dto)
{
return dao.insert(dto);
}
public Boolean delete(DTO dto)
{
return dao.delete(dto);
}
public Boolean update(DTO dto)
{
return dao.update(dto);
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/VatTu/BUS.cs | C# | asf20 | 614 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace QuanLyGaRaOTo.VatTu
{
public class DAO
{
private string cnStr = new DataProvider().getcnStr();
private SqlConnection cn;
private string procName;
private SqlCommand cmd;
private DataTable Kq;
private SqlDataAdapter da;
public DAO()
{
try
{
cn = new SqlConnection(cnStr);
}
catch (Exception e)
{
throw new Exception("Không kết nối được cơ sở dữ liệu!!! " + e.Message);
}
}
public DataTable read()
{
cn.Open();
Kq = new DataTable();
procName = "stpXemVatTu";
try
{
da = new SqlDataAdapter(procName, cn);
da.Fill(Kq);
}
catch { }
cn.Close();
return Kq;
}
public int insert(DTO dto)
{
cn.Open();
procName = "stpThemVatTu";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@TenVatTu", SqlDbType.NVarChar).Value = dto.TenVatTu;
cmd.Parameters.Add("@SoLuongTon", SqlDbType.VarChar).Value = dto.SoLuongTon;
cmd.Parameters.Add("@DonGia", SqlDbType.NVarChar).Value = dto.DonGia;
cmd.Parameters.Add("@MaVatTu", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
}
catch
{
return -1;
}
finally
{
cn.Close();
}
return Convert.ToInt32(cmd.Parameters["@MaVatTu"].Value);
}
public Boolean delete(DTO dto)
{
cn.Open();
procName = "stpXoaVatTu";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaVatTu", SqlDbType.Int).Value = dto.MaVatTu;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
public Boolean update(DTO dto)
{
cn.Open();
procName = "stpCapNhatVatTu";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaVatTu", SqlDbType.Int).Value = dto.MaVatTu;
cmd.Parameters.Add("@TenVatTu", SqlDbType.NVarChar).Value = dto.TenVatTu;
cmd.Parameters.Add("@SoLuongTon", SqlDbType.VarChar).Value = dto.SoLuongTon;
cmd.Parameters.Add("@DonGia", SqlDbType.NVarChar).Value = dto.DonGia;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/VatTu/DAO.cs | C# | asf20 | 3,530 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("QuanLyGaRaOTo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("QuanLyGaRaOTo")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ef424a7b-7117-4e17-9058-dce26fa72176")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/Properties/AssemblyInfo.cs | C# | asf20 | 1,456 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuanLyGaRaOTo.HieuXe
{
public class DTO
{
public int MaHieuXe { get; set; }
public string TenHieuXe { get; set; }
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/HieuXe/DTO.cs | C# | asf20 | 259 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuanLyGaRaOTo.HieuXe
{
public partial class Presentation : Form
{
private DataTable dtHieuXe = new DataTable();
public Presentation()
{
InitializeComponent();
}
private void loadHieuXe()
{
BUS bus = new BUS();
dtHieuXe = new DataTable();
dtHieuXe = bus.read();
dgv.DataSource = dtHieuXe.DefaultView;
}
private void Presentation_Load(object sender, EventArgs e)
{
loadHieuXe();
}
private void cbTenHieuXe_CheckedChanged(object sender, EventArgs e)
{
txtTenHieuXe.Enabled = cbTenHieuXe.Checked;
}
private void btnTim_Click(object sender, EventArgs e)
{
string filter = "";
if (cbTenHieuXe.Checked)
filter = string.Format("TENHIEUXE like '%{0}%'", txtTenHieuXe.Text);
DataView dv = new DataView(dtHieuXe);
dv.RowFilter = filter;
dgv.DataSource = dv;
}
private void tsbEdit_Click(object sender, EventArgs e)
{
btnStatus(false);
}
private void insert(DataRow row)
{
DTO dto = new DTO();
dto.TenHieuXe = row["TenHieuXe"].ToString();
BUS bus = new BUS();
int i = bus.insert(dto);
if (i == -1)
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình thêm dòng dữ liệu mới!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtHieuXe.RejectChanges();
btnStatus(true);
}
else
row["MaHieuXe"] = i;
}
private void delete(DataRow row)
{
DTO dto = new DTO();
dto.MaHieuXe = Convert.ToInt32(row["MaHieuXe", DataRowVersion.Original]);
BUS bus = new BUS();
if (!bus.delete(dto))
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình xóa dòng dữ liệu mới!!!", "Xóa", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtHieuXe.RejectChanges();
btnStatus(true);
}
}
private void update(DataRow row)
{
DTO dto = new DTO();
dto.MaHieuXe = Convert.ToInt32(row["MaHieuXe"]);
dto.TenHieuXe = row["TenHieuXe"].ToString();
BUS bus = new BUS();
if (!bus.update(dto))
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình cập nhật dòng dữ liệu mới!!!", "Cập nhật", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtHieuXe.RejectChanges();
btnStatus(true);
}
}
private void tsbSave_Click(object sender, EventArgs e)
{
foreach (DataRow row in dtHieuXe.Rows)
switch (row.RowState)
{
case DataRowState.Added:
insert(row);
break;
case DataRowState.Modified:
update(row);
break;
case DataRowState.Deleted:
delete(row); ;
break;
default: break;
}
dtHieuXe.AcceptChanges();
btnStatus(true);
}
private void tsbCancel_Click(object sender, EventArgs e)
{
dtHieuXe.RejectChanges();
btnStatus(true);
}
private void tsbExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnStatus(Boolean status)
{
try
{
grTraCuu.Enabled = status;
dgv.ReadOnly = status;
dgv.AllowUserToDeleteRows = !status;
tsbEdit.Enabled = tsbReset.Enabled = status;
tsbSave.Enabled = tsbCancel.Enabled = !status;
dgv.AllowUserToAddRows = !status;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void tsbReset_Click(object sender, EventArgs e)
{
dgv.DataSource = dtHieuXe.DefaultView;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/HieuXe/Presentation.cs | C# | asf20 | 4,850 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace QuanLyGaRaOTo.HieuXe
{
public class BUS
{
private DAO dao = new DAO();
public DataTable read()
{
return dao.read();
}
public int insert(DTO dto)
{
return dao.insert(dto);
}
public Boolean delete(DTO dto)
{
return dao.delete(dto);
}
public Boolean update(DTO dto)
{
return dao.update(dto);
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/HieuXe/BUS.cs | C# | asf20 | 615 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace QuanLyGaRaOTo.HieuXe
{
public class DAO
{
private string cnStr = new DataProvider().getcnStr();
private SqlConnection cn;
private string procName;
private SqlCommand cmd;
private DataTable Kq;
private SqlDataAdapter da;
public DAO()
{
try
{
cn = new SqlConnection(cnStr);
}
catch (Exception e)
{
throw new Exception("Không kết nối được cơ sở dữ liệu!!! " + e.Message);
}
}
public DataTable read()
{
cn.Open();
Kq = new DataTable();
procName = "stpXemHieuXe";
try
{
da = new SqlDataAdapter(procName, cn);
da.Fill(Kq);
}
catch { }
cn.Close();
return Kq;
}
public int insert(DTO dto)
{
cn.Open();
procName = "stpThemHieuXe";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@TenHieuXe", SqlDbType.NVarChar).Value = dto.TenHieuXe;
cmd.Parameters.Add("@MaHieuXe", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
}
catch
{
return -1;
}
finally
{
cn.Close();
}
return Convert.ToInt32(cmd.Parameters["@MaHieuXe"].Value);
}
public Boolean delete(DTO dto)
{
cn.Open();
procName = "stpXoaHieuXe";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaHieuXe", SqlDbType.Int).Value = dto.MaHieuXe;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
public Boolean update(DTO dto)
{
cn.Open();
procName = "stpCapNhatHieuXe";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaHieuXe", SqlDbType.Int).Value = dto.MaHieuXe;
cmd.Parameters.Add("@TenHieuXe", SqlDbType.NVarChar).Value = dto.TenHieuXe;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/HieuXe/DAO.cs | C# | asf20 | 3,187 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
namespace QuanLyGaRaOTo
{
public partial class frmMain : Office2007RibbonForm
{
public frmMain()
{
InitializeComponent();
}
private void closeMdiChildren()
{
foreach (Form frm in this.MdiChildren)
frm.Close();
}
private void buttonItem1_Click(object sender, EventArgs e)
{
closeMdiChildren();
PhieuTiepNhan.Presentation f = new PhieuTiepNhan.Presentation();
f.MdiParent = this;
f.Show();
}
private void buttonItem1_Click_1(object sender, EventArgs e)
{
closeMdiChildren();
HieuXe.Presentation f = new HieuXe.Presentation();
f.MdiParent = this;
f.Show();
}
private void buttonItem2_Click(object sender, EventArgs e)
{
closeMdiChildren();
VatTu.Presentation f = new VatTu.Presentation();
f.MdiParent = this;
f.Show();
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/frmMain.cs | C# | asf20 | 1,329 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuanLyGaRaOTo
{
public class DataProvider
{
public string getcnStr()
{
const string cnStr = "Data Source=localhost;Initial Catalog=QLGARAOTO;Integrated Security=True";
return cnStr;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/DataProvider.cs | C# | asf20 | 364 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuanLyGaRaOTo.PhieuSuaChua
{
public class DTO
{
public int MaPhieu { get; set; }
public int PhieuTiepNhan { get; set; }
public Nullable<DateTime> NgaySuaChua { get; set; }
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuSuaChua/DTO.cs | C# | asf20 | 336 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuanLyGaRaOTo.PhieuSuaChua
{
public partial class Presentation : Form
{
public Presentation()
{
InitializeComponent();
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuSuaChua/Presentation.cs | C# | asf20 | 390 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace QuanLyGaRaOTo.PhieuSuaChua
{
public class BUS
{
private DAO dao = new DAO();
public DataTable read()
{
return dao.read();
}
public int insert(DTO dto)
{
return dao.insert(dto);
}
public Boolean delete(DTO dto)
{
return dao.delete(dto);
}
public Boolean update(DTO dto)
{
return dao.update(dto);
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuSuaChua/BUS.cs | C# | asf20 | 621 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace QuanLyGaRaOTo.PhieuSuaChua
{
public class DAO
{
private string cnStr = new DataProvider().getcnStr();
private SqlConnection cn;
private string procName;
private SqlCommand cmd;
private DataTable Kq;
private SqlDataAdapter da;
public DAO()
{
try
{
cn = new SqlConnection(cnStr);
}
catch (Exception e)
{
throw new Exception("Không kết nối được cơ sở dữ liệu!!! " + e.Message);
}
}
public DataTable read()
{
cn.Open();
Kq = new DataTable();
procName = "stpXemPhieuSuaChua";
try
{
da = new SqlDataAdapter(procName, cn);
da.Fill(Kq);
}
catch { }
cn.Close();
return Kq;
}
public int insert(DTO dto)
{
cn.Open();
procName = "stpThemPhieuSuaChua";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@PhieuTiepNhan", SqlDbType.Int).Value = dto.PhieuTiepNhan;
cmd.Parameters.Add("@NgaySuaChua", SqlDbType.DateTime).Value = dto.NgaySuaChua;
cmd.Parameters.Add("@MaPhieu", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
}
catch
{
return -1;
}
finally
{
cn.Close();
}
return Convert.ToInt32(cmd.Parameters["@MaPhieu"].Value);
}
public Boolean delete(DTO dto)
{
cn.Open();
procName = "stpXoaPhieuSuaChua";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaPhieu", SqlDbType.Int).Value = dto.MaPhieu;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
public Boolean update(DTO dto)
{
cn.Open();
procName = "stpCapNhatPhieuSuaChua";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaPhieu", SqlDbType.Int).Value = dto.MaPhieu;
cmd.Parameters.Add("@PhieuTiepNhan", SqlDbType.Int).Value = dto.PhieuTiepNhan;
cmd.Parameters.Add("@NgaySuaChua", SqlDbType.DateTime).Value = dto.NgaySuaChua;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuSuaChua/DAO.cs | C# | asf20 | 3,407 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuanLyGaRaOTo
{
public class CheckValues
{
public Boolean checkDouble(string s)
{
double d;
return (double.TryParse(s, out d));
}
public Boolean checkInt(string s)
{
int i;
return (int.TryParse(s, out i));
}
public Boolean checkUint(string s)
{
uint i;
return (uint.TryParse(s, out i));
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/CheckValues.cs | C# | asf20 | 590 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuanLyGaRaOTo.PhieuTiepNhan
{
public class DTO
{
public int MaPhieu { get; set; }
public string TenChuXe { get; set; }
public string BienSo { get; set; }
public string DiaChi { get; set; }
public string DienThoai { get; set; }
public Nullable<int> HieuXe { get; set; }
public Nullable<DateTime> NgayTiepNhan { get; set; }
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuTiepNhan/DTO.cs | C# | asf20 | 521 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuanLyGaRaOTo.PhieuTiepNhan
{
public partial class Presentation : Form
{
private DataTable dtPhieuTiepNhan = new DataTable();
public Presentation()
{
InitializeComponent();
}
private void loadPhieuTiepNhan()
{
BUS bus = new BUS();
dtPhieuTiepNhan = new DataTable();
dtPhieuTiepNhan = bus.read();
dgv.DataSource = dtPhieuTiepNhan.DefaultView;
}
private DataTable loadHieuXe()
{
DataTable dt = new DataTable();
HieuXe.BUS bus = new HieuXe.BUS();
dt = bus.read();
return dt;
}
private void Presentation_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = loadHieuXe();
colHieuXe.DataSource = dt.DefaultView;
colHieuXe.ValueMember = "MAHIEUXE";
colHieuXe.DisplayMember = "TENHIEUXE";
DataTable dt1 = dt.Copy();
cbbHieuXe.DataSource = dt1.DefaultView;
cbbHieuXe.ValueMember = "MAHIEUXE";
cbbHieuXe.DisplayMember = "TENHIEUXE";
loadPhieuTiepNhan();
loadHieuXe();
}
private void cbTenChuXe_CheckedChanged(object sender, EventArgs e)
{
txtTenChuXe.Enabled = cbTenChuXe.Checked;
}
private void cbBienSo_CheckedChanged(object sender, EventArgs e)
{
txtBienSo.Enabled = cbBienSo.Checked;
}
private void cbDiaChi_CheckedChanged(object sender, EventArgs e)
{
txtDiaChi.Enabled = cbDiaChi.Checked;
}
private void cbDienThoai_CheckedChanged(object sender, EventArgs e)
{
txtDienThoai.Enabled = cbDienThoai.Checked;
}
private void cbHieuXe_CheckedChanged(object sender, EventArgs e)
{
cbbHieuXe.Enabled = cbHieuXe.Checked;
}
private void cbNgayTiepNhan_CheckedChanged(object sender, EventArgs e)
{
dtiNgayTiepNhan.Enabled = cbNgayTiepNhan.Checked;
}
private void btnTim_Click(object sender, EventArgs e)
{
string filter = "";
if (cbTenChuXe.Checked)
filter = string.Format("TENCHUXE like '%{0}%'", txtTenChuXe.Text);
if (cbBienSo.Checked)
{
if (filter != "")
filter += "and ";
filter += string.Format("BIENSO like '%{0}%'", txtBienSo.Text);
}
if (cbDiaChi.Checked)
{
if (filter != "")
filter += "and ";
filter += string.Format("DIACHI like '%{0}%'", txtDiaChi.Text);
}
if (cbDienThoai.Checked)
{
if (filter != "")
filter += "and ";
filter += string.Format("DIENTHOAI like '%{0}%'", txtDienThoai.Text);
}
if (cbHieuXe.Checked)
{
if (filter != "")
filter += "and ";
filter += string.Format("HIEUXE = '{0}'", cbbHieuXe.Text);
}
if (cbNgayTiepNhan.Checked)
if (dtiNgayTiepNhan.Text != "")
{
if (filter != "")
filter += "and ";
filter += string.Format("NGAYTIEPNHAN = '{0}'", dtiNgayTiepNhan.Text);
}
DataView dv = new DataView(dtPhieuTiepNhan);
dv.RowFilter = filter;
dgv.DataSource = dv;
}
private void cbChonTatCa_CheckedChanged(object sender, EventArgs e)
{
cbTenChuXe.Checked = cbChonTatCa.Checked;
cbBienSo.Checked = cbChonTatCa.Checked;
cbDiaChi.Checked = cbChonTatCa.Checked;
cbDienThoai.Checked = cbChonTatCa.Checked;
cbHieuXe.Checked = cbChonTatCa.Checked;
cbNgayTiepNhan.Checked = cbChonTatCa.Checked;
}
private void tsbEdit_Click(object sender, EventArgs e)
{
btnStatus(false);
}
private void insert(DataRow row)
{
DTO dto = new DTO();
dto.TenChuXe = row["TenChuXe"].ToString();
dto.BienSo = row["BienSo"].ToString();
dto.DiaChi = row["DiaChi"].ToString();
dto.DienThoai = row["DienThoai"].ToString();
if (row["HieuXe"].ToString() != "")
dto.HieuXe = Convert.ToInt32(row["HieuXe"]);
if (row["NgayTiepNhan"].ToString() != "")
dto.NgayTiepNhan = Convert.ToDateTime(row["NgayTiepNhan"]);
BUS bus = new BUS();
int i = bus.insert(dto);
if (i == -1)
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình thêm dòng dữ liệu mới!!!", "Thêm", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtPhieuTiepNhan.RejectChanges();
btnStatus(true);
}
else
row["MaPhieu"] = i;
}
private void delete(DataRow row)
{
DTO dto = new DTO();
dto.MaPhieu = Convert.ToInt32(row["MaPhieu", DataRowVersion.Original]);
BUS bus = new BUS();
if (!bus.delete(dto))
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình xóa dòng dữ liệu mới!!!", "Xóa", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtPhieuTiepNhan.RejectChanges();
btnStatus(true);
}
}
private void update(DataRow row)
{
DTO dto = new DTO();
dto.MaPhieu = Convert.ToInt32(row["MaPhieu"]);
dto.TenChuXe = row["TenChuXe"].ToString();
dto.BienSo = row["BienSo"].ToString();
dto.DiaChi = row["DiaChi"].ToString();
dto.DienThoai = row["DienThoai"].ToString();
dto.HieuXe = Convert.ToInt32(row["HieuXe"]);
if (row["NgayTiepNhan"].ToString() != "")
dto.NgayTiepNhan = Convert.ToDateTime(row["NgayTiepNhan"]);
BUS bus = new BUS();
if (!bus.update(dto))
{
MessageBox.Show("Đã xảy ra lỗi trong quá trình cập nhật dòng dữ liệu mới!!!", "Cập nhật", MessageBoxButtons.OK, MessageBoxIcon.Error);
dtPhieuTiepNhan.RejectChanges();
btnStatus(true);
}
}
private void tsbSave_Click(object sender, EventArgs e)
{
foreach (DataRow row in dtPhieuTiepNhan.Rows)
switch (row.RowState)
{
case DataRowState.Added:
insert(row);
break;
case DataRowState.Modified:
update(row);
break;
case DataRowState.Deleted:
delete(row);;
break;
default: break;
}
dtPhieuTiepNhan.AcceptChanges();
btnStatus(true);
}
private void tsbCancel_Click(object sender, EventArgs e)
{
dtPhieuTiepNhan.RejectChanges();
btnStatus(true);
}
private void tsbExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnStatus(Boolean status)
{
try
{
grTraCuu.Enabled = status;
dgv.ReadOnly = status;
dgv.AllowUserToDeleteRows = !status;
tsbEdit.Enabled = tsbReset.Enabled = status;
tsbSave.Enabled = tsbCancel.Enabled = !status;
dgv.AllowUserToAddRows = !status;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void tsbReset_Click(object sender, EventArgs e)
{
dgv.DataSource = dtPhieuTiepNhan.DefaultView;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuTiepNhan/Presentation.cs | C# | asf20 | 8,927 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace QuanLyGaRaOTo.PhieuTiepNhan
{
public class BUS
{
private DAO dao = new DAO();
public DataTable read()
{
return dao.read();
}
public int insert(DTO dto)
{
return dao.insert(dto);
}
public Boolean delete(DTO dto)
{
return dao.delete(dto);
}
public Boolean update(DTO dto)
{
return dao.update(dto);
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuTiepNhan/BUS.cs | C# | asf20 | 622 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace QuanLyGaRaOTo.PhieuTiepNhan
{
public class DAO
{
private string cnStr = new DataProvider().getcnStr();
private SqlConnection cn;
private string procName;
private SqlCommand cmd;
private DataTable Kq;
private SqlDataAdapter da;
public DAO()
{
try
{
cn = new SqlConnection(cnStr);
}
catch (Exception e)
{
throw new Exception("Không kết nối được cơ sở dữ liệu!!! " + e.Message);
}
}
public DataTable read()
{
cn.Open();
Kq = new DataTable();
procName = "stpXemPhieuTiepNhan";
try
{
da = new SqlDataAdapter(procName, cn);
da.Fill(Kq);
}
catch { }
cn.Close();
return Kq;
}
public int insert(DTO dto)
{
cn.Open();
procName = "stpThemPhieuTiepNhan";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@TenChuXe", SqlDbType.NVarChar).Value = dto.TenChuXe;
cmd.Parameters.Add("@BienSo", SqlDbType.VarChar).Value = dto.BienSo;
cmd.Parameters.Add("@DiaChi", SqlDbType.NVarChar).Value = dto.DiaChi;
cmd.Parameters.Add("@DienThoai", SqlDbType.VarChar).Value = dto.DienThoai;
cmd.Parameters.Add("@HieuXe", SqlDbType.Int).Value = dto.HieuXe;
cmd.Parameters.Add("@NgayTiepNhan", SqlDbType.DateTime).Value = dto.NgayTiepNhan;
cmd.Parameters.Add("@MaPhieu", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
}
catch
{
return -1;
}
finally
{
cn.Close();
}
return Convert.ToInt32(cmd.Parameters["@MaPhieu"].Value);
}
public Boolean delete(DTO dto)
{
cn.Open();
procName = "stpXoaPhieuTiepNhan";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaPhieu", SqlDbType.Int).Value = dto.MaPhieu;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
public Boolean update(DTO dto)
{
cn.Open();
procName = "stpCapNhatPhieuTiepNhan";
try
{
cmd = new SqlCommand(procName, cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@MaPhieu", SqlDbType.Int).Value = dto.MaPhieu;
cmd.Parameters.Add("@TenChuXe", SqlDbType.NVarChar).Value = dto.TenChuXe;
cmd.Parameters.Add("@BienSo", SqlDbType.VarChar).Value = dto.BienSo;
cmd.Parameters.Add("@DiaChi", SqlDbType.NVarChar).Value = dto.DiaChi;
cmd.Parameters.Add("@DienThoai", SqlDbType.VarChar).Value = dto.DienThoai;
cmd.Parameters.Add("@HieuXe", SqlDbType.Int).Value = dto.HieuXe;
cmd.Parameters.Add("@NgayTiepNhan", SqlDbType.DateTime).Value = dto.NgayTiepNhan;
cmd.ExecuteNonQuery();
}
catch
{
return false;
}
finally
{
cn.Close();
}
return true;
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/PhieuTiepNhan/DAO.cs | C# | asf20 | 4,100 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace QuanLyGaRaOTo
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
| 06tc106detaiquanlygaraoto | trunk/source/QuanLyGaRaOTo/QuanLyGaRaOTo/Program.cs | C# | asf20 | 507 |
/*
* File for the kernel exports of LoadExec
*/
#ifndef __LOADEXEC_KERNEL__
#define __LOADEXEC_KERNEL__
#include <psploadexec.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Structure for LoadExecVSH* functions */
struct SceKernelLoadExecVSHParam {
/** Size of the structure in bytes */
SceSize size;
/** Size of the arguments string */
SceSize args;
/** Pointer to the arguments strings */
void * argp;
/** The key, usually "game", "updater" or "vsh" */
const char * key;
/** The size of the vshmain arguments */
u32 vshmain_args_size;
/** vshmain arguments that will be passed to vshmain after the program has exited */
void *vshmain_args;
/** "/kd/pspbtcnf_game.txt" or "/kd/pspbtcnf.txt" if not supplied (max. 256 chars) */
char *configfile;
/** An unknown string (max. 256 chars) probably used in 2nd stage of loadexec */
u32 unk4;
/** unknown flag default value = 0x10000 */
u32 unk5;
};
/**
* Executes a new executable from a buffer.
*
* @param bufsize - Size in bytes of the buffer pointed by buf.
* @param buf - Pointer to a buffer containing the module to execute.
* @param param - Pointer to a ::SceKernelLoadExecParam structure, or NULL.
*
* @returns < 0 on some errors.
*/
int sceKernelLoadExecBufferPlain(SceSize bufsize, void *buf, struct SceKernelLoadExecParam *param);
/**
* Restart the vsh.
*
* @param unk - Unknown, I haven't checked it. Set it to NULL
*
* @returns < 0 on some errors.
*
* @note - when called in game mode it will have the same effect that sceKernelExitGame
*
*/
int sceKernelExitVSHVSH(void *unk);
/**
* Executes a new executable from a disc.
* It is the function used by the firmware to execute the EBOOT.BIN from a disc.
*
* @param file - The file to execute.
* @param param - Pointer to a ::SceKernelLoadExecVSHParam structure, or NULL.
*
* @returns < 0 on some errors.
*/
int sceKernelLoadExecVSHDisc(const char *file, struct SceKernelLoadExecVSHParam *param);
/**
* Executes a new executable from a disc.
* It is the function used by the firmware to execute an updater from a disc.
*
* @param file - The file to execute.
* @param param - Pointer to a ::SceKernelLoadExecVSHParam structure, or NULL.
*
* @returns < 0 on some errors.
*/
int sceKernelLoadExecVSHDiscUpdater(const char *file, struct SceKernelLoadExecVSHParam *param);
/**
* Executes a new executable from a memory stick.
* It is the function used by the firmware to execute an updater from a memory stick.
*
* @param file - The file to execute.
* @param param - Pointer to a ::SceKernelLoadExecVSHParam structure, or NULL.
*
* @returns < 0 on some errors.
*/
int sceKernelLoadExecVSHMs1(const char *file, struct SceKernelLoadExecVSHParam *param);
/**
* Executes a new executable from a memory stick.
* It is the function used by the firmware to execute games (and homebrew :P) from a memory stick.
*
* @param file - The file to execute.
* @param param - Pointer to a ::SceKernelLoadExecVSHParam structure, or NULL.
*
* @returns < 0 on some errors.
*/
int sceKernelLoadExecVSHMs2(const char *file, struct SceKernelLoadExecVSHParam *param);
/**
* Executes a new executable from a memory stick.
* It is the function used by the firmware to execute ... ?
*
* @param file - The file to execute.
* @param param - Pointer to a ::SceKernelLoadExecVSHParam structure, or NULL.
*
* @returns < 0 on some errors.
*/
int sceKernelLoadExecVSHMs3(const char *file, struct SceKernelLoadExecVSHParam *param);
#ifdef __cplusplus
}
#endif
#endif
| 100oecfw | psploadexec_kernel.h | C | gpl3 | 3,663 |
TARGET = recovery
OBJS = main.o menu.o mydebug.o conf.o
CFLAGS = -O2 -Os -G0 -Wall -fno-pic
CXXFLAGS = $(CFLAGS) -fno-exceptions -fno-rtti
ASFLAGS = $(CFLAGS)
LIBS = -lpspusb -lpspusbstor -lpspreg_driver
BUILD_PRX = 1
PSPSDK=$(shell psp-config --pspsdk-path)
include $(PSPSDK)/lib/build.mak
| 100oecfw | Makefile | Makefile | gpl3 | 306 |
#ifndef __CONF_H__
#define __CONF_H__
#define CONFIG_MAGIC 0x47434553
enum
{
FAKE_REGION_DISABLED = 0,
FAKE_REGION_JAPAN = 1,
FAKE_REGION_AMERICA = 2,
FAKE_REGION_EUROPE = 3,
FAKE_REGION_KOREA = 4, /* do not use, may cause brick on restore default settings */
FAKE_REGION_UNK = 5,
FAKE_REGION_UNK2 = 6,
FAKE_REGION_AUSTRALIA = 7,
FAKE_REGION_HONGKONG = 8, /* do not use, may cause brick on restore default settings */
FAKE_REGION_TAIWAN = 9, /* do not use, may cause brick on restore default settings */
FAKE_REGION_RUSSIA = 10,
FAKE_REGION_CHINA = 11, /* do not use, may cause brick on restore default settings */
};
typedef struct
{
int magic; /* 0x47434553 */
int hidecorrupt;
int skiplogo;
int umdactivatedplaincheck;
int executebootbin;
int startupprog;
int usenoumd;
int useisofsonumdinserted;
int vshcpuspeed; /* not available yet */
int vshbusspeed; /* not available yet */
int umdisocpuspeed; /* not available yet */
int umdisobusspeed; /* not available yet */
int fakeregion;
int freeumdregion;
int usevshmenu;
int usemp3;
int usescreen;
} SEConfig;
int SE_GetConfig(SEConfig *config);
int SE_SetConfig(SEConfig *config);
#endif
| 100oecfw | conf.h | C | gpl3 | 1,232 |
#include <pspctrl.h>
#include "mydebug.h"
#define SELECTBUTTON PSP_CTRL_CROSS
#define CANCELBUTTON PSP_CTRL_TRIANGLE
#define RGB(r, g, b) (0xFF000000 | ((b)<<16) | ((g)<<8) | (r))
#define printf myDebugScreenPrintf
#define setTextColor myDebugScreenSetTextColor
#define setXY myDebugScreenSetXY
#define clearScreen myDebugScreenClear
#define pspDebugScreenSetBackColor
int doMenu(char* picks[], int count, int selected, char* message, int x, int y) {
int done = 0;
while (!done) {
SceCtrlData pad;
int onepressed = 0;
int i;
setXY(0, 0);
setTextColor(RGB(0, 0, 205));
printf("1.50 EG-9 Recovery Men%c\n", 0x9a);
printf(" %s", message);
for(i=0;i<count;i++) {
setXY(x, y+i);
if(picks[i] == 0) break;
if(selected == i) {
setTextColor(RGB(0, 238, 0));
printf(" %s\n", picks[i]);
} else {
setTextColor(RGB(255, 0, 0));
printf(" %s\n", picks[i]);
}
}
setTextColor(RGB(0, 0, 0));
setXY(0, 23);
printf(" ------------------------------------------------------------------ \n\n");
while (!onepressed) {
sceCtrlReadBufferPositive(&pad, 1);
onepressed = ( (pad.Buttons & SELECTBUTTON ) ||
(pad.Buttons & CANCELBUTTON ) ||
(pad.Buttons & PSP_CTRL_UP ) ||
(pad.Buttons & PSP_CTRL_DOWN));
}
if (pad.Buttons & SELECTBUTTON) { done = 1; }
if (pad.Buttons & PSP_CTRL_UP) { selected = (selected + count - 1) % count; }
if (pad.Buttons & PSP_CTRL_DOWN){ selected = (selected+1) % count; }
if (pad.Buttons & CANCELBUTTON) { done = 1; selected = -1; }
while (onepressed) {
sceCtrlReadBufferPositive(&pad, 1);
onepressed = ( (pad.Buttons & SELECTBUTTON ) ||
(pad.Buttons & CANCELBUTTON ) ||
(pad.Buttons & PSP_CTRL_UP ) ||
(pad.Buttons & PSP_CTRL_DOWN));
}
}
return selected;
}
| 100oecfw | menu.c | C | gpl3 | 1,790 |
#include <pspsdk.h>
#include <pspkernel.h>
#include <string.h>
#include "conf.h"
int SE_GetConfig(SEConfig *config)
{
SceUID fd;
memset(config, 0, sizeof(SEConfig));
fd = sceIoOpen("ms0:/settings.txt", PSP_O_RDONLY, 0644);
if (fd < 0)
{
return -1;
}
if (sceIoRead(fd, config, sizeof(SEConfig)) < sizeof(SEConfig))
{
sceIoClose(fd);
return -1;
}
sceIoClose(fd);
return 0;
}
int SE_SetConfig(SEConfig *config)
{
sceIoRemove("ms0:/settings.txt");
SceUID fd = sceIoOpen("ms0:/settings.txt", PSP_O_WRONLY | PSP_O_CREAT | PSP_O_TRUNC, 0777);
if (fd < 0)
{
return -1;
}
config->magic = CONFIG_MAGIC;
if (sceIoWrite(fd, config, sizeof(SEConfig)) < sizeof(SEConfig))
{
sceIoClose(fd);
return -1;
}
sceIoClose(fd);
return 0;
}
| 100oecfw | conf.c | C | gpl3 | 820 |
#include <pspkernel.h>
#include <pspsdk.h>
#include <pspusb.h>
#include <pspusbstor.h>
#include <psploadexec_kernel.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "mydebug.h"
#include "menu.h"
#include "conf.h"
#include <pspreg.h>
PSP_MODULE_INFO("Recovery Modus", 0x1000, 1, 0);
PSP_MAIN_THREAD_ATTR(0);
#define printf myDebugScreenPrintf
#define RGB(r, g, b) (0xFF000000 | ((b)<<16) | ((g)<<8) | (r))
#define setTextColor myDebugScreenSetTextColor
#define setBackColor myDebugScreenSetBackColor
#define setXY myDebugScreenSetXY
#define delay sceKernelDelayThread
#define clearScreen myDebugScreenClear
SEConfig config;
int configchanged = 0;
int usbStatus = 0;
int usbModuleStatus = 0;
PspIoDrv *lflash_driver;
PspIoDrv *msstor_driver;
int get_registry_value(const char *dir, const char *name, unsigned int *val)
{
int ret = 0;
struct RegParam reg;
REGHANDLE h;
memset(®, 0, sizeof(reg));
reg.regtype = 1;
reg.namelen = strlen("/system");
reg.unk2 = 1;
reg.unk3 = 1;
strcpy(reg.name, "/system");
if(sceRegOpenRegistry(®, 2, &h) == 0)
{
REGHANDLE hd;
if(!sceRegOpenCategory(h, dir, 2, &hd))
{
REGHANDLE hk;
unsigned int type, size;
if(!sceRegGetKeyInfo(hd, name, &hk, &type, &size))
{
if(!sceRegGetKeyValue(hd, hk, val, 4))
{
ret = 1;
sceRegFlushCategory(hd);
}
}
sceRegCloseCategory(hd);
}
sceRegFlushRegistry(h);
sceRegCloseRegistry(h);
}
return ret;
}
int set_registry_value(const char *dir, const char *name, unsigned int val)
{
int ret = 0;
struct RegParam reg;
REGHANDLE h;
memset(®, 0, sizeof(reg));
reg.regtype = 1;
reg.namelen = strlen("/system");
reg.unk2 = 1;
reg.unk3 = 1;
strcpy(reg.name, "/system");
if(sceRegOpenRegistry(®, 2, &h) == 0)
{
REGHANDLE hd;
if(!sceRegOpenCategory(h, dir, 2, &hd))
{
if(!sceRegSetKeyValue(hd, name, &val, 4))
{
ret = 1;
sceRegFlushCategory(hd);
}
else
{
sceRegCreateKey(hd, name, REG_TYPE_INT, 4);
sceRegSetKeyValue(hd, name, &val, 4);
ret = 1;
sceRegFlushCategory(hd);
}
sceRegCloseCategory(hd);
}
sceRegFlushRegistry(h);
sceRegCloseRegistry(h);
}
return ret;
}
int ReadLine(SceUID fd, char *str)
{
char ch = 0;
int n = 0;
while (1)
{
if (sceIoRead(fd, &ch, 1) != 1)
return n;
if (ch < 0x20)
{
if (n != 0)
return n;
}
else
{
*str++ = ch;
n++;
}
}
}
int (* Orig_IoOpen)(PspIoDrvFileArg *arg, char *file, int flags, SceMode mode);
int (* Orig_IoClose)(PspIoDrvFileArg *arg);
int (* Orig_IoRead)(PspIoDrvFileArg *arg, char *data, int len);
int (* Orig_IoWrite)(PspIoDrvFileArg *arg, const char *data, int len);
SceOff(* Orig_IoLseek)(PspIoDrvFileArg *arg, SceOff ofs, int whence);
int (* Orig_IoIoctl)(PspIoDrvFileArg *arg, unsigned int cmd, void *indata, int inlen, void *outdata, int outlen);
int (* Orig_IoDevctl)(PspIoDrvFileArg *arg, const char *devname, unsigned int cmd, void *indata, int inlen, void *outdata, int outlen);
int unit;
/* 1.50 specific function */
PspIoDrv *FindDriver(char *drvname)
{
u32 *mod = (u32 *)sceKernelFindModuleByName("sceIOFileManager");
if (!mod)
{
return NULL;
}
u32 text_addr = *(mod+27);
u32 *(* GetDevice)(char *) = (void *)(text_addr+0x16D4);
u32 *u;
u = GetDevice(drvname);
if (!u)
{
return NULL;
}
return (PspIoDrv *)u[1];
}
static int New_IoOpen(PspIoDrvFileArg *arg, char *file, int flags, SceMode mode)
{
if (!lflash_driver->funcs->IoOpen)
return -1;
if (unit == 0)
file = "0,0";
else
file = "0,1";
return lflash_driver->funcs->IoOpen(arg, file, flags, mode);
}
static int New_IoClose(PspIoDrvFileArg *arg)
{
if (!lflash_driver->funcs->IoClose)
return -1;
return lflash_driver->funcs->IoClose(arg);
}
static int New_IoRead(PspIoDrvFileArg *arg, char *data, int len)
{
if (!lflash_driver->funcs->IoRead)
return -1;
return lflash_driver->funcs->IoRead(arg, data, len);
}
static int New_IoWrite(PspIoDrvFileArg *arg, const char *data, int len)
{
if (!lflash_driver->funcs->IoWrite)
return -1;
return lflash_driver->funcs->IoWrite(arg, data, len);
}
static SceOff New_IoLseek(PspIoDrvFileArg *arg, SceOff ofs, int whence)
{
if (!lflash_driver->funcs->IoLseek)
return -1;
return lflash_driver->funcs->IoLseek(arg, ofs, whence);
}
u8 data_5803[96] =
{
0x02, 0x00, 0x08, 0x00, 0x08, 0x00, 0x07, 0x9F, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x21, 0x21, 0x00, 0x00, 0x20, 0x01, 0x08, 0x00, 0x02, 0x00, 0x02, 0x00,
0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static int New_IoIoctl(PspIoDrvFileArg *arg, unsigned int cmd, void *indata, int inlen, void *outdata, int outlen)
{
if (cmd == 0x02125008)
{
u32 *x = (u32 *)outdata;
*x = 1; /* Enable writing */
return 0;
}
else if (cmd == 0x02125803)
{
memcpy(outdata, data_5803, 96);
return 0;
}
return -1;
}
static int New_IoDevctl(PspIoDrvFileArg *arg, const char *devname, unsigned int cmd, void *indata, int inlen, void *outdata, int outlen)
{
if (cmd == 0x02125801)
{
u8 *data8 = (u8 *)outdata;
data8[0] = 1;
data8[1] = 0;
data8[2] = 0,
data8[3] = 1;
data8[4] = 0;
return 0;
}
return -1;
}
void disableUsb(void)
{
if(usbStatus)
{
sceUsbDeactivate(0);
sceUsbStop(PSP_USBSTOR_DRIVERNAME, 0, 0);
sceUsbStop(PSP_USBBUS_DRIVERNAME, 0, 0);
msstor_driver->funcs->IoOpen = Orig_IoOpen;
msstor_driver->funcs->IoClose = Orig_IoClose;
msstor_driver->funcs->IoRead = Orig_IoRead;
msstor_driver->funcs->IoWrite = Orig_IoWrite;
msstor_driver->funcs->IoLseek = Orig_IoLseek;
msstor_driver->funcs->IoIoctl = Orig_IoIoctl;
msstor_driver->funcs->IoDevctl = Orig_IoDevctl;
usbStatus = 0;
}
}
void enableUsb(int device)
{
if (usbStatus)
{
disableUsb();
sceKernelDelayThread(300000);
}
if(!usbModuleStatus)
{
pspSdkLoadStartModule("ms0:/TM/150_340/kd/semawm.prx", PSP_MEMORY_PARTITION_KERNEL);
pspSdkLoadStartModule("ms0:/TM/150_340/kd/usbstor.prx", PSP_MEMORY_PARTITION_KERNEL);
pspSdkLoadStartModule("ms0:/TM/150_340/kd/usbstormgr.prx", PSP_MEMORY_PARTITION_KERNEL);
pspSdkLoadStartModule("ms0:/TM/150_340/kd/usbstorms.prx", PSP_MEMORY_PARTITION_KERNEL);
pspSdkLoadStartModule("ms0:/TM/150_340/kd/usbstorboot.prx", PSP_MEMORY_PARTITION_KERNEL);
lflash_driver = FindDriver("lflash");
msstor_driver = FindDriver("msstor");
Orig_IoOpen = msstor_driver->funcs->IoOpen;
Orig_IoClose = msstor_driver->funcs->IoClose;
Orig_IoRead = msstor_driver->funcs->IoRead;
Orig_IoWrite = msstor_driver->funcs->IoWrite;
Orig_IoLseek = msstor_driver->funcs->IoLseek;
Orig_IoIoctl = msstor_driver->funcs->IoIoctl;
Orig_IoDevctl = msstor_driver->funcs->IoDevctl;
usbModuleStatus = 1;
}
if (device != 0)
{
unit = device-1;
msstor_driver->funcs->IoOpen = New_IoOpen;
msstor_driver->funcs->IoClose = New_IoClose;
msstor_driver->funcs->IoRead = New_IoRead;
msstor_driver->funcs->IoWrite = New_IoWrite;
msstor_driver->funcs->IoLseek = New_IoLseek;
msstor_driver->funcs->IoIoctl = New_IoIoctl;
msstor_driver->funcs->IoDevctl = New_IoDevctl;
}
sceUsbStart(PSP_USBBUS_DRIVERNAME, 0, 0);
sceUsbStart(PSP_USBSTOR_DRIVERNAME, 0, 0);
sceUsbstorBootSetCapacity(0x800000);
sceUsbActivate(0x1c8);
usbStatus = 1;
}
#define PROGRAM "ms0:/PSP/GAME/RECOVERY/EBOOT.PBP"
char hide[64], game[64], bootprog[64], noumd[64], region[64];
char patch[128], bootbin[128], isofs[128], usevshmenu[64];
char plugins[11][64];
char vshspeed[64], umdspeed[64], usemp3[64], usescreen[64];
char freereg[64];
char *plugins_p[16];
u8 plugcon[15];
char button[50];
int nvsh = 0, ngame = 0, npops = 0;
char *regions[12] =
{
"Aus",
"Japan",
"Amerika",
"Europa",
"China",
"Polen",
"Deutschland",
"Australien/Neu Seeland",
"Polen",
"Danizig",
"Kommunistia",
""
};
int main(void) {
myDebugScreenInit();
char *items[] = { "USB Verbindung", "Konfiguration -> ", "Starte Programm -> /PSP/GAME/RECOVERY/EBOOT.PBP", "Erweitert -> ", "CPU Geschwindigkeit ->", "Plugins ->", "Registrierungs Hacks ->", "Beenden", 0 };
char *mainmsg = "Haupt Menu";
char *advitems[] = { "Zurueck", "Erweiterte Konfiguration -> ", "USB Verbindung [Flash0]", "USB Verbindung [Flash1]" };
char *advmsg = "Erweitert";
char *conitems[] = { "Zurueck", "", "", "", "", "", "", "", "", "" };
char *conmsg = "Konfiguration";
char *adconitems[] = { "Zurueck", "", "", "","", "" };
char *speeditems[] = { "Zuruek", "", "", "" };
char *regitems[] = { "Zurueck", "", "Aktiviere WMA", "Aktiviere Flash Player" };
int p = 1, u, o;
int oldselection;
//ReassignFlash0();
//myDebugScreenSetBackColor(RGB(164, 0, 164));
myDebugScreenSetBackColor(RGB(0, 255, 255));
while(p)
{
clearScreen();
int result;
result = doMenu(items, 8, 0, mainmsg, 0, 6);
if(result == 0) {
if(!usbStatus) {
printf(" > USB Verbunden"); enableUsb(0); delay(1000000);
} else {
printf(" > USB nicht mehr Verbunden"); disableUsb(); delay(1000000);
}
}
if(result == 3)
{
u = 1;
while(u)
{
clearScreen();
result = doMenu(advitems, 4, 0, advmsg, 0, 6);
if(result == 0)
{
printf(" > Zurueck...");
disableUsb();
delay(1000000);
u = 0;
}
else if (result == 3)
{
if(!usbStatus)
{
printf(" > USB Verbunden"); enableUsb(2); delay(1000000);
} else {
printf(" > USB nicht mehr Verbunden"); disableUsb(); delay(1000000);
}
}
else if (result == 2)
{
if(!usbStatus)
{
printf(" > USB Verbunden"); enableUsb(1); delay(1000000);
} else {
printf(" > USB nicht mehr Verbunden"); disableUsb(); delay(1000000);
}
}
else if (result == 1)
{
while (1)
{
clearScreen();
if (!configchanged)
{
SE_GetConfig(&config);
}
sprintf(patch, "Module in UMD/ISO (Derzeit: %s)", config.umdactivatedplaincheck ? "Benuzt" : "Unbenuzt");
sprintf(bootbin, "BOOT.BIN in UMD/ISO (Derzeit: %s)", config.executebootbin ? "Benuzt" : "Unbenuzt");
sprintf(isofs, "Isofs Treiber in UMD-inserted mode (Derzeit: %s)", config.useisofsonumdinserted ? "Benuzt" : "Unbenuzt");
adconitems[1] = patch;
adconitems[2] = bootbin;
adconitems[3] = isofs;
result = doMenu(adconitems, 4, 0, "Erweiterte Konfiguration", 0, 6);
if (result != 0 && result != -1)
{
if (!configchanged)
{
configchanged = 1;
}
}
if(result == 0) { printf(" > Zurueck..."); delay(1000000); break; }
if (result == 1)
{
config.umdactivatedplaincheck = !config.umdactivatedplaincheck;
printf(" > Module in UMD/ISO: %s", config.umdactivatedplaincheck ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if (result == 2)
{
config.executebootbin = !config.executebootbin;
printf(" > BOOT.BIN in UMD/ISO: %s", config.executebootbin ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if (result == 3)
{
config.useisofsonumdinserted = !config.useisofsonumdinserted;
printf(" > UMD-Eingelegtem Modus: %s", config.useisofsonumdinserted ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
}
}
}
}
if(result == 1)
{
o = 1;
oldselection = 0;
while(o)
{
char skip[96];
clearScreen();
if (!configchanged)
{
SE_GetConfig(&config);
}
sprintf(skip, "Sony Copmputer Entertaiment Logo (Derzeit: %s)", config.skiplogo ? "Benuzt" : "Unbenuzt");
sprintf(hide, "Verstecke Defekte ICONS (Derzeit: %s)", config.hidecorrupt ? "Benuzt" : "Unbenuzt");
sprintf(usevshmenu, "Benutze VSH Menu (Derzeit %s)", config.usevshmenu ? "Benutzt" : "Unbenutzt");
sprintf(usemp3, "Benutze MP3 Plugin (Derzeit: %s)", config.usemp3 ? "Benuzt" : "Unbenuzt");
sprintf(noumd, "Benutze NO-UMD (Derzeit: %s)", config.usenoumd ? "Benuzt" : "Unbenuzt");
sprintf(usescreen, "Benutze ScreenShoot Plugin (Derzeit: %s)", config.usescreen ? "Benuzt" : "Unbenuzt");
sprintf(bootprog, "Autostart -> /PSP/GAME/BOOT/EBOOT.PBP (Derzeit: %s)", config.startupprog ? "Benuzt" : "Unbenuzt");
if (config.fakeregion > 12)
config.fakeregion = 0;
sprintf(region, "Falsche Region (Derzeit: %s)", regions[config.fakeregion]);
sprintf(freereg, "Freie UMD Region (Derzeit: %s)", config.freeumdregion ? "Enabled" : "Unbenuzt");
conitems[1] = skip;
conitems[2] = hide;
conitems[3] = bootprog;
conitems[4] = noumd;
conitems[5] = region;
conitems[6] = freereg;
conitems[7] = usevshmenu;
conitems[8] = usemp3;
conitems[9] = usescreen;
result = doMenu(conitems, 10, oldselection, conmsg, 0, 6);
if (result != 0 && result != -1)
{
if (!configchanged)
{
configchanged = 1;
}
}
if(result == 0) { printf(" > Zurueck..."); delay(1000000); o = 0; }
else if(result == 1)
{
config.skiplogo = !config.skiplogo;
printf(" > SCE logo: %s", (config.skiplogo) ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if(result == 2)
{
config.hidecorrupt = !config.hidecorrupt;
printf(" > Verstecke Defekte icons: %s", (config.hidecorrupt) ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if (result == 3)
{
config.startupprog = !config.startupprog;
printf(" > Autstart Programm -> /PSP/GAME/BOOT/EBOOT.PBP: %s", (config.startupprog) ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if (result == 4)
{
config.usenoumd = !config.usenoumd;
printf(" > Benutze NO-UMD: %s", (config.usenoumd) ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if (result == 5)
{
config.freeumdregion = !config.freeumdregion;
printf(" > Freie UMD Region: %s", (config.freeumdregion) ? "Benuzt" : "Unbenuzt");
delay(1100000);
}
else if (result == 6)
{
config.usevshmenu = !config.usevshmenu;
printf(" > Benutze VSH Menu : %s", (config.usevshmenu) ? "Benutzt" : "Unbenutzt");
delay(1100000);
}
else if (result == 7)
{
config.usemp3 = !config.usemp3;
printf(" > Benutze MP3 Plugin : %s", (config.usemp3) ? "Benutzt" : "Unbenutzt");
delay(1100000);
}
else if (result == 8)
{
config.usescreen = !config.usescreen;
printf(" > Benutze ScreenShoot Plugin : %s", (config.usescreen) ? "Benutzt" : "Unbenutzt");
delay(1100000);
}
if (result == 6)
{
config.fakeregion++;
if (config.fakeregion == FAKE_REGION_KOREA)
config.fakeregion = FAKE_REGION_AUSTRALIA;
else if (config.fakeregion == FAKE_REGION_HONGKONG)
config.fakeregion = FAKE_REGION_RUSSIA;
else if (config.fakeregion == FAKE_REGION_CHINA)
config.fakeregion = FAKE_REGION_DISABLED;
oldselection = 6;
delay(300000);
}
else if (result != -1)
{
oldselection = 0;
}
}
}
if (result == 2)
{
struct SceKernelLoadExecVSHParam param;
pspSdkLoadStartModule("ms0:/TM/150_340/kd/eg_screen.prx", PSP_MEMORY_PARTITION_KERNEL);
memset(¶m, 0, sizeof(param));
param.size = sizeof(param);
param.args = strlen(PROGRAM)+1;
param.argp = PROGRAM;
param.key = "updater";
sceKernelLoadExecVSHMs1(PROGRAM, ¶m);
}
if (result == 4)
{
oldselection = 0;
while (1)
{
clearScreen();
/*doMenu(speeditems, 1, 0, "CPU Speed", 2, 6);
delay(1000000);
break; */
if (!configchanged)
{
SE_GetConfig(&config);
}
if (config.vshcpuspeed != 333 && config.vshcpuspeed != 266
&& config.vshcpuspeed != 222 && config.vshcpuspeed != 300
&& config.vshcpuspeed != 0)
{
config.vshcpuspeed = 0;
configchanged = 1;
}
if (config.vshbusspeed != 166 && config.vshbusspeed != 133 &&
config.vshbusspeed != 111 && config.vshbusspeed != 150)
{
config.vshbusspeed = 0;
configchanged = 1;
}
if (config.umdisocpuspeed != 333 && config.umdisocpuspeed != 266
&& config.umdisocpuspeed != 222 && config.umdisocpuspeed != 300
&& config.umdisocpuspeed != 0)
{
config.umdisocpuspeed = 0;
configchanged = 1;
}
if (config.umdisobusspeed != 166 && config.umdisobusspeed != 133 &&
config.umdisobusspeed != 111 && config.umdisobusspeed != 150)
{
config.umdisobusspeed = 0;
configchanged = 1;
}
sprintf(vshspeed, "CPU Geschwindigkeit in XMB (Derzeit: %d)", config.vshcpuspeed);
sprintf(umdspeed, "CPU Geschwindigkeit in UMD/ISO (Derzeit: %d)", config.umdisocpuspeed);
if (config.vshcpuspeed == 0)
{
strcpy(vshspeed+strlen(vshspeed)-2, "Normal)");
}
if (config.umdisocpuspeed == 0)
{
strcpy(umdspeed+strlen(umdspeed)-2, "Normal)");
}
speeditems[1] = vshspeed;
speeditems[2] = umdspeed;
result = doMenu(speeditems, 3, oldselection, "CPU Geschwindigkeit", 5, 6);
if (result != 0)
{
if (!configchanged)
configchanged = 1;
}
if(result == 0)
{
printf(" > Zurueck...");
delay(1000000);
break;
}
else if (result == 1)
{
if (config.vshcpuspeed == 0)
{
config.vshcpuspeed = 222;
config.vshbusspeed = 111;
}
else if (config.vshcpuspeed == 222)
{
config.vshcpuspeed = 266;
config.vshbusspeed = 133;
}
else if (config.vshcpuspeed == 266)
{
config.vshcpuspeed = 300;
config.vshbusspeed = 150;
}
else if (config.vshcpuspeed == 300)
{
config.vshcpuspeed = 333;
config.vshbusspeed = 166;
}
else if (config.vshcpuspeed == 333)
{
config.vshcpuspeed = 0;
config.vshbusspeed = 0;
}
sprintf(vshspeed, "CPU Geschwindigkeit in XMB: %d", config.vshcpuspeed);
if (config.vshcpuspeed == 0)
{
strcpy(vshspeed+strlen(vshspeed)-1, "Normal");
}
printf("%s", vshspeed);
oldselection = 1;
delay(1100000);
}
else if (result == 2)
{
if (config.umdisocpuspeed == 0)
{
config.umdisocpuspeed = 222;
config.umdisobusspeed = 111;
}
else if (config.umdisocpuspeed == 222)
{
config.umdisocpuspeed = 266;
config.umdisobusspeed = 133;
}
else if (config.umdisocpuspeed == 266)
{
config.umdisocpuspeed = 300;
config.umdisobusspeed = 150;
}
else if (config.umdisocpuspeed == 300)
{
config.umdisocpuspeed = 333;
config.umdisobusspeed = 166;
}
else if (config.umdisocpuspeed == 333)
{
config.umdisocpuspeed = 0;
config.umdisobusspeed = 0;
}
sprintf(umdspeed, "CPU Geschwindigkeit in UMD/ISO: %d", config.umdisocpuspeed);
if (config.umdisocpuspeed == 0)
{
strcpy(umdspeed+strlen(umdspeed)-1, "Normal");
}
printf("%s", umdspeed);
oldselection = 2;
delay(1100000);
}
}
}
if (result == 5)
{
while (1)
{
clearScreen();
SceUID fd;
int i;
char *p;
ngame = 0;
nvsh = 0;
npops = 0;
memset(plugcon, 0, 15);
fd = sceIoOpen("ms0:/PLUGINS/settings.txt", PSP_O_RDONLY, 0777);
sceIoRead(fd, plugcon, 15);
sceIoClose(fd);
memset(plugins, 0, sizeof(plugins));
fd= sceIoOpen("ms0:/PLUGINS/vsh.txt", PSP_O_RDONLY, 0777);
if (fd >= 0)
{
for (i = 0; i < 5; i++)
{
if (ReadLine(fd, plugins[i+1]) > 0)
{
p = strrchr(plugins[i+1], '/');
if (p)
{
strcpy(plugins[i+1], p+1);
}
strcat(plugins[i+1], " [VSH]");
nvsh++;
}
else
{
break;
}
}
sceIoClose(fd);
}
fd = sceIoOpen("ms0:/PLUGINS/game.txt", PSP_O_RDONLY, 0777);
if (fd >= 0)
{
for (i = 0; i < 5; i++)
{
if (ReadLine(fd, plugins[i+nvsh+1]) > 0)
{
p = strrchr(plugins[i+nvsh+1], '/');
if (p)
{
strcpy(plugins[i+nvsh+1], p+1);
}
strcat(plugins[i+nvsh+1], " [GAME]");
ngame++;
}
else
{
break;
}
}
sceIoClose(fd);
}
fd = sceIoOpen("ms0:/PLUGINS/POPS.txt", PSP_O_RDONLY, 0777);
if (fd >= 0)
{
for (i = 0; i < 5; i++)
{
if (ReadLine(fd, plugins[i+nvsh+ngame+1]) > 0)
{
p = strrchr(plugins[i+nvsh+ngame+1], '/');
if (p)
{
strcpy(plugins[i+nvsh+ngame+1], p+1);
}
strcat(plugins[i+nvsh+ngame+1], " [POPS]");
npops++;
}
else
{
break;
}
}
sceIoClose(fd);
}
strcpy(plugins[0], "Zurueck");
for (i = 0; i < (ngame+nvsh+npops+1); i++)
{
if (i != 0)
strcat(plugins[i], (plugcon[i-1]) ? " (Benuzt) " : " (Unbenuzt)");
plugins_p[i] = plugins[i];
}
result = doMenu(plugins_p, ngame+nvsh+npops+1, 0, "Plugins", 0, 7);
if(result == 0) { printf(" > Zurueck..."); delay(1000000); break; }
else if (result != -1)
{
char str[256];
strcpy(str, plugins_p[result]);
str[strlen(str)-11] = 0;
plugcon[result-1] = !plugcon[result-1];
if (plugcon[result-1])
strcat(str, ": Benuzt");
else
strcat(str, ": Unbenuzt");
printf(str);
SceUID fd = sceIoOpen("ms0:/PLUGINS/settings.txt", PSP_O_WRONLY | PSP_O_CREAT | PSP_O_TRUNC, 0777);
sceIoWrite(fd, plugcon, sizeof(plugcon));
sceIoClose(fd);
delay(900000);
}
}
}
if (result == 6)
{
while (1)
{
unsigned int value = 0;
clearScreen();
strcpy(button, "Benuzen Button (Derzeit: ");
get_registry_value("/CONFIG/SYSTEM/XMB", "button_assign", &value);
if (value == 0)
{
strcat(button, "O ist Benuzen)");
}
else
{
strcat(button, "X ist Benuzen)");
}
regitems[1] = button;
result = doMenu(regitems, 4, 0, "Registrierungs Hacks", 2, 6);
if(result == 0)
{
printf(" > Zurueck...");
delay(800000);
break;
}
else if (result == 1)
{
value = !value;
set_registry_value("/CONFIG/SYSTEM/XMB", "button_assign", value);
strcpy(button, " > Benuzen Button: ");
if (value == 0)
{
strcat(button, "O ist Benuzen");
}
else
{
strcat(button, "X ist Benuzen");
}
printf("%s", button);
delay(1000000);
}
else if (result == 2)
{
get_registry_value("/CONFIG/MUSIC", "wma_play", &value);
if (value == 1)
{
printf("WMA ist bereits Aktiviert.");
}
else
{
printf("Aktiviere WMA...\n");
set_registry_value("/CONFIG/MUSIC", "wma_play", 1);
}
delay(1000000);
}
else if (result == 3)
{
get_registry_value("/CONFIG/BROWSER", "flash_activated", &value);
if (value == 1)
{
printf("Flash player ist bereits Aktiviert.\n");
}
else
{
printf("Aktiviere Flash Player...");
set_registry_value("/CONFIG/BROWSER", "flash_activated", 1);
set_registry_value("/CONFIG/BROWSER", "flash_play", 1);
}
delay(1000000);
}
}
}
if(result == 7)
{
printf(" > Beende Recovery Menu");
delay(700000);
if (configchanged)
SE_SetConfig(&config);
sceKernelExitVSHVSH(NULL);
}
}
return 0;
}
| 100oecfw | main.c | C | gpl3 | 25,744 |
#ifndef INCLUDED_MENU
#define INCLUDED_MENU
int doMenu(char* picks[], int count, int selected, char* message, int x, int y);
#endif
| 100oecfw | menu.h | C | gpl3 | 134 |
/*****************************************
* Recovery - mydebug *
* by EG-Dev TEam *
*****************************************/
#ifndef __MYDEBUG_H__
#define __MYDEBUG_H__
#include <psptypes.h>
#include <pspmoduleinfo.h>
#ifdef __cplusplus
extern "C" {
#endif
void myDebugScreenInit(void);
void myDebugScreenPrintf(const char *fmt, ...) __attribute__((format(printf,1,2)));
void myDebugScreenSetBackColor(u32 color);
void myDebugScreenSetTextColor(u32 color);
void myDebugScreenPutChar(int x, int y, u32 color, u8 ch);
void myDebugScreenSetXY(int x, int y);
void myDebugScreenSetOffset(int offset);
int myDebugScreenGetX(void);
int myDebugScreenGetY(void);
void myDebugScreenClear(void);
int myDebugScreenPrintData(const char *buff, int size);
#ifdef __cplusplus
}
#endif
#endif
| 100oecfw | mydebug.h | C | gpl3 | 806 |
#include <stdio.h>
#include <psptypes.h>
#include <pspkernel.h>
#include <pspdisplay.h>
#include <pspge.h>
#include <stdarg.h>
#include <pspdebug.h>
#define PSP_SCREEN_WIDTH 480
#define PSP_SCREEN_HEIGHT 272
#define PSP_LINE_SIZE 512
#define PSP_PIXEL_FORMAT 3
static int X = 0, Y = 0;
static int MX=68, MY=34;
static u32 bg_col = 0xFFFFFFFF, fg_col = 0;
static u32* g_vram_base = (u32 *) 0x04000000;
static int g_vram_offset = 0;
static int init = 0;
static void clear_screen(u32 color)
{
int x;
u32 *vram = g_vram_base + (g_vram_offset>>2);
for(x = 0; x < (PSP_LINE_SIZE * PSP_SCREEN_HEIGHT); x++)
{
*vram++ = color;
}
}
void myDebugScreenInit()
{
X = Y = 0;
/* Place vram in uncached memory */
g_vram_base = (void *) (0x40000000 | (u32) sceGeEdramGetAddr());
g_vram_offset = 0;
sceDisplaySetMode(0, PSP_SCREEN_WIDTH, PSP_SCREEN_HEIGHT);
sceDisplaySetFrameBuf((void *) g_vram_base, PSP_LINE_SIZE, PSP_PIXEL_FORMAT, 1);
clear_screen(bg_col);
init = 1;
}
void myDebugScreenSetBackColor(u32 colour)
{
bg_col = colour;
}
void myDebugScreenSetTextColor(u32 colour)
{
fg_col = colour;
}
extern u8 msx[];
void
myDebugScreenPutChar( int x, int y, u32 color, u8 ch)
{
int i,j, l;
u8 *font;
u32 pixel;
u32 *vram_ptr;
u32 *vram;
if(!init)
{
return;
}
vram = g_vram_base + (g_vram_offset>>2) + x;
vram += (y * PSP_LINE_SIZE);
font = &msx[ (int)ch * 8];
for (i=l=0; i < 8; i++, l+= 8, font++)
{
vram_ptr = vram;
for (j=0; j < 8; j++)
{
if ((*font & (128 >> j)))
pixel = color;
else
pixel = bg_col;
*vram_ptr++ = pixel;
}
vram += PSP_LINE_SIZE;
}
}
static void clear_line( int Y)
{
int i;
for (i=0; i < MX; i++)
myDebugScreenPutChar( i*7 , Y * 8, bg_col, 219);
}
/* Print non-nul terminated strings */
int myDebugScreenPrintData(const char *buff, int size)
{
int i;
int j;
char c;
for (i = 0; i < size; i++)
{
c = buff[i];
switch (c)
{
case '\n':
X = 0;
Y ++;
if (Y == MY)
Y = 0;
clear_line(Y);
break;
case '\t':
for (j = 0; j < 5; j++) {
myDebugScreenPutChar( X*7 , Y * 8, fg_col, ' ');
X++;
}
break;
default:
myDebugScreenPutChar( X*7 , Y * 8, fg_col, c);
X++;
if (X == MX)
{
X = 0;
Y++;
if (Y == MY)
Y = 0;
clear_line(Y);
}
}
}
return i;
}
void myDebugScreenPrintf(const char *format, ...)
{
va_list opt;
char buff[2048];
int bufsz;
if(!init)
{
return;
}
va_start(opt, format);
bufsz = vsnprintf( buff, (size_t) sizeof(buff), format, opt);
(void) myDebugScreenPrintData(buff, bufsz);
}
void myDebugScreenSetXY(int x, int y)
{
if( x<MX && x>=0 ) X=x;
if( y<MY && y>=0 ) Y=y;
}
void myDebugScreenSetOffset(int offset)
{
g_vram_offset = offset;
}
int myDebugScreenGetX()
{
return X;
}
int myDebugScreenGetY()
{
return Y;
}
void myDebugScreenClear()
{
int y;
if(!init)
{
return;
}
for(y=0;y<MY;y++)
clear_line(y);
myDebugScreenSetXY(0,0);
clear_screen(bg_col);
}
| 100oecfw | mydebug.c | C | gpl3 | 4,459 |
#include <limits.h>
#include "matrix.h"
#include "/home/seecs/Downloads/APLab2/AAR_lab2/Sources/gtest-1.7.0/include/gtest/gtest.h"
TEST(AddTest, Blah) {
int test_arr1[5][5] = {{1,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1}};
int test_arr2[5][5] = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int expt_arr[5][5] = {{2,3,4,5,6},{2,3,4,5,6},{2,3,4,5,6},{2,3,4,5,6},{2,3,4,5,6}};
matrix_manipulation a;
int** result= a.m_add(test_arr1,test_arr2);
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
EXPECT_EQ(result[i][j], expt_arr[i][j]);
}
}
}
TEST(SUBTRACTTest, Blah) {
int test_arr1[5][5] = {{1,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1},{1,1,1,1,1}};
int test_arr2[5][5] = {{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3},{3,3,3,3,3}};
int expt_arr[5][5] = {{2,2,2,2,2},{2,2,2,2,2},{2,2,2,2,2},{2,2,2,2,2},{2,2,2,2,2}};
matrix_manipulation a;
int** result= a.m_subtract(test_arr2,test_arr1);
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
EXPECT_EQ(result[i][j], expt_arr[i][j]);
}
}
}
TEST(MULTIPLYTest, Blah) {
int test_arr1[5][5] = {{2,2,2,2,2},{2,2,2,2,2},{2,2,2,2,2},{2,2,2,2,2},{2,2,2,2,2}};
int test_arr2[5][5] = {{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int expt_arr[5][5] = {{10,20,30,40,50},{10,20,30,40,50},{10,20,30,40,50},{10,20,30,40,50},{10,20,30,40,50}};
matrix_manipulation a;
int** result= a.m_multiply(test_arr1,test_arr2);
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
EXPECT_EQ(result[i][j], expt_arr[i][j]);
}
}
}
| 02019-aar-ap-lab1 | trunk/source-files/matrix_unittest.cc | C++ | oos | 1,554 |
#include <iostream>
using namespace std;
// matrix size is fixed to 5x5
class matrix_manipulation {
private:
int** result;
public:
matrix_manipulation();
int** m_add (int m1[5][5], int m2[5][5]);
int** m_subtract (int m1[5][5], int m2[5][5]);
int** m_multiply (int m1[5][5], int m2[5][5]);
};
| 02019-aar-ap-lab1 | trunk/source-files/matrix.h | C++ | oos | 304 |
#include "matrix.h"
matrix_manipulation::matrix_manipulation() {
result = new int*[5];
for (int i = 0; i < 5; i++) {
result[i] = new int[5];
for (int j = 0; j < 5; j++) {
result[i][j] = 0;
}
}
}
int** matrix_manipulation::m_add (int m1[5][5], int m2[5][5]) {
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
result[i][j] = m1[i][j]+m2[i][j];
cout << result[i][j] << " ";
}
cout << "\n";
}
return result;
}
int** matrix_manipulation::m_subtract (int m1[5][5], int m2[5][5]) {
for (int i=0; i<5; i++) {
for (int j=0; j<5; j++) {
result[i][j] = m1[i][j]-m2[i][j];
cout << result[i][j] << " ";
}
cout << "\n";
}
return result;
}
int** matrix_manipulation::m_multiply (int m1[5][5], int m2[5][5]) {
for (int row = 0; row < 5; row++) {
for (int col = 0; col < 5; col++) {
result[row][col] = 0;
for (int inner = 0; inner < 5; inner++) {
result[row][col] += m1[row][inner] * m2[inner][col];
}
cout << result[row][col] << " ";
}
cout << "\n";
}
return result;
}
| 02019-aar-ap-lab1 | trunk/source-files/matrix.cpp | C++ | oos | 1,093 |
#!/system/bin/sh
DIR=/data/data/org.sshtunnel
PATH=$DIR:$PATH
case $1 in
start)
echo "
base {
log_debug = off;
log_info = off;
log = stderr;
daemon = on;
redirector = iptables;
}
" >$DIR/redsocks.conf
echo "
redsocks {
local_ip = 127.0.0.1;
local_port = 8123;
ip = 127.0.0.1;
port = $2;
type = http-relay;
}
redsocks {
local_ip = 127.0.0.1;
local_port = 8124;
ip = 127.0.0.1;
port = $2;
type = http-connect;
}
" >>$DIR/redsocks.conf
$DIR/redsocks -p $DIR/redsocks.pid -c $DIR/redsocks.conf
;;
stop)
kill -9 `cat $DIR/redsocks.pid`
rm $DIR/redsocks.pid
rm $DIR/redsocks.conf
;;
esac
| 07pratik-myssh | assets/proxy_http.sh | Shell | gpl3 | 633 |
#!/system/bin/sh
DIR=/data/data/org.sshtunnel
PATH=$DIR:$PATH
case $1 in
start)
echo "
base {
log_debug = off;
log_info = off;
log = stderr;
daemon = on;
redirector = iptables;
}
" >$DIR/redsocks.conf
echo "
redsocks {
local_ip = 127.0.0.1;
local_port = 8123;
ip = 127.0.0.1;
port = $2;
type = socks5;
}
" >>$DIR/redsocks.conf
$DIR/redsocks -p $DIR/redsocks.pid -c $DIR/redsocks.conf
;;
stop)
kill -9 `cat $DIR/redsocks.pid`
rm $DIR/redsocks.pid
rm $DIR/redsocks.conf
;;
esac
| 07pratik-myssh | assets/proxy_socks.sh | Shell | gpl3 | 522 |
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);
}
}
}
}
| 07pratik-myssh | src/org/sshtunnel/db/DatabaseHelper.java | Java | gpl3 | 3,593 |
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();
}
}
| 07pratik-myssh | src/org/sshtunnel/db/ProfileFactory.java | Java | gpl3 | 7,394 |