answer
stringlengths 17
10.2M
|
|---|
/* @java.file.header */
package org.gridgain.grid.kernal.processors.cache.distributed.dht.atomic;
import org.gridgain.grid.*;
import org.gridgain.grid.cache.*;
import org.gridgain.grid.kernal.processors.cache.*;
import org.gridgain.grid.kernal.processors.cache.distributed.dht.*;
import org.gridgain.grid.kernal.processors.cache.distributed.dht.preloader.*;
import org.gridgain.grid.kernal.processors.cache.distributed.near.*;
import org.gridgain.grid.kernal.processors.cache.dr.*;
import org.gridgain.grid.kernal.processors.dr.*;
import org.gridgain.grid.kernal.processors.timeout.*;
import org.gridgain.grid.kernal.processors.version.*;
import org.gridgain.grid.lang.*;
import org.gridgain.grid.product.*;
import org.gridgain.grid.security.*;
import org.gridgain.grid.util.*;
import org.gridgain.grid.util.future.*;
import org.gridgain.grid.util.lang.*;
import org.gridgain.grid.util.tostring.*;
import org.gridgain.grid.util.typedef.*;
import org.gridgain.grid.util.typedef.internal.*;
import org.gridgain.portable.*;
import org.jdk8.backport.*;
import org.jetbrains.annotations.*;
import sun.misc.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import static org.gridgain.grid.GridSystemProperties.*;
import static org.gridgain.grid.cache.GridCacheAtomicWriteOrderMode.*;
import static org.gridgain.grid.cache.GridCachePeekMode.*;
import static org.gridgain.grid.cache.GridCacheWriteSynchronizationMode.*;
import static org.gridgain.grid.kernal.processors.cache.GridCacheOperation.*;
import static org.gridgain.grid.kernal.processors.cache.GridCacheUtils.*;
import static org.gridgain.grid.kernal.processors.dr.GridDrType.*;
import static org.gridgain.grid.util.direct.GridTcpCommunicationMessageAdapter.*;
/**
* Non-transactional partitioned cache.
*/
@GridToStringExclude
public class GridDhtAtomicCache<K, V> extends GridDhtCacheAdapter<K, V> {
/** Version where FORCE_TRANSFORM_BACKUP flag was introduced. */
public static final GridProductVersion FORCE_TRANSFORM_BACKUP_SINCE = GridProductVersion.fromString("6.1.2");
private static final long serialVersionUID = 0L;
/** Deferred update response buffer size. */
private static final int DEFERRED_UPDATE_RESPONSE_BUFFER_SIZE =
Integer.getInteger(GG_ATOMIC_DEFERRED_ACK_BUFFER_SIZE, 256);
/** Deferred update response timeout. */
private static final int DEFERRED_UPDATE_RESPONSE_TIMEOUT =
Integer.getInteger(GG_ATOMIC_DEFERRED_ACK_TIMEOUT, 500);
/** Unsafe instance. */
private static final Unsafe UNSAFE = GridUnsafe.unsafe();
/** Update reply closure. */
private CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> updateReplyClos;
/** Pending */
private ConcurrentMap<UUID, DeferredResponseBuffer> pendingResponses = new ConcurrentHashMap8<>();
private GridNearAtomicCache<K, V> near;
/**
* Empty constructor required by {@link Externalizable}.
*/
public GridDhtAtomicCache() {
// No-op.
}
/**
* @param ctx Cache context.
*/
public GridDhtAtomicCache(GridCacheContext<K, V> ctx) {
super(ctx);
}
/**
* @param ctx Cache context.
* @param map Cache concurrent map.
*/
public GridDhtAtomicCache(GridCacheContext<K, V> ctx, GridCacheConcurrentMap<K, V> map) {
super(ctx, map);
}
/** {@inheritDoc} */
@Override public boolean isDhtAtomic() {
return true;
}
/** {@inheritDoc} */
@Override protected void init() {
map.setEntryFactory(new GridCacheMapEntryFactory<K, V>() {
/** {@inheritDoc} */
@Override public GridCacheMapEntry<K, V> create(GridCacheContext<K, V> ctx, long topVer, K key, int hash,
V val, GridCacheMapEntry<K, V> next, long ttl, int hdrId) {
return new GridDhtAtomicCacheEntry<>(ctx, topVer, key, hash, val, next, ttl, hdrId);
}
});
updateReplyClos = new CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>>() {
@Override public void apply(GridNearAtomicUpdateRequest<K, V> req, GridNearAtomicUpdateResponse<K, V> res) {
if (ctx.config().getAtomicWriteOrderMode() == CLOCK) {
// Always send reply in CLOCK ordering mode.
sendNearUpdateReply(res.nodeId(), res);
return;
}
// Request should be for primary keys only in PRIMARY ordering mode.
assert req.hasPrimary();
if (req.writeSynchronizationMode() != FULL_ASYNC)
sendNearUpdateReply(res.nodeId(), res);
else {
if (!F.isEmpty(res.remapKeys()))
// Remap keys on primary node in FULL_ASYNC mode.
remapToNewPrimary(req);
else if (res.error() != null) {
U.error(log, "Failed to process write update request in FULL_ASYNC mode for keys: " +
res.failedKeys(), res.error());
}
}
}
};
}
/** {@inheritDoc} */
@SuppressWarnings({"IfMayBeConditional", "SimplifiableIfStatement"})
@Override public void start() throws GridException {
resetMetrics();
preldr = new GridDhtPreloader<>(ctx);
preldr.start();
ctx.io().addHandler(GridNearGetRequest.class, new CI2<UUID, GridNearGetRequest<K, V>>() {
@Override public void apply(UUID nodeId, GridNearGetRequest<K, V> req) {
processNearGetRequest(nodeId, req);
}
});
ctx.io().addHandler(GridNearAtomicUpdateRequest.class, new CI2<UUID, GridNearAtomicUpdateRequest<K, V>>() {
@Override public void apply(UUID nodeId, GridNearAtomicUpdateRequest<K, V> req) {
processNearAtomicUpdateRequest(nodeId, req);
}
});
ctx.io().addHandler(GridNearAtomicUpdateResponse.class, new CI2<UUID, GridNearAtomicUpdateResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridNearAtomicUpdateResponse<K, V> res) {
processNearAtomicUpdateResponse(nodeId, res);
}
});
ctx.io().addHandler(GridDhtAtomicUpdateRequest.class, new CI2<UUID, GridDhtAtomicUpdateRequest<K, V>>() {
@Override public void apply(UUID nodeId, GridDhtAtomicUpdateRequest<K, V> req) {
processDhtAtomicUpdateRequest(nodeId, req);
}
});
ctx.io().addHandler(GridDhtAtomicUpdateResponse.class, new CI2<UUID, GridDhtAtomicUpdateResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridDhtAtomicUpdateResponse<K, V> res) {
processDhtAtomicUpdateResponse(nodeId, res);
}
});
ctx.io().addHandler(GridDhtAtomicDeferredUpdateResponse.class,
new CI2<UUID, GridDhtAtomicDeferredUpdateResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridDhtAtomicDeferredUpdateResponse<K, V> res) {
processDhtAtomicDeferredUpdateResponse(nodeId, res);
}
});
if (near == null) {
ctx.io().addHandler(GridNearGetResponse.class, new CI2<UUID, GridNearGetResponse<K, V>>() {
@Override public void apply(UUID nodeId, GridNearGetResponse<K, V> res) {
processNearGetResponse(nodeId, res);
}
});
}
}
/** {@inheritDoc} */
@Override public void resetMetrics() {
boolean isDrSndCache = cacheCfg.getDrSenderConfiguration() != null;
boolean isDrRcvCache = cacheCfg.getDrReceiverConfiguration() != null;
GridCacheMetricsAdapter m = new GridCacheMetricsAdapter(isDrSndCache, isDrRcvCache);
if (ctx.dht().near() != null)
m.delegate(ctx.dht().near().metrics0());
metrics = m;
}
/**
* @param near Near cache.
*/
public void near(GridNearAtomicCache<K, V> near) {
this.near = near;
}
/** {@inheritDoc} */
@Override public GridNearCacheAdapter<K, V> near() {
return near;
}
/** {@inheritDoc} */
@Override public GridCacheEntry<K, V> entry(K key) {
return new GridDhtCacheEntryImpl<>(ctx.projectionPerCall(), ctx, key, null);
}
/** {@inheritDoc} */
@Override public V peek(K key, @Nullable Collection<GridCachePeekMode> modes) throws GridException {
GridTuple<V> val = null;
if (ctx.isReplicated() || !modes.contains(NEAR_ONLY)) {
try {
val = peek0(true, key, modes, ctx.tm().txx());
}
catch (GridCacheFilterFailedException ignored) {
if (log.isDebugEnabled())
log.debug("Filter validation failed for key: " + key);
return null;
}
}
return val != null ? val.get() : null;
}
/** {@inheritDoc} */
@Override public GridCacheTxLocalAdapter<K, V> newTx(
boolean implicit,
boolean implicitSingle,
GridCacheTxConcurrency concurrency,
GridCacheTxIsolation isolation,
long timeout,
boolean invalidate,
boolean syncCommit,
boolean syncRollback,
boolean swapOrOffheapEnabled,
boolean storeEnabled,
int txSize,
@Nullable Object grpLockKey,
boolean partLock
) {
throw new UnsupportedOperationException("Transactions are not supported for " +
"GridCacheAtomicityMode.ATOMIC mode (use GridCacheAtomicityMode.TRANSACTIONAL instead)");
}
/** {@inheritDoc} */
@Override public GridFuture<Map<K, V>> getAllAsync(
@Nullable final Collection<? extends K> keys,
final boolean forcePrimary,
boolean skipTx,
@Nullable final GridCacheEntryEx<K, V> entry,
@Nullable UUID subjId,
final boolean deserializePortable,
@Nullable final GridPredicate<GridCacheEntry<K, V>>[] filter
) {
subjId = ctx.subjectIdPerCall(subjId);
final UUID subjId0 = subjId;
return asyncOp(new CO<GridFuture<Map<K, V>>>() {
@Override public GridFuture<Map<K, V>> apply() {
return getAllAsync0(keys, false, forcePrimary, filter, subjId0, deserializePortable);
}
});
}
/** {@inheritDoc} */
@Override public V put(K key, V val, @Nullable GridCacheEntryEx<K, V> cached, long ttl,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
return putAsync(key, val, cached, ttl, filter).get();
}
/** {@inheritDoc} */
@Override public boolean putx(K key, V val, @Nullable GridCacheEntryEx<K, V> cached,
long ttl, @Nullable GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
return putxAsync(key, val, cached, ttl, filter).get();
}
/** {@inheritDoc} */
@Override public boolean putx(K key, V val,
GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
return putxAsync(key, val, filter).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<V> putAsync(K key, V val, @Nullable GridCacheEntryEx<K, V> entry,
long ttl, @Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return updateAllAsync0(F0.asMap(key, val), null, null, null, true, false, entry, ttl, filter);
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<Boolean> putxAsync(K key, V val, @Nullable GridCacheEntryEx<K, V> entry, long ttl,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return updateAllAsync0(F0.asMap(key, val), null, null, null, false, false, entry, ttl, filter);
}
/** {@inheritDoc} */
@Override public V putIfAbsent(K key, V val) throws GridException {
return putIfAbsentAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<V> putIfAbsentAsync(K key, V val) {
return putAsync(key, val, ctx.noPeekArray());
}
/** {@inheritDoc} */
@Override public boolean putxIfAbsent(K key, V val) throws GridException {
return putxIfAbsentAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> putxIfAbsentAsync(K key, V val) {
return putxAsync(key, val, ctx.noPeekArray());
}
/** {@inheritDoc} */
@Override public V replace(K key, V val) throws GridException {
return replaceAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<V> replaceAsync(K key, V val) {
return putAsync(key, val, ctx.hasPeekArray());
}
/** {@inheritDoc} */
@Override public boolean replacex(K key, V val) throws GridException {
return replacexAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> replacexAsync(K key, V val) {
return putxAsync(key, val, ctx.hasPeekArray());
}
/** {@inheritDoc} */
@Override public boolean replace(K key, V oldVal, V newVal) throws GridException {
return replaceAsync(key, oldVal, newVal).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> replaceAsync(K key, V oldVal, V newVal) {
return putxAsync(key, newVal, ctx.equalsPeekArray(oldVal));
}
/** {@inheritDoc} */
@Override public GridCacheReturn<V> removex(K key, V val) throws GridException {
return removexAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridCacheReturn<V> replacex(K key, V oldVal, V newVal) throws GridException {
return replacexAsync(key, oldVal, newVal).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<GridCacheReturn<V>> removexAsync(K key, V val) {
return removeAllAsync0(F.asList(key), null, null, true, true, ctx.equalsPeekArray(val));
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<GridCacheReturn<V>> replacexAsync(K key, V oldVal, V newVal) {
return updateAllAsync0(F.asMap(key, newVal), null, null, null, true, true, null, 0,
ctx.equalsPeekArray(oldVal));
}
/** {@inheritDoc} */
@Override public void putAll(Map<? extends K, ? extends V> m,
GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
putAllAsync(m, filter).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> putAllAsync(Map<? extends K, ? extends V> m,
@Nullable GridPredicate<GridCacheEntry<K, V>>[] filter) {
return updateAllAsync0(m, null, null, null, false, false, null, 0, filter);
}
/** {@inheritDoc} */
@Override public void putAllDr(Map<? extends K, GridCacheDrInfo<V>> drMap) throws GridException {
putAllDrAsync(drMap).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> putAllDrAsync(Map<? extends K, GridCacheDrInfo<V>> drMap) {
metrics.onReceiveCacheEntriesReceived(drMap.size());
return updateAllAsync0(null, null, drMap, null, false, false, null, 0, null);
}
/** {@inheritDoc} */
@Override public void transform(K key, GridClosure<V, V> transformer) throws GridException {
transformAsync(key, transformer).get();
}
/** {@inheritDoc} */
@Override public <R> R transformAndCompute(K key, GridClosure<V, GridBiTuple<V, R>> transformer)
throws GridException {
return (R)updateAllAsync0(null,
Collections.singletonMap(key, new GridCacheTransformComputeClosure<>(transformer)), null, null, true,
false, null, 0, null).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> transformAsync(K key, GridClosure<V, V> transformer,
@Nullable GridCacheEntryEx<K, V> entry, long ttl) {
return updateAllAsync0(null, Collections.singletonMap(key, transformer), null, null, false, false, entry, ttl,
null);
}
/** {@inheritDoc} */
@Override public void transformAll(@Nullable Map<? extends K, ? extends GridClosure<V, V>> m) throws GridException {
transformAllAsync(m).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> transformAllAsync(@Nullable Map<? extends K, ? extends GridClosure<V, V>> m) {
if (F.isEmpty(m))
return new GridFinishedFuture<Object>(ctx.kernalContext());
return updateAllAsync0(null, m, null, null, false, false, null, 0, null);
}
/** {@inheritDoc} */
@Override public V remove(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
return removeAsync(key, entry, filter).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<V> removeAsync(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return removeAllAsync0(Collections.singletonList(key), null, entry, true, false, filter);
}
/** {@inheritDoc} */
@Override public void removeAll(Collection<? extends K> keys,
GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
removeAllAsync(keys, filter).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> removeAllAsync(Collection<? extends K> keys,
GridPredicate<GridCacheEntry<K, V>>[] filter) {
return removeAllAsync0(keys, null, null, false, false, filter);
}
/** {@inheritDoc} */
@Override public boolean removex(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) throws GridException {
return removexAsync(key, entry, filter).get();
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public GridFuture<Boolean> removexAsync(K key, @Nullable GridCacheEntryEx<K, V> entry,
@Nullable GridPredicate<GridCacheEntry<K, V>>... filter) {
return removeAllAsync0(Collections.singletonList(key), null, entry, false, false, filter);
}
/** {@inheritDoc} */
@Override public boolean remove(K key, V val) throws GridException {
return removeAsync(key, val).get();
}
/** {@inheritDoc} */
@Override public GridFuture<Boolean> removeAsync(K key, V val) {
return removexAsync(key, ctx.equalsPeekArray(val));
}
/** {@inheritDoc} */
@Override public void removeAll(GridPredicate<GridCacheEntry<K, V>>[] filter) throws GridException {
removeAllAsync(filter).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> removeAllAsync(GridPredicate<GridCacheEntry<K, V>>[] filter) {
return removeAllAsync(keySet(filter), filter);
}
/** {@inheritDoc} */
@Override public void removeAllDr(Map<? extends K, GridCacheVersion> drMap) throws GridException {
removeAllDrAsync(drMap).get();
}
/** {@inheritDoc} */
@Override public GridFuture<?> removeAllDrAsync(Map<? extends K, GridCacheVersion> drMap) {
metrics.onReceiveCacheEntriesReceived(drMap.size());
return removeAllAsync0(null, drMap, null, false, false, null);
}
/**
* @return {@code True} if store enabled.
*/
private boolean storeEnabled() {
return ctx.isStoreEnabled() && ctx.config().getStore() != null;
}
/**
* @param op Operation closure.
* @return Future.
*/
@SuppressWarnings("unchecked")
protected <T> GridFuture<T> asyncOp(final CO<GridFuture<T>> op) {
GridFuture<T> fail = asyncOpAcquire();
if (fail != null)
return fail;
FutureHolder holder = lastFut.get();
holder.lock();
try {
GridFuture fut = holder.future();
if (fut != null && !fut.isDone()) {
GridFuture<T> f = new GridEmbeddedFuture<>(fut,
new C2<T, Exception, GridFuture<T>>() {
@Override public GridFuture<T> apply(T t, Exception e) {
return op.apply();
}
}, ctx.kernalContext());
saveFuture(holder, f);
return f;
}
GridFuture<T> f = op.apply();
saveFuture(holder, f);
return f;
}
finally {
holder.unlock();
}
}
/** {@inheritDoc} */
@Override protected GridFuture<Boolean> lockAllAsync(Collection<? extends K> keys,
long timeout,
@Nullable GridCacheTxLocalEx<K, V> tx,
boolean isInvalidate,
boolean isRead,
boolean retval,
@Nullable GridCacheTxIsolation isolation,
GridPredicate<GridCacheEntry<K, V>>[] filter) {
return new FinishedLockFuture(new UnsupportedOperationException("Locks are not supported for " +
"GridCacheAtomicityMode.ATOMIC mode (use GridCacheAtomicityMode.TRANSACTIONAL instead)"));
}
/**
* Entry point for all public API put/transform methods.
*
* @param map Put map. Either {@code map}, {@code transformMap} or {@code drMap} should be passed.
* @param transformMap Transform map. Either {@code map}, {@code transformMap} or {@code drMap} should be passed.
* @param drPutMap DR put map.
* @param drRmvMap DR remove map.
* @param retval Return value required flag.
* @param rawRetval Return {@code GridCacheReturn} instance.
* @param cached Cached cache entry for key. May be passed if and only if map size is {@code 1}.
* @param ttl Entry time-to-live.
* @param filter Cache entry filter for atomic updates.
* @return Completion future.
*/
private GridFuture updateAllAsync0(
@Nullable final Map<? extends K, ? extends V> map,
@Nullable final Map<? extends K, ? extends GridClosure<V, V>> transformMap,
@Nullable final Map<? extends K, GridCacheDrInfo<V>> drPutMap,
@Nullable final Map<? extends K, GridCacheVersion> drRmvMap,
final boolean retval,
final boolean rawRetval,
@Nullable GridCacheEntryEx<K, V> cached,
long ttl,
@Nullable final GridPredicate<GridCacheEntry<K, V>>[] filter
) {
ctx.checkSecurity(GridSecurityPermission.CACHE_PUT);
UUID subjId = ctx.subjectIdPerCall(null);
final GridNearAtomicUpdateFuture<K, V> updateFut = new GridNearAtomicUpdateFuture<>(
ctx,
this,
ctx.config().getWriteSynchronizationMode(),
transformMap != null ? TRANSFORM : UPDATE,
map != null ? map.keySet() : transformMap != null ? transformMap.keySet() : drPutMap != null ?
drPutMap.keySet() : drRmvMap.keySet(),
map != null ? map.values() : transformMap != null ? transformMap.values() : null,
drPutMap != null ? drPutMap.values() : null,
drRmvMap != null ? drRmvMap.values() : null,
retval,
rawRetval,
cached,
ttl,
filter,
subjId);
return asyncOp(new CO<GridFuture<Object>>() {
@Override public GridFuture<Object> apply() {
updateFut.map();
return updateFut;
}
});
}
/**
* Entry point for all public API remove methods.
*
* @param keys Keys to remove.
* @param drMap DR map.
* @param cached Cached cache entry for key. May be passed if and only if keys size is {@code 1}.
* @param retval Return value required flag.
* @param rawRetval Return {@code GridCacheReturn} instance.
* @param filter Cache entry filter for atomic removes.
* @return Completion future.
*/
private GridFuture removeAllAsync0(
@Nullable final Collection<? extends K> keys,
@Nullable final Map<? extends K, GridCacheVersion> drMap,
@Nullable GridCacheEntryEx<K, V> cached,
final boolean retval,
boolean rawRetval,
@Nullable final GridPredicate<GridCacheEntry<K, V>>[] filter
) {
assert keys != null || drMap != null;
ctx.checkSecurity(GridSecurityPermission.CACHE_REMOVE);
UUID subjId = ctx.subjectIdPerCall(null);
final GridNearAtomicUpdateFuture<K, V> updateFut = new GridNearAtomicUpdateFuture<>(
ctx,
this,
ctx.config().getWriteSynchronizationMode(),
DELETE,
keys != null ? keys : drMap.keySet(),
null,
null,
keys != null ? null : drMap.values(),
retval,
rawRetval,
cached,
0,
filter,
subjId);
return asyncOp(new CO<GridFuture<Object>>() {
@Override public GridFuture<Object> apply() {
updateFut.map();
return updateFut;
}
});
}
/**
* Entry point to all public API get methods.
*
* @param keys Keys to remove.
* @param reload Reload flag.
* @param forcePrimary Force primary flag.
* @param filter Filter.
* @return Get future.
*/
private GridFuture<Map<K, V>> getAllAsync0(@Nullable Collection<? extends K> keys, boolean reload,
boolean forcePrimary, @Nullable GridPredicate<GridCacheEntry<K, V>>[] filter, UUID subjId,
boolean deserializePortable) {
ctx.checkSecurity(GridSecurityPermission.CACHE_READ);
if (F.isEmpty(keys))
return new GridFinishedFuture<>(ctx.kernalContext(), Collections.<K, V>emptyMap());
// Optimisation: try to resolve value locally and escape 'get future' creation.
if (!reload && !forcePrimary) {
Map<K, V> locVals = new HashMap<>(keys.size(), 1.0f);
GridCacheVersion obsoleteVer = null;
boolean success = true;
long topVer = ctx.affinity().affinityTopologyVersion();
// Optimistically expect that all keys are available locally (avoid creation of get future).
for (K key : keys) {
GridCacheEntryEx<K, V> entry = null;
while (true) {
try {
entry = ctx.isSwapOrOffheapEnabled() ? entryEx(key) : peekEx(key);
// If our DHT cache do has value, then we peek it.
if (entry != null) {
boolean isNew = entry.isNewLocked();
V v = entry.innerGet(null, /*swap*/true, /*read-through*/false, /*fail-fast*/true,
/*unmarshal*/true, /**update-metrics*/true, true, subjId, filter);
// Entry was not in memory or in swap, so we remove it from cache.
if (v == null) {
if (obsoleteVer == null)
obsoleteVer = context().versions().next();
if (isNew && entry.markObsoleteIfEmpty(obsoleteVer))
removeIfObsolete(key);
success = false;
}
else {
if (ctx.portableEnabled() && deserializePortable && v instanceof GridPortableObject)
v = ((GridPortableObject<V>)v).deserialize();
locVals.put(key, v);
}
}
else
success = false;
break; // While.
}
catch (GridCacheEntryRemovedException ignored) {
// No-op, retry.
}
catch (GridCacheFilterFailedException ignored) {
// No-op, skip the key.
break;
}
catch (GridDhtInvalidPartitionException ignored) {
success = false;
break; // While.
}
catch (GridException e) {
return new GridFinishedFuture<>(ctx.kernalContext(), e);
}
finally {
if (entry != null)
ctx.evicts().touch(entry, topVer);
}
}
if (!success)
break;
}
if (success)
return ctx.wrapCloneMap(new GridFinishedFuture<>(ctx.kernalContext(), locVals));
}
// Either reload or not all values are available locally.
GridPartitionedGetFuture<K, V> fut = new GridPartitionedGetFuture<>(ctx, keys, reload, forcePrimary, filter,
subjId, deserializePortable);
fut.init();
return ctx.wrapCloneMap(fut);
}
/**
* Executes local update.
*
* @param nodeId Node ID.
* @param req Update request.
* @param cached Cached entry if updating single local entry.
* @param completionCb Completion callback.
*/
public void updateAllAsyncInternal(
final UUID nodeId,
final GridNearAtomicUpdateRequest<K, V> req,
@Nullable final GridCacheEntryEx<K, V> cached,
final CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb
) {
GridFuture<Object> forceFut = preldr.request(req.keys(), req.topologyVersion());
if (forceFut.isDone())
updateAllAsyncInternal0(nodeId, req, cached, completionCb);
else {
forceFut.listenAsync(new CI1<GridFuture<Object>>() {
@Override public void apply(GridFuture<Object> t) {
updateAllAsyncInternal0(nodeId, req, cached, completionCb);
}
});
}
}
/**
* Executes local update after preloader fetched values.
*
* @param nodeId Node ID.
* @param req Update request.
* @param cached Cached entry if updating single local entry.
* @param completionCb Completion callback.
*/
public void updateAllAsyncInternal0(
UUID nodeId,
GridNearAtomicUpdateRequest<K, V> req,
@Nullable GridCacheEntryEx<K, V> cached,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb
) {
GridNearAtomicUpdateResponse<K, V> res = new GridNearAtomicUpdateResponse<>(nodeId, req.futureVersion());
List<K> keys = req.keys();
assert !req.returnValue() || keys.size() == 1;
GridDhtAtomicUpdateFuture<K, V> dhtFut = null;
boolean remap = false;
try {
// If batch store update is enabled, we need to lock all entries.
// First, need to acquire locks on cache entries, then check filter.
List<GridDhtCacheEntry<K, V>> locked = lockEntries(keys, req.topologyVersion());
Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted = null;
try {
topology().readLock();
try {
// Do not check topology version for CLOCK versioning since
// partition exchange will wait for near update future.
if (topology().topologyVersion() == req.topologyVersion() ||
ctx.config().getAtomicWriteOrderMode() == CLOCK) {
GridNode node = ctx.discovery().node(nodeId);
if (node == null) {
U.warn(log, "Node originated update request left grid: " + nodeId);
return;
}
checkClearForceTransformBackups(req, locked);
boolean hasNear = U.hasNearCache(node, name());
GridCacheVersion ver = req.updateVersion();
if (ver == null) {
// Assign next version for update inside entries lock.
ver = ctx.versions().next(req.topologyVersion());
if (hasNear)
res.nearVersion(ver);
}
assert ver != null : "Got null version for update request: " + req;
if (log.isDebugEnabled())
log.debug("Using cache version for update request on primary node [ver=" + ver +
", req=" + req + ']');
dhtFut = createDhtFuture(ver, req, res, completionCb, false);
GridCacheReturn<Object> retVal = null;
boolean replicate = ctx.isDrEnabled();
if (storeEnabled() && keys.size() > 1 && cacheCfg.getDrReceiverConfiguration() == null) {
// This method can only be used when there are no replicated entries in the batch.
UpdateBatchResult<K, V> updRes = updateWithBatch(nodeId, hasNear, req, res, locked, ver,
dhtFut, completionCb, replicate);
deleted = updRes.deleted();
dhtFut = updRes.dhtFuture();
}
else {
UpdateSingleResult<K, V> updRes = updateSingle(nodeId, hasNear, req, res, locked, ver,
dhtFut, completionCb, replicate);
retVal = updRes.returnValue();
deleted = updRes.deleted();
dhtFut = updRes.dhtFuture();
}
if (retVal == null)
retVal = new GridCacheReturn<>(null, true);
res.returnValue(retVal);
}
else
// Should remap all keys.
remap = true;
}
finally {
topology().readUnlock();
}
}
catch (GridCacheEntryRemovedException e) {
assert false : "Entry should not become obsolete while holding lock.";
e.printStackTrace();
}
finally {
unlockEntries(locked, req.topologyVersion());
// Enqueue if necessary after locks release.
if (deleted != null) {
assert !deleted.isEmpty();
assert ctx.deferredDelete();
for (GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion> e : deleted)
ctx.onDeferredDelete(e.get1(), e.get2());
}
}
}
catch (GridDhtInvalidPartitionException ignore) {
assert ctx.config().getAtomicWriteOrderMode() == PRIMARY;
if (log.isDebugEnabled())
log.debug("Caught invalid partition exception for cache entry (will remap update request): " + req);
remap = true;
}
if (remap) {
assert dhtFut == null;
res.remapKeys(req.keys());
completionCb.apply(req, res);
}
else {
// If there are backups, map backup update future.
if (dhtFut != null)
dhtFut.map();
// Otherwise, complete the call.
else
completionCb.apply(req, res);
}
}
/**
* Updates locked entries using batched write-through.
*
* @param nodeId Sender node ID.
* @param hasNear {@code True} if originating node has near cache.
* @param req Update request.
* @param res Update response.
* @param locked Locked entries.
* @param ver Assigned version.
* @param dhtFut Optional DHT future.
* @param completionCb Completion callback to invoke when DHT future is completed.
* @param replicate Whether replication is enabled.
* @return Deleted entries.
* @throws GridCacheEntryRemovedException Should not be thrown.
*/
@SuppressWarnings("unchecked")
private UpdateBatchResult<K, V> updateWithBatch(
UUID nodeId,
boolean hasNear,
GridNearAtomicUpdateRequest<K, V> req,
GridNearAtomicUpdateResponse<K, V> res,
List<GridDhtCacheEntry<K, V>> locked,
GridCacheVersion ver,
@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
boolean replicate
) throws GridCacheEntryRemovedException {
// Cannot update in batches during DR due to possible conflicts.
assert !req.returnValue(); // Should not request return values for putAll.
int size = req.keys().size();
Map<K, V> putMap = null;
Map<K, GridClosure<V, V>> transformMap = null;
Collection<K> rmvKeys = null;
UpdateBatchResult<K, V> updRes = new UpdateBatchResult<>();
List<GridDhtCacheEntry<K, V>> filtered = new ArrayList<>(size);
GridCacheOperation op = req.operation();
int firstEntryIdx = 0;
boolean intercept = ctx.config().getInterceptor() != null;
for (int i = 0; i < locked.size(); i++) {
GridDhtCacheEntry<K, V> entry = locked.get(i);
if (entry == null)
continue;
try {
if (!checkFilter(entry, req, res)) {
if (log.isDebugEnabled())
log.debug("Entry did not pass the filter (will skip write) [entry=" + entry +
", filter=" + Arrays.toString(req.filter()) + ", res=" + res + ']');
if (hasNear)
res.addSkippedIndex(i);
firstEntryIdx++;
continue;
}
if (op == TRANSFORM) {
V old = entry.innerGet(
null,
/*read swap*/true,
/*read through*/true,
/*fail fast*/false,
/*unmarshal*/true,
/*metrics*/true,
/*event*/true,
req.subjectId(),
CU.<K, V>empty());
GridClosure<V, V> transform = req.transformClosure(i);
if (transformMap == null)
transformMap = new HashMap<>();
transformMap.put(entry.key(), transform);
V updated = transform.apply(old);
if (updated == null) {
if (intercept) {
GridBiTuple<Boolean, ?> interceptorRes = ctx.config().getInterceptor().onBeforeRemove(
entry.key(), old);
if (ctx.cancelRemove(interceptorRes))
continue;
}
// Update previous batch.
if (putMap != null) {
dhtFut = updatePartialBatch(
hasNear,
firstEntryIdx,
filtered,
ver,
nodeId,
putMap,
null,
transformMap,
dhtFut,
completionCb,
req,
res,
replicate,
updRes);
firstEntryIdx = i + 1;
putMap = null;
transformMap = null;
filtered = new ArrayList<>();
}
// Start collecting new batch.
if (rmvKeys == null)
rmvKeys = new ArrayList<>(size);
rmvKeys.add(entry.key());
}
else {
if (intercept) {
updated = (V)ctx.config().getInterceptor().onBeforePut(entry.key(), old, updated);
if (updated == null)
continue;
}
// Update previous batch.
if (rmvKeys != null) {
dhtFut = updatePartialBatch(
hasNear,
firstEntryIdx,
filtered,
ver,
nodeId,
null,
rmvKeys,
transformMap,
dhtFut,
completionCb,
req,
res,
replicate,
updRes);
firstEntryIdx = i + 1;
rmvKeys = null;
transformMap = null;
filtered = new ArrayList<>();
}
if (putMap == null)
putMap = new LinkedHashMap<>(size, 1.0f);
putMap.put(entry.key(), updated);
}
}
else if (op == UPDATE) {
V updated = req.value(i);
if (intercept) {
V old = entry.innerGet(
null,
/*read swap*/true,
/*read through*/true,
/*fail fast*/false,
/*unmarshal*/true,
/*metrics*/true,
/*event*/true,
req.subjectId(),
CU.<K, V>empty());
updated = (V)ctx.config().getInterceptor().onBeforePut(entry.key(), old, updated);
if (updated == null)
continue;
}
assert updated != null;
if (putMap == null)
putMap = new LinkedHashMap<>(size, 1.0f);
putMap.put(entry.key(), updated);
}
else {
assert op == DELETE;
if (intercept) {
V old = entry.innerGet(
null,
/*read swap*/true,
/*read through*/true,
/*fail fast*/false,
/*unmarshal*/true,
/*metrics*/true,
/*event*/true,
req.subjectId(),
CU.<K, V>empty());
GridBiTuple<Boolean, ?> interceptorRes = ctx.config().getInterceptor().onBeforeRemove(
entry.key(), old);
if (ctx.cancelRemove(interceptorRes))
continue;
}
if (rmvKeys == null)
rmvKeys = new ArrayList<>(size);
rmvKeys.add(entry.key());
}
filtered.add(entry);
}
catch (GridException e) {
res.addFailedKey(entry.key(), e);
}
catch (GridCacheFilterFailedException ignore) {
assert false : "Filter should never fail with failFast=false and empty filter.";
}
}
// Store final batch.
if (putMap != null || rmvKeys != null) {
dhtFut = updatePartialBatch(
hasNear,
firstEntryIdx,
filtered,
ver,
nodeId,
putMap,
rmvKeys,
transformMap,
dhtFut,
completionCb,
req,
res,
replicate,
updRes);
}
else
assert filtered.isEmpty();
updRes.dhtFuture(dhtFut);
return updRes;
}
/**
* Updates locked entries one-by-one.
*
* @param nodeId Originating node ID.
* @param hasNear {@code True} if originating node has near cache.
* @param req Update request.
* @param res Update response.
* @param locked Locked entries.
* @param ver Assigned update version.
* @param dhtFut Optional DHT future.
* @param completionCb Completion callback to invoke when DHT future is completed.
* @param replicate Whether DR is enabled for that cache.
* @return Return value.
* @throws GridCacheEntryRemovedException Should be never thrown.
*/
private UpdateSingleResult<K, V> updateSingle(
UUID nodeId,
boolean hasNear,
GridNearAtomicUpdateRequest<K, V> req,
GridNearAtomicUpdateResponse<K, V> res,
List<GridDhtCacheEntry<K, V>> locked,
GridCacheVersion ver,
@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
boolean replicate
) throws GridCacheEntryRemovedException {
GridCacheReturn<Object> retVal = null;
Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted = null;
List<K> keys = req.keys();
long topVer = req.topologyVersion();
boolean checkReaders = hasNear || ctx.discovery().hasNearCache(name(), topVer);
boolean readersOnly = false;
boolean intercept = ctx.config().getInterceptor() != null;
// Avoid iterator creation.
for (int i = 0; i < keys.size(); i++) {
K k = keys.get(i);
GridCacheOperation op = req.operation();
// We are holding java-level locks on entries at this point.
// No GridCacheEntryRemovedException can be thrown.
try {
GridDhtCacheEntry<K, V> entry = locked.get(i);
if (entry == null)
continue;
GridCacheVersion newDrVer = req.drVersion(i);
long newDrTtl = req.drTtl(i);
long newDrExpireTime = req.drExpireTime(i);
assert !(newDrVer instanceof GridCacheVersionEx) : newDrVer; // Plain version is expected here.
if (newDrVer == null)
newDrVer = ver;
boolean primary = !req.fastMap() || ctx.affinity().primary(ctx.localNode(), entry.key(),
req.topologyVersion());
byte[] newValBytes = req.valueBytes(i);
Object writeVal = req.writeValue(i);
Collection<UUID> readers = null;
Collection<UUID> filteredReaders = null;
if (checkReaders) {
readers = entry.readers();
filteredReaders = F.view(entry.readers(), F.notEqualTo(nodeId));
}
GridCacheUpdateAtomicResult<K, V> updRes = entry.innerUpdate(
ver,
nodeId,
locNodeId,
op,
writeVal,
newValBytes,
primary && storeEnabled(),
req.returnValue(),
req.ttl(),
true,
true,
primary,
ctx.config().getAtomicWriteOrderMode() == CLOCK, // Check version in CLOCK mode on primary node.
req.filter(),
replicate ? primary ? DR_PRIMARY : DR_BACKUP : DR_NONE,
newDrTtl,
newDrExpireTime,
newDrVer,
true,
intercept,
req.subjectId());
if (dhtFut == null && !F.isEmpty(filteredReaders)) {
dhtFut = createDhtFuture(ver, req, res, completionCb, true);
readersOnly = true;
}
if (dhtFut != null) {
if (updRes.sendToDht()) { // Send to backups even in case of remove-remove scenarios.
GridDrReceiverConflictContextImpl ctx = updRes.drConflictContext();
long ttl = updRes.newTtl();
long drExpireTime = updRes.drExpireTime();
if (ctx == null)
newDrVer = null;
else if (ctx.isMerge()) {
newDrVer = null; // DR version is discarded in case of merge.
newValBytes = null; // Value has been changed.
}
GridClosure<V, V> transformC = null;
if (req.forceTransformBackups() && op == TRANSFORM)
transformC = (GridClosure<V, V>)writeVal;
if (!readersOnly)
dhtFut.addWriteEntry(entry, updRes.newValue(), newValBytes, transformC,
drExpireTime >= 0L ? ttl : -1L, drExpireTime, newDrVer, drExpireTime < 0L ? ttl : 0L);
if (!F.isEmpty(filteredReaders))
dhtFut.addNearWriteEntries(filteredReaders, entry, updRes.newValue(), newValBytes,
transformC, drExpireTime < 0L ? ttl : 0L);
}
else {
if (log.isDebugEnabled())
log.debug("Entry did not pass the filter or conflict resolution (will skip write) " +
"[entry=" + entry + ", filter=" + Arrays.toString(req.filter()) + ']');
}
}
if (hasNear) {
if (primary && updRes.sendToDht()) {
if (!U.nodeIds(context().affinity().nodes(entry.partition(), topVer)).contains(nodeId)) {
GridDrReceiverConflictContextImpl ctx = updRes.drConflictContext();
res.nearTtl(updRes.newTtl());
if (ctx != null && ctx.isMerge())
newValBytes = null;
// If put the same value as in request then do not need to send it back.
if (op == TRANSFORM || writeVal != updRes.newValue())
res.addNearValue(i, updRes.newValue(), newValBytes);
if (updRes.newValue() != null || newValBytes != null) {
GridFuture<Boolean> f = entry.addReader(nodeId, req.messageId(), topVer);
assert f == null : f;
}
}
else if (F.contains(readers, nodeId)) // Reader became primary or backup.
entry.removeReader(nodeId, req.messageId());
else
res.addSkippedIndex(i);
}
else
res.addSkippedIndex(i);
}
if (updRes.removeVersion() != null) {
if (deleted == null)
deleted = new ArrayList<>(keys.size());
deleted.add(F.t(entry, updRes.removeVersion()));
}
// Create only once.
if (retVal == null) {
Object ret = updRes.oldValue();
if (op == TRANSFORM && writeVal instanceof GridCacheTransformComputeClosure) {
assert req.returnValue();
ret = ((GridCacheTransformComputeClosure<V, ?>)writeVal).returnValue();
}
retVal = new GridCacheReturn<>(req.returnValue() ? ret : null, updRes.success());
}
}
catch (GridException e) {
res.addFailedKey(k, e);
}
}
return new UpdateSingleResult<>(retVal, deleted, dhtFut);
}
/**
* @param hasNear {@code True} if originating node has near cache.
* @param firstEntryIdx Index of the first entry in the request keys collection.
* @param entries Entries to update.
* @param ver Version to set.
* @param nodeId Originating node ID.
* @param putMap Values to put.
* @param rmvKeys Keys to remove.
* @param transformMap Transform closures.
* @param dhtFut DHT update future if has backups.
* @param completionCb Completion callback to invoke when DHT future is completed.
* @param req Request.
* @param res Response.
* @param replicate Whether replication is enabled.
* @param batchRes Batch update result.
* @return Deleted entries.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
@Nullable private GridDhtAtomicUpdateFuture<K, V> updatePartialBatch(
boolean hasNear,
int firstEntryIdx,
List<GridDhtCacheEntry<K, V>> entries,
final GridCacheVersion ver,
UUID nodeId,
@Nullable Map<K, V> putMap,
@Nullable Collection<K> rmvKeys,
@Nullable Map<K, GridClosure<V, V>> transformMap,
@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
final GridNearAtomicUpdateRequest<K, V> req,
final GridNearAtomicUpdateResponse<K, V> res,
boolean replicate,
UpdateBatchResult<K, V> batchRes
) {
assert putMap == null ^ rmvKeys == null;
assert req.drVersions() == null : "updatePartialBatch cannot be called when there are DR entries in the batch.";
long topVer = req.topologyVersion();
boolean checkReaders = hasNear || ctx.discovery().hasNearCache(name(), topVer);
try {
GridCacheOperation op;
if (putMap != null) {
// If fast mapping, filter primary keys for write to store.
Map<K, V> storeMap = req.fastMap() ?
F.view(putMap, new P1<K>() {
@Override public boolean apply(K key) {
return ctx.affinity().primary(ctx.localNode(), key, req.topologyVersion());
}
}) :
putMap;
ctx.store().putAllToStore(null, F.viewReadOnly(storeMap, new C1<V, GridBiTuple<V, GridCacheVersion>>() {
@Override public GridBiTuple<V, GridCacheVersion> apply(V v) {
return F.t(v, ver);
}
}));
op = UPDATE;
}
else {
// If fast mapping, filter primary keys for write to store.
Collection<K> storeKeys = req.fastMap() ?
F.view(rmvKeys, new P1<K>() {
@Override public boolean apply(K key) {
return ctx.affinity().primary(ctx.localNode(), key, req.topologyVersion());
}
}) :
rmvKeys;
ctx.store().removeAllFromStore(null, storeKeys);
op = DELETE;
}
boolean intercept = ctx.config().getInterceptor() != null;
// Avoid iterator creation.
for (int i = 0; i < entries.size(); i++) {
GridDhtCacheEntry<K, V> entry = entries.get(i);
assert Thread.holdsLock(entry);
if (entry.obsolete()) {
assert req.operation() == DELETE : "Entry can become obsolete only after remove: " + entry;
continue;
}
try {
// We are holding java-level locks on entries at this point.
V writeVal = op == UPDATE ? putMap.get(entry.key()) : null;
assert writeVal != null || op == DELETE : "null write value found.";
boolean primary = !req.fastMap() || ctx.affinity().primary(ctx.localNode(), entry.key(),
req.topologyVersion());
Collection<UUID> readers = null;
Collection<UUID> filteredReaders = null;
if (checkReaders) {
readers = entry.readers();
filteredReaders = F.view(entry.readers(), F.notEqualTo(nodeId));
}
GridCacheUpdateAtomicResult<K, V> updRes = entry.innerUpdate(
ver,
nodeId,
locNodeId,
op,
writeVal,
null,
false,
false,
req.ttl(),
true,
true,
primary,
ctx.config().getAtomicWriteOrderMode() == CLOCK, // Check version in CLOCK mode on primary node.
req.filter(),
replicate ? primary ? DR_PRIMARY : DR_BACKUP : DR_NONE,
-1L,
-1L,
null,
false,
false,
req.subjectId());
if (intercept) {
if (op == UPDATE)
ctx.config().getInterceptor().onAfterPut(entry.key(), updRes.newValue());
else {
assert op == DELETE : op;
// Old value should be already loaded for 'GridCacheInterceptor.onBeforeRemove'.
ctx.config().<K, V>getInterceptor().onAfterRemove(entry.key(), updRes.oldValue());
}
}
batchRes.addDeleted(entry, updRes, entries);
if (dhtFut == null && !F.isEmpty(filteredReaders)) {
dhtFut = createDhtFuture(ver, req, res, completionCb, true);
batchRes.readersOnly(true);
}
if (dhtFut != null) {
GridCacheValueBytes valBytesTuple = op == DELETE ? GridCacheValueBytes.nil():
entry.valueBytes();
byte[] valBytes = valBytesTuple.getIfMarshaled();
GridClosure<V, V> transformC = transformMap == null ? null : transformMap.get(entry.key());
if (!batchRes.readersOnly())
dhtFut.addWriteEntry(entry, writeVal, valBytes, transformC, -1, -1, null, req.ttl());
if (!F.isEmpty(filteredReaders))
dhtFut.addNearWriteEntries(filteredReaders, entry, writeVal, valBytes, transformC,
req.ttl());
}
if (hasNear) {
if (primary) {
if (!U.nodeIds(context().affinity().nodes(entry.partition(), topVer)).contains(nodeId)) {
if (req.operation() == TRANSFORM) {
int idx = firstEntryIdx + i;
GridCacheValueBytes valBytesTuple = entry.valueBytes();
byte[] valBytes = valBytesTuple.getIfMarshaled();
res.addNearValue(idx, writeVal, valBytes);
}
res.nearTtl(req.ttl());
if (writeVal != null || !entry.valueBytes().isNull()) {
GridFuture<Boolean> f = entry.addReader(nodeId, req.messageId(), topVer);
assert f == null : f;
}
} else if (readers.contains(nodeId)) // Reader became primary or backup.
entry.removeReader(nodeId, req.messageId());
else
res.addSkippedIndex(firstEntryIdx + i);
}
else
res.addSkippedIndex(firstEntryIdx + i);
}
}
catch (GridCacheEntryRemovedException e) {
assert false : "Entry cannot become obsolete while holding lock.";
e.printStackTrace();
}
}
}
catch (GridException e) {
res.addFailedKeys(putMap != null ? putMap.keySet() : rmvKeys, e);
}
return dhtFut;
}
/**
* Acquires java-level locks on cache entries. Returns collection of locked entries.
*
* @param keys Keys to lock.
* @param topVer Topology version to lock on.
* @return Collection of locked entries.
* @throws GridDhtInvalidPartitionException If entry does not belong to local node. If exception is thrown,
* locks are released.
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
private List<GridDhtCacheEntry<K, V>> lockEntries(List<K> keys, long topVer)
throws GridDhtInvalidPartitionException {
if (keys.size() == 1) {
K key = keys.get(0);
while (true) {
try {
GridDhtCacheEntry<K, V> entry = entryExx(key, topVer);
UNSAFE.monitorEnter(entry);
if (entry.obsolete())
UNSAFE.monitorExit(entry);
else
return Collections.singletonList(entry);
}
catch (GridDhtInvalidPartitionException e) {
// Ignore invalid partition exception in CLOCK ordering mode.
if (ctx.config().getAtomicWriteOrderMode() == CLOCK)
return Collections.singletonList(null);
else
throw e;
}
}
}
else {
List<GridDhtCacheEntry<K, V>> locked = new ArrayList<>(keys.size());
while (true) {
for (K key : keys) {
try {
GridDhtCacheEntry<K, V> entry = entryExx(key, topVer);
locked.add(entry);
}
catch (GridDhtInvalidPartitionException e) {
// Ignore invalid partition exception in CLOCK ordering mode.
if (ctx.config().getAtomicWriteOrderMode() == CLOCK)
locked.add(null);
else
throw e;
}
}
boolean retry = false;
for (int i = 0; i < locked.size(); i++) {
GridCacheMapEntry<K, V> entry = locked.get(i);
if (entry == null)
continue;
UNSAFE.monitorEnter(entry);
if (entry.obsolete()) {
// Unlock all locked.
for (int j = 0; j <= i; j++) {
if (locked.get(j) != null)
UNSAFE.monitorExit(locked.get(j));
}
// Clear entries.
locked.clear();
// Retry.
retry = true;
break;
}
}
if (!retry)
return locked;
}
}
}
/**
* Releases java-level locks on cache entries.
*
* @param locked Locked entries.
* @param topVer Topology version.
*/
private void unlockEntries(Collection<GridDhtCacheEntry<K, V>> locked, long topVer) {
// Process deleted entries before locks release.
assert ctx.deferredDelete();
// Entries to skip eviction manager notification for.
// Enqueue entries while holding locks.
Collection<K> skip = null;
for (GridCacheMapEntry<K, V> entry : locked) {
if (entry != null && entry.deleted()) {
if (skip == null)
skip = new HashSet<>(locked.size(), 1.0f);
skip.add(entry.key());
}
}
// Release locks.
for (GridCacheMapEntry<K, V> entry : locked) {
if (entry != null)
UNSAFE.monitorExit(entry);
}
// Try evict partitions.
for (GridDhtCacheEntry<K, V> entry : locked) {
if (entry != null)
entry.onUnlock();
}
if (skip != null && skip.size() == locked.size())
// Optimization.
return;
// Must touch all entries since update may have deleted entries.
// Eviction manager will remove empty entries.
for (GridCacheMapEntry<K, V> entry : locked) {
if (entry != null && (skip == null || !skip.contains(entry.key())))
ctx.evicts().touch(entry, topVer);
}
}
/**
* @param entry Entry to check.
* @param req Update request.
* @param res Update response. If filter evaluation failed, key will be added to failed keys and method
* will return false.
* @return {@code True} if filter evaluation succeeded.
*/
private boolean checkFilter(GridCacheEntryEx<K, V> entry, GridNearAtomicUpdateRequest<K, V> req,
GridNearAtomicUpdateResponse<K, V> res) {
try {
return ctx.isAll(entry.wrapFilterLocked(), req.filter());
}
catch (GridException e) {
res.addFailedKey(entry.key(), e);
return false;
}
}
/**
* @param req Request to remap.
*/
private void remapToNewPrimary(GridNearAtomicUpdateRequest<K, V> req) {
if (log.isDebugEnabled())
log.debug("Remapping near update request locally: " + req);
Collection<?> vals;
Collection<GridCacheDrInfo<V>> drPutVals;
Collection<GridCacheVersion> drRmvVals;
if (req.drVersions() == null) {
vals = req.values();
drPutVals = null;
drRmvVals = null;
}
else if (req.operation() == UPDATE) {
int size = req.keys().size();
drPutVals = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
Long ttl = req.drTtl(i);
if (ttl == null)
drPutVals.add(new GridCacheDrInfo<>(req.value(i), req.drVersion(i)));
else
drPutVals.add(new GridCacheDrExpirationInfo<>(req.value(i), req.drVersion(i), ttl,
req.drExpireTime(i)));
}
vals = null;
drRmvVals = null;
}
else {
assert req.operation() == DELETE;
drRmvVals = req.drVersions();
vals = null;
drPutVals = null;
}
final GridNearAtomicUpdateFuture<K, V> updateFut = new GridNearAtomicUpdateFuture<>(
ctx,
this,
ctx.config().getWriteSynchronizationMode(),
req.operation(),
req.keys(),
vals,
drPutVals,
drRmvVals,
req.returnValue(),
false,
null,
req.ttl(),
req.filter(),
req.subjectId());
updateFut.map();
}
/**
* Creates backup update future if necessary.
*
* @param writeVer Write version.
* @param updateReq Update request.
* @param updateRes Update response.
* @param completionCb Completion callback to invoke when future is completed.
* @param force If {@code true} then creates future without optimizations checks.
* @return Backup update future or {@code null} if there are no backups.
*/
@Nullable private GridDhtAtomicUpdateFuture<K, V> createDhtFuture(
GridCacheVersion writeVer,
GridNearAtomicUpdateRequest<K, V> updateReq,
GridNearAtomicUpdateResponse<K, V> updateRes,
CI2<GridNearAtomicUpdateRequest<K, V>, GridNearAtomicUpdateResponse<K, V>> completionCb,
boolean force
) {
if (!force) {
if (updateReq.fastMap())
return null;
long topVer = updateReq.topologyVersion();
Collection<GridNode> nodes = ctx.kernalContext().discovery().cacheAffinityNodes(name(), topVer);
// We are on primary node for some key.
assert !nodes.isEmpty();
if (nodes.size() == 1) {
if (log.isDebugEnabled())
log.debug("Partitioned cache topology has only one node, will not create DHT atomic update future " +
"[topVer=" + topVer + ", updateReq=" + updateReq + ']');
return null;
}
}
GridDhtAtomicUpdateFuture<K, V> fut = new GridDhtAtomicUpdateFuture<>(ctx, completionCb, writeVer, updateReq,
updateRes);
ctx.mvcc().addAtomicFuture(fut.version(), fut);
return fut;
}
/**
* @param nodeId Sender node ID.
* @param res Near get response.
*/
private void processNearGetResponse(UUID nodeId, GridNearGetResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing near get response [nodeId=" + nodeId + ", res=" + res + ']');
GridPartitionedGetFuture<K, V> fut = (GridPartitionedGetFuture<K, V>)ctx.mvcc().<Map<K, V>>future(
res.version(), res.futureId());
if (fut == null) {
if (log.isDebugEnabled())
log.debug("Failed to find future for get response [sender=" + nodeId + ", res=" + res + ']');
return;
}
fut.onResult(nodeId, res);
}
/**
* @param nodeId Sender node ID.
* @param req Near atomic update request.
*/
private void processNearAtomicUpdateRequest(UUID nodeId, GridNearAtomicUpdateRequest<K, V> req) {
if (log.isDebugEnabled())
log.debug("Processing near atomic update request [nodeId=" + nodeId + ", req=" + req + ']');
req.nodeId(ctx.localNodeId());
updateAllAsyncInternal(nodeId, req, null, updateReplyClos);
}
/**
* @param nodeId Sender node ID.
* @param res Near atomic update response.
*/
@SuppressWarnings("unchecked")
private void processNearAtomicUpdateResponse(UUID nodeId, GridNearAtomicUpdateResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing near atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
res.nodeId(ctx.localNodeId());
GridNearAtomicUpdateFuture<K, V> fut = (GridNearAtomicUpdateFuture)ctx.mvcc().atomicFuture(res.futureVersion());
if (fut != null)
fut.onResult(nodeId, res);
else
U.warn(log, "Failed to find near update future for update response (will ignore) " +
"[nodeId=" + nodeId + ", res=" + res + ']');
}
/**
* @param nodeId Sender node ID.
* @param req Dht atomic update request.
*/
private void processDhtAtomicUpdateRequest(UUID nodeId, GridDhtAtomicUpdateRequest<K, V> req) {
if (log.isDebugEnabled())
log.debug("Processing dht atomic update request [nodeId=" + nodeId + ", req=" + req + ']');
GridCacheVersion ver = req.writeVersion();
// Always send update reply.
GridDhtAtomicUpdateResponse<K, V> res = new GridDhtAtomicUpdateResponse<>(req.futureVersion());
Boolean replicate = ctx.isDrEnabled();
boolean intercept = req.forceTransformBackups() && ctx.config().getInterceptor() != null;
for (int i = 0; i < req.size(); i++) {
K key = req.key(i);
try {
while (true) {
GridDhtCacheEntry<K, V> entry = null;
try {
entry = entryExx(key);
V val = req.value(i);
byte[] valBytes = req.valueBytes(i);
GridClosure<V, V> transform = req.transformClosure(i);
GridCacheOperation op = transform != null ? TRANSFORM :
(val != null || valBytes != null) ?
UPDATE :
DELETE;
GridCacheUpdateAtomicResult<K, V> updRes = entry.innerUpdate(
ver,
nodeId,
nodeId,
op,
op == TRANSFORM ? transform : val,
valBytes,
/*write-through*/false,
/*retval*/false,
req.ttl(),
/*event*/true,
/*metrics*/true,
/*primary*/false,
/*check version*/!req.forceTransformBackups(),
CU.<K, V>empty(),
replicate ? DR_BACKUP : DR_NONE,
req.drTtl(i),
req.drExpireTime(i),
req.drVersion(i),
false,
intercept,
req.subjectId());
if (updRes.removeVersion() != null)
ctx.onDeferredDelete(entry, updRes.removeVersion());
entry.onUnlock();
break; // While.
}
catch (GridCacheEntryRemovedException ignored) {
if (log.isDebugEnabled())
log.debug("Got removed entry while updating backup value (will retry): " + key);
entry = null;
}
finally {
if (entry != null)
ctx.evicts().touch(entry, req.topologyVersion());
}
}
}
catch (GridDhtInvalidPartitionException ignored) {
// Ignore.
}
catch (GridException e) {
res.addFailedKey(key, new GridException("Failed to update key on backup node: " + key, e));
}
}
if (isNearEnabled(cacheCfg))
((GridNearAtomicCache<K, V>)near()).processDhtAtomicUpdateRequest(nodeId, req, res);
try {
if (res.failedKeys() != null || res.nearEvicted() != null || req.writeSynchronizationMode() == FULL_SYNC)
ctx.io().send(nodeId, res);
else {
// No failed keys and sync mode is not FULL_SYNC, thus sending deferred response.
sendDeferredUpdateResponse(nodeId, req.futureVersion());
}
}
catch (GridTopologyException ignored) {
U.warn(log, "Failed to send DHT atomic update response to node because it left grid: " +
req.nodeId());
}
catch (GridException e) {
U.error(log, "Failed to send DHT atomic update response (did node leave grid?) [nodeId=" + nodeId +
", req=" + req + ']', e);
}
}
/**
* Checks if entries being transformed are empty. Clears forceTransformBackup flag enforcing
* sending transformed value to backups if at least one empty entry is found.
*
* @param req Near atomic update request.
* @param locked Already locked entries (from the request).
*/
@SuppressWarnings("ForLoopReplaceableByForEach")
private void checkClearForceTransformBackups(GridNearAtomicUpdateRequest<K, V> req,
List<GridDhtCacheEntry<K, V>> locked) {
if (ctx.isStoreEnabled() && req.operation() == TRANSFORM) {
for (int i = 0; i < locked.size(); i++) {
if (!locked.get(i).hasValue()) {
req.forceTransformBackups(false);
return;
}
}
}
}
/**
* @param nodeId Node ID to send message to.
* @param ver Version to ack.
*/
private void sendDeferredUpdateResponse(UUID nodeId, GridCacheVersion ver) {
while (true) {
DeferredResponseBuffer buf = pendingResponses.get(nodeId);
if (buf == null) {
buf = new DeferredResponseBuffer(nodeId);
DeferredResponseBuffer old = pendingResponses.putIfAbsent(nodeId, buf);
if (old == null) {
// We have successfully added buffer to map.
ctx.time().addTimeoutObject(buf);
}
else
buf = old;
}
if (!buf.addResponse(ver))
// Some thread is sending filled up buffer, we can remove it.
pendingResponses.remove(nodeId, buf);
else
break;
}
}
/**
* @param nodeId Sender node ID.
* @param res Dht atomic update response.
*/
private void processDhtAtomicUpdateResponse(UUID nodeId, GridDhtAtomicUpdateResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing dht atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
GridDhtAtomicUpdateFuture<K, V> updateFut = (GridDhtAtomicUpdateFuture<K, V>)ctx.mvcc().
atomicFuture(res.futureVersion());
if (updateFut != null)
updateFut.onResult(nodeId, res);
else
U.warn(log, "Failed to find DHT update future for update response [nodeId=" + nodeId +
", res=" + res + ']');
}
/**
* @param nodeId Sender node ID.
* @param res Deferred atomic update response.
*/
private void processDhtAtomicDeferredUpdateResponse(UUID nodeId, GridDhtAtomicDeferredUpdateResponse<K, V> res) {
if (log.isDebugEnabled())
log.debug("Processing deferred dht atomic update response [nodeId=" + nodeId + ", res=" + res + ']');
for (GridCacheVersion ver : res.futureVersions()) {
GridDhtAtomicUpdateFuture<K, V> updateFut = (GridDhtAtomicUpdateFuture<K, V>)ctx.mvcc().atomicFuture(ver);
if (updateFut != null)
updateFut.onResult(nodeId);
else
U.warn(log, "Failed to find DHT update future for deferred update response [nodeId=" +
nodeId + ", res=" + res + ']');
}
}
/**
* @param nodeId Originating node ID.
* @param res Near update response.
*/
private void sendNearUpdateReply(UUID nodeId, GridNearAtomicUpdateResponse<K, V> res) {
try {
ctx.io().send(nodeId, res);
}
catch (GridTopologyException ignored) {
U.warn(log, "Failed to send near update reply to node because it left grid: " +
nodeId);
}
catch (GridException e) {
U.error(log, "Failed to send near update reply (did node leave grid?) [nodeId=" + nodeId +
", res=" + res + ']', e);
}
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridDhtAtomicCache.class, this, super.toString());
}
/**
* Result of {@link GridDhtAtomicCache#updateSingle} execution.
*/
private static class UpdateSingleResult<K, V> {
private final GridCacheReturn<Object> retVal;
private final Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted;
private final GridDhtAtomicUpdateFuture<K, V> dhtFut;
/**
* @param retVal Return value.
* @param deleted Deleted entries.
* @param dhtFut DHT future.
*/
private UpdateSingleResult(GridCacheReturn<Object> retVal,
Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted,
GridDhtAtomicUpdateFuture<K, V> dhtFut) {
this.retVal = retVal;
this.deleted = deleted;
this.dhtFut = dhtFut;
}
/**
* @return Return value.
*/
private GridCacheReturn<Object> returnValue() {
return retVal;
}
/**
* @return Deleted entries.
*/
private Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted() {
return deleted;
}
/**
* @return DHT future.
*/
public GridDhtAtomicUpdateFuture<K, V> dhtFuture() {
return dhtFut;
}
}
/**
* Result of {@link GridDhtAtomicCache#updateWithBatch} execution.
*/
private static class UpdateBatchResult<K, V> {
private Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted;
private GridDhtAtomicUpdateFuture<K, V> dhtFut;
private boolean readersOnly;
/**
* @param entry Entry.
* @param updRes Entry update result.
* @param entries All entries.
*/
private void addDeleted(GridDhtCacheEntry<K, V> entry, GridCacheUpdateAtomicResult<K, V> updRes,
Collection<GridDhtCacheEntry<K, V>> entries) {
if (updRes.removeVersion() != null) {
if (deleted == null)
deleted = new ArrayList<>(entries.size());
deleted.add(F.t(entry, updRes.removeVersion()));
}
}
/**
* @return Deleted entries.
*/
private Collection<GridBiTuple<GridDhtCacheEntry<K, V>, GridCacheVersion>> deleted() {
return deleted;
}
/**
* @return DHT future.
*/
public GridDhtAtomicUpdateFuture<K, V> dhtFuture() {
return dhtFut;
}
/**
* @param dhtFut DHT future.
*/
private void dhtFuture(@Nullable GridDhtAtomicUpdateFuture<K, V> dhtFut) {
this.dhtFut = dhtFut;
}
/**
* @return {@code True} if only readers (not backups) should be updated.
*/
private boolean readersOnly() {
return readersOnly;
}
/**
* @param readersOnly {@code True} if only readers (not backups) should be updated.
*/
private void readersOnly(boolean readersOnly) {
this.readersOnly = readersOnly;
}
}
private static class FinishedLockFuture extends GridFinishedFutureEx<Boolean> implements GridDhtFuture<Boolean> {
private static final long serialVersionUID = 0L;
/**
* Empty constructor required by {@link Externalizable}.
*/
public FinishedLockFuture() {
// No-op.
}
/**
* @param err Error.
*/
private FinishedLockFuture(Throwable err) {
super(err);
}
/** {@inheritDoc} */
@Override public Collection<Integer> invalidPartitions() {
return Collections.emptyList();
}
}
/**
* Deferred response buffer.
*/
private class DeferredResponseBuffer extends ReentrantReadWriteLock implements GridTimeoutObject {
private static final long serialVersionUID = 0L;
/** Filled atomic flag. */
private AtomicBoolean guard = new AtomicBoolean(false);
/** Response versions. */
private Collection<GridCacheVersion> respVers = new ConcurrentLinkedDeque8<>();
/** Node ID. */
private final UUID nodeId;
/** Timeout ID. */
private final GridUuid timeoutId;
/** End time. */
private final long endTime;
/**
* @param nodeId Node ID to send message to.
*/
private DeferredResponseBuffer(UUID nodeId) {
this.nodeId = nodeId;
timeoutId = GridUuid.fromUuid(nodeId);
endTime = U.currentTimeMillis() + DEFERRED_UPDATE_RESPONSE_TIMEOUT;
}
/** {@inheritDoc} */
@Override public GridUuid timeoutId() {
return timeoutId;
}
/** {@inheritDoc} */
@Override public long endTime() {
return endTime;
}
/** {@inheritDoc} */
@Override public void onTimeout() {
if (guard.compareAndSet(false, true)) {
writeLock().lock();
try {
finish();
}
finally {
writeLock().unlock();
}
}
}
/**
* Adds deferred response to buffer.
*
* @param ver Version to send.
* @return {@code True} if response was handled, {@code false} if this buffer is filled and cannot be used.
*/
public boolean addResponse(GridCacheVersion ver) {
readLock().lock();
boolean snd = false;
try {
if (guard.get())
return false;
respVers.add(ver);
if (respVers.size() > DEFERRED_UPDATE_RESPONSE_BUFFER_SIZE && guard.compareAndSet(false, true))
snd = true;
}
finally {
readLock().unlock();
}
if (snd) {
// Wait all threads in read lock to finish.
writeLock().lock();
try {
finish();
ctx.time().removeTimeoutObject(this);
}
finally {
writeLock().unlock();
}
}
return true;
}
/**
* Sends deferred notification message and removes this buffer from pending responses map.
*/
private void finish() {
GridDhtAtomicDeferredUpdateResponse<K, V> msg = new GridDhtAtomicDeferredUpdateResponse<>(respVers);
try {
ctx.gate().enter();
try {
ctx.io().send(nodeId, msg);
}
finally {
ctx.gate().leave();
}
}
catch (IllegalStateException ignored) {
if (log.isDebugEnabled())
log.debug("Failed to send deferred dht update response to remote node (grid is stopping) " +
"[nodeId=" + nodeId + ", msg=" + msg + ']');
}
catch (GridTopologyException ignored) {
if (log.isDebugEnabled())
log.debug("Failed to send deferred dht update response to remote node (did node leave grid?) " +
"[nodeId=" + nodeId + ", msg=" + msg + ']');
}
catch (GridException e) {
U.error(log, "Failed to send deferred dht update response to remote node [nodeId="
+ nodeId + ", msg=" + msg + ']', e);
}
pendingResponses.remove(nodeId, this);
}
}
@SuppressWarnings("PublicInnerClass")
public static class DhtAtomicUpdateRequestConverter603 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 1:
if (!commState.putInt(-1))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 1:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
}
return true;
}
}
@SuppressWarnings("PublicInnerClass")
public static class DhtAtomicUpdateResponseConverter603 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putInt(-1))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
}
return true;
}
}
@SuppressWarnings("PublicInnerClass")
public static class NearAtomicUpdateResponseConverter603 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 1:
if (!commState.putLong(0))
return false;
commState.idx++;
case 2:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 3:
if (!commState.putInt(-1))
return false;
commState.idx++;
case 4:
if (!commState.putCacheVersion(null))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 1:
if (buf.remaining() < 8)
return false;
long nearTtl = commState.getLong();
assert nearTtl == 0 : nearTtl;
commState.idx++;
case 2:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 3:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
assert commState.readSize == -1 : commState.readSize;
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 4:
GridCacheVersion nearVer0 = commState.getCacheVersion();
if (nearVer0 == CACHE_VER_NOT_READ)
return false;
assert nearVer0 == null : nearVer0;
commState.idx++;
}
return true;
}
}
/**
* GridNearAtomicUpdateRequest converter for version 6.1.2
*/
@SuppressWarnings("PublicInnerClass")
public static class GridNearAtomicUpdateRequestConverter612 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (!commState.putBoolean(false))
return false;
commState.idx++;
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0: {
if (buf.remaining() < 1)
return false;
commState.getBoolean();
commState.idx++;
}
}
return true;
}
}
/**
* GridDhtAtomicUpdateRequest converter for version 6.1.2
*/
@SuppressWarnings("PublicInnerClass")
public static class GridDhtAtomicUpdateRequestConverter612 extends GridVersionConverter {
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0: {
if (!commState.putInt(-1))
return false;
commState.idx++;
}
case 1: {
if (!commState.putBoolean(false))
return false;
commState.idx++;
}
case 2: {
if (!commState.putInt(-1))
return false;
commState.idx++;
}
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf) {
commState.setBuffer(buf);
switch (commState.idx) {
case 0:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
if (commState.readSize >= 0) {
for (int i = commState.readItems; i < commState.readSize; i++) {
byte[] _val = commState.getByteArray();
if (_val == BYTE_ARR_NOT_READ)
return false;
commState.readItems++;
}
}
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
case 1:
if (buf.remaining() < 1)
return false;
commState.getBoolean();
commState.idx++;
case 2:
if (commState.readSize == -1) {
if (buf.remaining() < 4)
return false;
commState.readSize = commState.getInt();
}
if (commState.readSize >= 0) {
for (int i = commState.readItems; i < commState.readSize; i++) {
byte[] _val = commState.getByteArray();
if (_val == BYTE_ARR_NOT_READ)
return false;
commState.readItems++;
}
}
commState.readSize = -1;
commState.readItems = 0;
commState.idx++;
}
return true;
}
}
}
|
package com.opengamma.strata.function.marketdata.curve;
import static com.opengamma.strata.collect.CollectProjectAssertions.assertThat;
import static com.opengamma.strata.collect.Guavate.toImmutableList;
import static com.opengamma.strata.collect.TestHelper.date;
import static org.assertj.core.api.Assertions.offset;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import org.jooq.lambda.Seq;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.currency.CurrencyAmount;
import com.opengamma.strata.basics.currency.MultiCurrencyAmount;
import com.opengamma.strata.basics.date.DayCounts;
import com.opengamma.strata.basics.date.Tenor;
import com.opengamma.strata.basics.index.IborIndices;
import com.opengamma.strata.basics.market.MarketDataFeed;
import com.opengamma.strata.basics.market.MarketDataKey;
import com.opengamma.strata.basics.market.ObservableId;
import com.opengamma.strata.basics.market.ObservableKey;
import com.opengamma.strata.collect.result.Result;
import com.opengamma.strata.collect.timeseries.LocalDateDoubleTimeSeries;
import com.opengamma.strata.engine.calculations.DefaultSingleCalculationMarketData;
import com.opengamma.strata.engine.marketdata.BaseMarketData;
import com.opengamma.strata.engine.marketdata.CalculationMarketData;
import com.opengamma.strata.engine.marketdata.MarketDataRequirements;
import com.opengamma.strata.engine.marketdata.config.MarketDataConfig;
import com.opengamma.strata.finance.Trade;
import com.opengamma.strata.finance.rate.fra.FraTrade;
import com.opengamma.strata.finance.rate.swap.SwapTrade;
import com.opengamma.strata.function.MarketDataRatesProvider;
import com.opengamma.strata.function.interpolator.CurveExtrapolators;
import com.opengamma.strata.function.interpolator.CurveInterpolators;
import com.opengamma.strata.market.curve.Curve;
import com.opengamma.strata.market.curve.CurveGroup;
import com.opengamma.strata.market.curve.CurveGroupName;
import com.opengamma.strata.market.curve.CurveMetadata;
import com.opengamma.strata.market.curve.CurveName;
import com.opengamma.strata.market.curve.CurveParameterMetadata;
import com.opengamma.strata.market.curve.ParRates;
import com.opengamma.strata.market.curve.config.CurveGroupConfig;
import com.opengamma.strata.market.curve.config.CurveNode;
import com.opengamma.strata.market.curve.config.FixedIborSwapCurveNode;
import com.opengamma.strata.market.curve.config.FraCurveNode;
import com.opengamma.strata.market.curve.config.InterpolatedCurveConfig;
import com.opengamma.strata.market.id.CurveGroupId;
import com.opengamma.strata.market.id.ParRatesId;
import com.opengamma.strata.market.key.DiscountFactorsKey;
import com.opengamma.strata.market.key.IndexRateKey;
import com.opengamma.strata.market.key.RateIndexCurveKey;
import com.opengamma.strata.market.value.DiscountFactors;
import com.opengamma.strata.market.value.ZeroRateDiscountFactors;
import com.opengamma.strata.pricer.rate.RatesProvider;
import com.opengamma.strata.pricer.rate.fra.DiscountingFraTradePricer;
import com.opengamma.strata.pricer.rate.swap.DiscountingSwapTradePricer;
@Test
public class CurveGroupMarketDataFunctionTest {
/** The maximum allowable PV when round-tripping an instrument used to calibrate a curve. */
private static final double PV_TOLERANCE = 5e-10;
/**
* Tests calibration a curve containing FRAs and pricing the curve instruments using the curve.
*/
public void roundTripFra() {
InterpolatedCurveConfig curveConfig = CurveTestUtils.fraCurveConfig();
List<FraCurveNode> nodes = curveConfig.getNodes().stream()
.map(FraCurveNode.class::cast)
.collect(toImmutableList());
List<ObservableId> ids = nodes.stream().map(CurveTestUtils::id).collect(toImmutableList());
Map<ObservableId, Double> parRateData = ImmutableMap.<ObservableId, Double>builder()
.put(ids.get(0), 0.003)
.put(ids.get(1), 0.0033)
.put(ids.get(2), 0.0037)
.put(ids.get(3), 0.0054)
.put(ids.get(4), 0.007)
.put(ids.get(5), 0.0091)
.put(ids.get(6), 0.0134)
.build();
CurveGroupName groupName = CurveGroupName.of("Curve Group");
CurveName curveName = CurveName.of("FRA Curve");
ParRates parRates = ParRates.of(parRateData, CurveMetadata.of(curveName));
CurveGroupConfig groupConfig = CurveGroupConfig.builder()
.name(groupName)
.addCurve(curveConfig, Currency.USD, IborIndices.USD_LIBOR_3M)
.build();
CurveGroupMarketDataFunction function = new CurveGroupMarketDataFunction(RootFinderConfig.defaults());
LocalDate valuationDate = date(2011, 3, 8);
BaseMarketData marketData = BaseMarketData.builder(valuationDate)
.addValue(ParRatesId.of(groupName, curveName, MarketDataFeed.NONE), parRates)
.build();
Result<CurveGroup> result = function.buildCurveGroup(groupConfig, marketData, MarketDataFeed.NONE);
assertThat(result).isSuccess();
CurveGroup curveGroup = result.getValue();
Curve curve = curveGroup.getDiscountCurve(Currency.USD).get();
DiscountFactorsKey discountFactorsKey = DiscountFactorsKey.of(Currency.USD);
RateIndexCurveKey forwardCurveKey = RateIndexCurveKey.of(IborIndices.USD_LIBOR_3M);
Map<ObservableKey, Double> quotesMap = Seq.seq(parRateData).toMap(tp -> tp.v1.toObservableKey(), tp -> tp.v2);
DiscountFactors discountFactors =
ZeroRateDiscountFactors.of(Currency.USD, valuationDate, DayCounts.ACT_ACT_ISDA, curve);
Map<MarketDataKey<?>, Object> marketDataMap = ImmutableMap.<MarketDataKey<?>, Object>builder()
.putAll(quotesMap)
.put(discountFactorsKey, discountFactors)
.put(forwardCurveKey, curve)
.build();
Map<ObservableKey, LocalDateDoubleTimeSeries> timeSeries =
ImmutableMap.of(IndexRateKey.of(IborIndices.USD_LIBOR_3M), LocalDateDoubleTimeSeries.empty());
CalculationMarketData calculationMarketData = new MarketDataMap(valuationDate, marketDataMap, timeSeries);
MarketDataRatesProvider ratesProvider =
new MarketDataRatesProvider(new DefaultSingleCalculationMarketData(calculationMarketData, 0));
// The PV should be zero for an instrument used to build the curve
nodes.stream().forEach(node -> checkFraPvIsZero(node, valuationDate, ratesProvider, quotesMap));
}
public void roundTripFraAndFixedFloatSwap() {
CurveGroupName groupName = CurveGroupName.of("Curve Group");
InterpolatedCurveConfig curveConfig = CurveTestUtils.fraSwapCurveConfig();
CurveName curveName = curveConfig.getName();
List<CurveNode> nodes = curveConfig.getNodes();
CurveGroupConfig groupConfig = CurveGroupConfig.builder()
.name(groupName)
.addCurve(curveConfig, Currency.USD, IborIndices.USD_LIBOR_3M)
.build();
CurveGroupMarketDataFunction function = new CurveGroupMarketDataFunction(RootFinderConfig.defaults());
LocalDate valuationDate = date(2011, 3, 8);
Map<ObservableId, Double> parRateData = ImmutableMap.<ObservableId, Double>builder()
.put(CurveTestUtils.id(nodes.get(0)), 0.0037)
.put(CurveTestUtils.id(nodes.get(1)), 0.0054)
.put(CurveTestUtils.id(nodes.get(2)), 0.005)
.put(CurveTestUtils.id(nodes.get(3)), 0.0087)
.put(CurveTestUtils.id(nodes.get(4)), 0.012)
.build();
ParRates parRates = ParRates.of(parRateData, CurveMetadata.of(curveName));
BaseMarketData marketData = BaseMarketData.builder(valuationDate)
.addValue(ParRatesId.of(groupName, curveName, MarketDataFeed.NONE), parRates)
.build();
Result<CurveGroup> result = function.buildCurveGroup(groupConfig, marketData, MarketDataFeed.NONE);
assertThat(result).isSuccess();
CurveGroup curveGroup = result.getValue();
Curve curve = curveGroup.getDiscountCurve(Currency.USD).get();
DiscountFactors discountFactors =
ZeroRateDiscountFactors.of(Currency.USD, valuationDate, DayCounts.ACT_ACT_ISDA, curve);
DiscountFactorsKey discountFactorsKey = DiscountFactorsKey.of(Currency.USD);
RateIndexCurveKey forwardCurveKey = RateIndexCurveKey.of(IborIndices.USD_LIBOR_3M);
Map<ObservableKey, Double> quotesMap = Seq.seq(parRateData).toMap(tp -> tp.v1.toObservableKey(), tp -> tp.v2);
Map<MarketDataKey<?>, Object> marketDataMap = ImmutableMap.<MarketDataKey<?>, Object>builder()
.putAll(quotesMap)
.put(discountFactorsKey, discountFactors)
.put(forwardCurveKey, curve)
.build();
Map<ObservableKey, LocalDateDoubleTimeSeries> timeSeries =
ImmutableMap.of(IndexRateKey.of(IborIndices.USD_LIBOR_3M), LocalDateDoubleTimeSeries.empty());
CalculationMarketData calculationMarketData = new MarketDataMap(valuationDate, marketDataMap, timeSeries);
MarketDataRatesProvider ratesProvider =
new MarketDataRatesProvider(new DefaultSingleCalculationMarketData(calculationMarketData, 0));
checkFraPvIsZero((FraCurveNode) nodes.get(0), valuationDate, ratesProvider, quotesMap);
checkFraPvIsZero((FraCurveNode) nodes.get(1), valuationDate, ratesProvider, quotesMap);
checkSwapPvIsZero((FixedIborSwapCurveNode) nodes.get(2), valuationDate, ratesProvider, quotesMap);
checkSwapPvIsZero((FixedIborSwapCurveNode) nodes.get(3), valuationDate, ratesProvider, quotesMap);
checkSwapPvIsZero((FixedIborSwapCurveNode) nodes.get(4), valuationDate, ratesProvider, quotesMap);
}
/**
* Tests that par rates are required for curves.
*/
public void requirements() {
FraCurveNode node1x4 = CurveTestUtils.fraNode(1, "foo");
List<CurveNode> nodes = ImmutableList.of(node1x4);
CurveGroupName groupName = CurveGroupName.of("Curve Group");
CurveName curveName = CurveName.of("FRA Curve");
MarketDataFeed feed = MarketDataFeed.of("TestFeed");
InterpolatedCurveConfig curveConfig = InterpolatedCurveConfig.builder()
.name(curveName)
.nodes(nodes)
.interpolator(CurveInterpolators.DOUBLE_QUADRATIC)
.leftExtrapolator(CurveExtrapolators.FLAT)
.rightExtrapolator(CurveExtrapolators.FLAT)
.build();
CurveGroupConfig groupConfig = CurveGroupConfig.builder()
.name(groupName)
.addCurve(curveConfig, Currency.USD, IborIndices.USD_LIBOR_3M)
.build();
MarketDataConfig marketDataConfig = MarketDataConfig.builder()
.add(groupName, groupConfig)
.build();
CurveGroupMarketDataFunction function = new CurveGroupMarketDataFunction(RootFinderConfig.defaults());
CurveGroupId curveGroupId = CurveGroupId.of(groupName, feed);
MarketDataRequirements requirements = function.requirements(curveGroupId, marketDataConfig);
assertThat(requirements.getNonObservables()).contains(ParRatesId.of(groupName, curveName, feed));
}
public void metadata() {
CurveGroupName groupName = CurveGroupName.of("Curve Group");
InterpolatedCurveConfig fraSwapCurveConfig = CurveTestUtils.fraSwapCurveConfig();
List<CurveNode> fraSwapNodes = fraSwapCurveConfig.getNodes();
InterpolatedCurveConfig fraCurveConfig = CurveTestUtils.fraCurveConfig();
List<CurveNode> fraNodes = fraCurveConfig.getNodes();
CurveGroupConfig groupConfig = CurveGroupConfig.builder()
.name(groupName)
.addDiscountingCurve(fraSwapCurveConfig, Currency.USD)
.addForwardCurve(fraCurveConfig, IborIndices.USD_LIBOR_3M)
.build();
MarketDataConfig marketDataConfig = MarketDataConfig.builder()
.add(groupName, groupConfig)
.build();
CurveGroupId curveGroupId = CurveGroupId.of(groupName);
Map<ObservableId, Double> fraParRateData = ImmutableMap.<ObservableId, Double>builder()
.put(CurveTestUtils.id(fraNodes.get(0)), 0.003)
.put(CurveTestUtils.id(fraNodes.get(1)), 0.0033)
.put(CurveTestUtils.id(fraNodes.get(2)), 0.0037)
.put(CurveTestUtils.id(fraNodes.get(3)), 0.0054)
.put(CurveTestUtils.id(fraNodes.get(4)), 0.007)
.put(CurveTestUtils.id(fraNodes.get(5)), 0.0091)
.put(CurveTestUtils.id(fraNodes.get(6)), 0.0134).build();
Map<ObservableId, Double> fraSwapParRateData = ImmutableMap.<ObservableId, Double>builder()
.put(CurveTestUtils.id(fraSwapNodes.get(0)), 0.0037)
.put(CurveTestUtils.id(fraSwapNodes.get(1)), 0.0054)
.put(CurveTestUtils.id(fraSwapNodes.get(2)), 0.005)
.put(CurveTestUtils.id(fraSwapNodes.get(3)), 0.0087)
.put(CurveTestUtils.id(fraSwapNodes.get(4)), 0.012).build();
LocalDate valuationDate = date(2011, 3, 8);
ParRates fraParRates = ParRates.of(fraParRateData, fraCurveConfig.metadata(valuationDate));
ParRates fraSwapParRates = ParRates.of(fraSwapParRateData, fraCurveConfig.metadata(valuationDate));
BaseMarketData marketData = BaseMarketData.builder(valuationDate)
.addValue(ParRatesId.of(groupName, fraCurveConfig.getName(), MarketDataFeed.NONE), fraParRates)
.addValue(ParRatesId.of(groupName, fraSwapCurveConfig.getName(), MarketDataFeed.NONE), fraSwapParRates)
.build();
CurveGroupMarketDataFunction function = new CurveGroupMarketDataFunction(RootFinderConfig.defaults());
Result<CurveGroup> result = function.build(curveGroupId, marketData, marketDataConfig);
assertThat(result).isSuccess();
CurveGroup curveGroup = result.getValue();
// Check the FRA/Swap curve identifiers are the expected tenors
Curve discountCurve = curveGroup.getDiscountCurve(Currency.USD).get();
List<CurveParameterMetadata> discountMetadata = discountCurve.getMetadata().getParameters().get();
List<Object> discountTenors = discountMetadata.stream()
.map(CurveParameterMetadata::getIdentifier)
.collect(toImmutableList());
List<Tenor> expectedDiscountTenors =
ImmutableList.of(Tenor.TENOR_6M, Tenor.TENOR_9M, Tenor.TENOR_1Y, Tenor.TENOR_2Y, Tenor.TENOR_3Y);
assertThat(discountTenors).isEqualTo(expectedDiscountTenors);
List<CurveParameterMetadata> expectedDiscountMetadata = fraSwapNodes.stream()
.map(node -> node.metadata(valuationDate))
.collect(toImmutableList());
assertThat(discountMetadata).isEqualTo(expectedDiscountMetadata);
// Check the FRA curve identifiers are the expected tenors
Curve forwardCurve = curveGroup.getForwardCurve(IborIndices.USD_LIBOR_3M).get();
List<CurveParameterMetadata> forwardMetadata = forwardCurve.getMetadata().getParameters().get();
List<Object> forwardTenors = forwardMetadata.stream()
.map(CurveParameterMetadata::getIdentifier)
.collect(toImmutableList());
List<Tenor> expectedForwardTenors =
ImmutableList.of(
Tenor.TENOR_4M,
Tenor.TENOR_5M,
Tenor.TENOR_6M,
Tenor.TENOR_9M,
Tenor.TENOR_12M,
Tenor.ofMonths(15),
Tenor.ofMonths(21));
assertThat(forwardTenors).isEqualTo(expectedForwardTenors);
List<CurveParameterMetadata> expectedForwardMetadata = fraNodes.stream()
.map(node -> node.metadata(valuationDate))
.collect(toImmutableList());
assertThat(forwardMetadata).isEqualTo(expectedForwardMetadata);
}
private void checkFraPvIsZero(
FraCurveNode node,
LocalDate valuationDate,
RatesProvider ratesProvider,
Map<ObservableKey, Double> marketDataMap) {
Trade trade = node.trade(valuationDate, marketDataMap);
CurrencyAmount currencyAmount = DiscountingFraTradePricer.DEFAULT.presentValue((FraTrade) trade, ratesProvider);
double pv = currencyAmount.getAmount();
assertThat(pv).isCloseTo(0, offset(PV_TOLERANCE));
}
private void checkSwapPvIsZero(
FixedIborSwapCurveNode node,
LocalDate valuationDate,
RatesProvider ratesProvider,
Map<ObservableKey, Double> marketDataMap) {
Trade trade = node.trade(valuationDate, marketDataMap);
MultiCurrencyAmount amount = DiscountingSwapTradePricer.DEFAULT.presentValue((SwapTrade) trade, ratesProvider);
double pv = amount.getAmount(Currency.USD).getAmount();
assertThat(pv).isCloseTo(0, offset(PV_TOLERANCE));
}
}
|
package com.google.android.gms.nearby.exposurenotification;
import org.microg.safeparcel.AutoSafeParcelable;
import java.util.Arrays;
public class TemporaryExposureKey extends AutoSafeParcelable {
@Field(1)
private byte[] keyData;
@Field(2)
private int rollingStartIntervalNumber;
@Field(3)
@RiskLevel
private int transmissionRiskLevel;
@Field(4)
private int rollingPeriod;
private TemporaryExposureKey() {
}
TemporaryExposureKey(byte[] keyData, int rollingStartIntervalNumber, @RiskLevel int transmissionRiskLevel, int rollingPeriod) {
this.keyData = (keyData == null ? new byte[0] : keyData);
this.rollingStartIntervalNumber = rollingStartIntervalNumber;
this.transmissionRiskLevel = transmissionRiskLevel;
this.rollingPeriod = rollingPeriod;
}
public byte[] getKeyData() {
return Arrays.copyOf(keyData, keyData.length);
}
public int getRollingStartIntervalNumber() {
return rollingStartIntervalNumber;
}
@RiskLevel
public int getTransmissionRiskLevel() {
return transmissionRiskLevel;
}
public int getRollingPeriod() {
return rollingPeriod;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TemporaryExposureKey that = (TemporaryExposureKey) o;
if (rollingStartIntervalNumber != that.rollingStartIntervalNumber) return false;
if (transmissionRiskLevel != that.transmissionRiskLevel) return false;
if (rollingPeriod != that.rollingPeriod) return false;
return Arrays.equals(keyData, that.keyData);
}
@Override
public int hashCode() {
int result = Arrays.hashCode(keyData);
result = 31 * result + rollingStartIntervalNumber;
result = 31 * result + transmissionRiskLevel;
result = 31 * result + rollingPeriod;
return result;
}
@Override
public String toString() {
return "TemporaryExposureKey{" +
"keyData=" + Arrays.toString(keyData) +
", rollingStartIntervalNumber=" + rollingStartIntervalNumber +
", transmissionRiskLevel=" + transmissionRiskLevel +
", rollingPeriod=" + rollingPeriod +
'}';
}
public static class TemporaryExposureKeyBuilder {
private byte[] keyData;
private int rollingStartIntervalNumber;
@RiskLevel
private int transmissionRiskLevel;
private int rollingPeriod;
public TemporaryExposureKeyBuilder setKeyData(byte[] keyData) {
this.keyData = Arrays.copyOf(keyData, keyData.length);
return this;
}
public TemporaryExposureKeyBuilder setRollingStartIntervalNumber(int rollingStartIntervalNumber) {
this.rollingStartIntervalNumber = rollingStartIntervalNumber;
return this;
}
public TemporaryExposureKeyBuilder setTransmissionRiskLevel(@RiskLevel int transmissionRiskLevel) {
this.transmissionRiskLevel = transmissionRiskLevel;
return this;
}
public TemporaryExposureKeyBuilder setRollingPeriod(int rollingPeriod) {
this.rollingPeriod = rollingPeriod;
return this;
}
public TemporaryExposureKey build() {
return new TemporaryExposureKey(keyData, rollingStartIntervalNumber, transmissionRiskLevel, rollingPeriod);
}
}
public static final Creator<TemporaryExposureKey> CREATOR = new AutoCreator<>(TemporaryExposureKey.class);
}
|
package com.intellij.refactoring.typeMigration.intentions;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.typeMigration.TypeConversionDescriptor;
import com.intellij.refactoring.typeMigration.TypeMigrationLabeler;
import com.intellij.refactoring.typeMigration.TypeMigrationReplacementUtil;
import com.intellij.refactoring.typeMigration.TypeMigrationRules;
import com.intellij.refactoring.typeMigration.rules.ThreadLocalConversionRule;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
public class ConvertFieldToThreadLocalIntention extends PsiElementBaseIntentionAction {
private static final Logger LOG = Logger.getInstance("#" + ConvertFieldToThreadLocalIntention.class.getName());
@NotNull
public String getText() {
return "Convert to ThreadLocal";
}
@NotNull
public String getFamilyName() {
return getText();
}
@Override
public boolean isAvailable(@NotNull Project project, Editor editor, @Nullable PsiElement element) {
final PsiField psiField = PsiTreeUtil.getParentOfType(element, PsiField.class);
if (psiField == null) return false;
if (psiField.getTypeElement() == null) return false;
final PsiType fieldType = psiField.getType();
final PsiClass fieldTypeClass = PsiUtil.resolveClassInType(fieldType);
if (fieldType instanceof PsiPrimitiveType) return true;
return fieldTypeClass != null && !Comparing.strEqual(fieldTypeClass.getQualifiedName(), ThreadLocal.class.getName());
}
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
if (!CodeInsightUtilBase.prepareFileForWrite(file)) return;
final PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
final PsiField psiField = PsiTreeUtil.getParentOfType(element, PsiField.class);
LOG.assertTrue(psiField != null);
final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
final PsiType fromType = psiField.getType();
final PsiClass threadLocalClass = psiFacade.findClass(ThreadLocal.class.getName(), GlobalSearchScope.allScope(project));
if (threadLocalClass == null) {//show warning
return;
}
final HashMap<PsiTypeParameter, PsiType> substitutor = new HashMap<PsiTypeParameter, PsiType>();
final PsiTypeParameter[] typeParameters = threadLocalClass.getTypeParameters();
if (typeParameters.length == 1) {
substitutor.put(typeParameters[0], fromType instanceof PsiPrimitiveType ? ((PsiPrimitiveType)fromType).getBoxedType(file) : fromType);
}
final PsiClassType toType = elementFactory.createType(threadLocalClass, elementFactory.createSubstitutor(substitutor));
try {
psiField.getTypeElement().replace(elementFactory.createTypeElement(toType));
final TypeMigrationRules rules = new TypeMigrationRules(fromType);
rules.setMigrationRootType(toType);
rules.setBoundScope(GlobalSearchScope.fileScope(file));
final TypeMigrationLabeler labeler = new TypeMigrationLabeler(rules);
labeler.getMigratedUsages(psiField, false);
for (PsiReference reference : ReferencesSearch.search(psiField)) {
PsiElement psiElement = reference.getElement();
if (psiElement instanceof PsiExpression) {
if (psiElement.getParent() instanceof PsiExpression) {
psiElement = psiElement.getParent();
}
final TypeConversionDescriptor directConversion = ThreadLocalConversionRule.findDirectConversion(psiElement, toType, fromType, labeler);
if (directConversion != null) {
TypeMigrationReplacementUtil.replaceExpression((PsiExpression)psiElement, project, directConversion);
}
}
}
final PsiExpression initializer = psiField.getInitializer();
if (initializer != null) {
final String boxedTypeName = fromType instanceof PsiPrimitiveType ? ((PsiPrimitiveType)fromType).getBoxedTypeName() : fromType.getCanonicalText();
psiField.setInitializer(elementFactory.createExpressionFromText("new " +
toType.getCanonicalText() +
"() {\n" +
"@Override \n" +
"protected " +
boxedTypeName +
" initialValue() {\n" +
" return " +
(PsiUtil.isLanguageLevel5OrHigher(psiField)
? initializer.getText()
: (fromType instanceof PsiPrimitiveType
? "new " + ((PsiPrimitiveType)fromType).getBoxedTypeName() + "(" + initializer.getText() + ")"
: initializer.getText())) +
";\n" +
"}\n" +
"}", psiField));
CodeStyleManager.getInstance(project).reformat(psiField);
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
public boolean startInWriteAction() {
return true;
}
}
|
package com.opengamma.component.factory.engine;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.fudgemsg.FudgeContext;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.impl.direct.DirectBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.google.common.base.Supplier;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.component.ComponentInfo;
import com.opengamma.component.ComponentRepository;
import com.opengamma.component.factory.AbstractComponentFactory;
import com.opengamma.engine.calcnode.CalcNodeSocketConfiguration;
import com.opengamma.transport.jaxrs.UriEndPointDescriptionProvider;
import com.opengamma.util.GUIDGenerator;
import com.opengamma.util.fudgemsg.OpenGammaFudgeContext;
import com.opengamma.util.rest.DataConfigurationResource;
/**
* Component factory providing a managed sub set of the server capabilities.
*/
@BeanDefinition
public class EngineConfigurationComponentFactory extends AbstractComponentFactory {
/**
* The name of the configuration document published.
* <p>
* This is used to support servers which publish multiple configurations, for example if they host multiple view processors, or that act as aggregators for a number of other servers at the
* installation site.
* <p>
* This default name may be hard-coded in native code and installation scripts. Changes may cause client tools such as Excel to stop working correctly.
*/
private static final String DEFAULT_CONFIGURATION_DOCUMENT_ID = "0";
/**
* The field name under which the logical server unique identifier is published.
* <p>
* This property may be set explicitly by calling {@link #setLogicalServerId}, or if omitted will be generated randomly.
* <p>
* This default name is hard-coded in native code. Changes may cause client tools such as Excel to stop working correctly.
*/
private static final String LOGICAL_SERVER_UNIQUE_IDENTIFIER = "lsid";
/**
* The classifier that the factory should publish under.
*/
@PropertyDefinition(validate = "notNull")
private String _classifier;
/**
* The Fudge context.
*/
@PropertyDefinition(validate = "notNull")
private FudgeContext _fudgeContext = OpenGammaFudgeContext.getInstance();
/**
* The logical server unique identifier. This is defined by the data environment. Clustered servers (that is, they appear suitably identical to any connecting clients) should have the same logical
* identifier to reflect this. Any server backed by a unique data environment must have a correspondingly unique identifier. If a server has a transient or temporary data environment it must
* generate a new logical identifier whenever that environment is flushed.
* <p>
* The default behavior, if this is not specified in the configuration file, is to generate a unique identifier at start up. This is suitable for most standard installations which include temporary
* (for example, in-memory) masters or other data stores.
*/
@PropertyDefinition
private String _logicalServerId /* = createLogicalServerId() */;
/**
* Creates a random logical server unique identifier. This is used if an explicit identifier is not set in the configuration file.
* <p>
* This is a 24 character string using base-64 characters, created using the algorithm from {@link GUIDGenerator} for uniqueness.
*
* @return the logical server unique identifier, not null
*/
protected String createLogicalServerId() {
final UUID uuid = GUIDGenerator.generate();
final byte[] bytes = new byte[16];
long x = uuid.getMostSignificantBits();
bytes[0] = (byte) x;
bytes[1] = (byte) (x >> 8);
bytes[2] = (byte) (x >> 16);
bytes[3] = (byte) (x >> 24);
bytes[4] = (byte) (x >> 32);
bytes[5] = (byte) (x >> 40);
bytes[6] = (byte) (x >> 48);
bytes[7] = (byte) (x >> 56);
x = uuid.getLeastSignificantBits();
bytes[8] = (byte) x;
bytes[9] = (byte) (x >> 8);
bytes[10] = (byte) (x >> 16);
bytes[11] = (byte) (x >> 24);
bytes[12] = (byte) (x >> 32);
bytes[13] = (byte) (x >> 40);
bytes[14] = (byte) (x >> 48);
bytes[15] = (byte) (x >> 56);
return Base64.encodeBase64String(bytes);
}
protected void afterPropertiesSet() {
if (getLogicalServerId() == null) {
setLogicalServerId(createLogicalServerId());
}
}
protected void buildConfiguration(final ComponentRepository repo, final Map<String, String> configuration, final Map<String, Object> map) {
map.put("lsid", getLogicalServerId());
for (final String key : configuration.keySet()) {
final String valueStr = configuration.get(key);
Object targetValue = valueStr;
if (valueStr.contains("::")) {
final String type = StringUtils.substringBefore(valueStr, "::");
final String classifier = StringUtils.substringAfter(valueStr, "::");
final ComponentInfo info = repo.findInfo(type, classifier);
if (info == null) {
throw new IllegalArgumentException("Component not found: " + valueStr);
}
final Object instance = repo.getInstance(info);
if ((instance instanceof CalcNodeSocketConfiguration) || (instance instanceof Supplier)) {
targetValue = instance;
} else {
if (info.getUri() == null) {
throw new OpenGammaRuntimeException("Unable to add component to configuration as it has not been published by REST: " + valueStr);
}
targetValue = new UriEndPointDescriptionProvider(info.getUri().toString());
}
}
buildMap(map, key, targetValue);
}
}
@Override
public void init(final ComponentRepository repo, final LinkedHashMap<String, String> configuration) {
afterPropertiesSet();
final Map<String, Object> map = new LinkedHashMap<String, Object>();
buildConfiguration(repo, configuration, map);
final Map<String, Object> outer = new LinkedHashMap<String, Object>();
outer.put("0", map);
final DataConfigurationResource resource = new DataConfigurationResource(getFudgeContext(), outer);
repo.getRestComponents().publishResource(resource);
// indicate that all component configuration was used
configuration.clear();
}
/**
* Builds the map, handling dot separate keys.
*
* @param map the map, not null
* @param key the key, not null
* @param targetValue the target value,not null
*/
protected void buildMap(final Map<String, Object> map, final String key, final Object targetValue) {
if (key.contains(".")) {
final String key1 = StringUtils.substringBefore(key, ".");
final String key2 = StringUtils.substringAfter(key, ".");
@SuppressWarnings("unchecked")
Map<String, Object> subMap = (Map<String, Object>) map.get(key1);
if (subMap == null) {
subMap = new LinkedHashMap<String, Object>();
map.put(key1, subMap);
}
buildMap(subMap, key2, targetValue);
} else {
map.put(key, targetValue);
}
}
///CLOVER:OFF
/**
* The meta-bean for {@code EngineConfigurationComponentFactory}.
*
* @return the meta-bean, not null
*/
public static EngineConfigurationComponentFactory.Meta meta() {
return EngineConfigurationComponentFactory.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(EngineConfigurationComponentFactory.Meta.INSTANCE);
}
@Override
public EngineConfigurationComponentFactory.Meta metaBean() {
return EngineConfigurationComponentFactory.Meta.INSTANCE;
}
@Override
protected Object propertyGet(String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return getClassifier();
case -917704420: // fudgeContext
return getFudgeContext();
case -41854233: // logicalServerId
return getLogicalServerId();
}
return super.propertyGet(propertyName, quiet);
}
@Override
protected void propertySet(String propertyName, Object newValue, boolean quiet) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
setClassifier((String) newValue);
return;
case -917704420: // fudgeContext
setFudgeContext((FudgeContext) newValue);
return;
case -41854233: // logicalServerId
setLogicalServerId((String) newValue);
return;
}
super.propertySet(propertyName, newValue, quiet);
}
@Override
protected void validate() {
JodaBeanUtils.notNull(_classifier, "classifier");
JodaBeanUtils.notNull(_fudgeContext, "fudgeContext");
super.validate();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
EngineConfigurationComponentFactory other = (EngineConfigurationComponentFactory) obj;
return JodaBeanUtils.equal(getClassifier(), other.getClassifier()) &&
JodaBeanUtils.equal(getFudgeContext(), other.getFudgeContext()) &&
JodaBeanUtils.equal(getLogicalServerId(), other.getLogicalServerId()) &&
super.equals(obj);
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash += hash * 31 + JodaBeanUtils.hashCode(getClassifier());
hash += hash * 31 + JodaBeanUtils.hashCode(getFudgeContext());
hash += hash * 31 + JodaBeanUtils.hashCode(getLogicalServerId());
return hash ^ super.hashCode();
}
/**
* Gets the classifier that the factory should publish under.
*
* @return the value of the property, not null
*/
public String getClassifier() {
return _classifier;
}
/**
* Sets the classifier that the factory should publish under.
*
* @param classifier the new value of the property, not null
*/
public void setClassifier(String classifier) {
JodaBeanUtils.notNull(classifier, "classifier");
this._classifier = classifier;
}
/**
* Gets the the {@code classifier} property.
*
* @return the property, not null
*/
public final Property<String> classifier() {
return metaBean().classifier().createProperty(this);
}
/**
* Gets the Fudge context.
*
* @return the value of the property, not null
*/
public FudgeContext getFudgeContext() {
return _fudgeContext;
}
/**
* Sets the Fudge context.
*
* @param fudgeContext the new value of the property, not null
*/
public void setFudgeContext(FudgeContext fudgeContext) {
JodaBeanUtils.notNull(fudgeContext, "fudgeContext");
this._fudgeContext = fudgeContext;
}
/**
* Gets the the {@code fudgeContext} property.
*
* @return the property, not null
*/
public final Property<FudgeContext> fudgeContext() {
return metaBean().fudgeContext().createProperty(this);
}
/**
* Gets the logical server unique identifier. This is defined by the data environment. Clustered servers (that is, they appear suitably identical to any connecting clients) should have the same
* logical identifier to reflect this. Any server backed by a unique data environment must have a correspondingly unique identifier. If a server has a transient or temporary data environment it must
* generate a new logical identifier whenever that environment is flushed.
* <p>
* The default behavior, if this is not specified in the configuration file, is to generate a unique identifier at start up. This is suitable for most standard installations which include temporary
* (for example, in-memory) masters or other data stores.
*
* @return the value of the property
*/
public String getLogicalServerId() {
return _logicalServerId;
}
/**
* Sets the logical server unique identifier. This is defined by the data environment. Clustered servers (that is, they appear suitably identical to any connecting clients) should have the same
* logical identifier to reflect this. Any server backed by a unique data environment must have a correspondingly unique identifier. If a server has a transient or temporary data environment it must
* generate a new logical identifier whenever that environment is flushed.
* <p>
* The default behavior, if this is not specified in the configuration file, is to generate a unique identifier at start up. This is suitable for most standard installations which include temporary
* (for example, in-memory) masters or other data stores.
*
* @param logicalServerId the new value of the property
*/
public void setLogicalServerId(String logicalServerId) {
this._logicalServerId = logicalServerId;
}
/**
* Gets the the {@code logicalServerId} property. identifier to reflect this. Any server backed by a unique data environment must have a correspondingly unique identifier. If a server has a
* transient or temporary data environment it must generate a new logical identifier whenever that environment is flushed.
* <p>
* The default behavior, if this is not specified in the configuration file, is to generate a unique identifier at start up. This is suitable for most standard installations which include temporary
* (for example, in-memory) masters or other data stores.
*
* @return the property, not null
*/
public final Property<String> logicalServerId() {
return metaBean().logicalServerId().createProperty(this);
}
/**
* The meta-bean for {@code EngineConfigurationComponentFactory}.
*/
public static class Meta extends AbstractComponentFactory.Meta {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code classifier} property.
*/
private final MetaProperty<String> _classifier = DirectMetaProperty.ofReadWrite(
this, "classifier", EngineConfigurationComponentFactory.class, String.class);
/**
* The meta-property for the {@code fudgeContext} property.
*/
private final MetaProperty<FudgeContext> _fudgeContext = DirectMetaProperty.ofReadWrite(
this, "fudgeContext", EngineConfigurationComponentFactory.class, FudgeContext.class);
/**
* The meta-property for the {@code logicalServerId} property.
*/
private final MetaProperty<String> _logicalServerId = DirectMetaProperty.ofReadWrite(
this, "logicalServerId", EngineConfigurationComponentFactory.class, String.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> _metaPropertyMap$ = new DirectMetaPropertyMap(
this, (DirectMetaPropertyMap) super.metaPropertyMap(),
"classifier",
"fudgeContext",
"logicalServerId");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -281470431: // classifier
return _classifier;
case -917704420: // fudgeContext
return _fudgeContext;
case -41854233: // logicalServerId
return _logicalServerId;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends EngineConfigurationComponentFactory> builder() {
return new DirectBeanBuilder<EngineConfigurationComponentFactory>(new EngineConfigurationComponentFactory());
}
@Override
public Class<? extends EngineConfigurationComponentFactory> beanType() {
return EngineConfigurationComponentFactory.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return _metaPropertyMap$;
}
/**
* The meta-property for the {@code classifier} property.
*
* @return the meta-property, not null
*/
public final MetaProperty<String> classifier() {
return _classifier;
}
/**
* The meta-property for the {@code fudgeContext} property.
*
* @return the meta-property, not null
*/
public final MetaProperty<FudgeContext> fudgeContext() {
return _fudgeContext;
}
/**
* The meta-property for the {@code logicalServerId} property.
*
* @return the meta-property, not null
*/
public final MetaProperty<String> logicalServerId() {
return _logicalServerId;
}
}
///CLOVER:ON
}
|
package gov.nih.nci.cabig.caaers.rules.business.service;
import gov.nih.nci.cabig.caaers.domain.AdverseEvent;
import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport;
import gov.nih.nci.cabig.caaers.domain.Site;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.rules.RuleException;
import gov.nih.nci.cabig.caaers.rules.brxml.RuleSet;
import gov.nih.nci.cabig.caaers.rules.common.CategoryConfiguration;
import gov.nih.nci.cabig.caaers.rules.common.RuleType;
import gov.nih.nci.cabig.caaers.rules.domain.AdverseEventEvaluationResult;
import gov.nih.nci.cabig.caaers.rules.runtime.BusinessRulesExecutionService;
import gov.nih.nci.cabig.caaers.rules.runtime.BusinessRulesExecutionServiceImpl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class AdverseEventEvaluationServiceImpl implements AdverseEventEvaluationService {
//Replace with spring injection
private BusinessRulesExecutionService businessRulesExecutionService = new BusinessRulesExecutionServiceImpl();
private RulesEngineService rulesEngineService= new RulesEngineServiceImpl();
/**
* This method will asses adverse event and will return one of the
* following vlue
* 1. Routine AE
* 2. SAE
* 3. Can't be determined
* Calling this method again and again will not affect the rules
* firing adversly as nothing gets fires subsequently
*
* Only fire the rules belonging to "Asses AE Rule Set" for Sponsor
*
*/
public String assesAdverseEvent(AdverseEvent ae, Study study) throws Exception{
String final_result = null;
String sponsor_level_evaluation = null;
String study_level_evaluation = null;
String sponsorName = study.getPrimarySponsorCode();
String studyName = study.getShortTitle();
String bindURI_ForSponsorLevelRules = this.getBindURI(sponsorName, studyName,"SPONSOR",RuleType.AE_ASSESMENT_RULES.getName());
String bindURI_ForStudyLevelRules = this.getBindURI(sponsorName,studyName,"STUDY", RuleType.AE_ASSESMENT_RULES.getName());
/**
* First asses the AE for Sponsor
*/
RuleSet ruleSetForSponsor = rulesEngineService.getRuleSetForSponsor(RuleType.AE_ASSESMENT_RULES.getName(), sponsorName);
if(ruleSetForSponsor==null){
throw new Exception("There are no rules configured for adverse event assesment for this sponsor!");
}
/*
boolean rulesDeployedForSponsor = rulesEngineService.isDeployed(ruleSetForSponsor);
if(!rulesDeployedForSponsor){
throw new Exception("There are no rules deployd for adverse event assesment for this sponsor!");
}
*/
AdverseEventEvaluationResult evaluationForSponsor = new AdverseEventEvaluationResult();
try {
evaluationForSponsor = this.getEvaluationObject(ae, study, bindURI_ForSponsorLevelRules);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new Exception(e.getMessage(),e);
}
System.out.println("Message: " + evaluationForSponsor.getMessage());
/**
* Now fire rules for Study
*/
RuleSet ruleSetForStudy = rulesEngineService.getRuleSetForStudy(RuleType.AE_ASSESMENT_RULES.getName(), studyName, sponsorName);
AdverseEventEvaluationResult evaluationForStudy = new AdverseEventEvaluationResult();
// if(ruleSetForStudy!=null){
//if(rulesEngineService.isDeployed(ruleSetForStudy)){
try {
evaluationForStudy = this.getEvaluationObject(ae, study, bindURI_ForStudyLevelRules);
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Exception occured while executing study rules");
}
/**
* Now we can compare both the decisions
* If the evaluation is same then just return that evaluation
* but if they are not same then Study evaluation overrides
*/
sponsor_level_evaluation = evaluationForSponsor.getMessage();
study_level_evaluation = evaluationForStudy.getMessage();
if((sponsor_level_evaluation!=null)&&(study_level_evaluation!=null)){
final_result = sponsor_level_evaluation.equalsIgnoreCase(study_level_evaluation)?sponsor_level_evaluation:study_level_evaluation;
}
if((sponsor_level_evaluation==null)&&(study_level_evaluation==null)){
final_result = "CAN_NOT_DETERMINED";
}
if((sponsor_level_evaluation==null)&&(study_level_evaluation!=null)){
final_result = study_level_evaluation;
}
if((sponsor_level_evaluation!=null)&&(study_level_evaluation==null)){
final_result = sponsor_level_evaluation;
}
return final_result;
}
public String assesAdverseEvent(AdverseEvent ae, Site site) throws Exception{
String final_result = null;
String institution_level_evaluation = null;
String institutionName = site.getName();
String bindURI_ForInstitutionLevelRules = this.getBindURI("", institutionName,"INSTITUTION",RuleType.AE_ASSESMENT_RULES.getName());
/**
* First asses the AE for Sponsor
*/
RuleSet ruleSetForInstitution = rulesEngineService.getRuleSetForInstitution(RuleType.AE_ASSESMENT_RULES.getName(), institutionName);
if(ruleSetForInstitution==null){
throw new Exception("There are no rules configured for adverse event assesment for this site!");
}
/*
boolean rulesDeployedForSponsor = rulesEngineService.isDeployed(ruleSetForSponsor);
if(!rulesDeployedForSponsor){
throw new Exception("There are no rules deployd for adverse event assesment for this sponsor!");
}
*/
AdverseEventEvaluationResult evaluationForInstitution = new AdverseEventEvaluationResult();
try {
evaluationForInstitution = this.getEvaluationObject(ae, site, bindURI_ForInstitutionLevelRules);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new Exception(e.getMessage(),e);
}
System.out.println("Message: " + evaluationForInstitution.getMessage());
/**
* Now we can compare both the decisions
* If the evaluation is same then just return that evaluation
* but if they are not same then Study evaluation overrides
*/
institution_level_evaluation = evaluationForInstitution.getMessage();
if((institution_level_evaluation==null)){
final_result = "CAN_NOT_DETERMINED";
}
if((institution_level_evaluation!=null)){
final_result = institution_level_evaluation;
}
return final_result;
}
//public String identifyAdverseEventType()
/**
* Go through all the Aes and fire the rules against them
* and return the collection of reports
*/
public String evaluateSAEReportSchedule(ExpeditedAdverseEventReport aeReport) throws Exception{
//Report rs = aeReport.getReportSchedule();
//aeReport.
Study study = aeReport.getStudy();
List<AdverseEvent> aes = aeReport.getAdverseEvents();
AdverseEvent ae = aes.get(0);
try {
return this.assesAdverseEvent(ae, study);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
}
private String getBindURI(String sponsorName, String studyOrSiteName, String type, String ruleSetName){
String bindURI = null;
if (type.equalsIgnoreCase("SPONSOR")){
bindURI = CategoryConfiguration.SPONSOR_BASE.getPackagePrefix() + "." +this.getStringWithoutSpaces(sponsorName)+"."+this.getStringWithoutSpaces(ruleSetName);
}
if(type.equalsIgnoreCase("STUDY")){
bindURI = CategoryConfiguration.STUDY_BASE.getPackagePrefix() + "."+this.getStringWithoutSpaces(studyOrSiteName)+"."+this.getStringWithoutSpaces(sponsorName)+"."+this.getStringWithoutSpaces(ruleSetName);
}
if(type.equalsIgnoreCase("INSTITUTION")){
bindURI = CategoryConfiguration.INSTITUTION_BASE.getPackagePrefix() + "."+this.getStringWithoutSpaces(studyOrSiteName)+"."+this.getStringWithoutSpaces(ruleSetName);
}
return bindURI;
}
private String getStringWithoutSpaces(String str){
String _str= str.trim();
return _str.replace(" ", "_");
}
private AdverseEventEvaluationResult getEvaluationObject(AdverseEvent ae, Study study, String bindURI) throws Exception{
AdverseEventEvaluationResult evaluationForSponsor = new AdverseEventEvaluationResult();
/* AdverseEventSDO adverseEventSDO = new AdverseEventSDO();
adverseEventSDO.setExpected(ae.getExpected().toString());
adverseEventSDO.setGrade(new Integer(ae.getGrade().getCode()));
adverseEventSDO.setHospitalization(ae.getHospitalization().getName());
adverseEventSDO.setPhase(study.getPhaseCode());
adverseEventSDO.setTerm(ae.getCtcTerm().getTerm());
StudySDO studySDO = new StudySDO();
studySDO.setPrimarySponsorCode(study.getPrimarySponsorCode());
studySDO.setShortTitle(study.getShortTitle());
*/
List<Object> inputObjects = new ArrayList<Object>();
inputObjects.add(ae);
//inputObjects.add(ae);
inputObjects.add(study);
//inputObjects.add(new AdverseEventEvaluationResult());
List<Object> outputObjects = null;
try{
outputObjects = businessRulesExecutionService.fireRules(bindURI, inputObjects);
}catch(Exception ex){
/**
* Don't do anything, it means there are no rules for this package
*/
throw new RuleException("There are no rule configured for this sponsor",ex);
//return evaluationForSponsor;
}
Iterator<Object> it = outputObjects.iterator();
while(it.hasNext()){
Object obj = it.next();
if(obj instanceof AdverseEventEvaluationResult) {
evaluationForSponsor = (AdverseEventEvaluationResult)obj;
break;
}
}
return evaluationForSponsor;
}
private AdverseEventEvaluationResult getEvaluationObject(AdverseEvent ae, Site site, String bindURI) throws Exception{
AdverseEventEvaluationResult evaluationForInstitution = new AdverseEventEvaluationResult();
List<Object> inputObjects = new ArrayList<Object>();
inputObjects.add(ae);
inputObjects.add(site);
List<Object> outputObjects = null;
try{
outputObjects = businessRulesExecutionService.fireRules(bindURI, inputObjects);
}catch(Exception ex){
/**
* Don't do anything, it means there are no rules for this package
*/
throw new RuleException("There are no rule configured for this institution",ex);
//return evaluationForSponsor;
}
Iterator<Object> it = outputObjects.iterator();
while(it.hasNext()){
Object obj = it.next();
if(obj instanceof AdverseEventEvaluationResult) {
evaluationForInstitution = (AdverseEventEvaluationResult)obj;
break;
}
}
return evaluationForInstitution;
}
}
|
package org.slc.sli.ingestion.transformation;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.ingestion.BatchJobStageType;
import org.slc.sli.ingestion.Job;
import org.slc.sli.ingestion.NeutralRecord;
import org.slc.sli.ingestion.WorkNote;
import org.slc.sli.ingestion.dal.NeutralRecordMongoAccess;
import org.slc.sli.ingestion.model.da.BatchJobDAO;
import org.slc.sli.ingestion.validation.DatabaseLoggingErrorReport;
import org.slc.sli.ingestion.validation.ErrorReport;
/**
* Base TransformationStrategy.
*
* @author dduran
* @author shalka
*/
public abstract class AbstractTransformationStrategy implements TransformationStrategy {
private static final Logger LOG = LoggerFactory.getLogger(AbstractTransformationStrategy.class);
protected static final String BATCH_JOB_ID_KEY = "batchJobId";
protected static final String TYPE_KEY = "type";
private String batchJobId;
private Job job;
private WorkNote workNote;
@Autowired
private NeutralRecordMongoAccess neutralRecordMongoAccess;
@Autowired
private BatchJobDAO batchJobDAO;
@Override
public void perform(Job job) {
this.setJob(job);
this.setBatchJobId(job.getId());
this.performTransformation();
}
@Override
public void perform(Job job, WorkNote workNote) {
this.setJob(job);
this.setBatchJobId(job.getId());
this.setWorkNote(workNote);
this.performTransformation();
}
protected abstract void performTransformation();
/**
* @return the neutralRecordMongoAccess
*/
public NeutralRecordMongoAccess getNeutralRecordMongoAccess() {
return neutralRecordMongoAccess;
}
/**
* @param neutralRecordMongoAccess
* the neutralRecordMongoAccess to set
*/
public void setNeutralRecordMongoAccess(NeutralRecordMongoAccess neutralRecordMongoAccess) {
this.neutralRecordMongoAccess = neutralRecordMongoAccess;
}
public String getBatchJobId() {
return batchJobId;
}
public ErrorReport getErrorReport(String fileName) {
return new DatabaseLoggingErrorReport(this.batchJobId, BatchJobStageType.TRANSFORMATION_PROCESSOR, fileName,
this.batchJobDAO);
}
public void setBatchJobId(String batchJobId) {
this.batchJobId = batchJobId;
}
public Job getJob() {
return job;
}
public void setJob(Job job) {
this.job = job;
}
/**
* Gets the Work Note corresponding to this job.
*
* @return Work Note containing information about collection and range to operate on.
*/
public WorkNote getWorkNote() {
return workNote;
}
/**
* Sets the Work Note for this job.
*
* @param workNote
* Work Note containing information about collection and range to operate on.
*/
public void setWorkNote(WorkNote workNote) {
this.workNote = workNote;
}
/**
* Returns collection entities found in staging ingestion database. If a work note was not
* provided for
* the job, then all entities in the collection will be returned.
*
* @param collectionName
* name of collection to be queried for.
*/
public Map<Object, NeutralRecord> getCollectionFromDb(String collectionName) {
WorkNote workNote = getWorkNote();
Query query = buildCreationTimeQuery(workNote);
Iterable<NeutralRecord> data = getNeutralRecordMongoAccess().getRecordRepository().findByQueryForJob(
collectionName, query, getJob().getId());
if (!data.iterator().hasNext()) {
LOG.warn("Pulled nothing from {}", collectionName);
LOG.warn("Total for {}: {}", collectionName, getNeutralRecordMongoAccess().getRecordRepository()
.countForJob(collectionName, new NeutralQuery(0), getJob().getId()));
}
Map<Object, NeutralRecord> collection = iterableResultsToMap(data);
if (collection.size() != workNote.getRecordsInRange()) {
LOG.error("Number of records in creationTime query result ({}) does not match resultsInRange of {} ",
collection.size(), workNote);
}
return collection;
}
/**
* Invokes the 'insert' mongo operation. Use when concurrent writes are known to provide
* uniqueness (one-to-one mapping between original and _transformed collection).
*
* @param record
* Neutral Record to be written to data store.
*/
public void insertRecord(NeutralRecord record) {
neutralRecordMongoAccess.getRecordRepository().insertForJob(record, job.getId());
}
/**
* Invokes the 'upsert' mongo operation. Use when concurrent writes fail to provide uniqueness
* (for instance, when many record are being condensed into a small subset of records).
*
* @param record
* Neutral Record to be written to data store.
*/
public void createRecord(NeutralRecord record) {
neutralRecordMongoAccess.getRecordRepository().createForJob(record, job.getId());
}
private Query buildCreationTimeQuery(WorkNote note) {
Query query = new Query().limit(0);
if (note.getBatchSize() == 1) {
Criteria limiter = Criteria.where("creationTime").gt(0);
query.addCriteria(limiter);
} else {
Criteria limiter = Criteria.where("creationTime").gte(note.getRangeMinimum()).lt(note.getRangeMaximum());
query.addCriteria(limiter);
}
return query;
}
private Map<Object, NeutralRecord> iterableResultsToMap(Iterable<NeutralRecord> data) {
Map<Object, NeutralRecord> collection = new HashMap<Object, NeutralRecord>();
NeutralRecord tempNr = null;
Iterator<NeutralRecord> neutralRecordIterator = data.iterator();
while (neutralRecordIterator.hasNext()) {
tempNr = neutralRecordIterator.next();
collection.put(tempNr.getRecordId(), tempNr);
}
return collection;
}
}
|
package org.getlantern.lantern.activity;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.VpnService;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.view.MenuItem;
import android.view.KeyEvent;
import android.support.v7.app.AppCompatActivity;
import org.getlantern.lantern.BuildConfig;
import org.getlantern.lantern.vpn.Service;
import org.getlantern.lantern.model.UI;
import org.getlantern.lantern.sdk.Utils;
import org.getlantern.lantern.R;
public class LanternMainActivity extends AppCompatActivity implements Handler.Callback {
private static final String TAG = "LanternMainActivity";
private static final String PREFS_NAME = "LanternPrefs";
private final static int REQUEST_VPN = 7777;
private SharedPreferences mPrefs = null;
private BroadcastReceiver mReceiver;
private Context context;
private UI LanternUI;
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_lantern_main);
// we want to use the ActionBar from the AppCompat
// support library, but with our custom design
// we hide the default action bar
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
context = getApplicationContext();
mPrefs = Utils.getSharedPrefs(context);
LanternUI = new UI(this, mPrefs);
// the ACTION_SHUTDOWN intent is broadcast when the phone is
// about to be shutdown. We register a receiver to make sure we
// clear the preferences and switch the VpnService to the off
// state when this happens
IntentFilter filter = new IntentFilter(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
mReceiver = new LanternReceiver();
registerReceiver(mReceiver, filter);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
// setup our UI
try {
// configure actions to be taken whenever slider changes state
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
String appVersion = pInfo.versionName;
Log.d(TAG, "Currently running Lantern version: " + appVersion);
LanternUI.setVersionNum(appVersion, BuildConfig.LANTERN_VERSION);
LanternUI.setupLanternSwitch();
} catch (Exception e) {
Log.d(TAG, "Got an exception " + e);
}
}
@Override
protected void onResume() {
super.onResume();
// we check if mPrefs has been initialized before
// since onCreate and onResume are always both called
if (mPrefs != null) {
LanternUI.setBtnStatus();
}
}
// override onKeyDown and onBackPressed default
// behavior to prevent back button from interfering
// with on/off switch
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (Integer.parseInt(android.os.Build.VERSION.SDK) > 5
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
Log.d(TAG, "onKeyDown Called");
onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
if (mReceiver != null) {
unregisterReceiver(mReceiver);
}
stopLantern();
} catch (Exception e) {
}
}
// quitLantern is the side menu option and cleanyl exits the app
public void quitLantern() {
try {
Log.d(TAG, "About to exit Lantern...");
stopLantern();
// sleep for a few ms before exiting
Thread.sleep(200);
finish();
moveTaskToBack(true);
} catch (Exception e) {
Log.e(TAG, "Got an exception when quitting Lantern " + e.getMessage());
}
}
@Override
public boolean handleMessage(Message message) {
if (message != null) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
}
return true;
}
public void sendDesktopVersion(View view) {
if (LanternUI != null) {
LanternUI.sendDesktopVersion(view);
}
}
// Make a VPN connection from the client
// We should only have one active VPN connection per client
private void startVpnService ()
{
Intent intent = VpnService.prepare(this);
if (intent != null) {
Log.w(TAG,"Requesting VPN connection");
startActivityForResult(intent, REQUEST_VPN);
} else {
Log.d(TAG, "VPN enabled, starting Lantern...");
LanternUI.toggleSwitch(true);
sendIntentToService();
}
}
// Prompt the user to enable full-device VPN mode
public void enableVPN() {
Log.d(TAG, "Load VPN configuration");
try {
startVpnService();
} catch (Exception e) {
Log.d(TAG, "Could not establish VPN connection: " + e.getMessage());
}
}
@Override
protected void onActivityResult(int request, int response, Intent data) {
super.onActivityResult(request, response, data);
if (request == REQUEST_VPN) {
if (response != RESULT_OK) {
// VPN connection; return to off state
LanternUI.toggleSwitch(false);
} else {
LanternUI.toggleSwitch(true);
Handler h = new Handler();
h.postDelayed(new Runnable () {
public void run ()
{
sendIntentToService();
}
}, 1000);
}
}
}
private void sendIntentToService() {
startService(new Intent(this, Service.class));
}
public void restart(final Context context, final Intent intent) {
if (LanternUI.useVpn()) {
Log.d(TAG, "Restarting Lantern...");
Service.IsRunning = false;
final LanternMainActivity activity = this;
Handler h = new Handler();
h.postDelayed(new Runnable () {
public void run() {
enableVPN();
}
}, 1000);
}
}
public void stopLantern() {
Service.IsRunning = false;
Utils.clearPreferences(this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle
// If it returns true, then it has handled
// the nav drawer indicator touch event
if (LanternUI != null &&
LanternUI.optionSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if (LanternUI != null) {
LanternUI.syncState();
}
}
// LanternReceiver is used to capture broadcasts
// such as network connectivity and when the app
// is powered off
public class LanternReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SHUTDOWN)) {
// whenever the device is powered off or the app
// abruptly closed, we want to clear user preferences
Utils.clearPreferences(context);
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
//restart(context, intent);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
// whenever a user disconnects from Wifi and Lantern is running
NetworkInfo networkInfo =
intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (LanternUI.useVpn() &&
networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
!networkInfo.isConnected()) {
stopLantern();
}
}
}
}
}
|
package org.eclipse.ice.viz.service.paraview.widgets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.ice.viz.service.paraview.web.IParaViewWebClient;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Control;
/**
* This class manages mouse controls for an {@link ParaViewCanvas} and feeds
* events to an associated Canvas at the appropriate intervals.
*
* @author Jordan Deyton
*
*/
public class ParaViewMouseAdapter {
/*-
* Notes on requests sent to the ParaView client for mouse movement:
*
* The ParaView web client expects a well-defined, ordered set of events
* when rotating or zooming. It is of critical importance that the below
* guidelines be followed when sending mouse events to the web client.
*
* Rotating:
* 1 - Left mouse is pressed
* action - down
* states - buttonLeft must be true, all else false
* x,y - should be the current cursor location, both normalized
* 2 - Mouse moves (this may repeat any number of times)
* action - move
* states - buttonLeft must be true, all else false
* x,y - should be the current cursor location, both normalized
* 3 - Left mouse is released
* action - up
* states - all states should be false
* x,y - should be the current cursor location, both normalized
*
* Zooming:
* 1 - Right mouse + CTRL is pressed (alternatively, when scrolling starts)
* action - down
* states - buttonRight and ctrlKey should be true, all else false
* x,y - y should be the current zoom ratio, normalized. x is 0.
* 2 - Mouse moves (this may repeat any number of times)
* action - move
* states - buttonRight and ctrlKey should be true, all else false
* x,y - y should be the current zoom ratio, normalized. x is 0.
* 3 - Right mouse + CTRL is released (alternatively, when scrolling stops)
* action - up
* states - all states should be false
* x,y - y should be the current zoom ratio, normalized. x is 0.
*
* In our code below, we adhere to these by using the following mechanisms:
*
* Mouse movement is handled as expected using mouseDown(...),
* mouseMove(...), and mouseUp(...).
*
* Zooming is instead associated with the scroll wheel. As there is only a
* mouseScrolled(...) event and no scroll equivalent to mouseDown(...) or
* mouseUp(...), we instead must apply the following changes:
*
* On the first scroll (using a boolean flag) -- send a zoom start event
* (step 1) followed by a zoom event (step 2).
* On subsequent scrolls -- send a zoom event (step 2).
* On the next non-scroll event -- send a zoom end event (step 3).
*/
// TODO I'm not sure how well this works if you try zooming and rotating at
// the same time.
/**
* The client that is providing a ParaView image. Mouse events will trigger
* updates to this client.
*/
private IParaViewWebClient client;
/**
* The current view ID on the client. It will be updated by mouse events.
*/
private int viewId;
/**
* The current SWT Control to which this adapter is registered for its
* various listener operations.
*/
private Control control;
/**
* The target ParaView Canvas for this adapter's mouse events. This will be
* refreshed after each mouse event is processed.
*/
private ParaViewCanvas canvas;
/**
* The service used to start worker threads. This should provide a single
* thread so that events are processed in order (which is required for
* correct behavior of the web client).
*/
private ExecutorService executorService;
/**
* A listener that updates {@link #inverseSizeX} and {@link #inverseSizeY}
* when the associated control is resized. These values will be used when
* computing the normalized coordinates that must be sent to the web client.
*/
private final ControlListener controlListener;
/**
* Listens for the associated control's dispose events. When the control is
* unset or disposed, the worker thread should be shut down.
*/
private final DisposeListener disposeListener;
/**
* When focus is lost, this stops the scroll event. This prevents the canvas
* from constantly refreshing when it was last zoomed.
*/
private final FocusListener focusListener;
/**
* The listener used to enable/disable rotating when the mouse buttons are
* pressed/released. This also disables zooming on mouse up if zooming is
* currently activated.
*/
private final MouseListener mouseListener;
/**
* The listener used to send rotate events when the mouse is being (clicked
* and) dragged.
*/
private final MouseMoveListener mouseMoveListener;
/**
* The listener used to start zooming and send additional zoom events when
* the mouse is scrolled.
*/
private final MouseWheelListener mouseWheelListener;
/**
* Holds the value 1.0 / the current width of the associated control.
* <p>
* This is only ever recomputed when the control's size changes.
* </p>
*/
private double inverseSizeX;
/**
* Holds the value 1.0 / the current height of the associated control.
* <p>
* This is only ever recomputed when the control's size changes.
* </p>
*/
private double inverseSizeY;
/**
* An array for holding the current normalized position.
* <p>
* This is only ever used on the lone worker thread from the
* {@link #executorService}, and using it eliminates the need to re-allocate
* a new array on every call to
* {@link #getNormalizedPosition(double, double)}.
* </p>
*/
private final double[] normalizedPosition;
/**
* Whether or not the mouse button is pressed down.
* <p>
* This is only ever accessed from the UI thread in
* {@link #mouseDown(MouseEvent)}, {@link #mouseMove(MouseEvent)}, and
* {@link #mouseUp(MouseEvent)}.
* </p>
*/
private boolean rotating;
/**
* The current rotation or mouse-drag event that needs to be processed.
* <p>
* This is used to eliminate intermediate requests to the client. When
* processed on the single worker thread, the <i>current</i> rotational
* values should be used.
* </p>
*/
private final AtomicReference<MouseInteraction> rotation;
/**
* Used when computing the normalized zoom.
*/
private static final double INVERSE_PI = 1.0 / Math.PI;
/**
* An integer representing the number of scroll clicks in either direction.
* It starts off at 0 and is updated when the mouse wheel is scrolled.
* <p>
* This is only ever accessed from the UI thread in
* {@link #mouseScrolled(MouseEvent)}.
* </p>
*/
private int scrollCount;
/**
* The current rotation or mouse-drag event that needs to be processed.
* <p>
* This is used to eliminate intermediate requests to the client. When
* processed on the single worker thread, the <i>current</i> rotational
* values should be used.
* </p>
*/
private final AtomicReference<MouseInteraction> zoom;
/**
* Whether or not the mouse wheel has been scrolled.
* <p>
* This is only ever accessed from the UI thread in
* {@link #mouseScrolled(MouseEvent)} and {@link #mouseDown(MouseEvent)}.
* </p>
*/
private boolean zooming;
/**
* A simple enumeration representing the allowed action strings.
*
* @author Jordan Deyton
*
*/
public enum MouseInteractionType {
/**
* A button has been pressed down. Usually the first action in a chain.
*/
DOWN("down"),
/**
* A button has been released. Usually the last action in a chain.
*/
UP("up"),
/**
* The mouse has been moved. Usually between a {@link #DOWN} and
* {@link #UP} action.
*/
MOVE("move");
/**
* The string used by the web client to denote the action.
*/
private final String actionString;
/**
* Creates the enum value.
*
* @param actionString
* The string used by the web client to denote the action.
*/
private MouseInteractionType(String actionString) {
this.actionString = actionString;
}
/**
* Returns the string used by the web client to denote the action.
*/
@Override
public String toString() {
return actionString;
}
}
/**
* A simple wrapper for MouseEvents, except it also maintains metadata
* required when posting mouse events to the web client.
*
* @author Jordan Deyton
*
*/
private class MouseInteraction {
/**
* The x position of the mouse event.
*/
public double x;
/**
* The y position of the mouse event. Remember that y increases from top
* to bottom.
*/
public double y;
/**
* The type of event.
*/
public final MouseInteractionType type;
/**
* If true, tells the client that the left mouse button is pressed.
*/
public boolean buttonLeft = false;
/**
* If true, tells the client that the right mouse button is pressed.
*/
public boolean buttonRight = false;
/**
* If true, tells the client that the CTRL key is pressed.
*/
public boolean ctrlKey = false;
/**
* The default constructor.
*
* @param x
* The normalized x coordinate for the mouse event.
* @param y
* The normalized y coordinate for the mouse event.
* @param action
* The action for the event. Expected not to be {@code null}.
*/
public MouseInteraction(double x, double y, MouseInteractionType action) {
this.x = x;
this.y = y;
this.type = action;
}
/**
* Gets the state. These correspond to, respectively, "buttonLeft",
* "buttonMiddle", "buttonRight", "shiftKey", "ctrlKey", "altKey", and
* "metaKey".
*
* @return An array of boolean representing the mouse buttons or keys
* pressed.
*/
public boolean[] getState() {
return new boolean[] { buttonLeft, false, buttonRight, false, ctrlKey, false, false };
}
}
/**
* The default constructor. The adapter will need to have its ParaView web
* client, view, and associated Control set.
*/
public ParaViewMouseAdapter() {
this(null, -1, null);
}
/**
* The full constructor.
*
* @param client
* The client that is providing a ParaView image. Mouse events
* will trigger updates to this client.
* @param viewId
* The current view ID on the client. It will be updated by mouse
* events.
* @param control
* The current SWT Control to which this adapter is registered
* for its various listener operations. Although this is
* typically a {@link ParaViewCanvas}, it may be any SWT Control.
*/
public ParaViewMouseAdapter(IParaViewWebClient client, int viewId, Control control) {
// There is no worker thread by default until a valid control is set.
executorService = null;
// Initialize rotation variables.
rotating = false;
normalizedPosition = new double[2];
rotation = new AtomicReference<MouseInteraction>();
controlListener = new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
refreshSizeVariables();
}
};
// Initialize zoom variables.
scrollCount = 0;
zooming = false;
zoom = new AtomicReference<MouseInteraction>();
// Initialize the listeners.
disposeListener = new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
// Unset the control as it is not of use when it is disposed.
setControl(null);
}
};
focusListener = new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
stopZoom();
}
};
mouseListener = new MouseAdapter() {
@Override
public void mouseDown(MouseEvent e) {
stopZoom();
startRotate(e.x, e.y);
}
@Override
public void mouseUp(MouseEvent e) {
stopRotate(e.x, e.y);
}
};
mouseMoveListener = new MouseMoveListener() {
@Override
public void mouseMove(MouseEvent e) {
rotate(e.x, e.y);
}
};
mouseWheelListener = new MouseWheelListener() {
@Override
public void mouseScrolled(MouseEvent e) {
startZoom();
zoom(e.count);
}
};
// Set the specified variables.
setClient(client);
setViewId(viewId);
setControl(control);
return;
}
/**
* Sets the current control with which this mouse adapter is linked. After
* this call, this adapter will no longer be registered with the previous
* control but will be registered with the new control.
*
* @param control
* The new SWT Control on which this adapter should listen for
* mouse events.
* @return True if the control was changed to a <i>new</i> value, false
* otherwise.
*/
public boolean setControl(Control control) {
boolean changed = false;
if (control != this.control) {
// If the previous control was valid, unregister its listeners.
if (this.control != null) {
this.control.removeControlListener(controlListener);
this.control.removeDisposeListener(disposeListener);
this.control.removeFocusListener(focusListener);
this.control.removeMouseListener(mouseListener);
this.control.removeMouseMoveListener(mouseMoveListener);
this.control.removeMouseWheelListener(mouseWheelListener);
// If there is no new control, shut down the worker thread.
if (control == null) {
executorService.shutdown();
executorService = null;
}
}
// Update the reference to the control.
this.control = control;
changed = true;
// If the new control is valid, register its listeners.
if (control != null) {
// Create the worker thread if necessary.
if (executorService == null) {
executorService = Executors.newSingleThreadExecutor();
}
// Update the size variables based on the new control.
control.getDisplay().syncExec(new Runnable() {
@Override
public void run() {
refreshSizeVariables();
}
});
control.addControlListener(controlListener);
control.addDisposeListener(disposeListener);
control.addFocusListener(focusListener);
control.addMouseListener(mouseListener);
control.addMouseMoveListener(mouseMoveListener);
control.addMouseWheelListener(mouseWheelListener);
}
}
return changed;
}
/**
* Sets the {@link ParaViewCanvas} that will be refreshed after a mouse
* event in the {@link #control} is processed and posted to the web client.
*
* @param canvas
* The target Canvas that will be updated. If {@code null}, no
* Canvas will be updated after mouse events.
* @return True if the Canvas was changed to a <i>new</i> value.
*/
public boolean setCanvas(ParaViewCanvas canvas) {
boolean changed = false;
if (canvas != this.canvas) {
this.canvas = canvas;
changed = true;
}
return changed;
}
/**
* Sets the current ParaView web client used by this mouse adapter.
* <p>
* <b>Note:</b> Any change is not guaranteed to take effect until the next
* mouse event on the associated {@link #control}.
* </p>
*
* @param client
* The new client. If {@code null} or not connected, then the
* rendered image will not be able to update.
* @return True if the client was changed to a <i>new</i> value, false
* otherwise.
*/
public boolean setClient(IParaViewWebClient client) {
boolean changed = false;
if (client != this.client) {
this.client = client;
changed = true;
}
return changed;
}
/**
* Sets the ID of the current view that is rendered via the associated
* ParaView web client.
* <p>
* <b>Note:</b> Any change is not guaranteed to take effect until the next
* mouse event on the associated {@link #control}.
* </p>
*
* @param viewId
* The ID of the view to be rendered. If invalid, then the
* rendered image will not be able to update.
* @return True if the view ID was changed to a <i>new</i> value, false
* otherwise.
*/
public boolean setViewId(int viewId) {
boolean changed = false;
if (viewId != this.viewId) {
this.viewId = viewId;
changed = true;
}
return changed;
}
/**
* Normalizes the specified x and y coordinates based on the size of the
* associated {@link #control}.
*
* @param x
* The x value to normalize.
* @param y
* The y value to normalize.
* @return An array of 2 elements containing the normalized x and y values,
* in that order.
*/
private double[] getNormalizedPosition(double x, double y) {
// Compute the normalized x and y positions using the
// control's current size.
normalizedPosition[0] = (double) x * inverseSizeX;
normalizedPosition[1] = 1.0 - (double) y * inverseSizeY;
return normalizedPosition;
}
/**
* Gets the current, normalized zoom based on the current scroll count.
*
* @param y
* The current scroll count. Should be the current or recent
* value of {@link #scrollCount}.
* @return A normalized zoom value between 0 and 1.
*/
private double getNormalizedZoom(double y) {
return Math.atan(0.005 * y) * INVERSE_PI + 0.5;
}
/**
* Updates {@link #inverseSizeX} and {@link #inverseSizeY} based on the size
* of the {@link #control}. <b>This must be called from the UI thread!</b>
*/
private void refreshSizeVariables() {
if (!control.isDisposed()) {
Point controlSize = control.getSize();
inverseSizeX = 1.0 / controlSize.x;
inverseSizeY = 1.0 / controlSize.y;
}
}
/**
* Sends a {@link MouseInteraction} event to the {@link #client} and
* triggers a refresh of the {@link #canvas} afterward if requested.
*
* @param interaction
* The mouse event to pass to the client.
* @param refresh
* If true and the event is successfully processed, the
* associated canvas will be refreshed. Otherwise, the canvas
* will <i>not</i> be refreshed.
* @return True if the event was successfully processed, false otherwise.
*/
private boolean sendMouseInteraction(MouseInteraction interaction, boolean refresh) {
boolean sent = false;
IParaViewWebClient clientRef = client;
if (clientRef != null) {
try {
// Send the mouse event to the client.
clientRef.event(viewId, interaction.x, interaction.y, interaction.type.toString(),
interaction.getState()).get();
// Set the flag that the event was processed.
sent = true;
// If the zoom request was processed, refresh the Canvas.
final ParaViewCanvas canvasRef = canvas;
if (refresh && canvasRef != null) {
canvas.refresh();
}
} catch (InterruptedException | ExecutionException e) {
// The event could not be processed.
}
}
return sent;
}
/**
* Signals the client to start rotating the view.
*
* @param x
* The current mouse x position when the mouse button was
* pressed.
* @param y
* The current mouse y position when the mouse button was
* pressed.
*/
private void startRotate(int x, int y) {
if (!rotating) {
// Get the actual mouse position when the mouse button was pressed.
final int mouseX = x;
final int mouseY = y;
// Submit a task to send a DOWN event with the current mouse
// position.
executorService.submit(new Runnable() {
@Override
public void run() {
// Get the normalized x and y values for the mouse position.
double[] normPosition = getNormalizedPosition(mouseX, mouseY);
double x = normPosition[0];
double y = normPosition[1];
// Create a MouseInteraction for pressing buttons.
MouseInteraction moveStart;
moveStart = new MouseInteraction(x, y, MouseInteractionType.DOWN);
moveStart.buttonLeft = true;
// Send the request to the client. There should be no need
// refresh.
sendMouseInteraction(moveStart, false);
return;
}
});
// Now we can set the mouse drag flag to true.
rotating = true;
}
return;
}
/**
* Signals the client to start zooming the view.
*/
private void startZoom() {
// On the first scroll event, send a client event to *start* scrolling.
if (!zooming) {
// Submit a task to send a DOWN event with the current zoom.
final int currentZoom = scrollCount;
executorService.submit(new Runnable() {
@Override
public void run() {
// Get the normalized x and y values for the current zoom.
double x = 0.0;
double y = getNormalizedZoom(currentZoom);
// Create a MouseInteraction for pressing buttons.
MouseInteraction zoomStart;
zoomStart = new MouseInteraction(x, y, MouseInteractionType.DOWN);
zoomStart.buttonRight = true;
zoomStart.ctrlKey = true;
// Send the request to the client. There should be no need
// to refresh.
sendMouseInteraction(zoomStart, false);
return;
}
});
// Now we can set the zoom flag to true.
zooming = true;
}
return;
}
/**
* Signals the client to rotate the view.
*
* @param x
* The current mouse x position when the mouse button was moved.
* @param y
* The current mouse y position when the mouse button was moved.
*/
private void rotate(int x, int y) {
// If the mouse is being dragged, send a mouse drag event to the web
// client.
if (rotating) {
// Create a MouseInteraction for moving (rotating).
rotation.set(new MouseInteraction(x, y, MouseInteractionType.MOVE));
// Submit a task to send an MOVE event with the current position.
executorService.submit(new Runnable() {
@Override
public void run() {
// Get the current mouse interaction.
MouseInteraction rotateEvent = rotation.getAndSet(null);
if (rotateEvent != null) {
// Update the rotate event.
rotateEvent.buttonLeft = true;
// Normalize the position values.
double[] normPosition = getNormalizedPosition(rotateEvent.x, rotateEvent.y);
rotateEvent.x = normPosition[0];
rotateEvent.y = normPosition[1];
// Send the request to the client. Refresh because a
// rotation has been applied.
sendMouseInteraction(rotateEvent, true);
}
return;
}
});
}
return;
}
/**
* Signals the client to zoom the view.
*
* @param count
* The count from the mouse scroll operation.
*/
private void zoom(int count) {
if (zooming) {
// Adjust the scroll count. Note that zooming in/out is inversely
// related to the direction of the count.
scrollCount -= count;
// Create a MouseInteraction for moving (zooming).
zoom.set(new MouseInteraction(0.0, scrollCount, MouseInteractionType.MOVE));
// Submit a task to send an MOVE event with the current zoom.
executorService.submit(new Runnable() {
@Override
public void run() {
// Get the current mouse interaction.
MouseInteraction zoomEvent = zoom.getAndSet(null);
if (zoomEvent != null) {
// Update the zoom event.
zoomEvent.buttonRight = true;
zoomEvent.ctrlKey = true;
// Get the normalized y value for the current zoom
// event.
zoomEvent.y = getNormalizedZoom(zoomEvent.y);
// Send the request to the client. Refresh because a
// rotation has been applied.
sendMouseInteraction(zoomEvent, true);
}
return;
}
});
}
return;
}
/**
* Signals the client to stop rotating the view.
*
* @param x
* The current mouse x position when the mouse button was
* released.
* @param y
* The current mouse y position when the mouse button was
* released.
*/
private void stopRotate(int x, int y) {
// Unset the mouse drag flag.
if (rotating == true) {
rotating = false;
// Get the actual mouse position when the mouse button was released.
final int mouseX = x;
final int mouseY = y;
// Submit a task to send an UP event with the current mouse
// position.
executorService.submit(new Runnable() {
@Override
public void run() {
// Get the normalized x and y values for the mouse position.
double[] normPosition = getNormalizedPosition(mouseX, mouseY);
double x = normPosition[0];
double y = normPosition[1];
// Create a MouseInteraction for releasing buttons.
MouseInteraction moveStop;
moveStop = new MouseInteraction(x, y, MouseInteractionType.UP);
// Send the request to the client. There should be no need
// refresh.
sendMouseInteraction(moveStop, false);
return;
}
});
}
return;
}
/**
* Signals the client to stop zooming the view.
*/
private void stopZoom() {
// If the mouse was scrolled previously, send an event to *stop*
// scrolling.
if (zooming) {
zooming = false;
// Submit a task to send an UP event with the current zoom.
final int currentZoom = scrollCount;
executorService.submit(new Runnable() {
@Override
public void run() {
// Get the normalized x and y values for the current zoom.
double x = 0.0;
double y = getNormalizedZoom(currentZoom);
// Create a MouseInteraction for releasing buttons.
MouseInteraction zoomStop;
zoomStop = new MouseInteraction(x, y, MouseInteractionType.UP);
// Send the request to the client. There should be no need
// to refresh.
sendMouseInteraction(zoomStop, false);
return;
}
});
}
return;
}
}
|
package org.statefulj.persistence.mongo;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.bson.types.ObjectId;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import static org.statefulj.common.utils.ReflectionUtils.*;
import org.statefulj.fsm.Persister;
import org.statefulj.fsm.StaleStateException;
import org.statefulj.fsm.model.State;
import org.statefulj.persistence.common.AbstractPersister;
import org.statefulj.persistence.mongo.model.StateDocument;
import com.mongodb.DBObject;
public class MongoPersister<T> extends AbstractPersister<T> implements Persister<T>, ApplicationContextAware, BeanDefinitionRegistryPostProcessor {
public static final String COLLECTION = "managedState";
MongoTemplate mongoTemplate;
// Private class
@Document(collection=COLLECTION)
class StateDocumentImpl implements StateDocument {
@Id
String id;
@Transient
boolean persisted = true;
String state;
String prevState;
@DBRef(lazy=true)
Object owner;
Date updated;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean isPersisted() {
return persisted;
}
public void setPersisted(boolean persisted) {
this.persisted = persisted;
}
public void setState(String state) {
this.state = state;
}
@Override
public String getState() {
return state;
}
public String getPrevState() {
return prevState;
}
public void setPrevState(String prevState) {
this.prevState = prevState;
}
public Object getOwner() {
return owner;
}
public void setOwner(Object owner) {
this.owner = owner;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
public MongoPersister(List<State<T>> states, String stateFieldName, State<T> start, Class<T> clazz) {
super(states, stateFieldName, start,clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.mongoTemplate = (MongoTemplate)applicationContext.getBean("mongoTemplate");
}
/**
* Set the current State. This method will ensure that the state in the db matches the expected current state.
* If not, it will throw a StateStateException
*
* @param stateful
* @param current
* @param next
* @throws StaleStateException
*/
public void setCurrent(T stateful, State<T> current, State<T> next) throws StaleStateException {
try {
// Has this Entity been persisted to Mongo?
StateDocumentImpl stateDoc = this.getStateDocument(stateful);
if (stateDoc != null && stateDoc.isPersisted()) {
// Entity is in the database - perform qualified update based off
// the current State value
Query query = buildQuery(stateDoc, current);
Update update = buildUpdate(current, next);
// Update state in DB
StateDocument updatedDoc = mongoTemplate.findAndModify(query, update, StateDocumentImpl.class);
if (updatedDoc != null) {
// Success update in memory
stateDoc.setState(next.getName());
} else {
// If we aren't able to update - it's most likely that we are out of sync.
// So, fetch the latest value and update the Stateful object. Then throw a RetryException
// This will cause the event to be reprocessed by the FSM
updatedDoc = (StateDocument)mongoTemplate.findById(stateDoc.getId(), StateDocumentImpl.class);
if (updatedDoc != null) {
String currentState = stateDoc.getState();
stateDoc.setState(updatedDoc.getState());
throwStaleState(currentState, updatedDoc.getState());
} else {
throw new RuntimeException("Unable to find StateDocument with id=" + stateDoc.getId());
}
}
} else {
// The Entity hasn't been persisted to Mongo - so it exists only
// this Application memory. So, serialize the qualified update to prevent
// concurrency conflicts
updateInMemory(stateful, stateDoc, current.getName(), next.getName());
}
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(
BeanDefinitionRegistry registry) throws BeansException {
BeanDefinition mongoCascadeSupportBean = BeanDefinitionBuilder
.genericBeanDefinition(MongoCascadeSupport.class)
.getBeanDefinition();
ConstructorArgumentValues args = mongoCascadeSupportBean.getConstructorArgumentValues();
args.addIndexedArgumentValue(0, this);
registry.registerBeanDefinition(Long.toString((new Random()).nextLong()), mongoCascadeSupportBean);
}
@SuppressWarnings("unchecked")
public void onAfterSave(Object obj, DBObject dbo) {
if (obj.getClass().equals(getClazz())) {
try {
boolean updateStateful = false;
StateDocumentImpl stateDoc = this.getStateDocument((T)obj);
if (stateDoc == null) {
stateDoc = createStateDocument((T)obj);
updateStateful = true;
}
if (!stateDoc.isPersisted()) {
stateDoc.setOwner(obj);
this.mongoTemplate.save(stateDoc);
stateDoc.setPersisted(true);
if (updateStateful) {
this.mongoTemplate.save(obj);
}
}
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
@Override
protected boolean validStateField(Field stateField) {
return stateField.getType().equals(StateDocument.class);
}
@Override
protected Field findIdField(Class<?> clazz) {
return getFirstAnnotatedField(this.getClazz(), Id.class);
}
@Override
protected Class<?> getStateFieldType() {
return StateDocumentImpl.class;
}
protected Query buildQuery(StateDocumentImpl state, State<T> current) {
return Query.query(new Criteria("_id").is(state.getId()).and("state").is(current.getName()));
}
protected Update buildUpdate(State<T> current, State<T> next) {
Update update = new Update();
update.set("prevState", current.getName());
update.set("state", next.getName());
update.set("updated", Calendar.getInstance().getTime());
return update;
}
protected String getState(T stateful) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
StateDocumentImpl stateDoc = this.getStateDocument(stateful);
return (stateDoc != null) ? stateDoc.getState() : getStart().getName();
}
protected void setState(T stateful, String state) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
StateDocumentImpl stateDoc = this.getStateDocument(stateful);
if (stateDoc == null) {
stateDoc = createStateDocument(stateful);
}
stateDoc.setPrevState(stateDoc.getState());
stateDoc.setState(state);
stateDoc.setUpdated(Calendar.getInstance().getTime());
}
@SuppressWarnings("unchecked")
protected StateDocumentImpl getStateDocument(T stateful) throws IllegalArgumentException, IllegalAccessException {
return (StateDocumentImpl)getStateField().get(stateful);
}
protected StateDocumentImpl createStateDocument(T stateful) throws IllegalArgumentException, IllegalAccessException {
StateDocumentImpl stateDoc = new StateDocumentImpl();
stateDoc.setPersisted(false);
stateDoc.setId(new ObjectId().toHexString());
stateDoc.setState(getStart().getName());
setStateDocument(stateful, stateDoc);
return stateDoc;
}
protected void setStateDocument(T stateful, StateDocument stateDoc) throws IllegalArgumentException, IllegalAccessException {
getStateField().set(stateful, stateDoc);
}
protected void updateInMemory(T stateful, StateDocumentImpl stateDoc, String current, String next) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, StaleStateException {
synchronized(stateful) {
if (stateDoc == null) {
stateDoc = createStateDocument(stateful);
}
if (stateDoc.getState().equals(current)) {
setState(stateful, next);
} else {
throwStaleState(current, next);
}
}
}
protected void throwStaleState(String current, String next) throws StaleStateException {
String err = String.format(
"Unable to update state, entity.state=%s, db.state=%s",
current,
next);
throw new StaleStateException(err);
}
}
|
package org.eclipse.birt.report.context;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.birt.report.IBirtConstants;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.exception.ViewerException;
import org.eclipse.birt.report.model.api.ConfigVariableHandle;
import org.eclipse.birt.report.model.api.DesignEngine;
import org.eclipse.birt.report.model.api.IModuleOption;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ParameterHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.ConfigVariable;
import org.eclipse.birt.report.model.api.metadata.ValidationValueException;
import org.eclipse.birt.report.model.api.util.ParameterValidationUtil;
import org.eclipse.birt.report.resource.BirtResources;
import org.eclipse.birt.report.resource.ResourceConstants;
import org.eclipse.birt.report.service.BirtReportServiceFactory;
import org.eclipse.birt.report.service.BirtViewerReportDesignHandle;
import org.eclipse.birt.report.service.ReportEngineService;
import org.eclipse.birt.report.service.api.IViewerReportDesignHandle;
import org.eclipse.birt.report.service.api.IViewerReportService;
import org.eclipse.birt.report.service.api.InputOptions;
import org.eclipse.birt.report.service.api.ReportServiceException;
import org.eclipse.birt.report.utility.DataUtil;
import org.eclipse.birt.report.utility.ParameterAccessor;
import com.ibm.icu.util.ULocale;
/**
* Data bean for viewing request. Birt viewer distributes process logic into
* viewer fragments. Each fragment seperates its front-end and back-end process
* into jsp page and "code behand" fragment class. Viewer attribute bean serves
* as:
* <ol>
* <li> object that carries the data shared among different fragments</li>
* <li> object that carries the date shared between front-end jsp page and
* back-end class</li>
* </ol>
* In current implementation, ViewerAttributeBean uses request scope.
* <p>
*/
public class ViewerAttributeBean extends BaseAttributeBean
{
/**
* Viewer preview max rows limited
*/
private int maxRows;
/**
* Report parameters as string map
*/
private Map parametersAsString = null;
/**
* Report parameter definitions List
*/
private Collection parameterDefList = null;
/**
* Display Text of Select Parameters
*/
private Map displayTexts = null;
/**
* Module Options
*/
private Map moduleOptions = null;
/**
* If document generated completely
*/
private boolean isDocumentProcessing = false;
/**
* Constructor.
*
* @param request
*/
public ViewerAttributeBean( HttpServletRequest request )
{
try
{
init( request );
}
catch ( Exception e )
{
this.exception = e;
}
}
/**
* Init the bean.
*
* @param request
* @throws Exception
*/
protected void __init( HttpServletRequest request ) throws Exception
{
if ( ParameterAccessor.isGetImageOperator( request ) )
{
return;
}
this.category = "BIRT"; //$NON-NLS-1$
this.masterPageContent = ParameterAccessor
.isMasterPageContent( request );
this.isDesigner = ParameterAccessor.isDesigner( request );
this.bookmark = ParameterAccessor.getBookmark( request );
this.reportPage = String.valueOf( ParameterAccessor.getPage( request ) );
this.reportDocumentName = ParameterAccessor.getReportDocument( request );
this.reportDesignName = ParameterAccessor.getReport( request );
this.format = ParameterAccessor.getFormat( request );
this.maxRows = ParameterAccessor.getMaxRows( request );
BirtResources.setLocale( ParameterAccessor.getLocale( request ) );
// Set preview report max rows
ReportEngineService.getInstance( ).setMaxRows( this.maxRows );
// Determine the report design and doc 's timestamp
processReport( request );
// Report title.
String title = BirtResources
.getMessage( ResourceConstants.BIRT_VIEWER_TITLE );
this.reportTitle = ParameterAccessor.htmlEncode( title );
this.__initParameters( request );
}
/*
* Prepare the report parameters
*/
protected void __initParameters( HttpServletRequest request )
throws Exception
{
this.reportDesignHandle = getDesignHandle( request );
if ( this.reportDesignHandle == null )
return;
InputOptions options = new InputOptions( );
options.setOption( InputOptions.OPT_REQUEST, request );
options.setOption( InputOptions.OPT_LOCALE, locale );
options.setOption( InputOptions.OPT_RTL, new Boolean( rtl ) );
// Get parameter handle list
Collection parameterList = getParameterList( );
// when in preview model, parse parameters from config file
if ( this.isDesigner
&& !IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) ) )
parseConfigVars( request, parameterList );
// Get parameters as String Map
this.parametersAsString = getParsedParametersAsString( parameterList,
request, options );
// Get parameter definition list
this.parameterDefList = getReportService( ).getParameterDefinitions(
this.reportDesignHandle, options, false );
// Check if miss parameter
if ( documentInUrl )
this.missingParameter = false;
else
this.missingParameter = validateParameters( parameterDefList,
this.parametersAsString );
// Get parameters as String Map with default value
this.parametersAsString = getParsedParametersAsStringWithDefaultValue(
this.parametersAsString, request, options );
// Get parameters as Object Map
this.parameters = (HashMap) getParsedParameters(
this.reportDesignHandle, parameterList, request, options );
// Get display text of select parameters
this.displayTexts = getDisplayTexts( this.displayTexts, request );
// get some module options
this.moduleOptions = getModuleOptions( request );
}
/**
* parse paramenters from config file.
*
* @param request
* HttpServletRequest
* @param parameterList
* @return
*/
protected void parseConfigVars( HttpServletRequest request,
Collection parameterList )
{
this.configMap = new HashMap( );
// get report config filename
String reportConfigName = ParameterAccessor
.getConfigFileName( this.reportDesignName );
if ( reportConfigName == null )
return;
// Generate the session handle
SessionHandle sessionHandle = DesignEngine.newSession( ULocale.US );
ReportDesignHandle handle = null;
try
{
// Open report config file
handle = sessionHandle.openDesign( reportConfigName );
// initial config map
if ( handle != null )
{
String displayTextParam = null;
Iterator configVars = handle.configVariablesIterator( );
while ( configVars != null && configVars.hasNext( ) )
{
ConfigVariableHandle configVar = (ConfigVariableHandle) configVars
.next( );
if ( configVar != null && configVar.getName( ) != null )
{
String paramName = configVar.getName( );
Object paramValue = configVar.getValue( );
// check if null parameter
if ( paramName.toLowerCase( ).startsWith(
ParameterAccessor.PARAM_ISNULL )
&& paramValue != null )
{
String nullParamName = getParameterName( (String) paramValue );
if ( nullParamName != null )
this.configMap.put( nullParamName, null );
continue;
}
// check if display text of select parameter
else if ( ( displayTextParam = ParameterAccessor
.isDisplayText( paramName ) ) != null )
{
paramName = getParameterName( displayTextParam );
if ( paramName != null )
{
if ( this.displayTexts == null )
this.displayTexts = new HashMap( );
this.displayTexts.put( paramName, paramValue );
}
continue;
}
// check the parameter whether exist or not
paramName = getParameterName( paramName );
ScalarParameterHandle parameter = (ScalarParameterHandle) findParameter( paramName );
// convert parameter from default locale to current
// locale
if ( paramValue != null && parameter != null )
{
// find cached parameter type
String typeVarName = configVar.getName( )
+ "_" + IBirtConstants.PROP_TYPE; //$NON-NLS-1$
ConfigVariable typeVar = handle
.findConfigVariable( typeVarName );
// get cached parameter type
String dataType = parameter.getDataType( );
String cachedDateType = null;
if ( typeVar != null )
cachedDateType = typeVar.getValue( );
// if null or data type changed, skip it
if ( cachedDateType == null
|| !cachedDateType
.equalsIgnoreCase( dataType ) )
{
continue;
}
try
{
// if parameter type isn't String ,convert it
if ( !DesignChoiceConstants.PARAM_TYPE_STRING
.equalsIgnoreCase( dataType ) )
{
String pattern = parameter.getPattern( );
Object paramValueObj = ParameterValidationUtil
.validate( dataType, pattern,
(String) paramValue,
ULocale.US );
// if DateTime type,return Date Object
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME
.equalsIgnoreCase( dataType ) )
paramValue = paramValueObj;
else
paramValue = ParameterValidationUtil
.getDisplayValue( dataType,
pattern, paramValueObj,
locale );
}
}
catch ( Exception err )
{
paramValue = configVar.getValue( );
}
this.configMap.put( paramName, paramValue );
}
}
}
handle.close( );
}
}
catch ( Exception e )
{
// do nothing
}
}
/**
* Parse report object and get the parameter default values
*
* @param design
* IViewerReportDesignHandle
* @param paramName
* String
* @param options
* InputOptionsF
*
* @return Object
*/
protected Object getParameterDefaultValues(
IViewerReportDesignHandle design, String paramName,
InputOptions options ) throws ReportServiceException
{
if ( design == null )
return null;
String defalutValue = null;
Object defaultValueObj = null;
// Get parameter default value as object
try
{
defaultValueObj = this.getReportService( )
.getParameterDefaultValue( design, paramName, options );
}
catch ( ReportServiceException e )
{
e.printStackTrace( );
}
// Get Scalar parameter handle
ScalarParameterHandle parameter = (ScalarParameterHandle) findParameter( paramName );
// convert default value object to locale format
if ( defaultValueObj != null && parameter != null )
{
String dataType = parameter.getDataType( );
String pattern = parameter.getPattern( );
if ( DesignChoiceConstants.PARAM_TYPE_DATETIME
.equalsIgnoreCase( dataType ) )
{
// if datetime format, return it directly
return defaultValueObj;
}
if ( DesignChoiceConstants.PARAM_TYPE_STRING
.equalsIgnoreCase( dataType ) )
{
pattern = null;
}
defalutValue = ParameterValidationUtil.getDisplayValue( null,
pattern, defaultValueObj, locale );
}
// get parameter default value as string
if ( defalutValue == null && parameter != null )
{
defalutValue = parameter.getDefaultValue( );
}
return defalutValue;
}
/**
* if parameter existed in config file, return the correct parameter name
*
* @param configVarName
* String
* @return String
*/
private String getParameterName( String configVarName )
throws ReportServiceException
{
String paramName = null;
// Get parameter handle list
List parameters = getParameterList( );
if ( parameters != null )
{
for ( int i = 0; i < parameters.size( ); i++ )
{
ScalarParameterHandle parameter = null;
if ( parameters.get( i ) instanceof ScalarParameterHandle )
{
parameter = ( (ScalarParameterHandle) parameters.get( i ) );
}
// get current name
String curName = null;
if ( parameter != null && parameter.getName( ) != null )
{
curName = parameter.getName( ) + "_" + parameter.getID( ); //$NON-NLS-1$
}
// if find the parameter exist, return true
if ( curName != null
&& curName.equalsIgnoreCase( configVarName ) )
{
paramName = parameter.getName( );
break;
}
}
}
return paramName;
}
protected IViewerReportDesignHandle getDesignHandle(
HttpServletRequest request )
{
IViewerReportDesignHandle design = null;
IReportRunnable reportRunnable = null;
// check if document file path is valid
boolean isValidDocument = ParameterAccessor
.isValidFilePath( this.reportDocumentName );
if ( isValidDocument )
{
IReportDocument reportDocumentInstance = ReportEngineService
.getInstance( ).openReportDocument( this.reportDesignName,
this.reportDocumentName,
this.getModuleOptions( request ) );
if ( reportDocumentInstance != null )
{
reportRunnable = reportDocumentInstance.getReportRunnable( );
if ( ParameterAccessor.getParameter( request,
ParameterAccessor.PARAM_REPORT_DOCUMENT ) != null )
this.documentInUrl = true;
// in frameset mode, parse parameter values from document file
// if the path is frameset, copy the parameter value from
// document
// to run the report. If the _document parameter from url is not
// null, means user wants to preview the document, copy the
// parameter from the document to do the preview.
if ( IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) )
|| this.documentInUrl )
{
this.parameterMap = reportDocumentInstance
.getParameterValues( );
}
// if generating document from report isn't completed
if ( !reportDocumentInstance.isComplete( )
&& ParameterAccessor.isReportParameterExist( request,
ParameterAccessor.PARAM_REPORT ) )
this.isDocumentProcessing = true;
reportDocumentInstance.close( );
}
}
// if report runnable is null, then get it from design file
if ( reportRunnable == null )
{
// if only set __document parameter, throw exception directly
if ( ParameterAccessor.isReportParameterExist( request,
ParameterAccessor.PARAM_REPORT_DOCUMENT )
&& !ParameterAccessor.isReportParameterExist( request,
ParameterAccessor.PARAM_REPORT ) )
{
if ( isValidDocument )
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_FILE_ERROR,
new String[]{this.reportDocumentName} );
else
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_ACCESS_ERROR,
new String[]{this.reportDocumentName} );
return design;
}
// check if the report file path is valid
if ( !ParameterAccessor.isValidFilePath( this.reportDesignName ) )
{
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_ACCESS_ERROR,
new String[]{this.reportDesignName} );
}
else
{
try
{
// check the design file if exist
File file = new File( this.reportDesignName );
if ( file.exists( ) )
{
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( this.reportDesignName,
this.getModuleOptions( request ) );
}
else if ( !ParameterAccessor.isWorkingFolderAccessOnly( ) )
{
// try to get resource from war package, when
// WORKING_FOLDER_ACCESS_ONLY set as false
this.reportDesignName = ParameterAccessor.getParameter(
request, ParameterAccessor.PARAM_REPORT );
InputStream is = null;
URL url = null;
try
{
String reportPath = this.reportDesignName;
if ( !reportPath.startsWith( "/" ) ) //$NON-NLS-1$
reportPath = "/" + reportPath; //$NON-NLS-1$
url = request.getSession( ).getServletContext( )
.getResource( reportPath );
if ( url != null )
is = url.openStream( );
if ( is != null )
reportRunnable = ReportEngineService
.getInstance( )
.openReportDesign( url.toString( ), is,
this.getModuleOptions( request ) );
}
catch ( Exception e )
{
}
}
if ( reportRunnable == null )
{
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_FILE_ERROR,
new String[]{this.reportDesignName} );
}
}
catch ( EngineException e )
{
this.exception = e;
}
}
}
if ( reportRunnable != null )
{
design = new BirtViewerReportDesignHandle(
IViewerReportDesignHandle.RPT_RUNNABLE_OBJECT,
reportRunnable );
}
return design;
}
/**
* Determine the report design and doc 's timestamp
*
* @param request
* @throws Exception
*/
protected void processReport( HttpServletRequest request ) throws Exception
{
File reportDocFile = new File( this.reportDocumentName );
File reportDesignDocFile = new File( reportDesignName );
if ( reportDesignDocFile != null && reportDesignDocFile.exists( )
&& reportDesignDocFile.isFile( ) && reportDocFile != null
&& reportDocFile.exists( ) && reportDocFile.isFile( )
&& "get".equalsIgnoreCase( request.getMethod( ) ) ) //$NON-NLS-1$
{
if ( reportDesignDocFile.lastModified( ) > reportDocFile
.lastModified( )
|| ParameterAccessor.isOverwrite( request ) )
{
reportDocFile.delete( );
}
}
}
/**
* Get report service instance.
*/
protected IViewerReportService getReportService( )
{
return BirtReportServiceFactory.getReportService( );
}
/**
* Clear our resources.
*
* @exception Throwable
* @return
*/
protected void __finalize( ) throws Throwable
{
}
/**
* get parsed parameters.
*
* @param design
* IViewerReportDesignHandle
* @param parameterList
* Collection
* @param request
* HttpServletRequest
* @param options
* InputOptions
*
* @return Map
*/
protected Map getParsedParameters( IViewerReportDesignHandle design,
Collection parameterList, HttpServletRequest request,
InputOptions options ) throws ReportServiceException
{
Map params = new HashMap( );
if ( parameterList == null || this.parametersAsString == null )
return params;
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
ScalarParameterHandle parameter = null;
Object parameterObj = iter.next( );
if ( parameterObj instanceof ScalarParameterHandle )
{
parameter = (ScalarParameterHandle) parameterObj;
}
// if current object is not Scalar parameter handle, then skip it
if ( parameter == null )
continue;
String paramName = parameter.getName( );
Object paramValueObj = this.parametersAsString.get( paramName );
if ( paramValueObj != null )
{
// if default value is Date object, put map directly
if ( paramValueObj instanceof Date )
{
params.put( paramName, paramValueObj );
continue;
}
try
{
// convert parameter to object
String format = ParameterAccessor.getFormat( request,
paramName );
if ( format == null || format.length( ) <= 0 )
{
format = parameter.getPattern( );
}
paramValueObj = DataUtil.validate(
parameter.getDataType( ), format, paramValueObj
.toString( ), locale );
params.put( paramName, paramValueObj );
}
catch ( ValidationValueException e )
{
// if in PREVIEW mode, then throw exception directly
if ( ParameterAccessor.SERVLET_PATH_PREVIEW
.equalsIgnoreCase( request.getServletPath( ) ) )
{
this.exception = e;
break;
}
}
}
else
{
params.put( paramName, null );
}
}
return params;
}
/**
* get parameter object.
*
* @param request
* HttpServletRequest
* @param parameter
* ScalarParameterHandle
*
* @return
*/
protected Object getParamValueAsString( HttpServletRequest request,
ScalarParameterHandle parameter )
{
String paramName = parameter.getName( );
String paramValue = null;
if ( ParameterAccessor.isReportParameterExist( request, paramName ) )
{
// Get value from http request
paramValue = ParameterAccessor.getReportParameter( request,
paramName, null );
return paramValue;
}
Object paramValueObj = null;
if ( this.isDesigner
&& ( IBirtConstants.SERVLET_PATH_RUN.equalsIgnoreCase( request
.getServletPath( ) ) || IBirtConstants.SERVLET_PATH_PARAMETER
.equalsIgnoreCase( request.getServletPath( ) ) )
&& this.configMap != null
&& this.configMap.containsKey( paramName ) )
{
// Get value from config file
paramValueObj = this.configMap.get( paramName );
}
else if ( this.parameterMap != null
&& this.parameterMap.containsKey( paramName ) )
{
// Get value from document
paramValueObj = this.parameterMap.get( paramName );
}
if ( paramValueObj == null )
return paramValue;
// if DateTime parameter, return it
if ( paramValueObj instanceof Date )
return paramValueObj;
else
return paramValueObj.toString( );
}
/**
* get parsed parameters as string.
*
* @param parameterList
* Collection
* @param request
* HttpServletRequest
* @param options
* InputOptions
*
* @return Map
*/
protected Map getParsedParametersAsString( Collection parameterList,
HttpServletRequest request, InputOptions options )
throws ReportServiceException
{
Map params = new HashMap( );
if ( parameterList == null )
return params;
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
ScalarParameterHandle parameter = null;
Object parameterObj = iter.next( );
if ( parameterObj instanceof ScalarParameterHandle )
{
parameter = (ScalarParameterHandle) parameterObj;
}
// if current object is not Scalar parameter handle, then skip it
if ( parameter == null )
continue;
String paramName = parameter.getName( );
Object paramValue = getParamValueAsString( request, parameter );
if ( paramName != null )
params.put( paramName, paramValue );
}
return params;
}
/**
* get parsed parameters as string.
*
* @param parsedParameters
* Map
* @param request
* HttpServletRequest
* @param options
* InputOptions
*
* @return Map
*/
protected Map getParsedParametersAsStringWithDefaultValue(
Map parsedParameters, HttpServletRequest request,
InputOptions options ) throws ReportServiceException
{
if ( parsedParameters == null )
{
parsedParameters = new HashMap( );
return parsedParameters;
}
for ( Iterator iter = parsedParameters.keySet( ).iterator( ); iter
.hasNext( ); )
{
String paramName = iter.next( ).toString( );
Object paramValue = parsedParameters.get( paramName );
// if parameter value is null, then set value to default value.
if ( paramValue == null
&& !ParameterAccessor.isReportParameterExist( request,
paramName )
&& ( IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) )
|| this.configMap == null || !this.configMap
.containsKey( paramName ) ) )
{
paramValue = this.getParameterDefaultValues(
reportDesignHandle, paramName, options );
parsedParameters.put( paramName, paramValue );
}
}
return parsedParameters;
}
/**
* @return the parameter handle list
*/
private List getParameterList( ) throws ReportServiceException
{
IReportRunnable runnable = (IReportRunnable) this.reportDesignHandle
.getDesignObject( );
ModuleHandle model = null;
if ( runnable != null )
model = runnable.getDesignHandle( ).getModuleHandle( );
if ( model != null )
return model.getFlattenParameters( );
else
return null;
}
/**
* @return the parameter handle
*/
public ParameterHandle findParameter( String paramName )
throws ReportServiceException
{
if ( paramName == null )
return null;
IReportRunnable runnable = (IReportRunnable) this.reportDesignHandle
.getDesignObject( );
ModuleHandle model = null;
if ( runnable != null )
model = runnable.getDesignHandle( ).getModuleHandle( );
if ( model != null )
return model.findParameter( paramName );
else
return null;
}
/**
* @return the maxRows
*/
public int getMaxRows( )
{
return maxRows;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.context.BaseAttributeBean#getReportTitle()
*/
public String getReportTitle( ) throws ReportServiceException
{
String title = reportTitle;
if ( reportDesignHandle != null )
{
Object design = reportDesignHandle.getDesignObject( );
if ( design instanceof IReportRunnable )
{
IReportRunnable runnable = (IReportRunnable) design;
String designTitle = (String) runnable
.getProperty( IReportRunnable.TITLE );
if ( designTitle != null && designTitle.trim( ).length( ) > 0 )
title = designTitle;
}
}
return title;
}
/**
* Get Display Text of select parameters
*
* @param request
* @return Map
*/
protected Map getDisplayTexts( Map displayTexts, HttpServletRequest request )
{
if ( displayTexts == null )
displayTexts = new HashMap( );
Enumeration params = request.getParameterNames( );
while ( params != null && params.hasMoreElements( ) )
{
String param = DataUtil.getString( params.nextElement( ) );
String paramName = ParameterAccessor.isDisplayText( param );
if ( paramName != null )
{
displayTexts.put( paramName, ParameterAccessor.getParameter(
request, param ) );
}
}
return displayTexts;
}
/**
* Gets the module option map from the request.
*
* @param request
* the request
* @return the module options
*/
protected Map getModuleOptions( HttpServletRequest request )
{
Map options = new HashMap( );
options.put( IModuleOption.RESOURCE_FOLDER_KEY, ParameterAccessor
.getResourceFolder( request ) );
return options;
}
/**
* @return the parametersAsString
*/
public Map getParametersAsString( )
{
return parametersAsString;
}
/**
* @return the parameterDefList
*/
public Collection getParameterDefList( )
{
return parameterDefList;
}
/**
* @return the displayTexts
*/
public Map getDisplayTexts( )
{
return displayTexts;
}
/**
* @return the moduleOptions
*/
public Map getModuleOptions( )
{
return moduleOptions;
}
/**
* @return the isDocumentProcessing
*/
public boolean isDocumentProcessing( )
{
return isDocumentProcessing;
}
}
|
package org.eclipse.birt.report.context;
import java.io.File;
import java.io.InputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.birt.report.IBirtConstants;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.exception.ViewerException;
import org.eclipse.birt.report.model.api.ConfigVariableHandle;
import org.eclipse.birt.report.model.api.DesignEngine;
import org.eclipse.birt.report.model.api.IModuleOption;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ParameterHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.ConfigVariable;
import org.eclipse.birt.report.model.api.metadata.ValidationValueException;
import org.eclipse.birt.report.model.api.util.ParameterValidationUtil;
import org.eclipse.birt.report.resource.BirtResources;
import org.eclipse.birt.report.resource.ResourceConstants;
import org.eclipse.birt.report.service.BirtReportServiceFactory;
import org.eclipse.birt.report.service.BirtViewerReportDesignHandle;
import org.eclipse.birt.report.service.ReportEngineService;
import org.eclipse.birt.report.service.api.IViewerReportDesignHandle;
import org.eclipse.birt.report.service.api.IViewerReportService;
import org.eclipse.birt.report.service.api.InputOptions;
import org.eclipse.birt.report.service.api.ReportServiceException;
import org.eclipse.birt.report.utility.DataUtil;
import org.eclipse.birt.report.utility.ParameterAccessor;
import com.ibm.icu.util.ULocale;
/**
* Data bean for viewing request. Birt viewer distributes process logic into
* viewer fragments. Each fragment seperates its front-end and back-end process
* into jsp page and "code behand" fragment class. Viewer attribute bean serves
* as:
* <ol>
* <li> object that carries the data shared among different fragments</li>
* <li> object that carries the date shared between front-end jsp page and
* back-end class</li>
* </ol>
* In current implementation, ViewerAttributeBean uses request scope.
* <p>
*/
public class ViewerAttributeBean extends BaseAttributeBean
{
/**
* Viewer preview max rows limited
*/
private int maxRows;
/**
* Report parameters as string map
*/
private Map parametersAsString = null;
/**
* Report parameter definitions List
*/
private Collection parameterDefList = null;
/**
* Display Text of Select Parameters
*/
private Map displayTexts = null;
private Map moduleOptions = null;
/**
* Constructor.
*
* @param request
*/
public ViewerAttributeBean( HttpServletRequest request )
{
try
{
init( request );
}
catch ( Exception e )
{
this.exception = e;
}
}
/**
* Init the bean.
*
* @param request
* @throws Exception
*/
protected void __init( HttpServletRequest request ) throws Exception
{
if ( ParameterAccessor.isGetImageOperator( request ) )
{
return;
}
this.category = "BIRT"; //$NON-NLS-1$
this.masterPageContent = ParameterAccessor
.isMasterPageContent( request );
this.isDesigner = ParameterAccessor.isDesigner( request );
this.bookmark = ParameterAccessor.getBookmark( request );
this.reportPage = String.valueOf( ParameterAccessor.getPage( request ) );
this.reportDocumentName = ParameterAccessor.getReportDocument( request );
this.reportDesignName = ParameterAccessor.getReport( request );
this.format = ParameterAccessor.getFormat( request );
this.maxRows = ParameterAccessor.getMaxRows( request );
BirtResources.setLocale( ParameterAccessor.getLocale( request ) );
// Set preview report max rows
ReportEngineService.getInstance( ).setMaxRows( this.maxRows );
// Determine the report design and doc 's timestamp
processReport( request );
// Report title.
String title = BirtResources
.getMessage( ResourceConstants.BIRT_VIEWER_TITLE );
this.reportTitle = ParameterAccessor.htmlEncode( title );
this.__initParameters( request );
}
/*
* Prepare the report parameters
*/
protected void __initParameters( HttpServletRequest request )
throws Exception
{
this.reportDesignHandle = getDesignHandle( request );
if ( this.reportDesignHandle == null )
return;
InputOptions options = new InputOptions( );
options.setOption( InputOptions.OPT_REQUEST, request );
options.setOption( InputOptions.OPT_LOCALE, locale );
options.setOption( InputOptions.OPT_RTL, new Boolean( rtl ) );
// Get parameter handle list
Collection parameterList = getParameterList( );
// when in preview model, parse parameters from config file
if ( this.isDesigner
&& !IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) ) )
parseConfigVars( request, parameterList );
// Get parameters as String Map
this.parametersAsString = getParsedParametersAsString( parameterList,
request, options );
// Get parameter definition list
this.parameterDefList = getReportService( ).getParameterDefinitions(
this.reportDesignHandle, options, false );
// Check if miss parameter
if ( documentInUrl )
this.missingParameter = false;
else
this.missingParameter = validateParameters( parameterDefList,
this.parametersAsString );
// Get parameters as String Map with default value
this.parametersAsString = getParsedParametersAsStringWithDefaultValue(
this.parametersAsString, request, options );
// Get parameters as Object Map
this.parameters = (HashMap) getParsedParameters(
this.reportDesignHandle, parameterList, request, options );
// Get display text of select parameters
this.displayTexts = getDisplayTexts( this.displayTexts, request );
// get some module options
this.moduleOptions = getModuleOptions( request );
}
/**
* parse paramenters from config file.
*
* @param request
* HttpServletRequest
* @param parameterList
* @return
*/
protected void parseConfigVars( HttpServletRequest request,
Collection parameterList )
{
this.configMap = new HashMap( );
// get report config filename
String reportConfigName = ParameterAccessor
.getConfigFileName( this.reportDesignName );
if ( reportConfigName == null )
return;
// Generate the session handle
SessionHandle sessionHandle = DesignEngine.newSession( ULocale.US );
ReportDesignHandle handle = null;
try
{
// Open report config file
handle = sessionHandle.openDesign( reportConfigName );
// initial config map
if ( handle != null )
{
String displayTextParam = null;
Iterator configVars = handle.configVariablesIterator( );
while ( configVars != null && configVars.hasNext( ) )
{
ConfigVariableHandle configVar = (ConfigVariableHandle) configVars
.next( );
if ( configVar != null && configVar.getName( ) != null )
{
String paramName = configVar.getName( );
String paramValue = configVar.getValue( );
// check if null parameter
if ( paramName.toLowerCase( ).startsWith(
ParameterAccessor.PARAM_ISNULL )
&& paramValue != null )
{
String nullParamName = getParameterName( paramValue );
if ( nullParamName != null )
this.configMap.put( nullParamName, null );
continue;
}
// check if display text of select parameter
else if ( ( displayTextParam = ParameterAccessor
.isDisplayText( paramName ) ) != null )
{
paramName = getParameterName( displayTextParam );
if ( paramName != null )
{
if ( this.displayTexts == null )
this.displayTexts = new HashMap( );
this.displayTexts.put( paramName, paramValue );
}
continue;
}
// check the parameter whether exist or not
paramName = getParameterName( paramName );
ScalarParameterHandle parameter = (ScalarParameterHandle) findParameter( paramName );
// convert parameter from default locale to current
// locale
if ( paramValue != null && parameter != null )
{
// find cached parameter type
String typeVarName = configVar.getName( )
+ "_" + IBirtConstants.PROP_TYPE; //$NON-NLS-1$
ConfigVariable typeVar = handle
.findConfigVariable( typeVarName );
// get cached parameter type
String dataType = null;
if ( typeVar != null )
dataType = typeVar.getValue( );
// if null or data type changed, skip it
if ( dataType == null
|| !dataType.equalsIgnoreCase( parameter
.getDataType( ) ) )
{
continue;
}
try
{
if ( !DesignChoiceConstants.PARAM_TYPE_STRING
.equalsIgnoreCase( parameter
.getDataType( ) ) )
{
Object paramValueObj = ParameterValidationUtil
.validate(
parameter.getDataType( ),
parameter.getPattern( ),
paramValue, ULocale.US );
paramValue = ParameterValidationUtil
.getDisplayValue( parameter
.getDataType( ), parameter
.getPattern( ),
paramValueObj, locale );
}
}
catch ( Exception err )
{
paramValue = configVar.getValue( );
}
this.configMap.put( paramName, paramValue );
}
}
}
handle.close( );
}
}
catch ( Exception e )
{
// do nothing
}
}
/**
* Parse report object and get the parameter default values
*
* @param design
* IViewerReportDesignHandle
* @param paramName
* String
* @param options
* InputOptionsF
*
* @return String
*/
protected String getParameterDefaultValues(
IViewerReportDesignHandle design, String paramName,
InputOptions options ) throws ReportServiceException
{
if ( design == null )
return null;
String defalutValue = null;
Object defaultValueObj = null;
// Get parameter default value as object
try
{
defaultValueObj = this.getReportService( )
.getParameterDefaultValue( design, paramName, options );
}
catch ( ReportServiceException e )
{
e.printStackTrace( );
}
// Get Scalar parameter handle
ScalarParameterHandle parameter = (ScalarParameterHandle) findParameter( paramName );
// convert default value object to locale format
if ( defaultValueObj != null && parameter != null )
{
defalutValue = ParameterValidationUtil.getDisplayValue( null,
parameter.getPattern( ), defaultValueObj, locale );
}
// get parameter default value as string
if ( defalutValue == null && parameter != null )
{
defalutValue = parameter.getDefaultValue( );
}
return defalutValue;
}
/**
* if parameter existed in config file, return the correct parameter name
*
* @param configVarName
* String
* @return String
*/
private String getParameterName( String configVarName )
throws ReportServiceException
{
String paramName = null;
// Get parameter handle list
List parameters = getParameterList( );
if ( parameters != null )
{
for ( int i = 0; i < parameters.size( ); i++ )
{
ScalarParameterHandle parameter = null;
if ( parameters.get( i ) instanceof ScalarParameterHandle )
{
parameter = ( (ScalarParameterHandle) parameters.get( i ) );
}
// get current name
String curName = null;
if ( parameter != null && parameter.getName( ) != null )
{
curName = parameter.getName( ) + "_" + parameter.getID( ); //$NON-NLS-1$
}
// if find the parameter exist, return true
if ( curName != null
&& curName.equalsIgnoreCase( configVarName ) )
{
paramName = parameter.getName( );
break;
}
}
}
return paramName;
}
protected IViewerReportDesignHandle getDesignHandle(
HttpServletRequest request )
{
IViewerReportDesignHandle design = null;
IReportRunnable reportRunnable = null;
// check if document file path is valid
boolean isValidDocument = ParameterAccessor
.isValidFilePath( this.reportDocumentName );
if ( isValidDocument )
{
IReportDocument reportDocumentInstance = ReportEngineService
.getInstance( ).openReportDocument( this.reportDesignName,
this.reportDocumentName,
this.getModuleOptions( request ) );
if ( reportDocumentInstance != null )
{
reportRunnable = reportDocumentInstance.getReportRunnable( );
// in frameset mode, parse parameter values from document file
// if the path is frameset, copy the parameter value from
// document
// to run the report. If the _document parameter from url is not
// null, means user wants to preview the document, copy the
// parameter from the document to do the preview.
if ( IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) ) )
{
this.parameterMap = reportDocumentInstance
.getParameterValues( );
}
if ( ParameterAccessor.getParameter( request,
ParameterAccessor.PARAM_REPORT_DOCUMENT ) != null )
this.documentInUrl = true;
reportDocumentInstance.close( );
}
}
// if report runnable is null, then get it from design file
if ( reportRunnable == null )
{
// if only set __document parameter, throw exception directly
if ( ParameterAccessor.isReportParameterExist( request,
ParameterAccessor.PARAM_REPORT_DOCUMENT )
&& !ParameterAccessor.isReportParameterExist( request,
ParameterAccessor.PARAM_REPORT ) )
{
if ( isValidDocument )
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_FILE_ERROR,
new String[]{this.reportDocumentName} );
else
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_ACCESS_ERROR,
new String[]{this.reportDocumentName} );
return design;
}
// check if the report file path is valid
if ( !ParameterAccessor.isValidFilePath( this.reportDesignName ) )
{
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_ACCESS_ERROR,
new String[]{this.reportDesignName} );
}
else
{
try
{
// check the design file if exist
File file = new File( this.reportDesignName );
if ( file.exists( ) )
{
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( this.reportDesignName,
this.getModuleOptions( request ) );
}
else if ( !ParameterAccessor.isWorkingFolderAccessOnly( ) )
{
// try to get resource from war package, when
// WORKING_FOLDER_ACCESS_ONLY set as false
this.reportDesignName = ParameterAccessor.getParameter(
request, ParameterAccessor.PARAM_REPORT );
InputStream is = request.getSession( )
.getServletContext( ).getResourceAsStream(
this.reportDesignName );
reportRunnable = ReportEngineService.getInstance( )
.openReportDesign( is,
this.getModuleOptions( request ) );
}
else
{
this.exception = new ViewerException(
ResourceConstants.GENERAL_EXCEPTION_REPORT_FILE_ERROR,
new String[]{this.reportDesignName} );
}
}
catch ( EngineException e )
{
this.exception = e;
}
}
}
if ( reportRunnable != null )
{
design = new BirtViewerReportDesignHandle(
IViewerReportDesignHandle.RPT_RUNNABLE_OBJECT,
reportRunnable );
}
return design;
}
/**
* Determine the report design and doc 's timestamp
*
* @param request
* @throws Exception
*/
protected void processReport( HttpServletRequest request ) throws Exception
{
File reportDocFile = new File( this.reportDocumentName );
File reportDesignDocFile = new File( reportDesignName );
if ( reportDesignDocFile != null && reportDesignDocFile.exists( )
&& reportDesignDocFile.isFile( ) && reportDocFile != null
&& reportDocFile.exists( ) && reportDocFile.isFile( )
&& "get".equalsIgnoreCase( request.getMethod( ) ) ) //$NON-NLS-1$
{
if ( reportDesignDocFile.lastModified( ) > reportDocFile
.lastModified( )
|| ParameterAccessor.isOverwrite( request ) )
{
reportDocFile.delete( );
}
}
}
/**
* Get report service instance.
*/
protected IViewerReportService getReportService( )
{
return BirtReportServiceFactory.getReportService( );
}
/**
* Clear our resources.
*
* @exception Throwable
* @return
*/
protected void __finalize( ) throws Throwable
{
}
/**
* get parsed parameters.
*
* @param design
* IViewerReportDesignHandle
* @param parameterList
* Collection
* @param request
* HttpServletRequest
* @param options
* InputOptions
*
* @return Map
*/
protected Map getParsedParameters( IViewerReportDesignHandle design,
Collection parameterList, HttpServletRequest request,
InputOptions options ) throws ReportServiceException
{
Map params = new HashMap( );
if ( parameterList == null || this.parametersAsString == null )
return params;
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
ScalarParameterHandle parameter = null;
Object parameterObj = iter.next( );
if ( parameterObj instanceof ScalarParameterHandle )
{
parameter = (ScalarParameterHandle) parameterObj;
}
// if current object is not Scalar parameter handle, then skip it
if ( parameter == null )
continue;
String paramName = parameter.getName( );
Object paramValueObj = this.parametersAsString.get( paramName );
if ( paramValueObj != null )
{
try
{
// convert parameter to object
String format = ParameterAccessor.getFormat( request,
paramName );
if ( format == null || format.length( ) <= 0 )
{
format = parameter.getPattern( );
}
paramValueObj = DataUtil.validate(
parameter.getDataType( ), format, paramValueObj
.toString( ), locale );
params.put( paramName, paramValueObj );
}
catch ( ValidationValueException e )
{
// if in RUN mode, then throw exception directly
if ( ParameterAccessor.SERVLET_PATH_RUN
.equalsIgnoreCase( request.getServletPath( ) ) )
{
this.exception = e;
break;
}
}
}
else
{
params.put( paramName, null );
}
}
return params;
}
/**
* get parameter object.
*
* @param request
* HttpServletRequest
* @param parameter
* ScalarParameterHandle
*
* @return
*/
protected String getParamValueAsString( HttpServletRequest request,
ScalarParameterHandle parameter )
{
String paramName = parameter.getName( );
String paramValue = null;
if ( ParameterAccessor.isReportParameterExist( request, paramName ) )
{
// Get value from http request
paramValue = ParameterAccessor.getReportParameter( request,
paramName, null );
return paramValue;
}
Object paramValueObj = null;
if ( this.isDesigner
&& ( IBirtConstants.SERVLET_PATH_RUN.equalsIgnoreCase( request
.getServletPath( ) ) || IBirtConstants.SERVLET_PATH_PARAMETER
.equalsIgnoreCase( request.getServletPath( ) ) )
&& this.configMap != null
&& this.configMap.containsKey( paramName ) )
{
// Get value from config file
paramValueObj = this.configMap.get( paramName );
}
else if ( this.parameterMap != null
&& this.parameterMap.containsKey( paramName ) )
{
// Get value from document
paramValueObj = this.parameterMap.get( paramName );
// Convert to locale string format
paramValueObj = ParameterValidationUtil.getDisplayValue( null,
parameter.getPattern( ), paramValueObj, locale );
}
if ( paramValueObj != null )
paramValue = paramValueObj.toString( );
return paramValue;
}
/**
* get parsed parameters as string.
*
* @param parameterList
* Collection
* @param request
* HttpServletRequest
* @param options
* InputOptions
*
* @return Map
*/
protected Map getParsedParametersAsString( Collection parameterList,
HttpServletRequest request, InputOptions options )
throws ReportServiceException
{
Map params = new HashMap( );
if ( parameterList == null )
return params;
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
ScalarParameterHandle parameter = null;
Object parameterObj = iter.next( );
if ( parameterObj instanceof ScalarParameterHandle )
{
parameter = (ScalarParameterHandle) parameterObj;
}
// if current object is not Scalar parameter handle, then skip it
if ( parameter == null )
continue;
String paramName = parameter.getName( );
String paramValue = getParamValueAsString( request, parameter );
if ( paramName != null )
params.put( paramName, paramValue );
}
return params;
}
/**
* get parsed parameters as string.
*
* @param parsedParameters
* Map
* @param request
* HttpServletRequest
* @param options
* InputOptions
*
* @return Map
*/
protected Map getParsedParametersAsStringWithDefaultValue(
Map parsedParameters, HttpServletRequest request,
InputOptions options ) throws ReportServiceException
{
if ( parsedParameters == null )
{
parsedParameters = new HashMap( );
return parsedParameters;
}
for ( Iterator iter = parsedParameters.keySet( ).iterator( ); iter
.hasNext( ); )
{
String paramName = iter.next( ).toString( );
Object paramValue = parsedParameters.get( paramName );
// if parameter value is null, then set value to default value.
if ( paramValue == null
&& !ParameterAccessor.isReportParameterExist( request,
paramName )
&& ( IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( request.getServletPath( ) )
|| this.configMap == null || !this.configMap
.containsKey( paramName ) ) )
{
paramValue = this.getParameterDefaultValues(
reportDesignHandle, paramName, options );
parsedParameters.put( paramName, paramValue );
}
}
return parsedParameters;
}
/**
* @return the parameter handle list
*/
private List getParameterList( ) throws ReportServiceException
{
IReportRunnable runnable = (IReportRunnable) this.reportDesignHandle
.getDesignObject( );
ModuleHandle model = null;
if ( runnable != null )
model = runnable.getDesignHandle( ).getModuleHandle( );
if ( model != null )
return model.getFlattenParameters( );
else
return null;
}
/**
* @return the parameter handle
*/
public ParameterHandle findParameter( String paramName )
throws ReportServiceException
{
if ( paramName == null )
return null;
IReportRunnable runnable = (IReportRunnable) this.reportDesignHandle
.getDesignObject( );
ModuleHandle model = null;
if ( runnable != null )
model = runnable.getDesignHandle( ).getModuleHandle( );
if ( model != null )
return model.findParameter( paramName );
else
return null;
}
/**
* @return the maxRows
*/
public int getMaxRows( )
{
return maxRows;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.report.context.BaseAttributeBean#getReportTitle()
*/
public String getReportTitle( ) throws ReportServiceException
{
String title = reportTitle;
if ( reportDesignHandle != null )
{
Object design = reportDesignHandle.getDesignObject( );
if ( design instanceof IReportRunnable )
{
IReportRunnable runnable = (IReportRunnable) design;
String designTitle = (String) runnable
.getProperty( IReportRunnable.TITLE );
if ( designTitle != null && designTitle.trim( ).length( ) > 0 )
title = designTitle;
}
}
return title;
}
/**
* Get Display Text of select parameters
*
* @param request
* @return Map
*/
protected Map getDisplayTexts( Map displayTexts, HttpServletRequest request )
{
if ( displayTexts == null )
displayTexts = new HashMap( );
Enumeration params = request.getParameterNames( );
while ( params != null && params.hasMoreElements( ) )
{
String param = DataUtil.getString( params.nextElement( ) );
String paramName = ParameterAccessor.isDisplayText( param );
if ( paramName != null )
{
displayTexts.put( paramName, ParameterAccessor.getParameter(
request, param ) );
}
}
return displayTexts;
}
/**
* Gets the module option map from the request.
*
* @param request
* the request
* @return the module options
*/
protected Map getModuleOptions( HttpServletRequest request )
{
Map options = new HashMap( );
options.put( IModuleOption.RESOURCE_FOLDER_KEY, ParameterAccessor
.getResourceFolder( request ) );
return options;
}
/**
* @return the parametersAsString
*/
public Map getParametersAsString( )
{
return parametersAsString;
}
/**
* @return the parameterDefList
*/
public Collection getParameterDefList( )
{
return parameterDefList;
}
/**
* @return the displayTexts
*/
public Map getDisplayTexts( )
{
return displayTexts;
}
/**
* @return the moduleOptions
*/
public Map getModuleOptions( )
{
return moduleOptions;
}
}
|
package org.eclipse.birt.report.service;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import org.apache.axis.AxisFault;
import org.eclipse.birt.core.data.DataTypeUtil;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.framework.IPlatformContext;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.data.engine.api.IBaseDataSetDesign;
import org.eclipse.birt.data.engine.api.IBaseDataSourceDesign;
import org.eclipse.birt.report.IBirtConstants;
import org.eclipse.birt.report.data.adapter.api.DataRequestSession;
import org.eclipse.birt.report.data.adapter.api.DataSessionContext;
import org.eclipse.birt.report.data.adapter.api.IModelAdapter;
import org.eclipse.birt.report.data.adapter.api.IRequestInfo;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineConstants;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.HTMLActionHandler;
import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IDataExtractionTask;
import org.eclipse.birt.report.engine.api.IDataIterator;
import org.eclipse.birt.report.engine.api.IExtractionResults;
import org.eclipse.birt.report.engine.api.IGetParameterDefinitionTask;
import org.eclipse.birt.report.engine.api.IHTMLRenderOption;
import org.eclipse.birt.report.engine.api.IRenderTask;
import org.eclipse.birt.report.engine.api.IReportDocument;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IResultMetaData;
import org.eclipse.birt.report.engine.api.IResultSetItem;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.IRunTask;
import org.eclipse.birt.report.engine.api.IScalarParameterDefn;
import org.eclipse.birt.report.engine.api.InstanceID;
import org.eclipse.birt.report.engine.api.PDFRenderOption;
import org.eclipse.birt.report.engine.api.RenderOption;
import org.eclipse.birt.report.engine.api.ReportParameterConverter;
import org.eclipse.birt.report.engine.i18n.MessageConstants;
import org.eclipse.birt.report.exception.ViewerException;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ListingHandle;
import org.eclipse.birt.report.model.api.ReportElementHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.resource.BirtResources;
import org.eclipse.birt.report.resource.ResourceConstants;
import org.eclipse.birt.report.service.api.InputOptions;
import org.eclipse.birt.report.soapengine.api.Column;
import org.eclipse.birt.report.soapengine.api.ResultSet;
import org.eclipse.birt.report.utility.BirtUtility;
import org.eclipse.birt.report.utility.DataUtil;
import org.eclipse.birt.report.utility.LoggingUtil;
import org.eclipse.birt.report.utility.ParameterAccessor;
/**
* Provides all the services from Engine.
*/
public class ReportEngineService
{
private static ReportEngineService instance;
/**
* Report engine instance.
*/
private IReportEngine engine = null;
/**
* Static engine config instance.
*/
private EngineConfig config = null;
/**
* URL accesses images.
*/
private String imageBaseUrl = null;
/**
* Image handler instance.
*/
private HTMLServerImageHandler imageHandler = null;
/**
* Constructor.
*
* @param servletContext
* @param config
*/
private ReportEngineService( ServletContext servletContext )
{
System.setProperty( "RUN_UNDER_ECLIPSE", "false" ); //$NON-NLS-1$ //$NON-NLS-2$
if ( servletContext == null )
{
return;
}
// Init context parameters
ParameterAccessor.initParameters( servletContext );
config = new EngineConfig( );
// Register new image handler
HTMLRenderOption emitterConfig = new HTMLRenderOption( );
emitterConfig.setActionHandler( new HTMLActionHandler( ) );
imageHandler = new HTMLServerImageHandler( );
emitterConfig.setImageHandler( imageHandler );
config.getEmitterConfigs( ).put( "html", emitterConfig ); //$NON-NLS-1$
// Prepare image base url.
imageBaseUrl = IBirtConstants.SERVLET_PATH_PREVIEW + "?__imageID="; //$NON-NLS-1$
// Prepare log level.
String logLevel = ParameterAccessor.logLevel;
Level level = logLevel != null && logLevel.length( ) > 0 ? Level
.parse( logLevel ) : Level.OFF;
config.setLogConfig( ParameterAccessor.logFolder, level );
// Prepare ScriptLib location
String scriptLibDir = ParameterAccessor.scriptLibDir;
ArrayList jarFileList = new ArrayList( );
if ( scriptLibDir != null )
{
File dir = new File( scriptLibDir );
getAllJarFiles( dir, jarFileList );
}
String scriptlibClassPath = ""; //$NON-NLS-1$
for ( int i = 0; i < jarFileList.size( ); i++ )
scriptlibClassPath += EngineConstants.PROPERTYSEPARATOR
+ ( (File) jarFileList.get( i ) ).getAbsolutePath( );
if ( scriptlibClassPath.startsWith( EngineConstants.PROPERTYSEPARATOR ) )
scriptlibClassPath = scriptlibClassPath
.substring( EngineConstants.PROPERTYSEPARATOR.length( ) );
config.setProperty( EngineConstants.WEBAPP_CLASSPATH_KEY,
scriptlibClassPath );
config.setEngineHome( "" ); //$NON-NLS-1$
// configure the loggers
LoggingUtil.configureLoggers( ParameterAccessor.loggers, level,
ParameterAccessor.logFolder );
}
/**
* Get engine instance.
*
* @return the single report engine service
*/
public static ReportEngineService getInstance( )
{
return instance;
}
/**
* Get engine instance.
*
* @param servletConfig
* @throws BirtException
*
*/
public synchronized static void initEngineInstance(
ServletConfig servletConfig ) throws BirtException
{
initEngineInstance( servletConfig.getServletContext( ) );
}
/**
* Get engine instance.
*
* @param servletContext
* @throws BirtException
*
*/
public synchronized static void initEngineInstance(
ServletContext servletContext ) throws BirtException
{
if ( ReportEngineService.instance != null )
{
return;
}
ReportEngineService.instance = new ReportEngineService( servletContext );
}
/**
* Get all the files under the specified folder (including all the files
* under sub-folders)
*
* @param dir -
* the folder to look into
* @param fileList -
* the fileList to be returned
*/
private void getAllJarFiles( File dir, ArrayList fileList )
{
if ( dir.exists( ) && dir.isDirectory( ) )
{
File[] files = dir.listFiles( );
if ( files == null )
return;
for ( int i = 0; i < files.length; i++ )
{
File file = files[i];
if ( file.isFile( ) )
{
if ( file.getName( ).endsWith( ".jar" ) ) //$NON-NLS-1$
fileList.add( file );
}
else if ( file.isDirectory( ) )
{
getAllJarFiles( file, fileList );
}
}
}
}
/**
* Set Engine context.
*
* @param servletContext
* @param request
* @deprecated
* @throws BirtException
*/
public synchronized void setEngineContext( ServletContext servletContext,
HttpServletRequest request ) throws BirtException
{
setEngineContext( servletContext );
}
/**
* Set Engine context.
*
* @param servletContext
* @throws BirtException
*/
public synchronized void setEngineContext( ServletContext servletContext )
throws BirtException
{
if ( engine == null )
{
IPlatformContext platformContext = new PlatformServletContext(
servletContext );
config.setPlatformContext( platformContext );
// Startup OSGI Platform
Platform.startup( config );
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
if ( factory == null )
{
// if null, throw exception
throw new ViewerException(
ResourceConstants.REPORT_SERVICE_EXCEPTION_STARTUP_REPORTENGINE_ERROR );
}
engine = factory.createReportEngine( config );
// Get supported output formats
ParameterAccessor.supportedFormats = engine.getSupportedFormats( );
}
}
/**
* Open report design.
*
* @param report
* @param options
* the config options in the report design
* @return the report runnable
* @throws EngineException
*/
public IReportRunnable openReportDesign( String report, Map options )
throws EngineException
{
File file = new File( report );
if ( !file.exists( ) )
{
throw new EngineException(
MessageConstants.DESIGN_FILE_NOT_FOUND_EXCEPTION, report );
}
try
{
InputStream in = new FileInputStream( file );
String systemId = report;
try
{
systemId = file.toURL( ).toString( );
}
catch ( MalformedURLException ue )
{
systemId = report;
}
return engine.openReportDesign( systemId, in, options );
}
catch ( FileNotFoundException ioe )
{
throw new EngineException(
MessageConstants.DESIGN_FILE_NOT_FOUND_EXCEPTION, report );
}
}
/**
* Open report design by using the input stream
*
* @param systemId
* the system Id of the report design
* @param reportStream -
* the input stream
* @param options
* the config options in the report design
* @return IReportRunnable
* @throws EngineException
*/
public IReportRunnable openReportDesign( String systemId,
InputStream reportStream, Map options ) throws EngineException
{
return engine.openReportDesign( systemId, reportStream, options );
}
/**
* createGetParameterDefinitionTask.
*
* @param runnable
* @deprecated
* @return the get parameter definition task
*/
public IGetParameterDefinitionTask createGetParameterDefinitionTask(
IReportRunnable runnable )
{
IGetParameterDefinitionTask task = null;
try
{
task = engine.createGetParameterDefinitionTask( runnable );
}
catch ( Exception e )
{
}
return task;
}
/**
* createGetParameterDefinitionTask.
*
* @param runnable
* @return the get parameter definition task
*/
public IGetParameterDefinitionTask createGetParameterDefinitionTask(
IReportRunnable runnable, InputOptions options )
{
IGetParameterDefinitionTask task = null;
try
{
HttpServletRequest request = (HttpServletRequest) options
.getOption( InputOptions.OPT_REQUEST );
task = engine.createGetParameterDefinitionTask( runnable );
// set app context
Map context = BirtUtility.getAppContext( request,
ReportEngineService.class.getClassLoader( ) );
task.setAppContext( context );
}
catch ( Exception e )
{
}
return task;
}
/**
* Open report document from archive,
*
* @param docName
* the name of the report document
* @param systemId
* the system ID to search the resource in the document,
* generally it is the file name of the report design
* @param options
* the config options used in document
* @return the report docuement
*/
public IReportDocument openReportDocument( String systemId, String docName,
Map options )
{
if ( docName == null )
return null;
IReportDocument document = null;
try
{
document = engine.openReportDocument( systemId, docName, options );
}
catch ( Exception e )
{
}
return document;
}
/**
* Render image.
*
* @param imageId
* @param request
* @param outputStream
* @throws RemoteException
*/
public void renderImage( String imageId, HttpServletRequest request,
OutputStream outputStream ) throws RemoteException
{
assert ( this.imageHandler != null );
try
{
this.imageHandler.getImage( outputStream, ParameterAccessor
.getImageTempFolder( request ), imageId );
}
catch ( EngineException e )
{
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault
.setFaultCode( new QName(
"ReportEngineService.renderImage( )" ) ); //$NON-NLS-1$
throw fault;
}
}
/**
* Create HTML render option.
*
* @param svgFlag
* @param servletPath
* @param request
* @return HTML render option from the given arguments
*/
private HTMLRenderOption createHTMLRenderOption( boolean svgFlag,
String servletPath, HttpServletRequest request )
{
String baseURL = null;
boolean isDesigner = ParameterAccessor.isDesigner( request );
// try to get base url from config file
if ( !isDesigner )
baseURL = ParameterAccessor.getBaseURL( );
if ( baseURL == null )
{
// if not HTML format, use full URL.
if ( ParameterAccessor.isOpenAsAttachment( request )
|| !ParameterAccessor.PARAM_FORMAT_HTML
.equalsIgnoreCase( ParameterAccessor
.getFormat( request ) ) )
{
baseURL = request.getScheme( ) + "://" //$NON-NLS-1$
+ request.getServerName( ) + ":" //$NON-NLS-1$
+ request.getServerPort( );
}
else
{
baseURL = ""; //$NON-NLS-1$
}
}
// append application context path
baseURL += request.getContextPath( );
HTMLRenderOption renderOption = new HTMLRenderOption( );
renderOption.setImageDirectory( ParameterAccessor
.getImageTempFolder( request ) );
renderOption.setBaseImageURL( baseURL + imageBaseUrl );
if ( servletPath != null && servletPath.length( ) > 0 )
{
renderOption.setBaseURL( baseURL + servletPath );
}
else
{
renderOption.setBaseURL( baseURL + IBirtConstants.SERVLET_PATH_RUN );
}
renderOption.setEnableAgentStyleEngine( ParameterAccessor
.isAgentStyle( request ) );
renderOption.setSupportedImageFormats( svgFlag
? "PNG;GIF;JPG;BMP;SVG" : "PNG;GIF;JPG;BMP" ); //$NON-NLS-1$ //$NON-NLS-2$
return renderOption;
}
/**
* Create PDF render option.
*
* @param servletPath
* @param request
* @param isDesigner
* @return the PDF render option
*/
private PDFRenderOption createPDFRenderOption( String servletPath,
HttpServletRequest request, boolean isDesigner )
{
String baseURL = null;
// try to get base url from config file
if ( !isDesigner )
baseURL = ParameterAccessor.getBaseURL( );
if ( baseURL == null )
{
if ( ParameterAccessor.isOpenAsAttachment( request ) )
{
baseURL = request.getScheme( ) + "://" //$NON-NLS-1$
+ request.getServerName( ) + ":" //$NON-NLS-1$
+ request.getServerPort( );
}
else
{
baseURL = ""; //$NON-NLS-1$
}
}
// append application context path
baseURL += request.getContextPath( );
PDFRenderOption renderOption = new PDFRenderOption( );
if ( servletPath != null && servletPath.length( ) > 0 )
{
renderOption.setBaseURL( baseURL + servletPath );
}
else
{
renderOption.setBaseURL( baseURL + IBirtConstants.SERVLET_PATH_RUN );
}
renderOption.setSupportedImageFormats( "PNG;GIF;JPG;BMP" ); //$NON-NLS-1$
// fit to page setting
renderOption.setOption( PDFRenderOption.FIT_TO_PAGE, new Boolean(
ParameterAccessor.isFitToPage( request ) ) );
// pagebreak pagination only setting
renderOption.setOption( PDFRenderOption.PAGEBREAK_PAGINATION_ONLY,
new Boolean( ParameterAccessor.isPagebreakOnly( request ) ) );
return renderOption;
}
/**
* Run and render a report,
*
* @param request
*
* @param runnable
* @param outputStream
* @param format
* @param locale
* @param rtl
* @param parameters
* @param masterPage
* @param svgFlag
* @throws RemoteException
* @throws IOException
*/
public void runAndRenderReport( HttpServletRequest request,
IReportRunnable runnable, OutputStream outputStream, String format,
Locale locale, boolean rtl, Map parameters, boolean masterPage,
boolean svgFlag ) throws RemoteException
{
runAndRenderReport( request, runnable, outputStream, format, locale,
rtl, parameters, masterPage, svgFlag, null, null, null, null,
null, null );
}
/**
* Run and render a report with certain servlet path
*
* @param request
*
* @param runnable
* @param outputStream
* @param format
* @param locale
* @param rtl
* @param parameters
* @param masterPage
* @param svgFlag
* @param displayTexts
* @param servletPath
* @param reportTitle
* @throws RemoteException
* @throws IOException
*/
public void runAndRenderReport( HttpServletRequest request,
IReportRunnable runnable, OutputStream outputStream, String format,
Locale locale, boolean rtl, Map parameters, boolean masterPage,
boolean svgFlag, Map displayTexts, String servletPath,
String reportTitle ) throws RemoteException
{
runAndRenderReport( request, runnable, outputStream, format, locale,
rtl, parameters, masterPage, svgFlag, null, null, null,
displayTexts, servletPath, reportTitle );
}
/**
* Run and render a report,
*
* @param request
*
* @param runnable
* @param outputStream
* @param locale
* @param rtl
* @param parameters
* @param masterPage
* @param svgFlag
* @param activeIds
* @param renderOption
* @param displayTexts
* @param iServletPath
* @param reportTitle
* @throws RemoteException
* @throws IOException
*/
public void runAndRenderReport( HttpServletRequest request,
IReportRunnable runnable, OutputStream outputStream, String format,
Locale locale, boolean rtl, Map parameters, boolean masterPage,
boolean svgFlag, Boolean embeddable, List activeIds,
RenderOption renderOption, Map displayTexts, String iServletPath,
String reportTitle ) throws RemoteException
{
assert runnable != null;
String servletPath = iServletPath;
if ( servletPath == null )
servletPath = request.getServletPath( );
IRunAndRenderTask runAndRenderTask = engine
.createRunAndRenderTask( runnable );
runAndRenderTask.setLocale( locale );
if ( parameters != null )
{
runAndRenderTask.setParameterValues( parameters );
}
// Set display Text for select parameters
if ( displayTexts != null )
{
Iterator keys = displayTexts.keySet( ).iterator( );
while ( keys.hasNext( ) )
{
String paramName = DataUtil.getString( keys.next( ) );
String displayText = DataUtil.getString( displayTexts
.get( paramName ) );
runAndRenderTask.setParameterDisplayText( paramName,
displayText );
}
}
// set app context
Map context = BirtUtility.getAppContext( request,
ReportEngineService.class.getClassLoader( ) );
runAndRenderTask.setAppContext( context );
// Render options
if ( renderOption == null )
{
if ( IBirtConstants.PDF_RENDER_FORMAT.equalsIgnoreCase( format )
|| IBirtConstants.POSTSCRIPT_RENDER_FORMAT
.equalsIgnoreCase( format ) )
{
renderOption = createPDFRenderOption( servletPath, request,
ParameterAccessor.isDesigner( request ) );
}
else
{
// If format isn't HTML, force SVG to false
if ( !IBirtConstants.HTML_RENDER_FORMAT
.equalsIgnoreCase( format ) )
svgFlag = false;
renderOption = createHTMLRenderOption( svgFlag, servletPath,
request );
}
}
renderOption.setOutputStream( outputStream );
renderOption.setOutputFormat( format );
renderOption.setOption( IHTMLRenderOption.MASTER_PAGE_CONTENT,
new Boolean( masterPage ) );
renderOption.setOption( IHTMLRenderOption.HTML_RTL_FLAG, new Boolean(
rtl ) );
ViewerHTMLActionHandler handler = new ViewerHTMLActionHandler( locale,
rtl, masterPage, format );
String resourceFolder = ParameterAccessor.getParameter( request,
ParameterAccessor.PARAM_RESOURCE_FOLDER );
handler.setResourceFolder( resourceFolder );
renderOption.setActionHandler( handler );
if ( reportTitle != null )
renderOption.setOption( IHTMLRenderOption.HTML_TITLE, reportTitle );
if ( renderOption instanceof IHTMLRenderOption )
{
boolean isEmbeddable = false;
if ( embeddable != null )
isEmbeddable = embeddable.booleanValue( );
if ( IBirtConstants.SERVLET_PATH_RUN.equalsIgnoreCase( servletPath ) )
isEmbeddable = true;
( (IHTMLRenderOption) renderOption ).setEmbeddable( isEmbeddable );
}
renderOption.setOption( IHTMLRenderOption.INSTANCE_ID_LIST, activeIds );
// initialize emitter configs
initializeEmitterConfigs( request, renderOption.getOptions( ) );
runAndRenderTask.setRenderOption( renderOption );
// add task into session
BirtUtility.addTask( request, runAndRenderTask );
try
{
runAndRenderTask.run( );
}
catch ( BirtException e )
{
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault.setFaultCode( new QName(
"ReportEngineService.runAndRenderReport( )" ) ); //$NON-NLS-1$
throw fault;
}
finally
{
// Remove task from http session
BirtUtility.removeTask( request );
runAndRenderTask.close( );
}
}
/**
* Fills dynamic options with parameters from request.
*/
private void initializeEmitterConfigs( HttpServletRequest request,
Map config )
{
if ( config == null )
{
return;
}
for ( Iterator itr = request.getParameterMap( ).entrySet( ).iterator( ); itr
.hasNext( ); )
{
Entry entry = (Entry) itr.next( );
String name = String.valueOf( entry.getKey( ) );
// only process parameters start with "__"
if ( name.startsWith( "__" ) ) //$NON-NLS-1$
{
config.put( name.substring( 2 ), ParameterAccessor
.getParameter( request, name ) );
}
}
}
/**
* Run report.
*
* @param request
*
* @param runnable
* @param archive
* @param documentName
* @param locale
* @param parameters
* @deprecated
* @throws RemoteException
*/
public void runReport( HttpServletRequest request,
IReportRunnable runnable, String documentName, Locale locale,
Map parameters ) throws RemoteException
{
runReport( request, runnable, documentName, locale, parameters, null );
}
/**
* Run report.
*
* @param request
*
* @param runnable
* @param archive
* @param documentName
* @param locale
* @param parameters
* @param displayTexts
* @throws RemoteException
*/
public void runReport( HttpServletRequest request,
IReportRunnable runnable, String documentName, Locale locale,
Map parameters, Map displayTexts ) throws RemoteException
{
assert runnable != null;
// Preapre the run report task.
IRunTask runTask = null;
runTask = engine.createRunTask( runnable );
runTask.setLocale( locale );
runTask.setParameterValues( parameters );
// add task into session
BirtUtility.addTask( request, runTask );
// Set display Text for select parameters
if ( displayTexts != null )
{
Iterator keys = displayTexts.keySet( ).iterator( );
while ( keys.hasNext( ) )
{
String paramName = DataUtil.getString( keys.next( ) );
String displayText = DataUtil.getString( displayTexts
.get( paramName ) );
runTask.setParameterDisplayText( paramName, displayText );
}
}
// set app context
Map context = BirtUtility.getAppContext( request,
ReportEngineService.class.getClassLoader( ) );
runTask.setAppContext( context );
// Run report.
try
{
runTask.run( documentName );
}
catch ( BirtException e )
{
// clear document file
File doc = new File( documentName );
if ( doc != null )
doc.delete( );
// Any Birt exception.
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault
.setFaultCode( new QName(
"ReportEngineService.runReport( )" ) ); //$NON-NLS-1$
throw fault;
}
finally
{
// Remove task from http session
BirtUtility.removeTask( request );
runTask.close( );
}
}
/**
* Render report page.
*
* @param request
* @param reportDocument
* @param pageNumber
* @param masterPage
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @deprecated
* @return report page content
* @throws RemoteException
*/
public ByteArrayOutputStream renderReport( HttpServletRequest request,
IReportDocument reportDocument, long pageNumber,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl ) throws RemoteException
{
ByteArrayOutputStream out = new ByteArrayOutputStream( );
renderReport( out, request, reportDocument, null, pageNumber, null,
masterPage, svgFlag, activeIds, locale, rtl, null );
return out;
}
/**
* Render report page.
*
* @param request
* @param reportDocument
* @param pageNumber
* @param masterPage
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @return report page content
* @throws RemoteException
*/
public ByteArrayOutputStream renderReport( HttpServletRequest request,
IReportDocument reportDocument, String format, long pageNumber,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl ) throws RemoteException
{
ByteArrayOutputStream out = new ByteArrayOutputStream( );
renderReport( out, request, reportDocument, format, pageNumber, null,
masterPage, svgFlag, activeIds, locale, rtl, null );
return out;
}
/**
* Render report page.
*
* @param os
* @param request
* @param reportDocument
* @param pageNumber
* @param pageRange
* @param masterPage
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @param iServletPath
* @deprecated
* @throws RemoteException
*/
public void renderReport( OutputStream os, HttpServletRequest request,
IReportDocument reportDocument, long pageNumber, String pageRange,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl, String iServletPath ) throws RemoteException
{
renderReport( os, request, reportDocument, null, pageNumber, pageRange,
masterPage, svgFlag, activeIds, locale, rtl, iServletPath );
}
/**
* Render report page.
*
* @param out
* @param request
* @param reportDocument
* @param format
* @param pageNumber
* @param pageRange
* @param masterPage
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @param iServletPath
* @throws RemoteException
*/
public void renderReport( OutputStream out, HttpServletRequest request,
IReportDocument reportDocument, String format, long pageNumber,
String pageRange, boolean masterPage, boolean svgFlag,
List activeIds, Locale locale, boolean rtl, String iServletPath )
throws RemoteException
{
if ( reportDocument == null )
{
AxisFault fault = new AxisFault(
BirtResources
.getMessage( ResourceConstants.ACTION_EXCEPTION_NO_REPORT_DOCUMENT ) );
fault.setFaultCode( new QName(
"ReportEngineService.renderReport( )" ) ); //$NON-NLS-1$
throw fault;
}
if ( out == null )
return;
// get servlet path
String servletPath = iServletPath;
if ( servletPath == null )
servletPath = request.getServletPath( );
// Create render task.
IRenderTask renderTask = engine.createRenderTask( reportDocument );
// add task into session
BirtUtility.addTask( request, renderTask );
// set app context
Map context = BirtUtility.getAppContext( request,
ReportEngineService.class.getClassLoader( ) );
renderTask.setAppContext( context );
RenderOption renderOption = null;
if ( format == null )
format = ParameterAccessor.getFormat( request );
if ( IBirtConstants.PDF_RENDER_FORMAT.equalsIgnoreCase( format )
|| IBirtConstants.POSTSCRIPT_RENDER_FORMAT
.equalsIgnoreCase( format ) )
{
renderOption = createPDFRenderOption( servletPath, request,
ParameterAccessor.isDesigner( request ) );
}
else
{
// If format isn't HTML, force SVG to false
if ( !IBirtConstants.HTML_RENDER_FORMAT.equalsIgnoreCase( format ) )
svgFlag = false;
renderOption = createHTMLRenderOption( svgFlag, servletPath,
request );
}
renderOption.setOutputStream( out );
renderOption.setOutputFormat( format );
ViewerHTMLActionHandler handler = null;
if ( IBirtConstants.PDF_RENDER_FORMAT.equalsIgnoreCase( format )
|| IBirtConstants.POSTSCRIPT_RENDER_FORMAT
.equalsIgnoreCase( format ) )
{
handler = new ViewerHTMLActionHandler( reportDocument, pageNumber,
locale, false, rtl, masterPage, format );
}
else
{
boolean isEmbeddable = false;
if ( IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( servletPath )
|| IBirtConstants.SERVLET_PATH_RUN
.equalsIgnoreCase( servletPath ) )
isEmbeddable = true;
if ( renderOption instanceof IHTMLRenderOption )
( (IHTMLRenderOption) renderOption )
.setEmbeddable( isEmbeddable );
// If exported with word format, set to pagination.
if ( IBirtConstants.DOC_RENDER_FORMAT.equalsIgnoreCase( format ) )
{
( (IHTMLRenderOption) renderOption ).setOption(
IHTMLRenderOption.HTML_PAGINATION, Boolean.TRUE );
}
renderOption.setOption( IHTMLRenderOption.HTML_RTL_FLAG,
new Boolean( rtl ) );
renderOption.setOption( IHTMLRenderOption.INSTANCE_ID_LIST,
activeIds );
renderOption.setOption( IHTMLRenderOption.MASTER_PAGE_CONTENT,
new Boolean( masterPage ) );
handler = new ViewerHTMLActionHandler( reportDocument, pageNumber,
locale, isEmbeddable, rtl, masterPage, format );
}
String resourceFolder = ParameterAccessor.getParameter( request,
ParameterAccessor.PARAM_RESOURCE_FOLDER );
handler.setResourceFolder( resourceFolder );
renderOption.setActionHandler( handler );
// initialize emitter configs
initializeEmitterConfigs( request, renderOption.getOptions( ) );
String reportTitle = ParameterAccessor.htmlDecode( ParameterAccessor
.getTitle( request ) );
if ( reportTitle != null )
renderOption.setOption( IHTMLRenderOption.HTML_TITLE, reportTitle );
renderTask.setRenderOption( renderOption );
renderTask.setLocale( locale );
// Render designated page.
try
{
if ( pageNumber > 0 )
renderTask.setPageNumber( pageNumber );
if ( pageRange != null )
{
if ( !IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( servletPath )
|| !ParameterAccessor.PARAM_FORMAT_HTML
.equalsIgnoreCase( format ) )
renderTask.setPageRange( pageRange );
}
renderTask.render( );
}
catch ( Exception e )
{
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault.setFaultCode( new QName(
"ReportEngineService.renderReport( )" ) ); //$NON-NLS-1$
throw fault;
}
finally
{
// Remove task from http session
BirtUtility.removeTask( request );
renderTask.close( );
}
}
/**
* Render reportlet page with certain servlet path
*
* @param os
* @param request
* @param reportDocument
* @param reportletId
* @param masterPage
* @param pageNumber
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @deprecated
* @throws RemoteException
*/
public void renderReportlet( OutputStream os, HttpServletRequest request,
IReportDocument reportDocument, String reportletId,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl ) throws RemoteException
{
renderReportlet( os, request, reportDocument, reportletId, null,
masterPage, svgFlag, activeIds, locale, rtl, null );
}
/**
* Render reportlet page.
*
* @param os
* @param request
* @param reportDocument
* @param reportletId
* @param masterPage
* @param pageNumber
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @param iServletPath
* @deprecated
* @throws RemoteException
*/
public void renderReportlet( OutputStream os, HttpServletRequest request,
IReportDocument reportDocument, String reportletId,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl, String iServletPath ) throws RemoteException
{
renderReportlet( os, request, reportDocument, reportletId, null,
masterPage, svgFlag, activeIds, locale, rtl, iServletPath );
}
/**
* Render reportlet.
*
* @param request
* @param reportDocument
* @param reportletId
* @param format
* @param masterPage
* @param pageNumber
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @param iServletPath
* @return outputstream
* @throws RemoteException
*/
public OutputStream renderReportlet( HttpServletRequest request,
IReportDocument reportDocument, String reportletId, String format,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl, String iServletPath ) throws RemoteException
{
ByteArrayOutputStream out = new ByteArrayOutputStream( );
renderReportlet( out, request, reportDocument, reportletId, format,
masterPage, svgFlag, activeIds, locale, rtl, iServletPath );
return out;
}
/**
* Render reportlet page.
*
* @param out
* @param request
* @param reportDocument
* @param reportletId
* @param format
* @param masterPage
* @param pageNumber
* @param svgFlag
* @param activeIds
* @param locale
* @param rtl
* @param iServletPath
* @throws RemoteException
*/
public void renderReportlet( OutputStream out, HttpServletRequest request,
IReportDocument reportDocument, String reportletId, String format,
boolean masterPage, boolean svgFlag, List activeIds, Locale locale,
boolean rtl, String iServletPath ) throws RemoteException
{
if ( reportDocument == null )
{
AxisFault fault = new AxisFault(
BirtResources
.getMessage( ResourceConstants.ACTION_EXCEPTION_NO_REPORT_DOCUMENT ) );
fault.setFaultCode( new QName(
"ReportEngineService.renderReportlet( )" ) ); //$NON-NLS-1$
throw fault;
}
if ( out == null )
return;
String servletPath = iServletPath;
if ( servletPath == null )
servletPath = request.getServletPath( );
// Create render task.
IRenderTask renderTask = engine.createRenderTask( reportDocument );
// add task into session
BirtUtility.addTask( request, renderTask );
HashMap context = new HashMap( );
context.put( EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST,
request );
context.put( EngineConstants.APPCONTEXT_CLASSLOADER_KEY,
ReportEngineService.class.getClassLoader( ) );
// Client DPI setting
context.put( EngineConstants.APPCONTEXT_CHART_RESOLUTION,
ParameterAccessor.getDpi( request ) );
// Push user-defined application context
ParameterAccessor.pushAppContext( context, request );
renderTask.setAppContext( context );
// Render option
RenderOption renderOption = null;
if ( format == null )
format = ParameterAccessor.getFormat( request );
if ( IBirtConstants.PDF_RENDER_FORMAT.equalsIgnoreCase( format )
|| IBirtConstants.POSTSCRIPT_RENDER_FORMAT
.equalsIgnoreCase( format ) )
{
renderOption = createPDFRenderOption( servletPath, request,
ParameterAccessor.isDesigner( request ) );
}
else
{
// If format isn't HTML, force SVG to false
if ( !IBirtConstants.HTML_RENDER_FORMAT.equalsIgnoreCase( format ) )
svgFlag = false;
renderOption = createHTMLRenderOption( svgFlag, servletPath,
request );
}
renderOption.setOutputFormat( format );
renderOption.setOutputStream( out );
ViewerHTMLActionHandler handler = null;
if ( IBirtConstants.PDF_RENDER_FORMAT.equalsIgnoreCase( format )
|| IBirtConstants.POSTSCRIPT_RENDER_FORMAT
.equalsIgnoreCase( format ) )
{
handler = new ViewerHTMLActionHandler( reportDocument, -1, locale,
false, rtl, masterPage, format );
}
else
{
boolean isEmbeddable = false;
if ( IBirtConstants.SERVLET_PATH_FRAMESET
.equalsIgnoreCase( servletPath )
|| IBirtConstants.SERVLET_PATH_OUTPUT
.equalsIgnoreCase( servletPath ) )
isEmbeddable = true;
if ( renderOption instanceof IHTMLRenderOption )
( (IHTMLRenderOption) renderOption )
.setEmbeddable( isEmbeddable );
// If exported with word format, set to pagination.
if ( IBirtConstants.DOC_RENDER_FORMAT.equalsIgnoreCase( format ) )
{
( (IHTMLRenderOption) renderOption ).setOption(
IHTMLRenderOption.HTML_PAGINATION, Boolean.TRUE );
}
renderOption.setOption( IHTMLRenderOption.HTML_RTL_FLAG,
new Boolean( rtl ) );
renderOption.setOption( IHTMLRenderOption.INSTANCE_ID_LIST,
activeIds );
renderOption.setOption( IHTMLRenderOption.MASTER_PAGE_CONTENT,
new Boolean( masterPage ) );
handler = new ViewerHTMLActionHandler( reportDocument, -1, locale,
isEmbeddable, rtl, masterPage, format );
}
String resourceFolder = ParameterAccessor.getParameter( request,
ParameterAccessor.PARAM_RESOURCE_FOLDER );
handler.setResourceFolder( resourceFolder );
renderOption.setActionHandler( handler );
String reportTitle = ParameterAccessor.htmlDecode( ParameterAccessor
.getTitle( request ) );
if ( reportTitle != null )
renderOption.setOption( IHTMLRenderOption.HTML_TITLE, reportTitle );
renderTask.setRenderOption( renderOption );
renderTask.setLocale( locale );
// Render designated page.
try
{
if ( ParameterAccessor.isIidReportlet( request ) )
{
InstanceID instanceId = InstanceID.parse( reportletId );
renderTask.setInstanceID( instanceId );
}
else
{
renderTask.setReportlet( reportletId );
}
renderTask.render( );
}
catch ( Exception e )
{
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault.setFaultCode( new QName(
"ReportEngineService.renderReport( )" ) ); //$NON-NLS-1$
throw fault;
}
finally
{
// Remove task from http session
BirtUtility.removeTask( request );
renderTask.close( );
}
}
/**
* Get query result sets.
*
* @param document
* @return the result sets from the document
* @throws RemoteException
*/
public ResultSet[] getResultSets( IReportDocument document )
throws RemoteException
{
assert document != null;
ResultSet[] resultSetArray = null;
IDataExtractionTask dataTask = engine
.createDataExtractionTask( document );
try
{
List resultSets = dataTask.getResultSetList( );
resultSetArray = new ResultSet[resultSets.size( )];
if ( resultSets.size( ) > 0 )
{
for ( int k = 0; k < resultSets.size( ); k++ )
{
resultSetArray[k] = new ResultSet( );
IResultSetItem resultSetItem = (IResultSetItem) resultSets
.get( k );
assert resultSetItem != null;
resultSetArray[k].setQueryName( resultSetItem
.getResultSetName( ) );
IResultMetaData metaData = resultSetItem
.getResultMetaData( );
assert metaData != null;
Column[] columnArray = new Column[metaData.getColumnCount( )];
for ( int i = 0; i < metaData.getColumnCount( ); i++ )
{
columnArray[i] = new Column( );
String name = metaData.getColumnName( i );
columnArray[i].setName( name );
String label = metaData.getColumnLabel( i );
if ( label == null || label.length( ) <= 0 )
{
label = name;
}
columnArray[i].setLabel( label );
columnArray[i].setVisibility( new Boolean( true ) );
}
resultSetArray[k].setColumn( columnArray );
}
}
}
catch ( Exception e )
{
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault.setFaultCode( new QName(
"ReportEngineService.getResultSets( )" ) ); //$NON-NLS-1$
throw fault;
}
finally
{
dataTask.close( );
}
return resultSetArray;
}
/**
* Extract data.
*
* @param document
* @param resultSetName
* @param id
* @param columns
* @param filters
* @param locale
* @param outputStream
* @param encoding
* @throws RemoteException
*/
public void extractData( IReportDocument document, String resultSetName,
Collection columns, Locale locale, OutputStream outputStream,
String encoding ) throws RemoteException
{
extractData( document, resultSetName, columns, locale, outputStream,
encoding, ParameterAccessor.DEFAULT_SEP, false );
}
/**
* Extract data.
*
* @param document
* @param resultSetName
* @param id
* @param columns
* @param filters
* @param locale
* @param outputStream
* @param encoding
* @param sep
* @param isExportDataType
* @throws RemoteException
*/
public void extractData( IReportDocument document, String resultSetName,
Collection columns, Locale locale, OutputStream outputStream,
String encoding, char sep, boolean isExportDataType )
throws RemoteException
{
assert document != null;
assert resultSetName != null && resultSetName.length( ) > 0;
assert columns != null && !columns.isEmpty( );
String[] columnNames = new String[columns.size( )];
Iterator iSelectedColumns = columns.iterator( );
for ( int i = 0; iSelectedColumns.hasNext( ); i++ )
{
columnNames[i] = (String) iSelectedColumns.next( );
}
IDataExtractionTask dataTask = null;
IExtractionResults result = null;
IDataIterator iData = null;
try
{
dataTask = engine.createDataExtractionTask( document );
dataTask.selectResultSet( resultSetName );
dataTask.selectColumns( columnNames );
dataTask.setLocale( locale );
result = dataTask.extract( );
if ( result != null )
{
iData = result.nextResultIterator( );
if ( iData != null && columnNames.length > 0 )
{
StringBuffer buf = new StringBuffer( );
// Captions
buf.append( csvConvertor( columnNames[0], sep ) );
for ( int i = 1; i < columnNames.length; i++ )
{
buf.append( sep );
buf.append( csvConvertor( columnNames[i], sep ) );
}
buf.append( '\n' );
if ( encoding != null && encoding.trim( ).length( ) > 0 )
{
outputStream.write( buf.toString( ).getBytes(
encoding.trim( ) ) );
}
else
{
outputStream.write( buf.toString( ).getBytes( ) );
}
buf.delete( 0, buf.length( ) );
// Column data type
if ( isExportDataType )
{
Map types = new HashMap( );
int count = result.getResultMetaData( )
.getColumnCount( );
for ( int i = 0; i < count; i++ )
{
String colName = result.getResultMetaData( )
.getColumnName( i );
String colType = result.getResultMetaData( )
.getColumnTypeName( i );
types.put( colName, colType );
}
buf.append( (String) types.get( columnNames[0] ) );
for ( int i = 1; i < columnNames.length; i++ )
{
buf.append( sep );
buf.append( (String) types.get( columnNames[i] ) );
}
buf.append( '\n' );
outputStream.write( buf.toString( ).getBytes( ) );
buf.delete( 0, buf.length( ) );
}
// Data
while ( iData.next( ) )
{
String value = null;
try
{
value = csvConvertor( DataTypeUtil.toString( iData
.getValue( columnNames[0] ) ), sep );
}
catch ( Exception e )
{
// do nothing
}
if ( value != null )
{
buf.append( value );
}
for ( int i = 1; i < columnNames.length; i++ )
{
buf.append( sep );
try
{
value = csvConvertor( DataTypeUtil
.toString( iData
.getValue( columnNames[i] ) ),
sep );
}
catch ( Exception e )
{
value = null;
}
if ( value != null )
{
buf.append( value );
}
}
buf.append( '\n' );
if ( encoding != null && encoding.trim( ).length( ) > 0 )
{
outputStream.write( buf.toString( ).getBytes(
encoding.trim( ) ) );
}
else
{
outputStream.write( buf.toString( ).getBytes( ) );
}
buf.delete( 0, buf.length( ) );
}
}
}
}
catch ( Exception e )
{
AxisFault fault = new AxisFault( e.getLocalizedMessage( ), e
.getCause( ) );
fault
.setFaultCode( new QName(
"ReportEngineService.extractData( )" ) ); //$NON-NLS-1$
throw fault;
}
finally
{
if ( iData != null )
{
iData.close( );
}
if ( result != null )
{
result.close( );
}
if ( dataTask != null )
{
dataTask.close( );
}
}
}
/**
* CSV format convertor. Here is the rule.
*
* 1) Fields with given separator must be delimited with double-quote
* characters. 2) Fields that contain double quote characters must be
* surounded by double-quotes, and the embedded double-quotes must each be
* represented by a pair of consecutive double quotes. 3) A field that
* contains embedded line-breaks must be surounded by double-quotes. 4)
* Fields with leading or trailing spaces must be delimited with
* double-quote characters.
*
* @param value
* @param sep
* @return the csv format string value
* @throws RemoteException
*/
private String csvConvertor( String value, char sep )
throws RemoteException
{
if ( value == null )
{
return null;
}
value = value.replaceAll( "\"", "\"\"" ); //$NON-NLS-1$ //$NON-NLS-2$
boolean needQuote = false;
needQuote = ( value.indexOf( sep ) != -1 )
|| ( value.indexOf( '"' ) != -1 )
|| ( value.indexOf( 0x0A ) != -1 )
|| value.startsWith( " " ) || value.endsWith( " " ); //$NON-NLS-1$ //$NON-NLS-2$
value = needQuote ? "\"" + value + "\"" : value; //$NON-NLS-1$ //$NON-NLS-2$
return value;
}
/**
* Prepare the report parameters.
*
* @param request
* @param task
* @param configVars
* @param locale
* @deprecated
* @return map of the request parameters
*/
public HashMap parseParameters( HttpServletRequest request,
IGetParameterDefinitionTask task, Map configVars, Locale locale )
{
assert task != null;
HashMap params = new HashMap( );
Collection parameterList = task.getParameterDefns( false );
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
IScalarParameterDefn parameterObj = (IScalarParameterDefn) iter
.next( );
String paramValue = null;
Object paramValueObj = null;
// ScalarParameterHandle paramHandle = ( ScalarParameterHandle )
// parameterObj
// .getHandle( );
String paramName = parameterObj.getName( );
String format = parameterObj.getDisplayFormat( );
// Get default value from task
ReportParameterConverter converter = new ReportParameterConverter(
format, locale );
if ( ParameterAccessor.isReportParameterExist( request, paramName ) )
{
// Get value from http request
paramValue = ParameterAccessor.getReportParameter( request,
paramName, paramValue );
paramValueObj = converter.parse( paramValue, parameterObj
.getDataType( ) );
}
else if ( ParameterAccessor.isDesigner( request )
&& configVars.containsKey( paramName ) )
{
// Get value from test config
String configValue = (String) configVars.get( paramName );
ReportParameterConverter cfgConverter = new ReportParameterConverter(
format, Locale.US );
paramValueObj = cfgConverter.parse( configValue, parameterObj
.getDataType( ) );
}
else
{
paramValueObj = task.getDefaultValue( parameterObj.getName( ) );
}
params.put( paramName, paramValueObj );
}
return params;
}
/**
* Check whether missing parameter or not.
*
* @param task
* @param parameters
* @deprecated
* @return true if all the parameter values are valid, otherwise false
*/
public boolean validateParameters( IGetParameterDefinitionTask task,
Map parameters )
{
assert task != null;
assert parameters != null;
boolean missingParameter = false;
Collection parameterList = task.getParameterDefns( false );
for ( Iterator iter = parameterList.iterator( ); iter.hasNext( ); )
{
IScalarParameterDefn parameterObj = (IScalarParameterDefn) iter
.next( );
// ScalarParameterHandle paramHandle = ( ScalarParameterHandle )
// parameterObj
// .getHandle( );
String parameterName = parameterObj.getName( );
Object parameterValue = parameters.get( parameterName );
if ( parameterObj.isHidden( ) )
{
continue;
}
if ( parameterValue == null && !parameterObj.allowNull( ) )
{
missingParameter = true;
break;
}
if ( IScalarParameterDefn.TYPE_STRING == parameterObj.getDataType( ) )
{
String parameterStringValue = (String) parameterValue;
if ( parameterStringValue != null
&& parameterStringValue.length( ) <= 0
&& !parameterObj.allowBlank( ) )
{
missingParameter = true;
break;
}
}
}
return missingParameter;
}
/**
* uses to clear the data cach.
*
* @param dataSet
* the dataset handle
* @throws BirtException
*/
public void clearCache( DataSetHandle dataSet ) throws BirtException
{
DataSessionContext context = new DataSessionContext(
DataSessionContext.MODE_DIRECT_PRESENTATION, dataSet
.getModuleHandle( ), null );
DataRequestSession requestSession = DataRequestSession
.newSession( context );
IModelAdapter modelAdaptor = requestSession.getModelAdaptor( );
DataSourceHandle dataSource = dataSet.getDataSource( );
IBaseDataSourceDesign sourceDesign = modelAdaptor
.adaptDataSource( dataSource );
IBaseDataSetDesign dataSetDesign = modelAdaptor.adaptDataSet( dataSet );
requestSession.clearCache( sourceDesign, dataSetDesign );
}
/**
* @param maxRows
*/
public void setMaxRows( int maxRows )
{
if ( config != null )
{
config.setMaxRowsPerQuery( maxRows );
}
}
/**
* Collects all the distinct values for the given element and
* bindColumnName. This method will traverse the design tree for the given
* element and get the nearest binding column holder of it. The nearest
* binding column holder must be a list or table item, and it defines a
* distinct data set and bingding columns in it. If the element is null,
* binding name is empty or the binding column holder is not found, then
* return <code>Collections.EMPTY_LIST</code>. Caller can specify the max
* row number and start row number by implement the interface IRequestInfo.
*
* @param bindingName
* @param elementHandle
* @param requestInfo
* @return list of available column value
* @throws BirtException
*/
public List getColumnValueSet( String bindingName,
DesignElementHandle elementHandle, IRequestInfo requestInfo )
throws BirtException
{
if ( bindingName == null || elementHandle == null
|| !( elementHandle instanceof ReportItemHandle ) )
return Collections.EMPTY_LIST;
// if there is no effective holder of bindings, return empty
ReportItemHandle reportItem = getBindingHolder( elementHandle );
if ( reportItem == null )
return Collections.EMPTY_LIST;
List selectValueList = new ArrayList( );
DataRequestSession session = DataRequestSession
.newSession( new DataSessionContext(
DataSessionContext.MODE_DIRECT_PRESENTATION, reportItem
.getModuleHandle( ) ) );
selectValueList.addAll( session.getColumnValueSet( reportItem
.getDataSet( ), reportItem.paramBindingsIterator( ), reportItem
.columnBindingsIterator( ), bindingName, requestInfo ) );
session.shutdown( );
return selectValueList;
}
/**
* Collects all the distinct values for the given element and
* bindColumnName. This method will traverse the design tree for the given
* element and get the nearest binding column holder of it. The nearest
* binding column holder must be a list or table item, and it defines a
* distinct data set and bingding columns in it. If the element is null,
* binding name is empty or the binding column holder is not found, then
* return <code>Collections.EMPTY_LIST</code>.
*
* @param bindingName
* @param elementHandle
* @return list of the avaliable column value
* @throws BirtException
*/
public List getColumnValueSet( String bindingName,
DesignElementHandle elementHandle ) throws BirtException
{
if ( bindingName == null || elementHandle == null
|| !( elementHandle instanceof ReportItemHandle ) )
return Collections.EMPTY_LIST;
// if there is no effective holder of bindings, return empty
ReportItemHandle reportItem = getBindingHolder( elementHandle );
if ( reportItem == null )
return Collections.EMPTY_LIST;
List selectValueList = new ArrayList( );
DataRequestSession session = DataRequestSession
.newSession( new DataSessionContext(
DataSessionContext.MODE_DIRECT_PRESENTATION, reportItem
.getModuleHandle( ) ) );
selectValueList.addAll( session.getColumnValueSet( reportItem
.getDataSet( ), reportItem.paramBindingsIterator( ), reportItem
.columnBindingsIterator( ), bindingName ) );
session.shutdown( );
return selectValueList;
}
/**
* Returns the element handle which can save binding columns the given
* element
*
* @param handle
* the handle of the element which needs binding columns
* @return the holder for the element,or itself if no holder available
*/
private ReportItemHandle getBindingHolder( DesignElementHandle handle )
{
if ( handle instanceof ReportElementHandle )
{
if ( handle instanceof ListingHandle )
{
return (ReportItemHandle) handle;
}
if ( handle instanceof ReportItemHandle )
{
if ( ( (ReportItemHandle) handle ).getDataSet( ) != null
|| ( (ReportItemHandle) handle )
.columnBindingsIterator( ).hasNext( ) )
{
return (ReportItemHandle) handle;
}
}
ReportItemHandle result = getBindingHolder( handle.getContainer( ) );
if ( result == null && handle instanceof ReportItemHandle )
{
result = (ReportItemHandle) handle;
}
return result;
}
return null;
}
/**
* Gets the mime-type of the given emitter format.
*
* @param format
* @return mime-type of the extended emitter format
*/
public String getMIMEType( String format )
{
return engine.getMIMEType( format );
}
/**
* Returns the engine config
*/
public EngineConfig getEngineConfig( )
{
return config;
}
/**
* Shutdown ReportEngineService, set instance as null
*/
public static void shutdown( )
{
instance = null;
}
}
|
package edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpSession;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.vocabulary.XSD;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationUtils;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.EditConfigurationVTwo;
import edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.fields.FieldVTwo;
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils;
import edu.cornell.mannlib.vitro.webapp.utils.FrontEndEditingUtils.EditMode;
import edu.cornell.mannlib.vitro.webapp.utils.generators.EditModeUtils;
public class DateTimeValueFormGenerator extends BaseEditConfigurationGenerator
implements EditConfigurationGenerator {
final static String vivoCore = "http://vivoweb.org/ontology/core
final String toDateTimeValue = vivoCore + "dateTimeValue";
final static String valueType = vivoCore + "DateTimeValue";
final static String dateTimeValue = vivoCore + "dateTime";
final static String dateTimePrecision = vivoCore + "dateTimePrecision";
@Override
public EditConfigurationVTwo getEditConfiguration(VitroRequest vreq,
HttpSession session) {
EditConfigurationVTwo conf = new EditConfigurationVTwo();
initBasics(conf, vreq);
initPropertyParameters(vreq, session, conf);
initObjectPropForm(conf, vreq);
conf.setTemplate(this.getTemplate());
conf.setVarNameForSubject("subject");
conf.setVarNameForPredicate("toDateTimeValue");
conf.setVarNameForObject("valueNode");
conf.setN3Optional(Arrays.asList(getN3ForValue()));
conf.addNewResource("valueNode", DEFAULT_NS_FOR_NEW_RESOURCE);
conf.addSparqlForExistingLiteral(
"dateTimeField-value", getExistingDateTimeValueQuery());
conf.addSparqlForExistingUris(
"dateTimeField-precision", getExistingPrecisionQuery());
conf.addSparqlForExistingUris("valueNode", getExistingNodeQuery());
FieldVTwo dateTimeField = new FieldVTwo().setName(this.getDateTimeFieldName());
dateTimeField.setEditElement(new DateTimeWithPrecisionVTwo(dateTimeField,
VitroVocabulary.Precision.SECOND.uri(),
VitroVocabulary.Precision.NONE.uri()));
conf.addField(dateTimeField);
//Adding additional data, specifically edit mode
addFormSpecificData(conf, vreq);
//prepare
prepare(vreq, conf);
return conf;
}
//Writing these as methods instead of static strings allows the method getToDateTimeValuePredicate
//to be called after the class has been initialized - this is important for subclasses of this generator
//that rely on vreq for predicate
protected String getN3ForValue() {
return "?subject <" + this.getToDateTimeValuePredicate() + "> ?valueNode . \n" +
"?valueNode a <" + valueType + "> . \n" +
"?valueNode <" + dateTimeValue + "> ?dateTimeField-value . \n" +
"?valueNode <" + dateTimePrecision + "> ?dateTimeField-precision .";
}
protected String getExistingDateTimeValueQuery () {
return "SELECT ?existingDateTimeValue WHERE { \n" +
"?subject <" + this.getToDateTimeValuePredicate() + "> ?existingValueNode . \n" +
"?existingValueNode a <" + valueType + "> . \n" +
"?existingValueNode <" + dateTimeValue + "> ?existingDateTimeValue }";
}
protected String getExistingPrecisionQuery() {
return "SELECT ?existingPrecision WHERE { \n" +
"?subject <" + this.getToDateTimeValuePredicate() + "> ?existingValueNode . \n" +
"?existingValueNode a <" + valueType + "> . \n" +
"?existingValueNode <" + dateTimePrecision + "> ?existingPrecision }";
}
protected String getExistingNodeQuery() {
return "SELECT ?existingNode WHERE { \n" +
"?subject <" + this.getToDateTimeValuePredicate() + "> ?existingNode . \n" +
"?existingNode a <" + valueType + "> }";
}
public static String getNodeVar() {
return "valueNode";
}
public static String getNodeN3Var() {
return "?" + getNodeVar();
}
//isolating the predicate in this fashion allows this class to be subclassed for other date time value
//properties
protected String getToDateTimeValuePredicate() {
return this.toDateTimeValue;
}
protected String getDateTimeFieldName() {
return "dateTimeField";
}
protected String getTemplate() {
return "dateTimeValueForm.ftl";
}
//Adding form specific data such as edit mode
public void addFormSpecificData(EditConfigurationVTwo editConfiguration, VitroRequest vreq) {
HashMap<String, Object> formSpecificData = new HashMap<String, Object>();
formSpecificData.put("editMode", getEditMode(vreq).name().toLowerCase());
editConfiguration.setFormSpecificData(formSpecificData);
}
public EditMode getEditMode(VitroRequest vreq) {
//In this case, the original jsp didn't rely on FrontEndEditingUtils
//but instead relied on whether or not the object Uri existed
String objectUri = EditConfigurationUtils.getObjectUri(vreq);
EditMode editMode = FrontEndEditingUtils.EditMode.ADD;
if(objectUri != null && !objectUri.isEmpty()) {
editMode = FrontEndEditingUtils.EditMode.EDIT;
}
return editMode;
}
}
|
package org.opendaylight.yangtools.yang.data.operations;
import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
import com.google.common.base.Optional;
import com.google.common.collect.Sets;
final class ChoiceNodeModification extends
AbstractContainerNodeModification<ChoiceNode, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> {
@Override
protected QName getQName(ChoiceNode schema) {
return schema.getQName();
}
@Override
protected Object findSchemaForChild(ChoiceNode schema, QName nodeType) {
return SchemaUtils.findSchemaForChild(schema, nodeType);
}
@Override
protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(ChoiceNode schema,
Optional<org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> actual,
Optional<org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> modification)
throws DataModificationException {
Set<YangInstanceIdentifier.PathArgument> childrenToProcess = super.getChildrenToProcess(schema, actual,
modification);
if (modification.isPresent() == false) {
return childrenToProcess;
}
// Detect case node from modification
ChoiceCaseNode detectedCase = null;
for (DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> child : modification.get().getValue()) {
Optional<ChoiceCaseNode> detectedCaseForChild = SchemaUtils.detectCase(schema, child);
if(detectedCaseForChild.isPresent() == false) {
DataModificationException.IllegalChoiceValuesException.throwUnknownChild(schema.getQName(),
child.getNodeType());
}
if (detectedCase != null && detectedCase.equals(detectedCaseForChild.get()) == false) {
DataModificationException.IllegalChoiceValuesException.throwMultipleCasesReferenced(schema.getQName(),
modification.get(), detectedCase.getQName(), detectedCaseForChild.get().getQName());
}
detectedCase = detectedCaseForChild.get();
}
if (detectedCase == null)
return childrenToProcess;
// Filter out child nodes that do not belong to detected case =
// Nodes from other cases present in actual
Set<YangInstanceIdentifier.PathArgument> childrenToProcessFiltered = Sets.newLinkedHashSet();
for (YangInstanceIdentifier.PathArgument childToProcess : childrenToProcess) {
// child from other cases, skip
if (childToProcess instanceof YangInstanceIdentifier.AugmentationIdentifier
&& SchemaUtils.belongsToCaseAugment(detectedCase,
(YangInstanceIdentifier.AugmentationIdentifier) childToProcess) == false) {
continue;
} else if (belongsToCase(detectedCase, childToProcess) == false) {
continue;
}
childrenToProcessFiltered.add(childToProcess);
}
return childrenToProcessFiltered;
}
private boolean belongsToCase(ChoiceCaseNode detectedCase, YangInstanceIdentifier.PathArgument childToProcess) {
return detectedCase.getDataChildByName(childToProcess.getNodeType()) != null;
}
@Override
protected Object findSchemaForAugment(ChoiceNode schema, YangInstanceIdentifier.AugmentationIdentifier childToProcessId) {
return SchemaUtils.findSchemaForAugment(schema, childToProcessId.getPossibleChildNames());
}
@Override
protected DataContainerNodeBuilder<?, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> getBuilder(
ChoiceNode schema) {
return Builders.choiceBuilder(schema);
}
}
|
package com.strobel.decompiler.languages.java.ast.transforms;
import com.strobel.assembler.metadata.DynamicCallSite;
import com.strobel.assembler.metadata.IMethodSignature;
import com.strobel.assembler.metadata.JvmType;
import com.strobel.assembler.metadata.TypeReference;
import com.strobel.decompiler.DecompilerContext;
import com.strobel.decompiler.languages.java.ast.*;
import com.strobel.decompiler.patterns.AnyNode;
import com.strobel.decompiler.patterns.IdentifierExpressionBackReference;
import com.strobel.decompiler.patterns.Match;
import com.strobel.decompiler.patterns.NamedNode;
import com.strobel.decompiler.patterns.OptionalNode;
import com.strobel.decompiler.patterns.Pattern;
import static com.strobel.core.CollectionUtilities.first;
public class RewriteNewArrayLambdas extends ContextTrackingVisitor<Void> {
protected RewriteNewArrayLambdas(final DecompilerContext context) {
super(context);
}
@Override
public Void visitLambdaExpression(final LambdaExpression node, final Void data) {
super.visitLambdaExpression(node, data);
final DynamicCallSite callSite = node.getUserData(Keys.DYNAMIC_CALL_SITE);
if (callSite != null &&
callSite.getBootstrapArguments().size() >= 3 &&
callSite.getBootstrapArguments().get(2) instanceof IMethodSignature) {
final IMethodSignature signature = (IMethodSignature) callSite.getBootstrapArguments().get(2);
if (signature.getParameters().size() == 1 &&
signature.getParameters().get(0).getParameterType().getSimpleType() == JvmType.Integer &&
signature.getReturnType().isArray() &&
!signature.getReturnType().getElementType().isGenericType()) {
final LambdaExpression pattern = new LambdaExpression(Expression.MYSTERY_OFFSET);
final ParameterDeclaration size = new ParameterDeclaration();
size.setName(Pattern.ANY_STRING);
size.setAnyModifiers(true);
size.setType(new OptionalNode(new SimpleType("int")).toType());
pattern.getParameters().add(new NamedNode("size", size).toParameterDeclaration());
final ArrayCreationExpression arrayCreation = new ArrayCreationExpression(Expression.MYSTERY_OFFSET);
arrayCreation.getDimensions().add(new IdentifierExpressionBackReference("size").toExpression());
arrayCreation.setType(new NamedNode("type", new AnyNode()).toType());
pattern.setBody(arrayCreation);
final Match match = pattern.match(node);
if (match.success()) {
final AstType type = first(match.<AstType>get("type"));
if (signature.getReturnType().getElementType().isEquivalentTo(type.toTypeReference())) {
final MethodGroupExpression replacement = new MethodGroupExpression(
node.getOffset(),
new TypeReferenceExpression(Expression.MYSTERY_OFFSET, type.clone().makeArrayType()),
"new"
);
final TypeReference lambdaType = node.getUserData(Keys.TYPE_REFERENCE);
if (lambdaType != null) {
replacement.putUserData(Keys.TYPE_REFERENCE, lambdaType);
}
replacement.putUserData(Keys.DYNAMIC_CALL_SITE, callSite);
node.replaceWith(replacement);
}
}
}
}
return null;
}
}
|
package org.openhealthtools.mdht.uml.cda.dita.internal;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.dita.dost.util.DitaUtil;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Text;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.Stereotype;
import org.openhealthtools.mdht.uml.cda.core.util.CDAProfileUtil;
import org.openhealthtools.mdht.uml.cda.core.util.ICDAProfileConstants;
import org.openhealthtools.mdht.uml.cda.dita.DitaTransformerOptions;
import org.openhealthtools.mdht.uml.cda.dita.TransformClassContent;
import org.openhealthtools.mdht.uml.ui.properties.internal.sections.ConstraintEditor;
public class TextEditor implements ConstraintEditor {
private Text text;
private Constraint constraint;
private Button closeErrorTextButton;
private Text errorText;
private boolean checkDita = false;
public void setText(Text text) {
this.text = text;
this.text.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
checkDita = true;
}
public void focusGained(FocusEvent e) {
// Not needed
}
});
this.text.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
handleChange();
}
});
}
/**
* @return the value stored in the Dita Enabled constraint
* true iff the constraint has a Boolean of true, false otherwise
*/
public boolean isDitaEnabled() {
Boolean ditaEnabled = false;
try {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION);
ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED);
} catch (IllegalArgumentException ex) { /* Swallow this */
}
return ditaEnabled;
}
/*
* (non-Javadoc)
*
* * @see org.openhealthtools.mdht.uml.ui.properties.internal.sections.ConstraintEditor#setDitaEnabled(boolean)
*/
@Override
public void setDitaEnabled(boolean isEnabled) {
Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(
constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION);
constraint.setValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED, isEnabled);
}
private void handleChange() {
if (checkDita && isDitaEnabled()) {
runHandleChange();
}
}
private void runHandleChange() {
checkDita = false;
IPath tmpFile = generateTempDita();
boolean errorOccured = false;
try {
DitaUtil.validate(tmpFile);
} catch (Exception exception) {
// Add UI here
showError(exception.toString());
errorOccured = true;
} finally {
hideError(errorOccured);
}
// Delete the temporary folder
try {
FileUtils.deleteDirectory(tmpFile.toFile().getParentFile());
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
private void hideError(boolean errorOccured) {
if (!errorOccured) {
errorText.setVisible(false);
closeErrorTextButton.setVisible(false);
}
}
private void showError(String error) {
errorText.setText(error);
errorText.setVisible(true);
closeErrorTextButton.setVisible(true);
}
/*
* (non-Javadoc)
*
* @see org.openhealthtools.mdht.uml.ui.properties.internal.sections.ConstraintEditor#setConstraint(org.eclipse.uml2.uml.Constraint)
*/
public void setConstraint(Constraint constraint) {
boolean firstRun = this.constraint == null && constraint != null;
this.constraint = constraint;
this.checkDita = true;
if (firstRun) {
runHandleChange();
} else {
handleChange();
}
}
private IPath generateTempDita() {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IPath tmpFileInWorkspaceDir = workspace.getRoot().getLocation().append("tmp").append(
constraint.getContext().getName()).addFileExtension("dita");
DitaTransformerOptions transformerOptions = new DitaTransformerOptions();
transformerOptions.setExampleDepth(0);
TransformClassContent transformer = new TransformClassContent(transformerOptions);
if (!tmpFileInWorkspaceDir.toFile().getParentFile().exists())
tmpFileInWorkspaceDir.toFile().getParentFile().mkdirs();
transformer.writeClassToFile((Class) constraint.getContext(), tmpFileInWorkspaceDir);
return tmpFileInWorkspaceDir;
}
/*
* (non-Javadoc)
*
* @see org.openhealthtools.mdht.uml.ui.properties.internal.sections.ConstraintEditor#setErrorText(org.eclipse.swt.widgets.Text)
*/
@Override
public void setErrorText(Text errorText) {
this.errorText = errorText;
}
/*
* (non-Javadoc)
*
* @see org.openhealthtools.mdht.uml.ui.properties.internal.sections.ConstraintEditor#setCloseErrorText(org.eclipse.swt.widgets.Button)
*/
@Override
public void setCloseErrorText(Button closeErrorTextButton) {
this.closeErrorTextButton = closeErrorTextButton;
}
}
|
package org.talend.dataprep.transformation.api.transformer.json;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Component;
import org.talend.dataprep.api.dataset.*;
import org.talend.dataprep.api.dataset.statistics.Statistics;
import org.talend.dataprep.api.dataset.statistics.StatisticsUtils;
import org.talend.dataprep.api.type.Type;
import org.talend.dataprep.api.type.TypeUtils;
import org.talend.dataprep.exception.TDPException;
import org.talend.dataprep.transformation.api.action.ActionParser;
import org.talend.dataprep.transformation.api.action.DataSetRowAction;
import org.talend.dataprep.transformation.api.action.ParsedActions;
import org.talend.dataprep.transformation.api.action.context.TransformationContext;
import org.talend.dataprep.transformation.api.action.metadata.SchemaChangeAction;
import org.talend.dataprep.transformation.api.transformer.Transformer;
import org.talend.dataprep.transformation.api.transformer.TransformerWriter;
import org.talend.dataprep.transformation.api.transformer.configuration.Configuration;
import org.talend.dataprep.transformation.exception.TransformationErrorCodes;
import org.talend.dataquality.semantic.recognizer.CategoryRecognizerBuilder;
import org.talend.dataquality.statistics.cardinality.CardinalityAnalyzer;
import org.talend.dataquality.statistics.frequency.DataFrequencyAnalyzer;
import org.talend.dataquality.statistics.frequency.PatternFrequencyAnalyzer;
import org.talend.dataquality.statistics.numeric.histogram.HistogramAnalyzer;
import org.talend.dataquality.statistics.numeric.quantile.QuantileAnalyzer;
import org.talend.dataquality.statistics.numeric.summary.SummaryAnalyzer;
import org.talend.dataquality.statistics.quality.ValueQualityAnalyzer;
import org.talend.dataquality.statistics.quality.ValueQualityStatistics;
import org.talend.dataquality.statistics.text.TextLengthAnalyzer;
import org.talend.datascience.common.inference.Analyzer;
import org.talend.datascience.common.inference.Analyzers;
import org.talend.datascience.common.inference.semantic.SemanticAnalyzer;
import org.talend.datascience.common.inference.semantic.SemanticType;
import org.talend.datascience.common.inference.type.DataType;
/**
* Base implementation of the Transformer interface.
*/
@Component
class SimpleTransformer implements Transformer {
public static final String CONTEXT_ANALYZER = "analyzer";
@Autowired
ActionParser actionParser;
/** The data-prep jackson builder. */
@Autowired
private Jackson2ObjectMapperBuilder builder;
private static Analyzer<Analyzers.Result> configureAnalyzer(TransformationContext context) {
try {
Analyzer<Analyzers.Result> analyzer = (Analyzer<Analyzers.Result>) context.get(CONTEXT_ANALYZER);
if (analyzer == null) {
// Configure quality & semantic analysis (if column metadata information is present in stream).
final List<ColumnMetadata> columns = context.getTransformedRowMetadata().getColumns();
final DataType.Type[] types = TypeUtils.convert(columns);
final URI ddPath = SimpleTransformer.class.getResource("/luceneIdx/dictionary").toURI(); //$NON-NLS-1$
final URI kwPath = SimpleTransformer.class.getResource("/luceneIdx/keyword").toURI(); //$NON-NLS-1$
final CategoryRecognizerBuilder categoryBuilder = CategoryRecognizerBuilder.newBuilder()
.ddPath(ddPath)
.kwPath(kwPath)
.setMode(CategoryRecognizerBuilder.Mode.LUCENE);
// Find global min and max for histogram
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
boolean hasMetNumeric = false;
for (ColumnMetadata column : columns) {
final boolean isNumeric = Type.NUMERIC.isAssignableFrom(Type.get(column.getType()));
if (isNumeric) {
final Statistics statistics = column.getStatistics();
if (statistics.getMax() > max) {
max = statistics.getMax();
}
if (statistics.getMin() < min) {
min = statistics.getMin();
}
hasMetNumeric = true;
}
}
final HistogramAnalyzer histogramAnalyzer = new HistogramAnalyzer(types);
if (hasMetNumeric) {
histogramAnalyzer.init(min, max, 8);
}
analyzer = Analyzers.with(new ValueQualityAnalyzer(types),
// Cardinality (distinct + duplicate)
new CardinalityAnalyzer(),
// Frequency analysis (Pattern + data)
new DataFrequencyAnalyzer(), new PatternFrequencyAnalyzer(),
// Quantile analysis
new QuantileAnalyzer(types),
// Summary (min, max, mean, variance)
new SummaryAnalyzer(types),
// Histogram
histogramAnalyzer,
// Text length analysis (for applicable columns)
new TextLengthAnalyzer(), new SemanticAnalyzer(categoryBuilder));
context.put(CONTEXT_ANALYZER, analyzer);
}
return analyzer;
} catch (URISyntaxException e) {
throw new TDPException(TransformationErrorCodes.UNABLE_TRANSFORM_DATASET, e);
}
}
/**
* @see Transformer#transform(DataSet, Configuration)
*/
@Override
public void transform(DataSet input, Configuration configuration) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null.");
}
final TransformerWriter writer = configuration.writer();
try {
writer.startObject();
final ParsedActions parsedActions = actionParser.parse(configuration.getActions());
final List<DataSetRowAction> rowActions = parsedActions.getRowTransformers();
final boolean transformColumns = !input.getColumns().isEmpty();
TransformationContext context = configuration.getTransformationContext();
// Row transformations
Stream<DataSetRow> records = input.getRecords();
writer.fieldName("records");
writer.startArray();
// Apply actions to records
for (DataSetRowAction action : rowActions) {
records = records.map(r -> action.apply(r.clone(), context));
}
records = records.map(r -> {
context.setTransformedRowMetadata(r.getRowMetadata());
// Configure analyzer
if (transformColumns) {
// Use analyzer (for empty values, semantic...)
if (!r.isDeleted()) {
final DataSetRow row = r.order(r.getRowMetadata().getColumns());
configureAnalyzer(context).analyze(row.toArray(DataSetRow.SKIP_TDP_ID));
}
}
return r;
});
// Write transformed records to stream
final AtomicBoolean wroteMetadata = new AtomicBoolean(false);
records.forEach(row -> {
try {
if (writer.requireMetadataForHeader() && !wroteMetadata.get()) {
writer.write(row.getRowMetadata());
wroteMetadata.set(true);
}
if (row.shouldWrite()) {
writer.write(row);
}
} catch (IOException e) {
throw new TDPException(TransformationErrorCodes.UNABLE_TRANSFORM_DATASET, e);
}
});
writer.endArray();
// Write columns
if (!wroteMetadata.get() && transformColumns) {
Set<String> forcedColumns = (Set<String>) context.get(SchemaChangeAction.FORCED_TYPE_SET_CTX_KEY);
if (forcedColumns == null) {
forcedColumns = Collections.emptySet();
}
writer.fieldName("columns");
final RowMetadata row = context.getTransformedRowMetadata();
final Analyzer<Analyzers.Result> analyzer = (Analyzer<Analyzers.Result>) context.get(CONTEXT_ANALYZER);
// Set metadata information (not in statistics).
final List<ColumnMetadata> dataSetColumns = row.getColumns();
final List<Analyzers.Result> results = analyzer.getResult();
for (int i = 0; i < results.size(); i++) {
final Analyzers.Result result = results.get(i);
final ColumnMetadata metadata = dataSetColumns.get(i);
// Value quality
final ValueQualityStatistics column = result.get(ValueQualityStatistics.class);
final Quality quality = metadata.getQuality();
quality.setEmpty((int) column.getEmptyCount());
quality.setInvalid((int) column.getInvalidCount());
quality.setValid((int) column.getValidCount());
quality.setInvalidValues(column.getInvalidValues());
// we do not change again the domain as it has been maybe override by the user
if (!(metadata.isDomainForced() || metadata.isTypeForced()) && !forcedColumns.contains(metadata.getId())) {
// Semantic types
final SemanticType semanticType = result.get(SemanticType.class);
metadata.setDomain(TypeUtils.getDomainLabel(semanticType));
}
}
// Set the statistics
analyzer.end(); // TODO SemanticAnalyzer is erased on end(), call end after metadata is set (wait for TDQ-10970).
StatisticsUtils.setStatistics(row.getColumns(), analyzer.getResult());
writer.write(context.getTransformedRowMetadata());
}
writer.endObject();
writer.flush();
} catch (IOException e) {
throw new TDPException(TransformationErrorCodes.UNABLE_TRANSFORM_DATASET, e);
}
}
@Override
public boolean accept(Configuration configuration) {
return Configuration.class.equals(configuration.getClass()) && configuration.volume() == Configuration.Volume.SMALL;
}
}
|
package org.epics.pvmanager.loc;
import org.epics.pvmanager.*;
import org.epics.pvmanager.data.VDouble;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
/**
*
* @author carcassi
*/
public class LocChannelHandlerTest {
public LocChannelHandlerTest() {
}
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Mock ValueCache<VDouble> vDoubleCache1;
@Mock ValueCache<VDouble> vDoubleCache2;
@Mock WriteFunction<Boolean> vDoubleConnCache1;
@Mock WriteFunction<Boolean> vDoubleConnCache2;
@Mock ChannelWriteCallback channelWriteCallback;
@Mock WriteFunction<Exception> exceptionHandler;
@Mock ValueCache<Boolean> vDoubleWriteConnCache1;
@Test
public void writeToLocalChannelSingleMonitor() {
// Creating a test local channel
LocalChannelHandler channel = new LocalChannelHandler("test1");
assertThat(channel.getChannelName(), equalTo("test1"));
assertThat(channel.getUsageCounter(), equalTo(0));
assertThat(channel.isConnected(), is(false));
// Attaching a monitor cache/collector
ChannelHandlerReadSubscription readSubscription = new ChannelHandlerReadSubscription(vDoubleCache1, exceptionHandler, vDoubleConnCache1);
channel.addMonitor(readSubscription);
assertThat(channel.getUsageCounter(), equalTo(1));
assertThat(channel.isConnected(), is(true));
// Adding a writer
WriteCache<?> cache = new WriteCache<Object>();
ChannelHandlerWriteSubscription writeSubscription =
new ChannelHandlerWriteSubscription(cache, exceptionHandler, vDoubleWriteConnCache1);
channel.addWriter(writeSubscription);
assertThat(channel.getUsageCounter(), equalTo(2));
assertThat(channel.isConnected(), is(true));
// Writing a number and see if it is converted to a VDouble
channel.write(6.28, channelWriteCallback);
// Removing all readers and writers
channel.removeMonitor(readSubscription);
channel.removeWrite(writeSubscription);
assertThat(channel.getUsageCounter(), equalTo(0));
assertThat(channel.isConnected(), is(false));
InOrder inOrder = inOrder(vDoubleCache1, channelWriteCallback, exceptionHandler);
ArgumentCaptor<VDouble> newValue = ArgumentCaptor.forClass(VDouble.class);
inOrder.verify(vDoubleCache1).setValue(newValue.capture());
assertThat(newValue.getValue().getValue(), equalTo(6.28));
inOrder.verify(channelWriteCallback).channelWritten(null);
inOrder.verifyNoMoreInteractions();
}
@Test
public void writeToLocalChannelTwoMonitors() {
// Creating a test local channel
LocalChannelHandler channel = new LocalChannelHandler("test2", 0.0);
assertThat(channel.getChannelName(), equalTo("test2"));
assertThat(channel.getUsageCounter(), equalTo(0));
assertThat(channel.isConnected(), is(false));
// Attaching a monitor cache/collector
ChannelHandlerReadSubscription readSubscription1 = new ChannelHandlerReadSubscription(vDoubleCache1, exceptionHandler, vDoubleConnCache1);
channel.addMonitor(readSubscription1);
assertThat(channel.getUsageCounter(), equalTo(1));
assertThat(channel.isConnected(), is(true));
ChannelHandlerReadSubscription readSubscription2 = new ChannelHandlerReadSubscription(vDoubleCache2, exceptionHandler, vDoubleConnCache2);
// Attaching a monitor cache/collector
channel.addMonitor(readSubscription2);
assertThat(channel.getUsageCounter(), equalTo(2));
assertThat(channel.isConnected(), is(true));
// Adding a writer
WriteCache<?> cache = new WriteCache<Object>();
ChannelHandlerWriteSubscription writeSubscription = new ChannelHandlerWriteSubscription(cache, exceptionHandler, vDoubleWriteConnCache1);
channel.addWriter(writeSubscription);
assertThat(channel.getUsageCounter(), equalTo(3));
assertThat(channel.isConnected(), is(true));
// Writing a number and see if it is converted to a VDouble
channel.write(16.28, channelWriteCallback);
// Remove reader/writers
channel.removeWrite(new ChannelHandlerWriteSubscription(cache, exceptionHandler, vDoubleWriteConnCache1));
channel.removeMonitor(readSubscription1);
channel.removeMonitor(readSubscription2);
assertThat(channel.getUsageCounter(), equalTo(0));
assertThat(channel.isConnected(), is(false));
ArgumentCaptor<VDouble> newValue = ArgumentCaptor.forClass(VDouble.class);
verify(vDoubleCache1, times(2)).setValue(newValue.capture());
assertThat(newValue.getAllValues().get(0).getValue(), equalTo(0.0));
assertThat(newValue.getAllValues().get(1).getValue(), equalTo(16.28));
ArgumentCaptor<VDouble> newValue2 = ArgumentCaptor.forClass(VDouble.class);
verify(vDoubleCache2, times(2)).setValue(newValue2.capture());
assertThat(newValue2.getAllValues().get(0).getValue(), equalTo(0.0));
assertThat(newValue2.getAllValues().get(1).getValue(), equalTo(16.28));
verify(channelWriteCallback).channelWritten(null);
verifyZeroInteractions(channelWriteCallback, exceptionHandler);
}
}
|
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
public class SendChannel implements LocalChannel {
private static final String TAG = "sender thrd";
private static final Logger log = new Logger(TAG);
private static final String senderUXInstruction =
"\tType messages & [enter] to send\n\t[enter] twice to exit.\n";
private boolean isOk = true;
private boolean stopped = false;
private InetAddress destIP;
private int destPort;
private Scanner msgSrc;
private DatagramSocket socket;
private Thread running;
public SendChannel(
final Scanner src,
final InetAddress destIP,
final int destPort,
DatagramSocket outSock) {
this.msgSrc = src;
this.destIP = destIP;
this.destPort = destPort;
this.socket = outSock;
}
public SendChannel setLogLevel(final Logger.Level lvl) {
this.log.setLevel(lvl);
return this;
}
public SendChannel start() {
this.stopped = false;
this.running = new Thread(this);
this.running.setName(TAG);
this.running.start();
this.log.printf("spawned \"%s\" thread: %s\n", TAG, this.running);
return this;
}
public SendChannel report() {
this.log.printf(
"READY to capture messages\n\tbound for %s on port %s\n\tvia socket: %s\n",
this.destIP,
this.destPort,
this.socket.getLocalSocketAddress());
return this;
}
public boolean isActive() { return !this.stopped; }
public boolean isFailed() { return this.isOk; }
public Thread thread() { return this.running; }
public Thread stop() {
this.stopped = true;
return this.running;
}
private void fatalf(Exception e, String format, Object... args) {
this.log.errorf(e, format, args);
this.stop();
this.isOk = false;
}
public void run() {
DatagramPacket packet;
String rawMsg = null;
String message = null;
this.log.printf("usage instructions:\n%s", senderUXInstruction);
boolean isPrevEmpty = false;
long msgIndex = 0;
while (true) {
if (this.stopped) {
break;
}
try {
rawMsg = this.msgSrc.nextLine().trim();
message = URLEncoder.encode(rawMsg, "UTF-8");
} catch (NoSuchElementException e) {
this.log.printf("caught EOF, exiting...\n");
break;
} catch (UnsupportedEncodingException e) {
this.fatalf(e, "failed encoding message %03d '%s'", rawMsg);
break;
}
if (message.length() == 0) {
if (isPrevEmpty) {
this.log.printf("caught two empty messages, exiting.... ");
break;
}
isPrevEmpty = true;
this.log.printf("press enter again to exit normally.\n");
continue;
}
isPrevEmpty = false;
msgIndex++;
packet = new DatagramPacket(message.getBytes(), message.length(), destIP, destPort);
this.log.printf("sending message #%03d: '%s'...", msgIndex, message);
try {
this.socket.send(packet);
System.out.printf(" Done.\n");
} catch (Exception e) {
System.out.printf("\n");
this.fatalf(e, "\nfailed sending '%s'", message);
break;
}
}
this.msgSrc.close();
}
}
|
package io.spine.gradle.compiler.lookup.enrichments;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import static org.junit.Assert.assertFalse;
/**
* @author Dmytro Dashenkov
*/
@Ignore("setUp() fails in the Travis environment")
public class EnrichmentLookupPluginShould {
private static final Properties prop = new Properties();
@BeforeClass
public static void setUp() {
try {
// Get the properties file generated by the plugin
final File propFile = new File("generated/test/resources/enrichments.properties");
InputStream input = new FileInputStream(propFile);
prop.load(input);
input.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Test
public void find_enrichments() {
assertFalse(prop.isEmpty());
}
}
|
package com.atlassian.jira.plugins.dvcs.spi.bitbucket;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import com.atlassian.jira.plugins.dvcs.exception.SourceControlException;
import com.atlassian.jira.plugins.dvcs.model.AccountInfo;
import com.atlassian.jira.plugins.dvcs.model.Changeset;
import com.atlassian.jira.plugins.dvcs.model.DvcsUser;
import com.atlassian.jira.plugins.dvcs.model.Group;
import com.atlassian.jira.plugins.dvcs.model.Organization;
import com.atlassian.jira.plugins.dvcs.model.Repository;
import com.atlassian.jira.plugins.dvcs.service.ChangesetCache;
import com.atlassian.jira.plugins.dvcs.service.remote.BranchTip;
import com.atlassian.jira.plugins.dvcs.service.remote.BranchedChangesetIterator;
import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicator;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.BitbucketRemoteClient;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.client.JsonParsingException;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketAccount;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketBranch;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketBranchesAndTags;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketChangeset;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketChangesetWithDiffstat;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketGroup;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketRepository;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketServiceEnvelope;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.model.BitbucketServiceField;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.clientlibrary.request.BitbucketRequestException;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.linker.BitbucketLinker;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.transformers.ChangesetTransformer;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.transformers.DetailedChangesetTransformer;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.transformers.GroupTransformer;
import com.atlassian.jira.plugins.dvcs.spi.bitbucket.transformers.RepositoryTransformer;
import com.atlassian.jira.plugins.dvcs.util.DvcsConstants;
import com.atlassian.jira.plugins.dvcs.util.Retryer;
import com.atlassian.plugin.PluginAccessor;
/**
* The Class BitbucketCommunicator.
*
*/
public class BitbucketCommunicator implements DvcsCommunicator
{
/** The Constant log. */
private static final Logger log = LoggerFactory.getLogger(BitbucketCommunicator.class);
/** The Constant BITBUCKET. */
private static final String BITBUCKET = "bitbucket";
private final BitbucketLinker bitbucketLinker;
private final String pluginVersion;
private final BitbucketClientRemoteFactory bitbucketClientRemoteFactory;
private final ChangesetCache changesetCache;
/**
* The Constructor.
*
* @param bitbucketLinker
* @param pluginAccessor
* @param oauth
* @param bitbucketClientRemoteFactory
*/
public BitbucketCommunicator(@Qualifier("defferedBitbucketLinker") BitbucketLinker bitbucketLinker,
PluginAccessor pluginAccessor, BitbucketClientRemoteFactory bitbucketClientRemoteFactory,
ChangesetCache changesetCache)
{
this.bitbucketLinker = bitbucketLinker;
this.bitbucketClientRemoteFactory = bitbucketClientRemoteFactory;
this.changesetCache = changesetCache;
this.pluginVersion = DvcsConstants.getPluginVersion(pluginAccessor);
}
/**
* {@inheritDoc}
*/
@Override
public String getDvcsType()
{
return BITBUCKET;
}
/**
* {@inheritDoc}
*/
@Override
public AccountInfo getAccountInfo(String hostUrl, String accountName)
{
try
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getNoAuthClient(hostUrl);
// just to call the rest
remoteClient.getAccountRest().getUser(accountName);
return new AccountInfo(BitbucketCommunicator.BITBUCKET);
} catch (BitbucketRequestException e)
{
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public List<Repository> getRepositories(Organization organization)
{
try
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForOrganization(organization);
List<BitbucketRepository> repositories = remoteClient.getRepositoriesRest().getAllRepositories(
organization.getName());
return RepositoryTransformer.fromBitbucketRepositories(repositories);
} catch (BitbucketRequestException.Unauthorized_401 e)
{
log.debug("Invalid credentials", e);
throw new SourceControlException.UnauthorisedException("Invalid credentials", e);
} catch ( BitbucketRequestException.BadRequest_400 e)
{
// We received bad request status code and we assume that an invalid OAuth is the cause
throw new SourceControlException.UnauthorisedException("Invalid credentials");
} catch (BitbucketRequestException e)
{
log.debug(e.getMessage(), e);
throw new SourceControlException(e.getMessage(), e);
} catch (JsonParsingException e)
{
log.debug(e.getMessage(), e);
if (organization.isIntegratedAccount())
{
throw new SourceControlException.UnauthorisedException("Unexpected response was returned back from server side. Check that all provided information of account '"
+ organization.getName() + "' is valid. Basically it means: unexisting account or invalid key/secret combination.", e);
}
throw new SourceControlException.InvalidResponseException("The response could not be parsed. This is most likely caused by invalid credentials.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public Changeset getChangeset(Repository repository, String node)
{
try
{
// get the changeset
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForRepository(repository);
BitbucketChangeset bitbucketChangeset = remoteClient.getChangesetsRest().getChangeset(repository.getOrgName(),
repository.getSlug(), node);
Changeset fromBitbucketChangeset = ChangesetTransformer.fromBitbucketChangeset(repository.getId(), bitbucketChangeset);
return fromBitbucketChangeset;
} catch (BitbucketRequestException e)
{
log.debug(e.getMessage(), e);
throw new SourceControlException("Could not get changeset [" + node + "] from " + repository.getRepositoryUrl(), e);
} catch (JsonParsingException e)
{
log.debug(e.getMessage(), e);
throw new SourceControlException.InvalidResponseException("Could not get changeset [" + node + "] from " + repository.getRepositoryUrl(), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public Changeset getDetailChangeset(Repository repository, Changeset changeset)
{
try
{
// get the commit statistics for changeset
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForRepository(repository);
List<BitbucketChangesetWithDiffstat> changesetDiffStat = remoteClient.getChangesetsRest().getChangesetDiffStat(repository.getOrgName(),
repository.getSlug(), changeset.getNode(), Changeset.MAX_VISIBLE_FILES);
// merge it all
return DetailedChangesetTransformer.fromChangesetAndBitbucketDiffstats(changeset, changesetDiffStat);
} catch (BitbucketRequestException e)
{
log.debug(e.getMessage(), e);
throw new SourceControlException("Could not get detailed changeset [" + changeset.getNode() + "] from " + repository.getRepositoryUrl(), e);
} catch (JsonParsingException e)
{
log.debug(e.getMessage(), e);
throw new SourceControlException.InvalidResponseException("Could not get changeset [" + changeset.getNode() + "] from " + repository.getRepositoryUrl(), e);
}
}
@Override
public Iterable<Changeset> getChangesets(final Repository repository)
{
return new Iterable<Changeset>()
{
@Override
public Iterator<Changeset> iterator()
{
List<BranchTip> branches = getBranches(repository);
return new BranchedChangesetIterator(changesetCache, BitbucketCommunicator.this, repository, branches);
}
};
}
private List<BranchTip> getBranches(Repository repository)
{
List<BranchTip> branchTips = new ArrayList<BranchTip>();
BitbucketBranchesAndTags branchesAndTags = retrieveBranchesAndTags(repository);
List<BitbucketBranch> bitbucketBranches = branchesAndTags.getBranches();
for (BitbucketBranch bitbucketBranch : bitbucketBranches)
{
List<String> heads = bitbucketBranch.getHeads();
for (String head : heads)
{
// make sure "master" branch is first in the list
if ("master".equals(bitbucketBranch.getName()))
{
branchTips.add(0, new BranchTip(bitbucketBranch.getName(), head));
} else
{
branchTips.add(new BranchTip(bitbucketBranch.getName(), head));
}
}
}
// Bitbucket returns raw_nodes for each branch, but changesetiterator works
// with nodes. We need to use only first 12 characters from the node
for (BranchTip branchTip : branchTips)
{
String rawNode = branchTip.getNode();
if (StringUtils.length(rawNode)>12)
{
String node = rawNode.substring(0, 12);
branchTip.setNode(node);
}
}
return branchTips;
}
private BitbucketBranchesAndTags retrieveBranchesAndTags(final Repository repository)
{
return new Retryer<BitbucketBranchesAndTags>().retry(new Callable<BitbucketBranchesAndTags>()
{
@Override
public BitbucketBranchesAndTags call() throws Exception
{
return getBranchesAndTags(repository);
}
});
}
private BitbucketBranchesAndTags getBranchesAndTags(Repository repository)
{
try
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForRepository(repository);
return remoteClient.getBranchesAndTagsRemoteRestpoint().getBranchesAndTags(repository.getOrgName(),repository.getSlug());
} catch (BitbucketRequestException e)
{
log.debug("Could not retrieve list of branches", e);
throw new SourceControlException("Could not retrieve list of branches", e);
} catch (JsonParsingException e)
{
log.debug("The response could not be parsed", e);
throw new SourceControlException.InvalidResponseException("Could not retrieve list of branches", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void setupPostcommitHook(Repository repository, String postCommitUrl)
{
try
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForRepository(repository);
remoteClient.getServicesRest().addPOSTService(repository.getOrgName(), // owner
repository.getSlug(), postCommitUrl);
} catch (BitbucketRequestException e)
{
throw new SourceControlException.PostCommitHookRegistrationException("Could not add postcommit hook", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void linkRepository(Repository repository, Set<String> withProjectkeys)
{
try
{
bitbucketLinker.linkRepository(repository, withProjectkeys);
} catch (Exception e)
{
log.warn("Failed to link repository " + repository.getName() + " : " + e.getClass() + " :: "
+ e.getMessage());
}
}
/**
* {@inheritDoc}
*/
@Override
public void linkRepositoryIncremental(Repository repository, Set<String> withPossibleNewProjectkeys)
{
try
{
bitbucketLinker.linkRepositoryIncremental(repository, withPossibleNewProjectkeys);
} catch (Exception e)
{
log.warn("Failed to do incremental repository linking " + repository.getName() + " : " + e.getClass()
+ " :: " + e.getMessage());
}
}
/**
* {@inheritDoc}
*/
@Override
public void removePostcommitHook(Repository repository, String postCommitUrl)
{
try
{
bitbucketLinker.unlinkRepository(repository);
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForRepository(repository);
List<BitbucketServiceEnvelope> services = remoteClient.getServicesRest().getAllServices(
repository.getOrgName(), // owner
repository.getSlug());
for (BitbucketServiceEnvelope bitbucketServiceEnvelope : services)
{
for (BitbucketServiceField serviceField : bitbucketServiceEnvelope.getService().getFields())
{
boolean fieldNameIsUrl = serviceField.getName().equals("URL");
boolean fieldValueIsRequiredPostCommitUrl = serviceField.getValue().equals(postCommitUrl);
if (fieldNameIsUrl && fieldValueIsRequiredPostCommitUrl)
{
remoteClient.getServicesRest().deleteService(repository.getOrgName(), // owner
repository.getSlug(), bitbucketServiceEnvelope.getId());
}
}
}
} catch (BitbucketRequestException e)
{
throw new SourceControlException.PostCommitHookRegistrationException("Could not remove postcommit hook", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getCommitUrl(Repository repository, Changeset changeset)
{
return MessageFormat.format("{0}/{1}/{2}/changeset/{3}?dvcsconnector={4}", repository.getOrgHostUrl(),
repository.getOrgName(), repository.getSlug(), changeset.getNode(), pluginVersion);
}
/**
* {@inheritDoc}
*/
@Override
public String getFileCommitUrl(Repository repository, Changeset changeset, String file, int index)
{
return MessageFormat.format("{0}#chg-{1}", getCommitUrl(repository, changeset), file);
}
/**
* {@inheritDoc}
*/
@Override
public DvcsUser getUser(Repository repository, String author)
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForRepository(repository);
BitbucketAccount bitbucketAccount = remoteClient.getAccountRest().getUser(author);
String username = bitbucketAccount.getUsername();
String fullName = bitbucketAccount.getFirstName() + " " + bitbucketAccount.getLastName();
String avatar = bitbucketAccount.getAvatar();
return new DvcsUser(username, fullName, null, avatar, repository.getOrgHostUrl() + "/" + username);
}
/**
* {@inheritDoc}
*/
@Override
public DvcsUser getTokenOwner(Organization organization)
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForOrganization(organization);
BitbucketAccount bitbucketAccount = remoteClient.getAccountRest().getCurrentUser();
String username = bitbucketAccount.getUsername();
String fullName = bitbucketAccount.getFirstName() + " " + bitbucketAccount.getLastName();
String avatar = bitbucketAccount.getAvatar();
return new DvcsUser(username, fullName, null, avatar, organization.getHostUrl() + "/" + username);
}
/**
* {@inheritDoc}
*/
@Override
public Set<Group> getGroupsForOrganization(Organization organization)
{
try
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForOrganization(organization);
Set<BitbucketGroup> groups = remoteClient.getGroupsRest().getGroups(organization.getName()); // owner
return GroupTransformer.fromBitbucketGroups(groups);
} catch (BitbucketRequestException.Forbidden_403 e)
{
log.debug("Could not get groups for organization [" + organization.getName() + "]");
throw new SourceControlException.Forbidden_403(e);
} catch (BitbucketRequestException e)
{
log.debug("Could not get groups for organization [" + organization.getName() + "]");
throw new SourceControlException(e);
} catch (JsonParsingException e)
{
log.debug(e.getMessage(), e);
throw new SourceControlException.InvalidResponseException("Could not parse response [" + organization.getName() + "]. This is most likely caused by invalid credentials.", e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean supportsInvitation(Organization organization)
{
return organization.getDvcsType().equalsIgnoreCase(BITBUCKET);
}
/**
* {@inheritDoc}
*/
@Override
public void inviteUser(Organization organization, Collection<String> groupSlugs, String userEmail)
{
try
{
BitbucketRemoteClient remoteClient = bitbucketClientRemoteFactory.getForOrganization(organization);
for (String groupSlug : groupSlugs)
{
log.debug("Going invite " + userEmail + " to group " + groupSlug + " of bitbucket organization "
+ organization.getName());
remoteClient.getAccountRest().inviteUser(organization.getName(), userEmail, organization.getName(),
groupSlug);
}
} catch (BitbucketRequestException exception)
{
log.warn("Failed to invite user {} to organization {}. Response HTTP code {}", new Object[] { userEmail,
organization.getName(), exception.getClass().getName() });
}
}
public static String getApiUrl(String hostUrl)
{
return hostUrl + "/!api/1.0";
}
}
|
package edu.wustl.catissuecore.actionForm;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.bean.GenericSpecimen;
import edu.wustl.catissuecore.bean.GenericSpecimenVO;
/**
* action form used to carry specimens, aliquotes and derived
* for specimen summary page.
* @author abhijit_naik
*
*/
public class ViewSpecimenSummaryForm extends ActionForm {
/**
* Unique Serial verson uid.
*/
private static final long serialVersionUID = -7978857673984149449L;
public static final String ADD_USER_ACTION = "ADD";
public static final String UPDATE_USER_ACTION = "UPDATE";
public static final String REQUEST_TYPE_MULTI_SPECIMENS= "Multiple Specimen";
public static final String REQUEST_TYPE_COLLECTION_PROTOCOL= "Collection Protocol";
public static final String REQUEST_TYPE_ANTICIPAT_SPECIMENS= "anticipatory specimens";
private List<GenericSpecimen> specimenList = null;
private List<GenericSpecimen> aliquotList = null;
private List<GenericSpecimen> derivedList = null;
private String eventId= null;
private String selectedSpecimenId= null;
private String userAction;
private String requestType;
private Object summaryObject = null;
private String lastSelectedSpecimenId = null;
private String containerMap;
private String targetSuccess;
private String submitAction;
private HashMap<String, String> titleMap = new HashMap<String, String>();
private static String collectionProtocolStatus = "";
public ViewSpecimenSummaryForm()
{
titleMap.put(REQUEST_TYPE_MULTI_SPECIMENS, "Specimen details");
titleMap.put(REQUEST_TYPE_COLLECTION_PROTOCOL, "Specimen requirement(s)");
titleMap.put(REQUEST_TYPE_ANTICIPAT_SPECIMENS, "Specimen details");
specimenList = new ArrayList<GenericSpecimen> ();
aliquotList = new ArrayList<GenericSpecimen> ();
derivedList = new ArrayList<GenericSpecimen> ();
userAction = ADD_USER_ACTION;
requestType = REQUEST_TYPE_COLLECTION_PROTOCOL;
collectionProtocolStatus = "";
}
public void reset(ActionMapping mapping, ServletRequest request){
specimenList = new ArrayList<GenericSpecimen> ();
aliquotList = new ArrayList<GenericSpecimen> ();
derivedList = new ArrayList<GenericSpecimen> ();
}
public String getTitle(){
return titleMap.get(requestType);
}
public String getUserAction() {
return userAction;
}
public void setUserAction(String userAction) {
this.userAction = userAction;
}
public String getRequestType() {
return requestType;
}
public void switchUserAction(){
if ( UPDATE_USER_ACTION.equals(this.userAction)){
this.userAction = ADD_USER_ACTION;
}
else
{
this.userAction = UPDATE_USER_ACTION;
}
}
public void setRequestType(String requestType) {
this.requestType = requestType;
}
public String getSelectedSpecimenId() {
return selectedSpecimenId;
}
public void setSelectedSpecimenId(String selectedSpecimenId) {
this.selectedSpecimenId = selectedSpecimenId;
}
public List<GenericSpecimen> getSpecimenList() {
return specimenList;
}
public void setSpecimenList(List<GenericSpecimen> specimenList) {
if (specimenList != null)
{
this.specimenList = specimenList;
}
}
public List<GenericSpecimen> getAliquotList() {
return aliquotList;
}
public void setAliquotList(List<GenericSpecimen> aliquoteList) {
if (aliquoteList != null){
this.aliquotList = aliquoteList;
}
}
public List<GenericSpecimen> getDerivedList() {
return derivedList;
}
public void setDerivedList(List<GenericSpecimen> derivedList) {
if (derivedList != null){
this.derivedList = derivedList;
}
}
public GenericSpecimen getDerived(int index){
while(index >= derivedList.size()){
derivedList.add( getNewSpecimen());
}
return derivedList.get(index);
}
public void setDerived(int index, GenericSpecimen derivedSpecimen){
derivedList.add(index,derivedSpecimen);
}
public GenericSpecimen getAliquot(int index){
while(index >= aliquotList.size()){
aliquotList.add( getNewSpecimen());
}
return aliquotList.get(index);
}
public void setAliquot(int index, GenericSpecimen aliquotSpecimen){
aliquotList.add(index,aliquotSpecimen);
}
public GenericSpecimen getSpecimen(int index){
while(index >= specimenList.size()){
specimenList.add( getNewSpecimen());
}
return specimenList.get(index);
}
public void setSpecimen(int index, GenericSpecimen specimen){
aliquotList.add(index,specimen);
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
private GenericSpecimen getNewSpecimen()
{
return new GenericSpecimenVO();
}
public Object getSummaryObject() {
return summaryObject;
}
public void setSummaryObject(Object summaryObject) {
this.summaryObject = summaryObject;
}
public String getLastSelectedSpecimenId() {
return lastSelectedSpecimenId;
}
public void setLastSelectedSpecimenId(String lastEventId) {
this.lastSelectedSpecimenId = lastEventId;
}
public String getContainerMap() {
return containerMap;
}
public void setContainerMap(String containerMap) {
this.containerMap = containerMap;
}
public String getTargetSuccess() {
return targetSuccess;
}
public void setTargetSuccess(String targetSuccess) {
this.targetSuccess = targetSuccess;
}
public String getSubmitAction() {
return submitAction;
}
public void setSubmitAction(String submitAction) {
this.submitAction = submitAction;
}
public String getCollectionProtocolStatus() {
return collectionProtocolStatus;
}
public static void setCollectionProtocolStatus(String collectionProtocolStatus) {
ViewSpecimenSummaryForm.collectionProtocolStatus = collectionProtocolStatus;
}
}
|
package org.opennms.netmgt.provision.service.lifecycle;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.opennms.netmgt.provision.service.lifecycle.annotations.Activity;
import org.opennms.netmgt.provision.service.lifecycle.annotations.ActivityProvider;
/**
* LifecycleTest
*
* @author brozow
*/
public class LifeCycleTest {
// activity(LifeCycle lifeCycle, OnmsIpInterface iface)
// if there is only one attribute that contains that type then
// pass it in as an argument. Should be able to annotate the
// type as well
// if would be good if return values could be automatically added
// to the lifecycle don't know what attribute that would use but
// we could define that with an annotation... if it matters.. could
// be that type info is enough
// need a way to handle nested lifecycles without waiting...
// mark an activity as 'asynchronous=true' this would run
// without waiting...
// mark an activity as 'depends-on='previous task' this would
// force it to wait for other activities that are running in the background
// Activities can return LifeCycles (or maybe more generic Tasks??). If the
// activities are synchronous then the next phase doesn't run into those tasks
// are all complete.
// If they are asynchronous then activities that depend on the phase cannot
// run until all the return LifeCycles/Tasks are completed
// Another NOTE: Callbacks and task scheduling implemented around a CompletionService
// The CompletionService has and executor behind it running tasks and a thread whose job
// it is to process completed tasks and schedule the next. This would make the schronization
// requirements of the task tracking much easy to keep thread safe.
// Can the importer be implemented with this mechanism?
// how do we build scanners when we need to run them
// how do we find the scanners
// lifecycles should be defined in configuration
// how do we pass data into the scanner methods
// scanners should be dependency injected
// resource scanners will take the 'resource' in the scan method
// node scanners will take the 'node' in the scan method
// import scanner can take the foreign source.... how do I get the URL?
// persist lifecycles that are in progress?
/*
* A run of a lifecycle has a 'trigger' of some kind....
* 1. newSuspectEvent
* 2. forceRescanEvent
* 3. 'scheduled' rescan
* 4. 'import' event
* 5. 'scheduled' import
* 6. import triggers a node scan
* 7 node scan triggers a service scan
*
* We can pass a trigger object into each
*
* Need to use generics in some way so that I end up with the correct type for triggers and/or other parameters
*
* I could pass the Lifecycle object into each phase method... and I could set attributes on the lifecycle object
*
* I would need to define a set of attributes that could be set for each lifecycle
*
* I could use annotations to pass those attributes as methods
*
* Maybe 'resourceFactories' could be annotated as well and implement a simple interface
*
*
*
*/
private static final String PHASE_DATA = "phaseData";
public static final String NESTED_DATA = "nestedData";
public static final String NEST_LEVEL = "nestLevel";
public static final String MAX_DEPTH = "maxDepth";
private static LifeCycleFactory m_lifeCycleFactory;
public static class DefaultLifeCycleFactory implements LifeCycleFactory {
private Map<String, LifeCycleDefinition> m_definition = new HashMap<String, LifeCycleDefinition>();
public LifeCycle createLifeCycle(String lifeCycleName) {
LifeCycleDefinition defn = m_definition.get(lifeCycleName);
if (defn == null) {
throw new IllegalArgumentException("Unable to find a definition for lifecycle "+lifeCycleName);
}
return defn.build();
}
public void addDefinition(LifeCycleDefinition definition) {
m_definition.put(definition.getLifeCycleName(), definition);
}
}
@Before
public void setUp() {
DefaultLifeCycleFactory factory = new DefaultLifeCycleFactory();
NestedLifeCycleActivites nested = new NestedLifeCycleActivites();
nested.setLifeCycleDefinition(factory);
LifeCycleDefinition lifeCycleDefinition = new LifeCycleDefinition("sample")
.addPhases("phase1", "phase2", "phase3")
.addProviders(nested, new PhaseTestActivities());
factory.addDefinition(lifeCycleDefinition);
m_lifeCycleFactory = factory;
}
@ActivityProvider
public static class PhaseTestActivities extends ActivityProviderSupport {
private void appendPhase(LifeCycle lifecycle, final String value) {
appendToStringAttribute(lifecycle, PHASE_DATA, value);
}
// this should be called first
@Activity(phase="phase1", lifecycle="sample")
public void doPhaseOne(LifeCycle lifecycle) {
appendPhase(lifecycle, "phase1 ");
}
// this should be called last
@Activity(phase="phase3", lifecycle = "sample")
public void doPhaseThree(LifeCycle lifecycle) {
appendPhase(lifecycle, "phase3");
}
// this should be called in the middle
@Activity(phase="phase2", lifecycle = "sample")
public void doPhaseTwo(LifeCycle lifecycle) {
appendPhase(lifecycle, "phase2 ");
}
// this should not be called
@Activity(phase="phase3", lifecycle = "invalidLifecycle")
public void doPhaseInvalidLifeCycle(LifeCycle lifecycle) {
appendPhase(lifecycle, " invalidLifecycle");
}
// this should not be called
@Activity(phase="invalidPhase", lifecycle = "sample")
public void doPhaseInvalid(LifeCycle lifecycle) {
appendPhase(lifecycle, " invalidPhase");
}
}
// waitFor should throw an exception if its not been triggered
// if we don't call trigger then the getAttribute should return ""
@Test
public void testLifeCycleAttributes() {
LifeCycle lifecycle = m_lifeCycleFactory.createLifeCycle("sample");
lifecycle.setAttribute(PHASE_DATA, "phase1 phase2 phase3");
assertEquals("phase1 phase2 phase3", lifecycle.getAttribute(PHASE_DATA, String.class));
}
@Test
public void testTriggerLifeCycle() {
LifeCycle lifecycle = m_lifeCycleFactory.createLifeCycle("sample");
lifecycle.trigger();
lifecycle.waitFor();
assertEquals("phase1 phase2 phase3", lifecycle.getAttribute(PHASE_DATA, String.class));
}
@ActivityProvider
public static class NestedLifeCycleActivites extends ActivityProviderSupport {
private LifeCycleFactory m_lifeCycleFactory;
public void setLifeCycleDefinition(DefaultLifeCycleFactory factory) {
m_lifeCycleFactory = factory;
}
private void appendPhase(LifeCycle lifecycle, final String phase) {
appendToStringAttribute(lifecycle, NESTED_DATA, phase);
}
// this should be called first
@Activity(phase="phase1", lifecycle="sample")
public void doPhaseOne(LifeCycle lifecycle) {
appendPhase(lifecycle, getPrefix(lifecycle)+"phase1 ");
}
// this should be called last
@Activity(phase="phase3", lifecycle = "sample")
public void doPhaseThree(LifeCycle lifecycle) {
appendPhase(lifecycle, getPrefix(lifecycle)+"phase3 ");
}
// this should be called in the middle
@Activity(phase="phase2", lifecycle = "sample")
public LifeCycle doPhaseTwo(LifeCycle lifecycle) {
appendPhase(lifecycle, getPrefix(lifecycle)+"phase2start ");
LifeCycle nested = null;
int nestLevel = lifecycle.getAttribute(NEST_LEVEL, 0);
int maxDepth = lifecycle.getAttribute(MAX_DEPTH, 0);
if (nestLevel < maxDepth) {
nested = m_lifeCycleFactory.createLifeCycle("sample");
nested.setAttribute(MAX_DEPTH, maxDepth);
nested.setAttribute(NEST_LEVEL, nestLevel+1);
//fail("I'd like to have trigger by called by the framework rather than here...");
nested.trigger();
nested.waitFor();
appendPhase(lifecycle, nested.getAttribute(NESTED_DATA, String.class));
}
appendPhase(lifecycle, getPrefix(lifecycle)+"phase2end ");
return nested;
}
private String getPrefix(LifeCycle lifecycle) {
int nestLevel = lifecycle.getAttribute(NEST_LEVEL, 0);
return buildPrefix(nestLevel);
}
private String buildPrefix(int nestLevel) {
StringBuilder buf = new StringBuilder();
buildPrefixHelper(nestLevel, buf);
return buf.toString();
}
private void buildPrefixHelper(int nestLevel, StringBuilder buf) {
if (nestLevel == 0) {
return;
} else {
buildPrefixHelper(nestLevel-1, buf);
buf.append("level").append(nestLevel).append('.');
}
}
}
@Test
public void testNestedLifeCycle() {
LifeCycle lifecycle = m_lifeCycleFactory.createLifeCycle("sample");
lifecycle.setAttribute(MAX_DEPTH, 1);
lifecycle.trigger();
lifecycle.waitFor();
assertEquals("phase1 phase2start level1.phase1 level1.phase2start level1.phase2end level1.phase3 phase2end phase3 ", lifecycle.getAttribute(NESTED_DATA, String.class));
}
public static class ActivityProviderSupport {
protected void appendToStringAttribute(LifeCycle lifecycle, String key, String value) {
lifecycle.setAttribute(key, lifecycle.getAttribute(key, "")+value);
}
}
}
|
package com.intellij.vcs.log.ui.actions.history;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.AnActionExtensionProvider;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction;
import com.intellij.vcs.log.VcsLog;
import com.intellij.vcs.log.VcsLogDataKeys;
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector;
import com.intellij.vcs.log.ui.VcsLogInternalDataKeys;
import org.jetbrains.annotations.NotNull;
import java.awt.event.KeyEvent;
import java.util.Arrays;
public class CompareRevisionsFromFileHistoryActionProvider implements AnActionExtensionProvider {
@Override
public boolean isActive(@NotNull AnActionEvent e) {
FilePath filePath = e.getData(VcsDataKeys.FILE_PATH);
return e.getData(VcsLogInternalDataKeys.FILE_HISTORY_UI) != null && filePath != null && !filePath.isDirectory();
}
@Override
public void update(@NotNull AnActionEvent e) {
Project project = e.getProject();
FilePath filePath = e.getData(VcsDataKeys.FILE_PATH);
VcsLog log = e.getData(VcsLogDataKeys.VCS_LOG);
if (project == null || filePath == null || filePath.isDirectory() || log == null) {
e.getPresentation().setEnabledAndVisible(false);
return;
}
CompareRevisionsFromFolderHistoryActionProvider.updateActionText(e, log);
e.getPresentation().setVisible(true);
if (e.getInputEvent() instanceof KeyEvent) {
e.getPresentation().setEnabled(true);
}
else {
Change[] changes = e.getData(VcsDataKeys.SELECTED_CHANGES);
e.getPresentation().setEnabled(changes != null && changes.length == 1 && changes[0] != null);
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
VcsLogUsageTriggerCollector.triggerUsage(e, this);
Project project = e.getRequiredData(CommonDataKeys.PROJECT);
Change[] changes = e.getData(VcsDataKeys.SELECTED_CHANGES);
if (changes == null || changes.length != 1 || changes[0] == null) return;
ShowDiffAction.showDiffForChange(project, Arrays.asList(changes));
}
}
|
package com.abstratt.mdd.internal.frontend.textuml;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.uml2.uml.Action;
import org.eclipse.uml2.uml.Activity;
import org.eclipse.uml2.uml.ActivityNode;
import org.eclipse.uml2.uml.AddStructuralFeatureValueAction;
import org.eclipse.uml2.uml.AddVariableValueAction;
import org.eclipse.uml2.uml.Association;
import org.eclipse.uml2.uml.BehavioralFeature;
import org.eclipse.uml2.uml.BehavioredClassifier;
import org.eclipse.uml2.uml.CallOperationAction;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Clause;
import org.eclipse.uml2.uml.ConditionalNode;
import org.eclipse.uml2.uml.Constraint;
import org.eclipse.uml2.uml.CreateObjectAction;
import org.eclipse.uml2.uml.DataType;
import org.eclipse.uml2.uml.DestroyObjectAction;
import org.eclipse.uml2.uml.Enumeration;
import org.eclipse.uml2.uml.EnumerationLiteral;
import org.eclipse.uml2.uml.ExceptionHandler;
import org.eclipse.uml2.uml.InputPin;
import org.eclipse.uml2.uml.InstanceValue;
import org.eclipse.uml2.uml.LinkEndData;
import org.eclipse.uml2.uml.LiteralUnlimitedNatural;
import org.eclipse.uml2.uml.LoopNode;
import org.eclipse.uml2.uml.MultiplicityElement;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.ObjectFlow;
import org.eclipse.uml2.uml.ObjectNode;
import org.eclipse.uml2.uml.Operation;
import org.eclipse.uml2.uml.OutputPin;
import org.eclipse.uml2.uml.Package;
import org.eclipse.uml2.uml.Parameter;
import org.eclipse.uml2.uml.ParameterDirectionKind;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.RaiseExceptionAction;
import org.eclipse.uml2.uml.ReadExtentAction;
import org.eclipse.uml2.uml.ReadIsClassifiedObjectAction;
import org.eclipse.uml2.uml.ReadLinkAction;
import org.eclipse.uml2.uml.ReadSelfAction;
import org.eclipse.uml2.uml.ReadStructuralFeatureAction;
import org.eclipse.uml2.uml.ReadVariableAction;
import org.eclipse.uml2.uml.SendSignalAction;
import org.eclipse.uml2.uml.Signal;
import org.eclipse.uml2.uml.StateMachine;
import org.eclipse.uml2.uml.StructuredActivityNode;
import org.eclipse.uml2.uml.TemplateableElement;
import org.eclipse.uml2.uml.TestIdentityAction;
import org.eclipse.uml2.uml.Type;
import org.eclipse.uml2.uml.TypedElement;
import org.eclipse.uml2.uml.UMLPackage;
import org.eclipse.uml2.uml.UMLPackage.Literals;
import org.eclipse.uml2.uml.ValueSpecification;
import org.eclipse.uml2.uml.ValueSpecificationAction;
import org.eclipse.uml2.uml.Variable;
import org.eclipse.uml2.uml.Vertex;
import org.eclipse.uml2.uml.VisibilityKind;
import org.eclipse.uml2.uml.WriteLinkAction;
import org.eclipse.uml2.uml.WriteVariableAction;
import com.abstratt.mdd.core.IBasicRepository;
import com.abstratt.mdd.core.IRepository;
import com.abstratt.mdd.core.UnclassifiedProblem;
import com.abstratt.mdd.core.IProblem.Severity;
import com.abstratt.mdd.core.util.ActivityUtils;
import com.abstratt.mdd.core.util.BasicTypeUtils;
import com.abstratt.mdd.core.util.DataTypeUtils;
import com.abstratt.mdd.core.util.FeatureUtils;
import com.abstratt.mdd.core.util.MDDExtensionUtils;
import com.abstratt.mdd.core.util.MDDUtil;
import com.abstratt.mdd.core.util.PackageUtils;
import com.abstratt.mdd.core.util.StateMachineUtils;
import com.abstratt.mdd.core.util.TypeUtils;
import com.abstratt.mdd.frontend.core.CannotModifyADerivedAttribute;
import com.abstratt.mdd.frontend.core.FrontEnd;
import com.abstratt.mdd.frontend.core.InternalProblem;
import com.abstratt.mdd.frontend.core.MissingRequiredArgument;
import com.abstratt.mdd.frontend.core.NotAConcreteClassifier;
import com.abstratt.mdd.frontend.core.NotInAssociation;
import com.abstratt.mdd.frontend.core.QueryOperationsMustBeSideEffectFree;
import com.abstratt.mdd.frontend.core.ReadSelfFromStaticContext;
import com.abstratt.mdd.frontend.core.ReturnStatementRequired;
import com.abstratt.mdd.frontend.core.ReturnValueNotExpected;
import com.abstratt.mdd.frontend.core.ReturnValueRequired;
import com.abstratt.mdd.frontend.core.TypeMismatch;
import com.abstratt.mdd.frontend.core.UnknownAttribute;
import com.abstratt.mdd.frontend.core.UnknownOperation;
import com.abstratt.mdd.frontend.core.UnknownRole;
import com.abstratt.mdd.frontend.core.UnknownType;
import com.abstratt.mdd.frontend.core.spi.AbortedCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedScopeCompilationException;
import com.abstratt.mdd.frontend.core.spi.AbortedStatementCompilationException;
import com.abstratt.mdd.frontend.core.spi.IActivityBuilder;
import com.abstratt.mdd.frontend.core.spi.IDeferredReference;
import com.abstratt.mdd.frontend.core.spi.IReferenceTracker.Step;
import com.abstratt.mdd.frontend.textuml.core.TextUMLCore;
import com.abstratt.mdd.internal.frontend.textuml.analysis.DepthFirstAdapter;
import com.abstratt.mdd.internal.frontend.textuml.node.AArithmeticBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AAttributeIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.ABinaryExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.ABlockKernel;
import com.abstratt.mdd.internal.frontend.textuml.node.ABroadcastSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ACatchSection;
import com.abstratt.mdd.internal.frontend.textuml.node.AClassAttributeIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AClassOperationIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AClosure;
import com.abstratt.mdd.internal.frontend.textuml.node.AClosureExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.ADestroySpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AElseRestIf;
import com.abstratt.mdd.internal.frontend.textuml.node.AEmptyExpressionList;
import com.abstratt.mdd.internal.frontend.textuml.node.AEmptyReturnSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AEmptySet;
import com.abstratt.mdd.internal.frontend.textuml.node.AEqualsComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AExpressionListElement;
import com.abstratt.mdd.internal.frontend.textuml.node.AExpressionSimpleBlockResolved;
import com.abstratt.mdd.internal.frontend.textuml.node.AExtentIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AFunctionIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AGreaterOrEqualsComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AGreaterThanComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AIdentityBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AIfClause;
import com.abstratt.mdd.internal.frontend.textuml.node.AIfStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AIsClassifiedExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.ALinkIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.ALinkRole;
import com.abstratt.mdd.internal.frontend.textuml.node.ALinkSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ALiteralOperand;
import com.abstratt.mdd.internal.frontend.textuml.node.ALogicalBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.ALoopSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ALoopTest;
import com.abstratt.mdd.internal.frontend.textuml.node.ALowerOrEqualsComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.ALowerThanComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AMinusUnaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.ANamedArgument;
import com.abstratt.mdd.internal.frontend.textuml.node.ANewIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.ANotEqualsComparisonBinaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.ANotNullUnaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.ANotUnaryOperator;
import com.abstratt.mdd.internal.frontend.textuml.node.AOperationIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AParenthesisOperand;
import com.abstratt.mdd.internal.frontend.textuml.node.AQualifiedAssociationTraversal;
import com.abstratt.mdd.internal.frontend.textuml.node.ARaiseSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ARepeatLoopBody;
import com.abstratt.mdd.internal.frontend.textuml.node.ASelfIdentifierExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.ASendSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ASimpleAssociationTraversal;
import com.abstratt.mdd.internal.frontend.textuml.node.AStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ATryStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.ATupleComponentValue;
import com.abstratt.mdd.internal.frontend.textuml.node.ATupleConstructor;
import com.abstratt.mdd.internal.frontend.textuml.node.AUnaryExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.AUnlinkSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AValuedReturnSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AVarDecl;
import com.abstratt.mdd.internal.frontend.textuml.node.AVariableAccess;
import com.abstratt.mdd.internal.frontend.textuml.node.AWhileLoopBody;
import com.abstratt.mdd.internal.frontend.textuml.node.AWriteAttributeSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AWriteClassAttributeSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.AWriteVariableSpecificStatement;
import com.abstratt.mdd.internal.frontend.textuml.node.Node;
import com.abstratt.mdd.internal.frontend.textuml.node.PAssociationTraversal;
import com.abstratt.mdd.internal.frontend.textuml.node.PClauseBody;
import com.abstratt.mdd.internal.frontend.textuml.node.PExpressionList;
import com.abstratt.mdd.internal.frontend.textuml.node.PRootExpression;
import com.abstratt.mdd.internal.frontend.textuml.node.TAnd;
import com.abstratt.mdd.internal.frontend.textuml.node.TDiv;
import com.abstratt.mdd.internal.frontend.textuml.node.TMinus;
import com.abstratt.mdd.internal.frontend.textuml.node.TMult;
import com.abstratt.mdd.internal.frontend.textuml.node.TNot;
import com.abstratt.mdd.internal.frontend.textuml.node.TNotNull;
import com.abstratt.mdd.internal.frontend.textuml.node.TOr;
import com.abstratt.mdd.internal.frontend.textuml.node.TPlus;
import com.abstratt.pluginutils.LogUtils;
/**
* This tree visitor will generate the behavioral model for a given input.
*/
public class BehaviorGenerator extends AbstractGenerator {
class DeferredActivity {
private Activity activity;
private Node block;
public DeferredActivity(Activity activity, Node block) {
this.activity = activity;
this.block = block;
}
public Activity getActivity() {
return activity;
}
public Node getBlock() {
return block;
}
}
class OperationInfo {
String operationName;
// operand (target)[, operand (argument)], result (return)
Classifier[] types;
public OperationInfo(int numberOfTypes) {
types = new Classifier[numberOfTypes];
}
}
private IActivityBuilder builder;
private List<DeferredActivity> deferredActivities;
public BehaviorGenerator(SourceCompilationContext<Node> sourceContext) {
super(sourceContext);
deferredActivities = new LinkedList<DeferredActivity>();
builder = FrontEnd.newActivityBuilder(getRepository());
}
/**
* Creates an anonymous activity and returns a reference.
*/
private Activity buildClosure(BehavioredClassifier parent, StructuredActivityNode context, AClosure node) {
Activity newClosure = MDDExtensionUtils.createClosure(parent, context);
// create activity parameters
node.getSimpleSignature().apply(newSignatureProcessor(newClosure));
deferBlockCreation(node.getBlock(), newClosure);
return newClosure;
}
private ValueSpecificationAction buildValueSpecificationAction(ValueSpecification valueSpec, Node node) {
ValueSpecificationAction action =
(ValueSpecificationAction) builder.createAction(IRepository.PACKAGE
.getValueSpecificationAction());
try {
action.setValue(valueSpec);
builder.registerOutput(action.createResult(null, valueSpec.getType()));
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
return action;
}
@Override
public void caseAAttributeIdentifierExpression(AAttributeIdentifierExpression node) {
ReadStructuralFeatureAction action =
(ReadStructuralFeatureAction) builder.createAction(IRepository.PACKAGE
.getReadStructuralFeatureAction());
try {
builder.registerInput(action.createObject(null, null));
super.caseAAttributeIdentifierExpression(node);
builder.registerOutput(action.createResult(null, null));
final ObjectNode source = ActivityUtils.getSource(action.getObject());
Classifier targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), source, true);
Assert.isNotNull(targetClassifier, "Target type not determined");
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute =
FeatureUtils.findAttribute(targetClassifier,
attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addProblem(new UnknownAttribute(targetClassifier.getName(), attributeIdentifier, false), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isStatic()) {
problemBuilder.addError("Non-static attribute expected: '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setStructuralFeature(attribute);
action.getObject().setType(source.getType());
TypeUtils.copyType(attribute, action.getResult(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseABinaryExpression(ABinaryExpression node) {
if (node.getBinaryOperator() instanceof AIdentityBinaryOperator) {
handleIdentityBinaryOperator(node);
return;
}
CallOperationAction action =
(CallOperationAction) builder.createAction(IRepository.PACKAGE.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// register the argument input pins
builder.registerInput(action.createArgument(null, null));
// process the target and argument expressions - this will connect
// their output pins to the input pins we just created
super.caseABinaryExpression(node);
InputPin target = action.getTarget();
InputPin argument = action.getArguments().get(0);
Type targetType = ActivityUtils.getSource(target).getType();
target.setType(targetType);
argument.setType(ActivityUtils.getSource(argument).getType());
String operationName = parseOperationName(node.getBinaryOperator());
List<TypedElement> argumentList = Collections
.singletonList((TypedElement) argument);
Operation operation =
FeatureUtils.findOperation(getRepository(), (Classifier) targetType, operationName, argumentList, false, true);
if (operation == null) {
if (context.getRepositoryProperties().containsKey(IRepository.EXTEND_BASE_OBJECT)) {
Classifier baseObjectClass = (Classifier) findBuiltInType("Object", node);
if (baseObjectClass != null)
operation = FeatureUtils.findOperation(getRepository(), baseObjectClass, operationName, argumentList, false, true);
}
if (operation == null) {
Classifier baseBasicClass = (Classifier) findBuiltInType("Basic", node);
if (baseBasicClass != null)
operation = FeatureUtils.findOperation(getRepository(), baseBasicClass, operationName, argumentList, false, true);
if (operation == null)
missingOperation(true, node.getBinaryOperator(), (Classifier) targetType, operationName, argumentList, false);
}
}
if (operation.isStatic())
missingOperation(true, node.getBinaryOperator(), (Classifier) targetType, operationName, argumentList, false);
List<Parameter> parameters = operation.getOwnedParameters();
if (parameters.size() != 2 && parameters.get(0).getDirection() != ParameterDirectionKind.IN_LITERAL
&& parameters.get(1).getDirection() != ParameterDirectionKind.RETURN_LITERAL) {
problemBuilder.addError("Unexpected signature: '" + operationName + "' in '"
+ target.getType().getQualifiedName() + "'", node.getBinaryOperator());
throw new AbortedStatementCompilationException();
}
// register the result output pin
builder.registerOutput(action.createResult(null, operation.getType()));
action.setOperation(operation);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getBinaryOperator(), getBoundElement());
}
private void handleIdentityBinaryOperator(ABinaryExpression node) {
TestIdentityAction action =
(TestIdentityAction) builder.createAction(IRepository.PACKAGE.getTestIdentityAction());
try {
builder.registerInput(action.createFirst(null, null));
builder.registerInput(action.createSecond(null, null));
node.getExpression().apply(this);
node.getOperand().apply(this);
Classifier expressionType = BasicTypeUtils.findBuiltInType("Boolean");
builder.registerOutput(action.createResult(null, expressionType));
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseAIsClassifiedExpression(AIsClassifiedExpression node) {
ReadIsClassifiedObjectAction action =
(ReadIsClassifiedObjectAction) builder.createAction(IRepository.PACKAGE.getReadIsClassifiedObjectAction());
try {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getQualifiedIdentifier());
Classifier classifier =
(Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier + "'", node.getQualifiedIdentifier());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createObject(null, null));
node.getExpression().apply(this);
Classifier expressionType = BasicTypeUtils.findBuiltInType("Boolean");
builder.registerOutput(action.createResult(null, expressionType));
action.setClassifier(classifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
/**
* Blocks can be simple (curly brackets) or wordy (begin...end). Regardless
* the delimiters, the kernel of the block is processed here.
*/
@Override
public void caseABlockKernel(ABlockKernel node) {
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
fillDebugInfo(builder.getCurrentBlock(), node);
BehaviorGenerator.super.caseABlockKernel(node);
// isolation determines whether the block should be treated as a transaction
Activity currentActivity = builder.getCurrentActivity();
if (!MDDExtensionUtils.isClosure(currentActivity))
if (ActivityUtils.shouldIsolate(builder.getCurrentBlock())) {
builder.getCurrentBlock().setMustIsolate(true);
// if blocks themselves are isolated, the main body does not need isolation
ActivityUtils.getBodyNode(currentActivity).setMustIsolate(false);
}
} catch (AbortedScopeCompilationException e) {
// aborted activity block compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} finally {
builder.closeBlock();
}
}
@Override
public void caseAExpressionSimpleBlockResolved(AExpressionSimpleBlockResolved node) {
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
buildReturnStatement(node.getSimpleExpressionBlock());
} catch (AbortedScopeCompilationException e) {
// aborted activity block compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} finally {
builder.closeBlock();
}
}
@Override
public void caseAClassAttributeIdentifierExpression(AClassAttributeIdentifierExpression node) {
String typeIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier targetClassifier =
(Classifier) getRepository().findNamedElement(typeIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentNamespace(null));
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + typeIdentifier + "'", node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute =
FeatureUtils.findAttribute(targetClassifier,
attributeIdentifier, false, true);
if (attribute != null) {
buildReadStaticStructuralFeature(targetClassifier, attribute, node);
return;
}
if (targetClassifier instanceof Enumeration) {
EnumerationLiteral enumerationValue = ((Enumeration) targetClassifier).getOwnedLiteral(attributeIdentifier);
if (enumerationValue != null) {
InstanceValue valueSpec = (InstanceValue) namespaceTracker.currentPackage().createPackagedElement(null, IRepository.PACKAGE.getInstanceValue());
valueSpec.setInstance(enumerationValue);
valueSpec.setType(targetClassifier);
buildValueSpecificationAction(valueSpec, node);
return;
}
}
if (targetClassifier instanceof StateMachine) {
Vertex state = StateMachineUtils.getVertex((StateMachine) targetClassifier, attributeIdentifier);
if (state != null) {
ValueSpecification stateReference = MDDExtensionUtils.buildVertexLiteral(namespaceTracker.currentPackage(), state);
buildValueSpecificationAction(stateReference, node);
return;
}
}
problemBuilder.addProblem(new UnknownAttribute(targetClassifier.getName(), attributeIdentifier, true), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
private void buildReadStaticStructuralFeature(Classifier targetClassifier, Property attribute, AClassAttributeIdentifierExpression node) {
ReadStructuralFeatureAction action =
(ReadStructuralFeatureAction) builder.createAction(IRepository.PACKAGE
.getReadStructuralFeatureAction());
try {
// features is undefined. (...)"
// // our intepretation is that they are allowed and the input is a
// null value spec
// builder.registerInput(action.createObject(null, null));
// LiteralNull literalNull = (LiteralNull)
// currentPackage().createPackagedElement(null,
// IRepository.PACKAGE.getLiteralNull());
// buildValueSpecificationAction(literalNull, node);
builder.registerOutput(action.createResult(null, targetClassifier));
if (!attribute.isStatic()) {
problemBuilder.addError("Static attribute expected: '" + attribute.getName() + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setStructuralFeature(attribute);
// action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getResult(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAClassOperationIdentifierExpression(final AClassOperationIdentifierExpression node) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Class targetClassifier =
(Class) getRepository().findNamedElement(qualifiedIdentifier, IRepository.PACKAGE.getClass_(),
namespaceTracker.currentPackage());
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + qualifiedIdentifier + "'", node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
CallOperationAction action =
(CallOperationAction) builder.createAction(IRepository.PACKAGE.getCallOperationAction());
try {
int argumentCount = countElements(node.getExpressionList());
for (int i = 0; i < argumentCount; i++)
builder.registerInput(action.createArgument(null, null));
super.caseAClassOperationIdentifierExpression(node);
// collect sources so we can match the right operation (in
// case of overloading)
List<ObjectNode> sources = new ArrayList<ObjectNode>();
for (InputPin argument : action.getArguments())
sources.add(ActivityUtils.getSource(argument));
String operationName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Operation operation = findOperation(node.getIdentifier(), targetClassifier, operationName, new ArrayList<TypedElement>(sources), true, true);
if (!operation.isQuery() && !PackageUtils.isModelLibrary(operation.getNearestPackage()))
ensureNotQuery(node);
action.setOperation(operation);
List<Parameter> inputParameters = FeatureUtils.getInputParameters(operation.getOwnedParameters());
Map<Type, Type> wildcardSubstitutions = FeatureUtils.buildWildcardSubstitutions(new HashMap<Type, Type>(), inputParameters, sources);
int argumentPos = 0;
for (Parameter current : operation.getOwnedParameters()) {
OutputPin result;
InputPin argument;
switch (current.getDirection().getValue()) {
case ParameterDirectionKind.IN:
if (argumentPos == argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
throw new AbortedStatementCompilationException();
}
argument = action.getArguments().get(argumentPos++);
argument.setName(current.getName());
TypeUtils.copyType(current, argument, targetClassifier);
break;
case ParameterDirectionKind.RETURN:
// there should be only one of these
Assert.isTrue(action.getResults().isEmpty());
result = builder.registerOutput(action.createResult(null, null));
TypeUtils.copyType(current, result, targetClassifier);
resolveWildcardTypes(wildcardSubstitutions, current, result);
break;
case ParameterDirectionKind.OUT:
case ParameterDirectionKind.INOUT:
Assert.isTrue(false);
}
}
if (argumentPos != argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
return;
}
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
/**
* In the context of an operation call, copies types from source to target for every target that still has a wildcard type.
*
* In the case of a target that is a signature,
* @param wildcardSubstitutions
* @param source
* @param target
*/
private void resolveWildcardTypes(Map<Type, Type> wildcardSubstitutions, TypedElement source, TypedElement target) {
if (wildcardSubstitutions.isEmpty())
return;
if (MDDExtensionUtils.isWildcardType(target.getType())) {
Type subbedType = wildcardSubstitutions.get(source.getType());
if (subbedType != null)
target.setType(subbedType);
} else if (MDDExtensionUtils.isSignature(target.getType())) {
List<Parameter> originalSignatureParameters = MDDExtensionUtils.getSignatureParameters(target.getType());
boolean signatureUsesWildcardTypes = false;
for (Parameter parameter : originalSignatureParameters) {
if (MDDExtensionUtils.isWildcardType(parameter.getType())) {
signatureUsesWildcardTypes = true;
break;
}
}
if (signatureUsesWildcardTypes) {
Activity closure = (Activity) ActivityUtils.resolveBehaviorReference((Action) ((OutputPin) source).getOwner());
Type resolvedSignature = MDDExtensionUtils.createSignature(namespaceTracker.currentNamespace(null));
for (Parameter closureParameter : closure.getOwnedParameters()) {
Parameter resolvedParameter = MDDExtensionUtils.createSignatureParameter(resolvedSignature, closureParameter.getName(), closureParameter.getType());
resolvedParameter.setDirection(closureParameter.getDirection());
resolvedParameter.setUpper(closureParameter.getUpper());
}
target.setType(resolvedSignature);
}
}
}
@Override
public void caseAClosureExpression(AClosureExpression node) {
BehavioredClassifier parent = builder.getCurrentActivity();
StructuredActivityNode closureContext = builder.getCurrentBlock();
Activity closure = buildClosure(parent , closureContext, (AClosure) node.getClosure());
buildValueSpecificationAction(ActivityUtils.buildBehaviorReference(namespaceTracker.currentPackage(), closure, null), node);
}
@Override
public void caseADestroySpecificStatement(ADestroySpecificStatement node) {
final DestroyObjectAction action =
(DestroyObjectAction) builder.createAction(IRepository.PACKAGE.getDestroyObjectAction());
final InputPin object;
try {
object = action.createTarget(null, null);
builder.registerInput(object);
super.caseADestroySpecificStatement(node);
final Type expressionType = ActivityUtils.getSource(object).getType();
object.setType(expressionType);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseAElseRestIf(AElseRestIf node) {
Clause newClause = createClause();
// all this gymnastic is to create the always-true test action
ValueSpecificationAction action =
(ValueSpecificationAction) builder.createAction(IRepository.PACKAGE
.getValueSpecificationAction());
newClause.getTests().add(action);
try {
action.setValue(MDDUtil.createLiteralBoolean(namespaceTracker.currentPackage(), true));
builder.registerOutput(action.createResult(null, action.getValue().getType()));
newClause.setDecider(action.getResult());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
createClauseBody(newClause, node.getClauseBody());
checkIncomings(action, node.getElse(), getBoundElement());
}
@Override
public void caseAExtentIdentifierExpression(AExtentIdentifierExpression node) {
String classifierName = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
final Classifier classifier =
(Classifier) getRepository().findNamedElement(classifierName,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder
.addError("Unknown classifier '" + classifierName + "'", node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
ReadExtentAction action = (ReadExtentAction) builder.createAction(IRepository.PACKAGE.getReadExtentAction());
try {
action.setClassifier(classifier);
final OutputPin result = action.createResult(null, classifier);
result.setUpperValue(MDDUtil.createLiteralUnlimitedNatural(namespaceTracker.currentPackage(), LiteralUnlimitedNatural.UNLIMITED));
result.setIsUnique(true);
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
}
//TODO function call temporarily disabled
// /**
// * Processes a function invocation expression. We restrict function
// * invocations to be variable based.
// */
// @Override
// public void caseAFunctionIdentifierExpression(AFunctionIdentifierExpression node) {
// DynamicCallBehaviorAction action =
// (DynamicCallBehaviorAction) builder.createAction(MetaPackage.eINSTANCE
// .getDynamicCallBehaviorAction());
// try {
// // register the behavior input pin
// builder.registerInput(action.createBehavior(null, null));
// // register the argument input pins
// int argumentCount = countElements(node.getExpressionList());
// for (int i = 0; i < argumentCount; i++)
// builder.registerInput(action.createArgument(null, null));
// // process the variable and argument expressions - this will connect
// // their output pins to the input pins we just created
// super.caseAFunctionIdentifierExpression(node);
// // match the list of arguments with the behavior parameters
// final Type functionType = ActivityUtils.getSource(action.getBehavior()).getType();
// if (!(functionType instanceof Signature)) {
// problemBuilder.addProblem( new TypeMismatch("function type", functionType.getName()), node
// .getVariableAccess());
// throw new AbortedStatementCompilationException();
// Signature signature = (Signature) functionType;
// Assert.isNotNull(signature, "Function not found");
// // collect argument types so we can match the right operation (in
// // case of overloading)
// List<ObjectNode> argumentSources = new ArrayList<ObjectNode>();
// for (InputPin argument : action.getArguments())
// argumentSources.add(ActivityUtils.getSource(argument));
// final List<Parameter> inputParameters =
// FeatureUtils.filterParameters(signature.getOwnedParameters(),
// ParameterDirectionKind.IN_LITERAL);
// if (!TypeUtils.isCompatible(getRepository(), argumentSources, inputParameters, null)) {
// problemBuilder.addProblem( new UnresolvedSymbol("Unknown function"), node.getVariableAccess());
// throw new AbortedStatementCompilationException();
// int argumentPos = 0;
// for (Parameter current : signature.getOwnedParameters()) {
// OutputPin result;
// InputPin argument;
// switch (current.getDirection().getValue()) {
// case ParameterDirectionKind.IN:
// if (argumentPos == argumentCount) {
// problemBuilder.addError("Wrong number of arguments", node.getLParen());
// throw new AbortedStatementCompilationException();
// argument = action.getArguments().get(argumentPos++);
// argument.setName(current.getName());
// TypeUtils.copyType(current, argument);
// break;
// case ParameterDirectionKind.RETURN:
// // there should be only one of these
// result = builder.registerOutput(action.createResult(null, null));
// TypeUtils.copyType(current, result);
// break;
// case ParameterDirectionKind.OUT:
// case ParameterDirectionKind.INOUT:
// Assert.isTrue(false);
// if (argumentPos != argumentCount) {
// problemBuilder.addError("Wrong number of arguments", node.getLParen());
// return;
// // action.getBehavior().setType(targetClassifier);
// fillDebugInfo(action, node);
// } finally {
// builder.closeAction();
// checkIncomings(action, node.getVariableAccess());
@Override
public void caseAIfClause(AIfClause node) {
Clause newClause = createClause();
createClauseTest(newClause, node.getTest());
createClauseBody(newClause, node.getClauseBody());
}
@Override
public void caseAIfStatement(AIfStatement node) {
builder.createBlock(IRepository.PACKAGE.getConditionalNode());
try {
super.caseAIfStatement(node);
} catch (AbortedScopeCompilationException e) {
// aborted activity block compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} finally {
builder.closeBlock();
}
}
@Override
public void caseALinkIdentifierExpression(ALinkIdentifierExpression node) {
ReadLinkAction action = (ReadLinkAction) builder.createAction(IRepository.PACKAGE.getReadLinkAction());
try {
InputPin linkEndValue = builder.registerInput(action.createInputValue(null, null));
node.getIdentifierExpression().apply(this);
ObjectNode source = ActivityUtils.getSource(linkEndValue);
Classifier targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), source, true);
Property openEnd = parseRole(targetClassifier, node.getAssociationTraversal());
if (!openEnd.isNavigable()) {
problemBuilder.addProblem( new UnclassifiedProblem("Role '" + openEnd.getQualifiedName() + "' is not navigable"), node
.getIdentifierExpression());
throw new AbortedStatementCompilationException();
}
Association association = openEnd.getAssociation();
linkEndValue.setType(targetClassifier);
int openEndIndex = association.getMemberEnds().indexOf(openEnd);
Property fedEnd = association.getMemberEnds().get(1 - openEndIndex);
LinkEndData endData = action.createEndData();
endData.setEnd(fedEnd);
endData.setValue(linkEndValue);
builder.registerOutput(action.createResult(null, openEnd.getType()));
TypeUtils.copyType(openEnd, action.getResult());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getAssociationTraversal(), getBoundElement());
}
private Property parseRole(Classifier sourceType, PAssociationTraversal node) {
return (node instanceof ASimpleAssociationTraversal) ? parseSimpleTraversal(sourceType, (ASimpleAssociationTraversal) node) : parseQualifiedTraversal(sourceType, (AQualifiedAssociationTraversal) node);
}
private Property parseSimpleTraversal(Classifier sourceType, ASimpleAssociationTraversal node) {
final String openEndName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property openEnd = sourceType.getAttribute(openEndName, null);
Association association;
if (openEnd == null) {
EList<Association> associations = sourceType.getAssociations();
for (Association current : associations)
if ((openEnd = current.getMemberEnd(openEndName, null)) != null)
break;
if (openEnd == null) {
problemBuilder.addProblem( new UnknownRole(sourceType.getQualifiedName() + NamedElement.SEPARATOR + openEndName), node
.getIdentifier());
throw new AbortedStatementCompilationException();
}
}
association = openEnd.getAssociation();
if (association == null) {
problemBuilder.addError(openEndName + " is not an association member end", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
return openEnd;
}
private Property parseQualifiedTraversal(Classifier sourceType, AQualifiedAssociationTraversal node) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
final Association association =
(Association) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getAssociation(), namespaceTracker.currentPackage());
if (association == null) {
problemBuilder.addError("Unknown association '" + qualifiedIdentifier + "'", node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
boolean associated =
sourceType.getRelationships(IRepository.PACKAGE.getAssociation()).contains(association);
if (!associated) {
problemBuilder.addProblem(new NotInAssociation(sourceType.getQualifiedName(), association.getQualifiedName()), node.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
final String openEndName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
// XXX implementation limitation: only binary associations are
// supported
Property openEnd = association.getMemberEnd(openEndName, null);
if (openEnd == null) {
problemBuilder.addProblem( new UnknownRole(association.getQualifiedName(), openEndName), node
.getIdentifier());
throw new AbortedStatementCompilationException();
}
return openEnd;
}
@Override
public void caseALinkSpecificStatement(ALinkSpecificStatement node) {
buildWriteLinkAction(node, node.getMinimalTypeIdentifier(), IRepository.PACKAGE.getCreateLinkAction());
}
private void buildWriteLinkAction(Node linkStatementNode, Node associationIdentifierNode, EClass linkActionClass) {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(associationIdentifierNode);
final Association association =
(Association) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getAssociation(), namespaceTracker.currentPackage());
if (association == null) {
problemBuilder.addError("Unknown association '" + qualifiedIdentifier + "'", associationIdentifierNode);
throw new AbortedStatementCompilationException();
}
final WriteLinkAction action =
(WriteLinkAction) builder.createAction(linkActionClass);
try {
linkStatementNode.apply(new DepthFirstAdapter() {
@Override
public void caseALinkRole(ALinkRole node) {
String roleName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property end = association.getMemberEnd(roleName, null);
if (end == null) {
problemBuilder.addProblem( new UnknownRole(association.getQualifiedName(), roleName), node
.getIdentifier());
throw new AbortedStatementCompilationException();
}
LinkEndData endData = action.createEndData();
endData.setEnd(end);
InputPin input = action.createInputValue(null, end.getType());
endData.setValue(input);
builder.registerInput(input);
node.getRootExpression().apply(BehaviorGenerator.this);
}
});
// TODO need to validate that all ends declared have input values,
// no repetitions, etc
fillDebugInfo(action, linkStatementNode);
} finally {
builder.closeAction();
}
checkIncomings(action, linkStatementNode, getBoundElement());
}
@Override
public void caseAFunctionIdentifierExpression(AFunctionIdentifierExpression node) {
String functionName = sourceMiner.getIdentifier(node.getVariableAccess());
problemBuilder.addProblem(new UnclassifiedProblem("Function call not supported yet: " + functionName ), node
.getVariableAccess());
throw new AbortedStatementCompilationException();
}
@Override
public void caseALiteralOperand(ALiteralOperand node) {
ValueSpecification value = LiteralValueParser.parseLiteralValue(node.getLiteral(), namespaceTracker.currentPackage(), problemBuilder);
buildValueSpecificationAction(value, node);
}
@Override
public void caseAEmptySet(AEmptySet node) {
final ValueSpecificationAction action =
(ValueSpecificationAction) builder.createAction(IRepository.PACKAGE.getValueSpecificationAction());
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier classifier =
(Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addProblem(new UnknownType(qualifiedIdentifier), node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
try {
action.setValue(MDDUtil.createLiteralNull(namespaceTracker.currentPackage()));
OutputPin result = action.createResult(null, classifier);
result.setUpperValue(MDDUtil.createLiteralUnlimitedNatural(namespaceTracker.currentPackage(), LiteralUnlimitedNatural.UNLIMITED));
builder.registerOutput(result);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
}
@Override
public void caseALoopSpecificStatement(ALoopSpecificStatement node) {
LoopNode loop = (LoopNode) builder.createBlock(IRepository.PACKAGE.getLoopNode());
loop.setIsTestedFirst(true);
try {
super.caseALoopSpecificStatement(node);
} catch (AbortedScopeCompilationException e) {
// aborted activity block compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} finally {
builder.closeBlock();
}
}
@Override
public void caseALoopTest(ALoopTest node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
super.caseALoopTest(node);
currentLoop.getTests().add(builder.getCurrentBlock());
final OutputPin decider = ActivityUtils.getActionOutputs(builder.getLastRootAction()).get(0);
currentLoop.setDecider(decider);
} finally {
builder.closeBlock();
}
}
@Override
public void caseANewIdentifierExpression(final ANewIdentifierExpression node) {
ensureNotQuery(node);
final CreateObjectAction action =
(CreateObjectAction) builder.createAction(IRepository.PACKAGE.getCreateObjectAction());
try {
super.caseANewIdentifierExpression(node);
final OutputPin output = builder.registerOutput(action.createResult(null, null));
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier classifier =
(Classifier) getRepository().findNamedElement(qualifiedIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (classifier == null) {
problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier + "'", node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
if (classifier.isAbstract()) {
problemBuilder.addProblem( new NotAConcreteClassifier(qualifiedIdentifier), node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
output.setType(classifier);
action.setClassifier(classifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getNew(), getBoundElement());
}
private void ensureNotQuery(Node node) {
boolean isReadOnly = builder.getCurrentActivity().isReadOnly();
QueryOperationsMustBeSideEffectFree.ensure(!isReadOnly, problemBuilder, node);
}
@Override
public void caseASendSpecificStatement(ASendSpecificStatement node) {
ensureNotQuery(node);
final SendSignalAction action =
(SendSignalAction) builder.createAction(IRepository.PACKAGE
.getSendSignalAction());
try {
final String signalIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getSignal());
final Signal signal = this.context.getRepository().findNamedElement(signalIdentifier, UMLPackage.Literals.SIGNAL, namespaceTracker.currentNamespace(null));
if (signal == null) {
problemBuilder.addError("Unknown signal '" + signalIdentifier + "'", node.getSignal());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createTarget(null, null));
node.getTarget().apply(this);
if (node.getNamedArgumentList() != null)
node.getNamedArgumentList().apply(new DepthFirstAdapter() {
@Override
public void caseANamedArgument(ANamedArgument node) {
String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute = FeatureUtils.findAttribute(signal, attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addProblem(new UnknownAttribute(signal.getName(), attributeIdentifier, false), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
builder.registerInput(action.createArgument(attribute.getName(), attribute.getType()));
node.getExpression().apply(BehaviorGenerator.this);
}
});
for (Property signalAttribute : signal.getAllAttributes())
if (signalAttribute.getLower() == 1 && signalAttribute.getDefaultValue() == null && action.getArgument(signalAttribute.getName(), signalAttribute.getType()) == null) {
problemBuilder.addProblem(new MissingRequiredArgument(signalAttribute.getName()), node);
throw new AbortedStatementCompilationException();
}
action.setSignal(signal);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSignal(), getBoundElement());
}
@Override
public void caseABroadcastSpecificStatement(ABroadcastSpecificStatement node) {
SendSignalAction action =
(SendSignalAction) builder.createAction(IRepository.PACKAGE
.getSendSignalAction());
try {
super.caseABroadcastSpecificStatement(node);
final String signalIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getSignal());
Signal signal = this.context.getRepository().findNamedElement(signalIdentifier, UMLPackage.Literals.SIGNAL, namespaceTracker.currentNamespace(null));
if (signal == null) {
problemBuilder.addError("Unknown signal '" + signalIdentifier + "'", node.getSignal());
throw new AbortedStatementCompilationException();
}
action.setSignal(signal);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSignal(), getBoundElement());
}
//FIXME a lot of duplication between this and caseAClassOperationIdentifierExpression
@Override
public void caseAOperationIdentifierExpression(AOperationIdentifierExpression node) {
Classifier targetClassifier = null;
String operationName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
CallOperationAction action =
(CallOperationAction) builder.createAction(IRepository.PACKAGE.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, null));
// register the argument input pins
int argumentCount = countElements(node.getExpressionList());
for (int i = 0; i < argumentCount; i++)
builder.registerInput(action.createArgument(null, null));
// process the target and argument expressions - this will connect
// their output pins to the input pins we just created
super.caseAOperationIdentifierExpression(node);
final ObjectNode targetSource = ActivityUtils.getSource(action.getTarget());
targetClassifier = (Classifier) TypeUtils.getTargetType(getRepository(), targetSource, true);
if (targetClassifier == null) {
problemBuilder.addProblem(new UnclassifiedProblem(Severity.ERROR, "Could not determine the type of the target"), node.getExpressionList());
throw new AbortedStatementCompilationException();
}
// collect sources so we can match the right operation (in
// case of overloading)
List<TypedElement> sources = new ArrayList<TypedElement>();
for (InputPin argument : action.getArguments()) {
ObjectNode argumentSource = ActivityUtils.getSource(argument);
if (argumentSource == null) {
problemBuilder.addProblem(new UnclassifiedProblem(Severity.ERROR, "One of the arguments does not produce a result value"), node.getExpressionList());
throw new AbortedStatementCompilationException();
}
sources.add(argumentSource);
}
Operation operation = findOperation(node.getIdentifier(), targetClassifier, operationName, sources, false, true);
if (!operation.isQuery() && !PackageUtils.isModelLibrary(operation.getNearestPackage()))
ensureNotQuery(node);
action.setOperation(operation);
List<Parameter> inputParameters = FeatureUtils.getInputParameters(operation.getOwnedParameters());
Map<Type, Type> wildcardSubstitutions = FeatureUtils.buildWildcardSubstitutions(new HashMap<Type, Type>(), inputParameters, sources);
int argumentPos = 0;
for (Parameter current : operation.getOwnedParameters()) {
OutputPin result;
InputPin argument;
switch (current.getDirection().getValue()) {
case ParameterDirectionKind.IN:
if (argumentPos == argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
throw new AbortedStatementCompilationException();
}
argument = action.getArguments().get(argumentPos++);
argument.setName(current.getName());
TypeUtils.copyType(current, argument, targetClassifier);
break;
case ParameterDirectionKind.RETURN:
// there should be only one of these
Assert.isTrue(action.getResults().isEmpty());
result = builder.registerOutput(action.createResult(null, null));
TypeUtils.copyType(current, result, targetClassifier);
resolveWildcardTypes(wildcardSubstitutions, current, result);
break;
case ParameterDirectionKind.OUT:
case ParameterDirectionKind.INOUT:
Assert.isTrue(false);
}
}
if (argumentPos != argumentCount) {
problemBuilder.addError("Wrong number of arguments", node.getLParen());
return;
}
// set the type of the target input pin using copy type so we
// understand collections
TypeUtils.copyType(targetSource, action.getTarget(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), targetClassifier);
}
@Override
public void caseARaiseSpecificStatement(ARaiseSpecificStatement node) {
final RaiseExceptionAction action =
(RaiseExceptionAction) builder.createAction(IRepository.PACKAGE.getRaiseExceptionAction());
final InputPin exception;
try {
exception = action.createException(null, null);
builder.registerInput(exception);
super.caseARaiseSpecificStatement(node);
final Type exceptionType = ActivityUtils.getSource(exception).getType();
exception.setType(exceptionType);
if (ActivityUtils.findHandler(action, (Classifier) exceptionType, true ) == null)
if (!builder.getCurrentActivity().getSpecification().getRaisedExceptions().contains(exceptionType))
problemBuilder.addWarning("Exception '" + exceptionType.getQualifiedName()
+ "' is not declared by operation", node.getRootExpression());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getRaise(), getBoundElement());
// a raise exception action is a final action
ActivityUtils.makeFinal(builder.getCurrentBlock(), action);
}
@Override
public void caseARepeatLoopBody(ARepeatLoopBody node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
currentLoop.setIsTestedFirst(false);
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
super.caseARepeatLoopBody(node);
currentLoop.getBodyParts().add(builder.getCurrentBlock());
} finally {
builder.closeBlock();
}
}
@Override
public void caseATryStatement(ATryStatement node) {
if (node.getCatchSection() == null && node.getFinallySection() == null) {
problemBuilder.addError("One or both catch and finally sections are required", node.getTry());
throw new AbortedStatementCompilationException();
}
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
if (node.getCatchSection() != null)
node.getCatchSection().apply(this);
node.getProtectedBlock().apply(this);
} finally {
builder.closeBlock();
}
}
@Override
public void caseACatchSection(ACatchSection node) {
StructuredActivityNode protectedBlock = builder.getCurrentBlock();
StructuredActivityNode handlerBlock = builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
// declare exception variable
node.getVarDecl().apply(this);
node.getHandlerBlock().apply(this);
Variable exceptionVar = handlerBlock.getVariables().get(0);
ExceptionHandler exceptionHandler = protectedBlock.createHandler();
exceptionHandler.getExceptionTypes().add((Classifier) exceptionVar.getType());
InputPin exceptionInputPin = (InputPin) handlerBlock.createNode(exceptionVar.getName(), UMLPackage.Literals.INPUT_PIN);
exceptionInputPin.setType(exceptionVar.getType());
exceptionHandler.setExceptionInput(exceptionInputPin);
exceptionHandler.setHandlerBody(handlerBlock);
} finally {
builder.closeBlock();
}
}
@Override
public void caseASelfIdentifierExpression(ASelfIdentifierExpression node) {
ReadSelfAction action = (ReadSelfAction) builder.createAction(IRepository.PACKAGE.getReadSelfAction());
try {
super.caseASelfIdentifierExpression(node);
Activity currentActivity = builder.getCurrentActivity();
while (MDDExtensionUtils.isClosure(currentActivity)) {
//TODO refactor to use ActivityUtils
ActivityNode rootNode = MDDExtensionUtils.getClosureContext(currentActivity);
currentActivity = ActivityUtils.getActionActivity(rootNode);
}
final BehavioralFeature operation = currentActivity.getSpecification();
if (operation != null && operation.isStatic()) {
problemBuilder.addProblem( new ReadSelfFromStaticContext(), node);
throw new AbortedStatementCompilationException();
}
Classifier currentClassifier = ActivityUtils.getContext(currentActivity);
if (currentClassifier == null) {
problemBuilder.addProblem(new InternalProblem("Could not determine context"), node);
throw new AbortedStatementCompilationException();
}
builder.registerOutput(action.createResult(null, currentClassifier));
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getSelf(), getBoundElement());
}
//TODO temporarily disabled during refactor to remove metamodel extensions
// @Override
// public void caseASetLiteralIdentifierExpression(ASetLiteralIdentifierExpression node) {
// String qualifiedIdentifier = Util.parseQualifiedIdentifier(node.getMinimalTypeIdentifier());
// final Classifier classifier =
// (Classifier) getRepository().findNamedElement(qualifiedIdentifier,
// IRepository.PACKAGE.getClassifier(), currentPackage());
// if (classifier == null) {
// problemBuilder.addError("Unknown classifier '" + qualifiedIdentifier + "'", node
// .getMinimalTypeIdentifier());
// throw new AbortedStatementCompilationException();
// final CollectionLiteral valueSpec =
// (CollectionLiteral) currentPackage().createPackagedElement(null,
// MetaPackage.eINSTANCE.getCollectionLiteral());
// valueSpec.setType(classifier);
// node.apply(new DepthFirstAdapter() {
// @Override
// public void caseASetValue(ASetValue node) {
// // TODO create a value specification and add it to
// ValueSpecification value =
// MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(), valueSpec.getValues()
// .size());
// valueSpec.getValues().add(value);
// super.caseASetValue(node);
// ValueSpecificationAction valueSpecAction = buildValueSpecificationAction(valueSpec, node);
// final OutputPin outputPin = valueSpecAction.getOutputs().get(0);
// outputPin.setLowerValue(MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(), 0));
// outputPin.setUpperValue(MDDUtil.createUnlimitedNatural(classifier.getNearestPackage(), null));
@Override
public void caseAStatement(AStatement node) {
try {
super.caseAStatement(node);
} catch (AbortedStatementCompilationException e) {
// aborted statement compilation...
if (builder.isDebug())
LogUtils.logWarning(TextUMLCore.PLUGIN_ID, null, e);
} catch (AbortedCompilationException e) {
// we don't handle those here
throw e;
} catch (AssertionError e) {
LogUtils.logError(TextUMLCore.PLUGIN_ID, "Assertion failed", e);
problemBuilder.addError("Exception: " + e.toString(), node);
} catch (RuntimeException e) {
LogUtils.logError(TextUMLCore.PLUGIN_ID, "Unexpected exception", e);
problemBuilder.addError("Exception: " + e.toString(), node);
}
}
@Override
public void caseAParenthesisOperand(AParenthesisOperand node) {
if (node.getCast() == null) {
// no casting, just process inner expression
node.getExpression().apply(this);
return;
}
StructuredActivityNode action = (StructuredActivityNode) builder.createAction(Literals.STRUCTURED_ACTIVITY_NODE);
try {
String qualifiedIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getCast());
// register the target input pin (type is null)
InputPin sourcePin = (InputPin) action.createNode(null, Literals.INPUT_PIN);
builder.registerInput(sourcePin);
// process the target expression - this will connect its output pin
// to the input pin we just created
node.getExpression().apply(this);
// copy whatever multiplicity coming into the source to the source
TypeUtils.copyMultiplicity((MultiplicityElement) sourcePin.getIncomings().get(0).getSource(), sourcePin);
// register the result output pin
OutputPin destinationPin = (OutputPin) action.createNode(null, Literals.OUTPUT_PIN);
new TypeSetter(sourceContext, namespaceTracker.currentNamespace(null), destinationPin).process(node.getCast());
builder.registerOutput(destinationPin);
// copy whatever multiplicity coming into the source to the destination
TypeUtils.copyMultiplicity(sourcePin, destinationPin);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getCast(), getBoundElement());
}
@Override
public void caseAUnaryExpression(AUnaryExpression node) {
OperationInfo operationInfo = parseOperationInfo(node.getUnaryOperator(), 2);
Operation operation = findOperation(node.getUnaryOperator(), operationInfo.types[0], operationInfo.operationName, Collections
.<TypedElement> emptyList(), false, true);
List<Parameter> parameters = operation.getOwnedParameters();
if (parameters.size() != 1 && parameters.get(0).getDirection() != ParameterDirectionKind.RETURN_LITERAL) {
problemBuilder.addError("Unexpected signature: '" + operationInfo.operationName + "' in '"
+ operationInfo.types[0].getName() + "'", node.getUnaryOperator());
throw new AbortedStatementCompilationException();
}
CallOperationAction action =
(CallOperationAction) builder.createAction(IRepository.PACKAGE.getCallOperationAction());
try {
// register the target input pin
builder.registerInput(action.createTarget(null, operationInfo.types[0]));
// process the target expression - this will connect its output pin
// to the input pin we just created
super.caseAUnaryExpression(node);
// register the result output pin
builder.registerOutput(action.createResult(null, operationInfo.types[1]));
action.setOperation(operation);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getUnaryOperator(), getBoundElement());
}
@Override
public void caseAUnlinkSpecificStatement(AUnlinkSpecificStatement node) {
buildWriteLinkAction(node, node.getMinimalTypeIdentifier(), IRepository.PACKAGE.getDestroyLinkAction());
}
@Override
public void caseAEmptyReturnSpecificStatement(
AEmptyReturnSpecificStatement node) {
Variable variable = builder.getReturnValueVariable();
if (variable != null) {
problemBuilder.addProblem(new ReturnValueRequired(), node.getReturn());
throw new AbortedScopeCompilationException();
}
Action previousStatement = builder.getLastRootAction();
if (previousStatement != null)
ActivityUtils.makeFinal(builder.getCurrentBlock(), previousStatement);
}
@Override
public void caseAValuedReturnSpecificStatement(AValuedReturnSpecificStatement node) {
buildReturnStatement(node.getRootExpression());
}
protected void buildReturnStatement(Node node) {
TemplateableElement bound =
(Class) MDDUtil.getNearest(builder.getCurrentActivity(), IRepository.PACKAGE.getClass_());
AddVariableValueAction action =
(AddVariableValueAction) builder.createAction(IRepository.PACKAGE.getAddVariableValueAction());
try {
Variable variable = builder.getReturnValueVariable();
if (variable == null) {
problemBuilder.addProblem(new ReturnValueNotExpected(), node);
throw new AbortedScopeCompilationException();
}
final InputPin value = builder.registerInput(action.createValue(null, null));
node.apply(this);
action.setVariable(variable);
TypeUtils.copyType(variable, value, bound);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node, getBoundElement());
ActivityUtils.makeFinal(builder.getCurrentBlock(), action);
}
@Override
public void caseAVarDecl(final AVarDecl node) {
super.caseAVarDecl(node);
String varIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
final Variable var = builder.getCurrentBlock().createVariable(varIdentifier, null);
if (node.getOptionalType() != null)
// type is optional for local vars
new TypeSetter(sourceContext, namespaceTracker.currentNamespace(null), var).process(node.getOptionalType());
}
@Override
public void caseAVariableAccess(AVariableAccess node) {
ReadVariableAction action =
(ReadVariableAction) builder.createAction(IRepository.PACKAGE.getReadVariableAction());
try {
super.caseAVariableAccess(node);
final OutputPin result = action.createResult(null, null);
builder.registerOutput(result);
String variableName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Variable variable = builder.getVariable(variableName);
if (variable == null) {
problemBuilder.addError("Unknown local variable '" + variableName + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setVariable(variable);
TypeUtils.copyType(variable, result, getBoundElement());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
private Class getBoundElement() {
return (Class) MDDUtil.getNearest(builder.getCurrentActivity().getOwner(), IRepository.PACKAGE
.getClass_());
}
@Override
public void caseAWhileLoopBody(AWhileLoopBody node) {
LoopNode currentLoop = (LoopNode) builder.getCurrentBlock();
currentLoop.setIsTestedFirst(true);
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
super.caseAWhileLoopBody(node);
currentLoop.getBodyParts().add(builder.getCurrentBlock());
} finally {
builder.closeBlock();
}
}
@Override
public void caseAWriteAttributeSpecificStatement(AWriteAttributeSpecificStatement node) {
AddStructuralFeatureValueAction action =
(AddStructuralFeatureValueAction) builder.createAction(IRepository.PACKAGE
.getAddStructuralFeatureValueAction());
action.setIsReplaceAll(true);
try {
builder.registerInput(action.createObject(null, null));
builder.registerInput(action.createValue(null, null));
super.caseAWriteAttributeSpecificStatement(node);
Classifier targetClassifier = (Classifier) ActivityUtils.getSource(action.getObject()).getType();
Assert.isNotNull(targetClassifier, "Target type not determined");
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute =
FeatureUtils.findAttribute(targetClassifier,
attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addError("Unknown attribute '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isDerived()) {
problemBuilder.addProblem( new CannotModifyADerivedAttribute(), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
ensureNotQuery(node);
action.setStructuralFeature(attribute);
action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getValue(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
@Override
public void caseAWriteClassAttributeSpecificStatement(AWriteClassAttributeSpecificStatement node) {
ensureNotQuery(node);
TemplateableElement bound = null;
AddStructuralFeatureValueAction action =
(AddStructuralFeatureValueAction) builder.createAction(IRepository.PACKAGE
.getAddStructuralFeatureValueAction());
action.setIsReplaceAll(true);
try {
String typeIdentifier = TextUMLCore.getSourceMiner().getQualifiedIdentifier(node.getMinimalTypeIdentifier());
Classifier targetClassifier =
(Classifier) getRepository().findNamedElement(typeIdentifier,
IRepository.PACKAGE.getClassifier(), namespaceTracker.currentPackage());
if (targetClassifier == null) {
problemBuilder.addError("Class reference expected: '" + typeIdentifier + "'", node
.getMinimalTypeIdentifier());
throw new AbortedStatementCompilationException();
}
bound = targetClassifier;
final String attributeIdentifier = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Property attribute =
FeatureUtils.findAttribute(targetClassifier,
attributeIdentifier, false, true);
if (attribute == null) {
problemBuilder.addError("Unknown attribute '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (attribute.isDerived()) {
problemBuilder.addProblem( new CannotModifyADerivedAttribute(), node.getIdentifier());
throw new AbortedStatementCompilationException();
}
if (!attribute.isStatic()) {
problemBuilder.addError("Static attribute expected: '" + attributeIdentifier + "' in '"
+ targetClassifier.getName() + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
// features is undefined. (...)"
// builder.registerInput(action.createObject(null, null));
// // our intepretation is that they are allowed and the input
// object is a null value spec
// LiteralNull literalNull = (LiteralNull)
// currentPackage().createPackagedElement(null,
// IRepository.PACKAGE.getLiteralNull());
// buildValueSpecificationAction(literalNull, node);
builder.registerInput(action.createValue(null, null));
// builds expression
node.getRootExpression().apply(this);
action.setStructuralFeature(attribute);
// action.getObject().setType(targetClassifier);
TypeUtils.copyType(attribute, action.getValue(), targetClassifier);
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), bound);
}
@Override
public void caseAWriteVariableSpecificStatement(AWriteVariableSpecificStatement node) {
AddVariableValueAction action =
(AddVariableValueAction) builder.createAction(IRepository.PACKAGE.getAddVariableValueAction());
action.setIsReplaceAll(true);
try {
final InputPin value = builder.registerInput(action.createValue(null, null));
super.caseAWriteVariableSpecificStatement(node);
String variableName = TextUMLCore.getSourceMiner().getIdentifier(node.getIdentifier());
Variable variable = builder.getVariable(variableName);
if (variable == null) {
problemBuilder.addError("Unknown local variable '" + variableName + "'", node.getIdentifier());
throw new AbortedStatementCompilationException();
}
action.setVariable(variable);
if (variable.getType() == null)
// infer variable type if omitted
TypeUtils.copyType(ActivityUtils.getSource(value), variable, getBoundElement());
TypeUtils.copyType(variable, value, getBoundElement());
fillDebugInfo(action, node);
} finally {
builder.closeAction();
}
checkIncomings(action, node.getIdentifier(), getBoundElement());
}
private void checkIncomings(final Action action, final Node node, TemplateableElement bound) {
ObjectFlow incompatible = TypeUtils.checkCompatibility(getRepository(), action, bound);
if (incompatible == null)
return;
final ObjectNode target = ((ObjectNode) incompatible.getTarget());
final ObjectNode source = ((ObjectNode) incompatible.getSource());
final Type anyType = findBuiltInType(TypeUtils.ANY_TYPE, node);
if (target.getType() != null && target.getType() != anyType && (source.getType() == null || source.getType() == anyType))
source.setType(target.getType());
else
problemBuilder.addProblem(
new TypeMismatch(MDDUtil.getDisplayName(target), MDDUtil.getDisplayName(source)), node);
}
private int countElements(PExpressionList list) {
if (list instanceof AEmptyExpressionList)
return 0;
final int[] counter = { 0 };
list.apply(new DepthFirstAdapter() {
@Override
public void caseAExpressionListElement(AExpressionListElement node) {
counter[0]++;
}
});
return counter[0];
}
/**
* Fills in the given activity with behavior parsed from the given node.
*/
public void createBody(Node bodyNode, Activity activity) {
namespaceTracker.enterNamespace(activity);
try {
builder.createRootBlock(activity);
try {
bodyNode.apply(this);
} finally {
builder.closeRootBlock();
}
} finally {
namespaceTracker.leaveNamespace();
}
validateReturnStatement(bodyNode, activity);
// process any deferred activities
while (!deferredActivities.isEmpty()) {
DeferredActivity next = deferredActivities.remove(0);
createBody(next.getBlock(), next.getActivity());
}
}
public void validateReturnStatement(Node bodyNode, Activity activity) {
if (!problemBuilder.hasErrors() && ActivityUtils.getFinalAction(ActivityUtils.getBodyNode(activity)) == null) {
boolean returnValueRequired = FeatureUtils.findReturnParameter(activity.getOwnedParameters()) != null;
if (returnValueRequired) {
problemBuilder.addProblem(new ReturnStatementRequired(), bodyNode);
throw new AbortedScopeCompilationException();
}
}
}
private Clause createClause() {
ConditionalNode currentConditional = (ConditionalNode) builder.getCurrentBlock();
boolean hasClauses = !currentConditional.getClauses().isEmpty();
Clause newClause = currentConditional.createClause();
if (hasClauses) {
Clause previousClause = currentConditional.getClauses().get(currentConditional.getClauses().size() - 1);
previousClause.getSuccessorClauses().add(newClause);
}
return newClause;
}
private void createClauseBody(Clause clause, PClauseBody node) {
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
node.apply(this);
clause.getBodies().add(builder.getCurrentBlock());
} finally {
builder.closeBlock();
}
}
private void createClauseTest(Clause clause, PRootExpression node) {
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
node.apply(this);
clause.getTests().add(builder.getCurrentBlock());
final OutputPin decider = ActivityUtils.getActionOutputs(builder.getLastRootAction()).get(0);
clause.setDecider(decider);
} finally {
builder.closeBlock();
}
}
private void deferBlockCreation(Node block, Activity activity) {
deferredActivities.add(new DeferredActivity(activity, block));
}
private Operation findOperation(Node node, Classifier classifier, String operationName, List<TypedElement> arguments,
boolean isStatic, boolean required) {
Operation found = FeatureUtils.findOperation(getRepository(), classifier, operationName, arguments,
false, true);
if (found != null) {
if (found.isStatic() != isStatic) {
problemBuilder.addError((isStatic ? "Static" : "Non-static")+ " operation expected: '" + operationName + "' in '"
+ found.getType().getQualifiedName() + "'", node);
throw new AbortedStatementCompilationException();
}
return found;
}
return missingOperation(required, node, classifier, operationName, arguments, isStatic);
}
protected Operation missingOperation(boolean required, Node node, Classifier classifier, String operationName,
List<TypedElement> arguments, boolean isStatic) {
if (!required)
return null;
Operation alternative = FeatureUtils.findOperation(getRepository(), classifier, operationName, null,
false, true);
problemBuilder.addProblem(
new UnknownOperation(
classifier.getQualifiedName(),
operationName,
MDDUtil.getArgumentListString(arguments),
isStatic,
alternative)
, node);
throw new AbortedStatementCompilationException();
}
String parseOperationName(Node operatorNode) {
final String[] operationName = {null};
operatorNode.apply(new DepthFirstAdapter() {
@Override
public void caseAEqualsComparisonBinaryOperator(AEqualsComparisonBinaryOperator node) {
operationName[0] = "equals";
}
@Override
public void caseANotEqualsComparisonBinaryOperator(ANotEqualsComparisonBinaryOperator node) {
operationName[0] = "notEquals";
}
@Override
public void caseAGreaterOrEqualsComparisonBinaryOperator(AGreaterOrEqualsComparisonBinaryOperator node) {
operationName[0] = "greaterOrEquals";
}
@Override
public void caseAGreaterThanComparisonBinaryOperator(AGreaterThanComparisonBinaryOperator node) {
operationName[0] = "greaterThan";
}
@Override
public void caseAIdentityBinaryOperator(AIdentityBinaryOperator node) {
operationName[0] = "same";
}
@Override
public void caseALowerOrEqualsComparisonBinaryOperator(ALowerOrEqualsComparisonBinaryOperator node) {
operationName[0] = "lowerOrEquals";
}
@Override
public void caseALowerThanComparisonBinaryOperator(ALowerThanComparisonBinaryOperator node) {
operationName[0] = "lowerThan";
}
public void caseTAnd(TAnd node) {
operationName[0] = "and";
}
public void caseTDiv(TDiv node) {
operationName[0] = "divide";
}
public void caseTMinus(TMinus node) {
operationName[0] = "subtract";
}
public void caseTMult(TMult node) {
operationName[0] = "multiply";
}
public void caseTOr(TOr node) {
operationName[0] = "or";
}
public void caseTPlus(TPlus node) {
operationName[0] = "add";
}
});
return operationName[0];
}
OperationInfo parseOperationInfo(Node operatorNode, int infoCount) {
final OperationInfo info = new OperationInfo(infoCount);
operatorNode.apply(new DepthFirstAdapter() {
@Override
public void caseAArithmeticBinaryOperator(AArithmeticBinaryOperator node) {
super.caseAArithmeticBinaryOperator(node);
info.types[0] =
info.types[1] =
info.types[2] =
(Classifier) getRepository().findNamedElement(
"base::Integer",
IRepository.PACKAGE.getType(), null);
}
@Override
public void caseAComparisonBinaryOperator(AComparisonBinaryOperator node) {
super.caseAComparisonBinaryOperator(node);
info.types[0] =
info.types[1] =
(Classifier) getRepository().findNamedElement("base::Comparable",
IRepository.PACKAGE.getType(), null);
info.types[2] =
(Classifier) getRepository().findNamedElement("base::Boolean",
IRepository.PACKAGE.getType(), null);
}
@Override
public void caseAEqualsComparisonBinaryOperator(AEqualsComparisonBinaryOperator node) {
info.operationName = "equals";
}
@Override
public void caseANotEqualsComparisonBinaryOperator(ANotEqualsComparisonBinaryOperator node) {
info.operationName = "not";
}
@Override
public void caseAGreaterOrEqualsComparisonBinaryOperator(AGreaterOrEqualsComparisonBinaryOperator node) {
info.operationName = "greaterOrEquals";
}
@Override
public void caseAGreaterThanComparisonBinaryOperator(AGreaterThanComparisonBinaryOperator node) {
info.operationName = "greater";
}
@Override
public void caseAIdentityBinaryOperator(AIdentityBinaryOperator node) {
info.operationName = "same";
info.types[0] =
info.types[1] =
(Classifier) getRepository().findNamedElement("base::Any",
IRepository.PACKAGE.getClass_(), null);
info.types[2] =
(Classifier) getRepository().findNamedElement("base::Boolean",
IRepository.PACKAGE.getType(), null);
}
@Override
public void caseALogicalBinaryOperator(ALogicalBinaryOperator node) {
super.caseALogicalBinaryOperator(node);
info.types[0] =
info.types[1] =
info.types[2] =
(Classifier) getRepository().findNamedElement(
"base::Boolean",
IRepository.PACKAGE.getType(), null);
}
@Override
public void caseALowerOrEqualsComparisonBinaryOperator(ALowerOrEqualsComparisonBinaryOperator node) {
info.operationName = "lowerOrEquals";
}
@Override
public void caseALowerThanComparisonBinaryOperator(ALowerThanComparisonBinaryOperator node) {
info.operationName = "lowerThan";
}
@Override
public void caseAMinusUnaryOperator(AMinusUnaryOperator node) {
super.caseAMinusUnaryOperator(node);
info.types[0] =
info.types[1] =
(Classifier) getRepository().findNamedElement("base::Integer",
IRepository.PACKAGE.getType(), null);
}
@Override
public void caseANotUnaryOperator(ANotUnaryOperator node) {
super.caseANotUnaryOperator(node);
info.types[0] =
info.types[1] =
(Classifier) getRepository().findNamedElement("base::Boolean",
IRepository.PACKAGE.getType(), null);
}
@Override
public void caseANotNullUnaryOperator(ANotNullUnaryOperator node) {
super.caseANotNullUnaryOperator(node);
info.types[0] = (Classifier) getRepository().findNamedElement("base::Basic",
IRepository.PACKAGE.getType(), null);
info.types[1] = (Classifier) getRepository().findNamedElement("base::Boolean",
IRepository.PACKAGE.getType(), null);
}
public void caseTAnd(TAnd node) {
info.operationName = "and";
}
public void caseTDiv(TDiv node) {
info.operationName = "divide";
}
public void caseTMinus(TMinus node) {
info.operationName = "subtract";
}
public void caseTMult(TMult node) {
info.operationName = "multiply";
}
@Override
public void caseTNot(TNot node) {
info.operationName = "not";
}
public void caseTNotNull(TNotNull node) {
info.operationName = "notNull";
}
public void caseTOr(TOr node) {
info.operationName = "or";
}
public void caseTPlus(TPlus node) {
info.operationName = "add";
}
});
return info;
}
@Override
public void caseATupleConstructor(ATupleConstructor node) {
final Package currentPackage = namespaceTracker.currentPackage();
final List<Node> componentNodes = new ArrayList<Node>();
final List<String> slotNames = new ArrayList<String>();
List<Type> slotTypes = new ArrayList<Type>();
DataType dataType;
List<Variable> argumentVariables = new ArrayList<Variable>();
node.apply(new DepthFirstAdapter() {
@Override
public void caseATupleComponentValue(ATupleComponentValue node) {
slotNames.add(sourceMiner.getIdentifier(node.getIdentifier()));
componentNodes.add(node.getExpression());
}
});
// create the var to hold the created/returned object so it is accessible to the init code and the final read var
Variable objectVar = ((StructuredActivityNode) builder.getCurrentBlock().getOwner()).createVariable(null, null);
objectVar.setVisibility(VisibilityKind.PRIVATE_LITERAL);
StructuredActivityNode structureBlock = builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
int values = componentNodes.size();
for (int i = 0; i < values; i++) {
Variable argumentVar = builder.getCurrentBlock().createVariable(null, null);
argumentVar.setVisibility(VisibilityKind.PRIVATE_LITERAL);
argumentVar.setName("__" + slotNames.get(i));
argumentVariables.add(argumentVar);
}
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
for (int i = 0; i < values; i++) {
Node componentNode = componentNodes.get(i);
Variable argumentVar = argumentVariables.get(i);
WriteVariableAction storeArgumentAction;
try {
storeArgumentAction =
(WriteVariableAction) builder.createAction(UMLPackage.Literals.ADD_VARIABLE_VALUE_ACTION);
storeArgumentAction.setVariable(argumentVar);
builder.registerInput(storeArgumentAction.createValue(null, null));
componentNode.apply(this);
} finally {
builder.closeAction();
}
slotTypes.add(storeArgumentAction.getValue().getType());
checkIncomings(storeArgumentAction, node.getTupleComponentValue(), getBoundElement());
}
} finally {
builder.closeBlock();
}
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
WriteVariableAction storeObjectAction;
try {
storeObjectAction =
(WriteVariableAction) builder.createAction(UMLPackage.Literals.ADD_VARIABLE_VALUE_ACTION);
storeObjectAction.setVariable(objectVar);
builder.registerInput(storeObjectAction.createValue(null, null));
dataType = DataTypeUtils.findOrCreateDataType(currentPackage, slotNames, slotTypes);
objectVar.setType(dataType);
CreateObjectAction createObjectAction;
try {
createObjectAction =
(CreateObjectAction) builder.createAction(UMLPackage.Literals.CREATE_OBJECT_ACTION);
createObjectAction.setClassifier(dataType);
builder.registerOutput(createObjectAction.createResult(null, dataType));
} finally {
builder.closeAction();
}
checkIncomings(createObjectAction, node.getTupleComponentValue(), getBoundElement());
} finally {
builder.closeAction();
}
checkIncomings(storeObjectAction, node.getTupleComponentValue(), getBoundElement());
} finally {
builder.closeBlock();
}
builder.createBlock(IRepository.PACKAGE.getStructuredActivityNode());
try {
for (int i = 0; i < componentNodes.size(); i++) {
Variable argumentVar = argumentVariables.get(i);
Property slot = dataType.getAttribute(slotNames.get(i), null);
AddStructuralFeatureValueAction copyArgumentIntoSlot;
try {
copyArgumentIntoSlot =
(AddStructuralFeatureValueAction) builder.createAction(UMLPackage.Literals.ADD_STRUCTURAL_FEATURE_VALUE_ACTION);
copyArgumentIntoSlot.setStructuralFeature(slot);
builder.registerInput(copyArgumentIntoSlot.createObject(null, null));
// read target object
ReadVariableAction readObjectFromVar;
try {
readObjectFromVar =
(ReadVariableAction) builder.createAction(UMLPackage.Literals.READ_VARIABLE_ACTION);
readObjectFromVar.setVariable(objectVar);
builder.registerOutput(readObjectFromVar.createResult(null, dataType));
} finally {
builder.closeAction();
}
checkIncomings(readObjectFromVar, node.getTupleComponentValue(), getBoundElement());
builder.registerInput(copyArgumentIntoSlot.createValue(null, slotTypes.get(i)));
ReadVariableAction readComponentValueFromVar;
try {
readComponentValueFromVar =
(ReadVariableAction) builder.createAction(UMLPackage.Literals.READ_VARIABLE_ACTION);
readComponentValueFromVar.setVariable(argumentVar);
builder.registerOutput(readComponentValueFromVar.createResult(null, slotTypes.get(i)));
} finally {
builder.closeAction();
}
checkIncomings(readComponentValueFromVar, node.getTupleComponentValue(), getBoundElement());
} finally {
builder.closeAction();
}
checkIncomings(copyArgumentIntoSlot, node.getTupleComponentValue(), getBoundElement());
}
} finally {
builder.closeBlock();
}
} finally {
// structure block
builder.closeBlock();
}
// moves the block just created into the grand parent block
StructuredActivityNode parentBlock = (StructuredActivityNode) builder.getCurrentBlock().getOwner();
int toInsertAt = parentBlock.getNodes().indexOf(builder.getCurrentBlock());
parentBlock.getNodes().add(toInsertAt, structureBlock);
// finally we read the initialized object to be consumed by a downstream pin
ReadVariableAction retrieveObjectAction;
try {
retrieveObjectAction =
(ReadVariableAction) builder.createAction(UMLPackage.Literals.READ_VARIABLE_ACTION);
retrieveObjectAction.setVariable(objectVar);
builder.registerOutput(retrieveObjectAction.createResult(null, dataType));
} finally {
builder.closeAction();
}
checkIncomings(retrieveObjectAction, node.getTupleComponentValue(), getBoundElement());
}
public void createBodyLater(final Node bodyNode, final Activity body) {
sourceContext.getContext().getReferenceTracker().add(new IDeferredReference() {
@Override
public void resolve(IBasicRepository repository) {
createBody(bodyNode, body);
}
}, Step.LAST);
}
public void createConstraintBehaviorLater(final BehavioredClassifier parent, final Constraint constraint, final Node constraintBlock, final List<Parameter> parameters) {
sourceContext.getContext().getReferenceTracker().add(new IDeferredReference() {
@Override
public void resolve(IBasicRepository repository) {
createConstraintBehavior(parent, constraint, constraintBlock, parameters);
}
}, Step.LAST);
}
public Activity createConstraintBehavior(BehavioredClassifier parent, Constraint constraint, Node constraintBlock, List<Parameter> parameters) {
Activity activity = MDDExtensionUtils.createConstraintBehavior(parent, constraint);
for (Parameter parameter : parameters)
activity.getOwnedParameters().add(parameter);
Classifier constraintType = BasicTypeUtils.findBuiltInType("Boolean");
activity.createOwnedParameter(null, constraintType).setDirection(ParameterDirectionKind.RETURN_LITERAL);
createBody(constraintBlock, activity);
ValueSpecification reference = ActivityUtils.buildBehaviorReference(constraint.getNearestPackage(), activity, constraintType);
constraint.setSpecification(reference);
return activity;
}
}
|
package hu.eltesoft.modelexecution.ide.debug.jvm;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IVariable;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Vertex;
import org.eclipse.xtext.xbase.lib.Pair;
import com.sun.jdi.ClassType;
import com.sun.jdi.Field;
import com.sun.jdi.IncompatibleThreadStateException;
import com.sun.jdi.IntegerValue;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.StringReference;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.Value;
import com.sun.jdi.VirtualMachine;
import hu.eltesoft.modelexecution.ide.common.PluginLogger;
import hu.eltesoft.modelexecution.ide.debug.Messages;
import hu.eltesoft.modelexecution.ide.debug.model.ModelVariable;
import hu.eltesoft.modelexecution.ide.debug.model.SingleValue;
import hu.eltesoft.modelexecution.ide.debug.model.StackFrame;
import hu.eltesoft.modelexecution.ide.debug.model.StateMachineInstance;
import hu.eltesoft.modelexecution.ide.debug.model.StateMachineStackFrame;
import hu.eltesoft.modelexecution.ide.debug.model.XUMLRTDebugTarget;
import hu.eltesoft.modelexecution.ide.debug.util.ModelUtils;
import hu.eltesoft.modelexecution.m2t.java.templates.RegionTemplate;
import hu.eltesoft.modelexecution.runtime.InstanceRegistry;
import hu.eltesoft.modelexecution.runtime.meta.OwnerMeta;
import hu.eltesoft.modelexecution.runtime.meta.SignalMeta;
import hu.eltesoft.modelexecution.runtime.meta.VariableMeta;
/**
* A class to query the state of the runtime running in the given virtual
* machine. Only one {@link VirtualMachineBrowser} should be used for each
* {@link VirtualMachine}.
*/
@SuppressWarnings("restriction")
public class VirtualMachineBrowser {
private static final String NAME_METHOD = "name"; //$NON-NLS-1$
private static final String GET_STATE_MACHINE_METHOD = "getStateMachine"; //$NON-NLS-1$
private static final String GET_INSTANCE_METHOD = "getInstance"; //$NON-NLS-1$
private static final String GET_INSTANCE_REGISTRY_METHOD = "getInstanceRegistry"; //$NON-NLS-1$
private static final String MAIN_THREAD_NAME = "main"; //$NON-NLS-1$
private VirtualMachine virtualMachine;
private JDIThreadWrapper mainThread;
public VirtualMachineBrowser(VirtualMachine virtualMachine) {
this.virtualMachine = virtualMachine;
}
/**
* @return the instance of a class that has a state machine which is
* currently under execution
*/
public synchronized Pair<String, Integer> getActualSMInstance() {
JDIThreadWrapper mainThread = getMainThread();
try {
ObjectReference thisObject = mainThread.getActualThis();
Field ownerField = thisObject.referenceType().fieldByName(RegionTemplate.OWNER_FIELD_NAME);
ObjectReference owner = (ObjectReference) thisObject.getValue(ownerField);
Field objectIdField = thisObject.referenceType().fieldByName("instanceID");
// FIXME: why can't I execute toString???????
return new Pair<>(owner.referenceType().name(), ((IntegerValue) owner.getValue(objectIdField)).intValue());
} catch (Exception e) {
PluginLogger.logError("Could not ask the current SM instance", e); //$NON-NLS-1$
return null;
}
}
protected ModelVariable createVariable(StackFrame frame, JDIThreadWrapper mainThread, Value value,
VariableMeta leftVal) {
XUMLRTDebugTarget debugTarget = frame.getXUmlRtDebugTarget();
return new ModelVariable(debugTarget, leftVal, mainThread, value);
}
/**
* Gets the thread on which the runtime runs. It is safe to use this method
* multiple times, because if a valid thread exists, it returns that and
* evade concurrent use of the same jvm thread.
*/
public JDIThreadWrapper getMainThread() {
if (mainThread == null || !mainThread.isValid()) {
List<ThreadReference> threads = virtualMachine.allThreads();
for (ThreadReference thread : threads) {
if (thread.name().equals(MAIN_THREAD_NAME)) {
mainThread = new JDIThreadWrapper(thread);
}
}
}
return mainThread;
}
public synchronized List<ModelVariable> getAttributes(StateMachineInstance instance) throws DebugException {
try {
List<ModelVariable> ret = new LinkedList<>();
JDIThreadWrapper mainThread = getMainThread();
ObjectReference smInstance = getInstanceFromRegistry(instance, mainThread);
SingleValue value = new SingleValue(instance.getXUmlRtDebugTarget(), mainThread, smInstance);
for (IVariable variable : value.getVariables()) {
if (variable instanceof ModelVariable) {
ret.add((ModelVariable) variable);
}
}
return ret;
} catch (IncompatibleThreadStateException e) {
// thread not suspended: fall through
return null;
}
}
private ObjectReference getInstanceFromRegistry(StateMachineInstance stateMachineInstance,
JDIThreadWrapper mainThread) throws IncompatibleThreadStateException {
try {
ClassType instanceRegistryClass = (ClassType) virtualMachine
.classesByName(InstanceRegistry.class.getCanonicalName()).get(0);
ObjectReference instanceRegistry = (ObjectReference) mainThread.invokeStaticMethod(instanceRegistryClass,
GET_INSTANCE_REGISTRY_METHOD);
ReferenceType actualClass = virtualMachine.classesByName(stateMachineInstance.getClassId()).get(0);
ObjectReference instance = (ObjectReference) mainThread.invokeMethod(instanceRegistry, GET_INSTANCE_METHOD,
actualClass.classObject(), virtualMachine.mirrorOf(stateMachineInstance.getInstanceId()));
return instance;
} catch (IncompatibleThreadStateException e) {
throw e;
} catch (Exception e) {
PluginLogger.logError("Error while accessing state machine instance", e);
throw new RuntimeException(e);
}
}
/**
* Loads the actual state machine instance into a stack frame. Fills the
* model element if it is empty.
*/
public synchronized List<ModelVariable> getVariables(StateMachineStackFrame stackFrame) throws DebugException {
List<ModelVariable> ret = new LinkedList<>();
StateMachineInstance stateMachineInstance = (StateMachineInstance) stackFrame.getThread();
try {
JDIThreadWrapper mainThread = getMainThread();
ObjectReference instance = getInstanceFromRegistry(stateMachineInstance, mainThread);
ObjectReference stateMachine = (ObjectReference) mainThread.invokeMethod(instance,
GET_STATE_MACHINE_METHOD);
EObject modelElement = stackFrame.getModelElement();
if (modelElement == null || modelElement instanceof Vertex) {
// because null means we are not stopped on a breakpoint, so the
// current model element can only be a vertex
// see: StateMachineStackFrame
ObjectReference actualState = (ObjectReference) stateMachine
.getValue(stateMachine.referenceType().fieldByName(RegionTemplate.CURRENT_STATE_ATTRIBUTE));
ret.add(createCurrentStateVariable(stackFrame, mainThread, actualState));
} else {
// the model element is a transition
addEventVariable(stackFrame, ret, mainThread);
}
ret.add(createThisVariable(stackFrame, mainThread, instance));
} catch (IncompatibleThreadStateException e) {
// thread not suspended: fall through
return null;
} catch (Exception e) {
PluginLogger.logError("Error while accessing stack frame variables", e);
}
return ret;
}
private void addEventVariable(StateMachineStackFrame stackFrame, List<ModelVariable> ret,
JDIThreadWrapper mainThread) {
try {
Value eventObj = mainThread.getLocalVariable(RegionTemplate.SIGNAL_VARIABLE);
if (eventObj != null) {
ret.add(createVariable(stackFrame, mainThread, eventObj,
new SignalMeta(Messages.VirtualMachineConnection_variable_signal_label)));
}
} catch (IllegalStateException e) {
// thread not suspended: fall through
}
}
public synchronized NamedElement loadModelElement(StateMachineStackFrame stackFrame, ResourceSet resourceSet) {
try {
JDIThreadWrapper mainThread = getMainThread();
ObjectReference instance = getInstanceFromRegistry(stackFrame.getStateMachineInstance(), mainThread);
ObjectReference stateMachine = (ObjectReference) mainThread.invokeMethod(instance,
GET_STATE_MACHINE_METHOD);
ObjectReference actualState = (ObjectReference) stateMachine
.getValue(stateMachine.referenceType().fieldByName(RegionTemplate.CURRENT_STATE_ATTRIBUTE));
StringReference stringVal = (StringReference) mainThread.invokeMethod(actualState, NAME_METHOD);
return (NamedElement) ModelUtils.javaNameToEObject(stringVal.value(), resourceSet);
} catch (IncompatibleThreadStateException e) {
// thread not suspended: fall through
return null;
} catch (Exception e) {
PluginLogger.logError("Error while accessing stack frame model element", e);
return null;
}
}
private ModelVariable createThisVariable(StackFrame stackFrame, JDIThreadWrapper mainThread, Value instance) {
return createVariable(stackFrame, mainThread, instance,
new OwnerMeta(Messages.VirtualMachineConnection_variable_this_label));
}
private ModelVariable createCurrentStateVariable(StackFrame stackFrame, JDIThreadWrapper mainThread,
Value actualState) {
return createVariable(stackFrame, mainThread, actualState,
new OwnerMeta(Messages.VirtualMachineConnection_variable_currentState_label));
}
}
|
package org.yakindu.sct.model.stext.ui.validation;
import java.util.Collection;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.NotationPackage;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.xtext.EcoreUtil2;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.util.IAcceptor;
import org.eclipse.xtext.validation.DiagnosticConverterImpl;
import org.eclipse.xtext.validation.Issue;
import org.yakindu.sct.model.sgraph.SpecificationElement;
import org.yakindu.sct.model.sgraph.ui.validation.SCTMarkerCreator;
/**
*
* @author andreas muelder - Initial contribution and API
*
*/
public class SCTDiagnosticConverterImpl extends DiagnosticConverterImpl {
@Override
public void convertValidatorDiagnostic(final Diagnostic diagnostic, final IAcceptor<Issue> acceptor) {
super.convertValidatorDiagnostic(diagnostic, new IAcceptor<Issue>() {
public void accept(Issue t) {
boolean notAccepted = true;
if (diagnostic.getData().get(0) instanceof EObject) {
EObject eObject = (EObject) diagnostic.getData().get(0);
if (eObject != null && eObject.eResource() != null) {
if (NodeModelUtils.getNode(eObject) != null) {
eObject = EcoreUtil2.getContainerOfType(eObject, SpecificationElement.class);
}
if (eObject != null && eObject.eResource() != null) {
View notationView = findNotationView(eObject);
if (notationView != null && notationView.eResource() != null) {
acceptor.accept(new SCTMarkerCreator.WrappingIssue(t, notationView.eResource()
.getURIFragment(notationView)));
notAccepted = false;
}
}
}
}
if (notAccepted) {
acceptor.accept(t);
}
}
});
}
protected View findNotationView(EObject semanticElement) {
Collection<Diagram> objects = EcoreUtil.getObjectsByType(semanticElement.eResource().getContents(),
NotationPackage.Literals.DIAGRAM);
for (Diagram diagram : objects) {
TreeIterator<EObject> eAllContents = diagram.eAllContents();
while (eAllContents.hasNext()) {
EObject next = eAllContents.next();
if (next instanceof View) {
if (EcoreUtil.equals(((View) next).getElement(), semanticElement)) {
return ((View) next);
}
}
}
}
return null;
}
}
|
package com.nobodyiam.spring.in.action.reservation.client;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestTemplate;
@EnableZuulProxy
@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class ReservationClientApplication {
@Bean
CommandLineRunner runner(DiscoveryClient dc) {
return args -> {
dc.getInstances("reservation-service")
.forEach(si -> System.out.println(String.format(
"Found %s %s:%s", si.getServiceId(), si.getHost(), si.getPort())));
};
}
/**
* The load balanced rest template
*/
@LoadBalanced
@Bean
RestTemplate loadBalanced() {
return new RestTemplate();
}
/**
* The normal rest template
*/
@Primary
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ReservationClientApplication.class, args);
}
}
|
package com.jivesoftware.os.routing.bird.server.session;
import com.google.common.collect.Maps;
import com.jivesoftware.os.mlogger.core.MetricLogger;
import com.jivesoftware.os.mlogger.core.MetricLoggerFactory;
import com.jivesoftware.os.routing.bird.http.client.HttpRequestHelper;
import com.jivesoftware.os.routing.bird.http.client.NonSuccessStatusCodeException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Cookie;
public class RouteSessionValidator implements SessionValidator {
private static final MetricLogger LOG = MetricLoggerFactory.getLogger();
public static final String SESSION_ID = "rb_session_id";
public static final String SESSION_TOKEN = "rb_session_token";
private final String instanceKey;
private final HttpRequestHelper requestHelper;
private final String validatorPath;
private final String exchangePath;
private final long sessionCacheDurationMillis;
private final Map<String, Session> sessions = Maps.newConcurrentMap();
public RouteSessionValidator(String instanceKey,
HttpRequestHelper requestHelper,
String validatorPath,
String exchangePath,
long sessionCacheDurationMillis) {
this.instanceKey = instanceKey;
this.requestHelper = requestHelper;
this.validatorPath = validatorPath;
this.exchangePath = exchangePath;
this.sessionCacheDurationMillis = sessionCacheDurationMillis;
}
@Override
public boolean isAuthenticated(ContainerRequestContext requestContext) throws SessionValidationException {
Cookie sessionIdCookie = requestContext.getCookies().get(SESSION_ID);
String sessionId = sessionIdCookie == null ? null : sessionIdCookie.getValue();
Cookie sessionTokenCookie = requestContext.getCookies().get(SESSION_TOKEN);
String sessionToken = sessionTokenCookie == null ? null : sessionTokenCookie.getValue();
Boolean result = null;
if (sessionId != null && sessionToken != null) {
Session session = sessions.get(sessionToken);
if (session == null || session.timestamp < System.currentTimeMillis() - sessionCacheDurationMillis) {
Map<String, String> cookies = Maps.newHashMap();
cookies.put(SESSION_ID, sessionId);
cookies.put(SESSION_TOKEN, sessionToken);
result = requestHelper.executeRequest(cookies, validatorPath, Boolean.class, null);
if (result == null) {
throw new SessionValidationException("Routes failed to respond to validation request for id:" + sessionId);
} else if (result) {
Session got = sessions.compute(sessionToken, (key, value) -> {
long timestamp = System.currentTimeMillis();
if (value == null || timestamp > value.timestamp) {
value = new Session(sessionId, timestamp);
}
return value;
});
if (!got.id.equals(sessionId)) {
LOG.warn("Invalid session for token: {} != {}", sessionId, got.id);
result = false;
}
} else {
sessions.remove(sessionToken);
}
} else {
result = true;
}
}
LOG.info("Session validator for id:{} returned result:{}", sessionId, result);
return result != null && result;
}
@Override
public String getId(ContainerRequestContext requestContext) {
Cookie sessionIdCookie = requestContext.getCookies().get(SESSION_ID);
return sessionIdCookie == null ? null : sessionIdCookie.getValue();
}
@Override
public boolean exchangeAccessToken(ContainerRequestContext requestContext) {
String sessionId = (String) requestContext.getProperty("rb_session_id");
if (sessionId == null) {
List<String> accessToken = requestContext.getUriInfo().getQueryParameters().get("rb_access_token");
if (accessToken != null && !accessToken.isEmpty()) {
try {
byte[] sessionToken = requestHelper.executeGet(exchangePath + "/" + instanceKey + "/" + accessToken.get(0));
if (sessionToken != null) {
requestContext.setProperty("rb_session_id", instanceKey);
requestContext.setProperty("rb_session_token", new String(sessionToken, StandardCharsets.UTF_8));
return true;
}
} catch (NonSuccessStatusCodeException e) {
LOG.warn("access token rejected.", e);
return false;
}
}
}
return false;
}
private static class Session {
private final String id;
private final long timestamp;
private Session(String id, long timestamp) {
this.id = id;
this.timestamp = timestamp;
}
}
}
|
package ca.corefacility.bioinformatics.irida.web.controller.api.samples;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import ca.corefacility.bioinformatics.irida.exceptions.EntityNotFoundException;
import ca.corefacility.bioinformatics.irida.model.enums.AnalysisState;
import ca.corefacility.bioinformatics.irida.model.run.SequencingRun;
import ca.corefacility.bioinformatics.irida.model.sample.Sample;
import ca.corefacility.bioinformatics.irida.model.sample.SampleSequencingObjectJoin;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFile;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequenceFilePair;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SequencingObject;
import ca.corefacility.bioinformatics.irida.model.sequenceFile.SingleEndSequenceFile;
import ca.corefacility.bioinformatics.irida.model.workflow.analysis.AnalysisFastQC;
import ca.corefacility.bioinformatics.irida.model.workflow.submission.AnalysisSubmission;
import ca.corefacility.bioinformatics.irida.service.AnalysisService;
import ca.corefacility.bioinformatics.irida.service.SequencingObjectService;
import ca.corefacility.bioinformatics.irida.service.SequencingRunService;
import ca.corefacility.bioinformatics.irida.service.sample.SampleService;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.ResourceCollection;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.RootResource;
import ca.corefacility.bioinformatics.irida.web.assembler.resource.sequencefile.SequenceFileResource;
import ca.corefacility.bioinformatics.irida.web.controller.api.RESTAnalysisSubmissionController;
import ca.corefacility.bioinformatics.irida.web.controller.api.RESTGenericController;
import ca.corefacility.bioinformatics.irida.web.controller.api.projects.RESTProjectSamplesController;
import com.google.common.base.Objects;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.net.HttpHeaders;
/**
* Controller for managing relationships between {@link Sample} and
* {@link SequenceFile}.
*
*/
@Controller
public class RESTSampleSequenceFilesController {
private static final Logger logger = LoggerFactory.getLogger(RESTSampleSequenceFilesController.class);
/**
* Rel to get back to the {@link Sample}.
*/
public static final String REL_SAMPLE = "sample";
/**
* Rel to the {@link SequenceFile} pair
*/
public static final String REL_PAIR = "pair";
/**
* Rel to get to the new location of the {@link SequenceFile}.
*/
public static final String REL_SAMPLE_SEQUENCE_FILES = "sample/sequenceFiles";
/**
* Rel for paired sequence files for a given sample
*/
public static final String REL_SAMPLE_SEQUENCE_FILE_PAIRS = "sample/sequenceFiles/pairs";
/**
* rel for the unpaired sequence files for a given sample
*/
public static final String REL_SAMPLE_SEQUENCE_FILE_UNPAIRED = "sample/sequenceFiles/unpaired";
public static final String REL_SEQUENCEFILE_SAMPLE = "sequenceFile/sample";
public static final String REL_PAIR_SAMPLE = "sequenceFilePair/sample";
/**
* Rel to a sequencefile's sequencing object
*/
public static final String REL_SEQ_OBJECT = "sequenceFile/sequencingObject";
/**
* Rel for a sequencefile's fastqc info
*/
public static final String REL_SEQ_QC = "sequencefile/qc";
public static final String REL_QC_SEQFILE = "qc/sequencefile";
/**
* rel for forward and reverse files
*/
public static final String REL_PAIR_FORWARD = "pair/forward";
public static final String REL_PAIR_REVERSE = "pair/reverse";
/**
* rel for automated analyses associated with sequencing object
*/
public static final String REL_AUTOMATED_ASSEMBLY = "analysis/assembly";
public static final String REL_SISTR_TYPING = "analysis/sistr";
/**
* The key used in the request to add an existing {@link SequenceFile} to a
* {@link Sample}.
*/
public static final String SEQUENCE_FILE_ID_KEY = "sequenceFileId";
/**
* Filetype labels for different {@link SequencingObject} subclasses. These
* will be used in the hrefs for reading {@link SequencingObject}s
*/
public static BiMap<Class<? extends SequencingObject>, String> objectLabels = ImmutableBiMap.of(
SequenceFilePair.class, "pairs", SingleEndSequenceFile.class, "unpaired");
/**
* Reference to the {@link SampleService}.
*/
private SampleService sampleService;
/**
* Reference to the {@link MiseqRunService}
*/
private SequencingRunService miseqRunService;
private SequencingObjectService sequencingObjectService;
private AnalysisService analysisService;
protected RESTSampleSequenceFilesController() {
}
@Autowired
public RESTSampleSequenceFilesController(SampleService sampleService, SequencingRunService miseqRunService,
SequencingObjectService sequencingObjectService, AnalysisService analysisService) {
this.sampleService = sampleService;
this.miseqRunService = miseqRunService;
this.sequencingObjectService = sequencingObjectService;
this.analysisService = analysisService;
}
/**
* Get the {@link SequenceFile} entities associated with a specific
* {@link Sample}.
*
* @param sampleId
* the identifier for the {@link Sample}.
* @return the {@link SequenceFile} entities associated with the
* {@link Sample}.
*/
@RequestMapping(value = "/api/samples/{sampleId}/sequenceFiles", method = RequestMethod.GET)
public ModelMap getSampleSequenceFiles(@PathVariable Long sampleId) {
ModelMap modelMap = new ModelMap();
logger.debug("Reading seq files for sample " + sampleId);
Sample sample = sampleService.read(sampleId);
Collection<SampleSequencingObjectJoin> sequencingObjectsForSample = sequencingObjectService
.getSequencingObjectsForSample(sample);
ResourceCollection<SequenceFile> resources = new ResourceCollection<>();
/*
* Note: This is a kind of antiquated seeing we should be referencing
* sequencing objects instead. At the very least the link we're pointing
* to here should be going through the sequencing object
*/
for (SampleSequencingObjectJoin r : sequencingObjectsForSample) {
for (SequenceFile sf : r.getObject().getFiles()) {
String fileLabel = objectLabels.get(r.getObject().getClass());
sf.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequenceFileForSequencingObject(sampleId,
fileLabel, r.getObject().getId(), sf.getId())).withSelfRel());
resources.add(sf);
}
}
// add a link to this collection
resources.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).getSampleSequenceFiles(sampleId))
.withSelfRel());
// add a link back to the sample
resources.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(
RESTSampleSequenceFilesController.REL_SAMPLE));
resources.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).listSequencingObjectsOfTypeForSample(sample.getId(),
RESTSampleSequenceFilesController.objectLabels.get(SequenceFilePair.class))).withRel(
RESTSampleSequenceFilesController.REL_SAMPLE_SEQUENCE_FILE_PAIRS));
resources.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).listSequencingObjectsOfTypeForSample(sample.getId(),
RESTSampleSequenceFilesController.objectLabels.get(SingleEndSequenceFile.class))).withRel(
RESTSampleSequenceFilesController.REL_SAMPLE_SEQUENCE_FILE_UNPAIRED));
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, resources);
return modelMap;
}
/**
* List all {@link SequencingObject}s of a given type for a {@link Sample}
*
* @param sampleId
* ID of the {@link Sample} to read from
* @param objectType
* {@link SequencingObject} type
* @return The {@link SequencingObject}s of the given type for the
* {@link Sample}
*/
@RequestMapping(value = "/api/samples/{sampleId}/{objectType}", method = RequestMethod.GET)
public ModelMap listSequencingObjectsOfTypeForSample(@PathVariable Long sampleId, @PathVariable String objectType) {
ModelMap modelMap = new ModelMap();
logger.debug("Reading seq file for sample " + sampleId);
Sample sample = sampleService.read(sampleId);
Class<? extends SequencingObject> type = objectLabels.inverse().get(objectType);
Collection<SampleSequencingObjectJoin> unpairedSequenceFilesForSample = sequencingObjectService
.getSequencesForSampleOfType(sample, type);
ResourceCollection<SequencingObject> resources = new ResourceCollection<>(unpairedSequenceFilesForSample.size());
for (SampleSequencingObjectJoin join : unpairedSequenceFilesForSample) {
SequencingObject sequencingObject = join.getObject();
sequencingObject = addSequencingObjectLinks(sequencingObject, sampleId);
resources.add(sequencingObject);
}
// add a link to this collection
resources.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).listSequencingObjectsOfTypeForSample(sampleId,
objectType)).withSelfRel());
// add a link back to the sample
resources.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(
RESTSampleSequenceFilesController.REL_SAMPLE));
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, resources);
return modelMap;
}
/**
* Read a single {@link SequencingObject} of the given type from a
* {@link Sample}
*
* @param sampleId
* {@link Sample} identifier
* @param objectType
* type of {@link SequencingObject}
* @param objectId
* ID of the {@link SequencingObject}
* @return A single {@link SequencingObject}
*/
@RequestMapping(value = "/api/samples/{sampleId}/{objectType}/{objectId}", method = RequestMethod.GET)
public ModelMap readSequencingObject(@PathVariable Long sampleId, @PathVariable String objectType,
@PathVariable Long objectId) {
ModelMap modelMap = new ModelMap();
Sample sample = sampleService.read(sampleId);
SequencingObject sequencingObject = sequencingObjectService.readSequencingObjectForSample(sample, objectId);
sequencingObject = addSequencingObjectLinks(sequencingObject, sampleId);
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, sequencingObject);
return modelMap;
}
/**
* Read a single {@link SequenceFile} for a given {@link Sample} and
* {@link SequencingObject}
*
* @param sampleId
* ID of the {@link Sample}
* @param objectType
* type of {@link SequencingObject}
* @param objectId
* id of the {@link SequencingObject}
* @param fileId
* ID of the {@link SequenceFile} to read
* @return a {@link SequenceFile}
*/
@RequestMapping(value = "/api/samples/{sampleId}/{objectType}/{objectId}/files/{fileId}", method = RequestMethod.GET)
public ModelMap readSequenceFileForSequencingObject(@PathVariable Long sampleId, @PathVariable String objectType,
@PathVariable Long objectId, @PathVariable Long fileId) {
ModelMap modelMap = new ModelMap();
Sample sample = sampleService.read(sampleId);
SequencingObject readSequenceFilePairForSample = sequencingObjectService.readSequencingObjectForSample(sample,
objectId);
Optional<SequenceFile> findFirst = readSequenceFilePairForSample.getFiles().stream()
.filter(f -> f.getId().equals(fileId)).findFirst();
if (!findFirst.isPresent()) {
throw new EntityNotFoundException("File with id " + fileId
+ " is not associated with this sequencing object");
}
SequenceFile file = findFirst.get();
file.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).getSampleSequenceFiles(sampleId)).withRel(
REL_SAMPLE_SEQUENCE_FILES));
file.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(REL_SAMPLE));
file.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequencingObject(sampleId, objectType, objectId))
.withRel(REL_SEQ_OBJECT));
file.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).readQCForSequenceFile(sampleId, objectType,
objectId, fileId)).withRel(REL_SEQ_QC));
file.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequenceFileForSequencingObject(sampleId,
objectType, objectId, fileId)).withSelfRel());
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, file);
return modelMap;
}
@RequestMapping("/api/samples/{sampleId}/{objectType}/{objectId}/sistr")
public ModelMap readSistrTypingForSequencingObject(@PathVariable Long sampleId, @PathVariable String objectType,
@PathVariable Long objectId) {
ModelMap map = new ModelMap();
Sample sample = sampleService.read(sampleId);
SequencingObject sequencingObject = sequencingObjectService.readSequencingObjectForSample(sample, objectId);
AnalysisSubmission sistrTyping = sequencingObject.getSistrTyping();
if (sistrTyping != null) {
sistrTyping.add(linkTo(methodOn(RESTSampleSequenceFilesController.class)
.readSistrTypingForSequencingObject(sampleId, objectType, sistrTyping.getId())).withSelfRel());
sistrTyping.add(linkTo(methodOn(RESTAnalysisSubmissionController.class).getResource(sistrTyping.getId()))
.withRel("submission"));
if (AnalysisState.COMPLETED.equals(sistrTyping.getAnalysisState())) {
sistrTyping.add(linkTo(methodOn(RESTAnalysisSubmissionController.class)
.getAnalysisForSubmission(sistrTyping.getId()))
.withRel(RESTAnalysisSubmissionController.ANALYSIS_REL));
}
map.addAttribute(RESTGenericController.RESOURCE_NAME, sistrTyping);
}
return map;
}
/**
* Get the fastqc metrics for a {@link SequenceFile}
*
* @param sampleId
* {@link Sample} id of the file
* @param objectType
* type of {@link SequencingObject}
* @param objectId
* id of the {@link SequencingObject}
* @param fileId
* id of the {@link SequenceFile}
* @return an {@link AnalysisFastQC} for the file
*/
@RequestMapping(value = "/api/samples/{sampleId}/{objectType}/{objectId}/files/{fileId}/qc", method = RequestMethod.GET)
public ModelMap readQCForSequenceFile(@PathVariable Long sampleId, @PathVariable String objectType,
@PathVariable Long objectId, @PathVariable Long fileId) {
ModelMap modelMap = new ModelMap();
Sample sample = sampleService.read(sampleId);
SequencingObject readSequencingObjectForSample = sequencingObjectService.readSequencingObjectForSample(sample,
objectId);
AnalysisFastQC fastQCAnalysisForSequenceFile = analysisService
.getFastQCAnalysisForSequenceFile(readSequencingObjectForSample, fileId);
if (fastQCAnalysisForSequenceFile == null) {
throw new EntityNotFoundException("No QC data for file");
}
fastQCAnalysisForSequenceFile.add(linkTo(methodOn(RESTSampleSequenceFilesController.class)
.readSequenceFileForSequencingObject(sampleId, objectType, objectId, fileId)).withRel(REL_QC_SEQFILE));
fastQCAnalysisForSequenceFile.add(linkTo(methodOn(RESTSampleSequenceFilesController.class)
.readQCForSequenceFile(sampleId, objectType, objectId, fileId)).withSelfRel());
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, fastQCAnalysisForSequenceFile);
return modelMap;
}
/**
* Add a new {@link SequenceFile} to a {@link Sample}.
*
* @param sampleId
* the identifier for the {@link Sample}.
* @param file
* the content of the {@link SequenceFile}.
* @param fileResource
* the parameters for the file
* @param response
* the servlet response.
* @return a response indicating the success of the submission.
* @throws IOException
* if we can't write the file to disk.
*/
@RequestMapping(value = "/api/samples/{sampleId}/sequenceFiles", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ModelMap addNewSequenceFileToSample(@PathVariable Long sampleId, @RequestPart("file") MultipartFile file,
@RequestPart(value = "parameters", required = false) SequenceFileResource fileResource,
HttpServletResponse response) throws IOException {
ModelMap modelMap = new ModelMap();
logger.debug("Adding sequence file to sample " + sampleId);
logger.trace("Uploaded file size: " + file.getSize() + " bytes");
// load the sample from the database
Sample sample = sampleService.read(sampleId);
logger.trace("Read sample " + sampleId);
// prepare a new sequence file using the multipart file supplied by the
// caller
Path temp = Files.createTempDirectory(null);
Path target = temp.resolve(file.getOriginalFilename());
// Changed to MultipartFile.transerTo(File) because it was truncating
// large files to 1039956336 bytes
// target = Files.write(target, file.getBytes());
file.transferTo(target.toFile());
logger.trace("Wrote temp file to " + target);
SequenceFile sf;
SequencingRun miseqRun = null;
if (fileResource != null) {
sf = fileResource.getResource();
Long miseqRunId = fileResource.getMiseqRunId();
if (miseqRunId != null) {
miseqRun = miseqRunService.read(miseqRunId);
logger.trace("Read miseq run " + miseqRunId);
}
} else {
sf = new SequenceFile();
}
sf.setFile(target);
SingleEndSequenceFile singleEndSequenceFile = new SingleEndSequenceFile(sf);
if (miseqRun != null) {
singleEndSequenceFile.setSequencingRun(miseqRun);
logger.trace("Added seqfile to miseqrun");
}
// save the seqobject and sample
SampleSequencingObjectJoin createSequencingObjectInSample = sequencingObjectService
.createSequencingObjectInSample(singleEndSequenceFile, sample);
singleEndSequenceFile = (SingleEndSequenceFile) createSequencingObjectInSample.getObject();
logger.trace("Created seqfile in sample " + createSequencingObjectInSample.getObject().getId());
// clean up the temporary files.
Files.deleteIfExists(target);
Files.deleteIfExists(temp);
logger.trace("Deleted temp file");
// prepare a link to the sequence file itself (on the sequence file
// controller)
String objectType = objectLabels.get(SingleEndSequenceFile.class);
Long sequenceFileId = singleEndSequenceFile.getSequenceFile().getId();
Link selfRel = linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequenceFileForSequencingObject(sampleId,
objectType, singleEndSequenceFile.getId(), sequenceFileId)).withSelfRel();
// Changed, because sfr.setResource(sf)
// and sfr.setResource(sampleSequenceFileRelationship.getObject())
// both will not pass a GET-POST comparison integration test.
singleEndSequenceFile = (SingleEndSequenceFile) sequencingObjectService.read(singleEndSequenceFile.getId());
SequenceFile sequenceFile = singleEndSequenceFile.getFileWithId(sequenceFileId);
// add links to the resource
sequenceFile.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).getSampleSequenceFiles(sampleId))
.withRel(REL_SAMPLE_SEQUENCE_FILES));
sequenceFile.add(selfRel);
sequenceFile.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(REL_SAMPLE));
sequenceFile.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequencingObject(sampleId, objectType,
singleEndSequenceFile.getId())).withRel(REL_SEQ_OBJECT));
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, sequenceFile);
// add a location header.
response.addHeader(HttpHeaders.LOCATION, selfRel.getHref());
// set the response status.
response.setStatus(HttpStatus.CREATED.value());
// respond to the client
return modelMap;
}
/**
* Add a pair of {@link SequenceFile}s to a {@link Sample}
*
* @param sampleId
* The {@link Sample} id to add to
* @param file1
* The first multipart file
* @param fileResource1
* The metadata for the first file
* @param file2
* The second multipart file
* @param fileResource2
* the metadata for the second file
* @param response
* a reference to the servlet response.
* @return Response containing the locations for the created files
* @throws IOException
* if we can't write the files to disk
*/
@RequestMapping(value = "/api/samples/{sampleId}/pairs", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ModelMap addNewSequenceFilePairToSample(@PathVariable Long sampleId,
@RequestPart("file1") MultipartFile file1,
@RequestPart(value = "parameters1") SequenceFileResource fileResource1,
@RequestPart("file2") MultipartFile file2,
@RequestPart(value = "parameters2") SequenceFileResource fileResource2, HttpServletResponse response)
throws IOException {
logger.debug("Adding pair of sequence files to sample " + sampleId);
logger.trace("First uploaded file size: " + file1.getSize() + " bytes");
logger.trace("Second uploaded file size: " + file2.getSize() + " bytes");
ModelMap modelMap = new ModelMap();
// confirm that a relationship exists between the project and the sample
Sample sample = sampleService.read(sampleId);
logger.trace("Read sample " + sampleId);
// create temp files
Path temp1 = Files.createTempDirectory(null);
Path target1 = temp1.resolve(file1.getOriginalFilename());
Path temp2 = Files.createTempDirectory(null);
Path target2 = temp2.resolve(file2.getOriginalFilename());
// transfer the files to temp directories
file1.transferTo(target1.toFile());
file2.transferTo(target2.toFile());
// create the model objects
SequenceFile sf1 = fileResource1.getResource();
SequenceFile sf2 = fileResource2.getResource();
sf1.setFile(target1);
sf2.setFile(target2);
// get the sequencing run
SequencingRun sequencingRun = null;
if (!Objects.equal(fileResource1.getMiseqRunId(), fileResource2.getMiseqRunId())) {
throw new IllegalArgumentException("Cannot upload a pair of files from different sequencing runs");
}
Long runId = fileResource1.getMiseqRunId();
SequenceFilePair sequenceFilePair = new SequenceFilePair(sf1, sf2);
if (runId != null) {
sequencingRun = miseqRunService.read(runId);
sequenceFilePair.setSequencingRun(sequencingRun);
logger.trace("Added sequencing run to files" + runId);
}
// add the files and join
SampleSequencingObjectJoin createSequencingObjectInSample = sequencingObjectService
.createSequencingObjectInSample(sequenceFilePair, sample);
// clean up the temporary files.
Files.deleteIfExists(target1);
Files.deleteIfExists(temp1);
Files.deleteIfExists(target2);
Files.deleteIfExists(temp2);
logger.trace("Deleted temp files");
SequencingObject sequencingObject = createSequencingObjectInSample.getObject();
sequencingObject = addSequencingObjectLinks(sequencingObject, sampleId);
sequencingObject.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).getSampleSequenceFiles(sampleId))
.withRel(REL_SAMPLE_SEQUENCE_FILES));
// add location header
response.addHeader(HttpHeaders.LOCATION, sequencingObject.getLink("self").getHref());
// set the response status.
response.setStatus(HttpStatus.CREATED.value());
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, sequencingObject);
// respond to the client
return modelMap;
}
/**
* Remove a {@link SequencingObject} from a {@link Sample}.
*
* @param sampleId
* the source {@link Sample} identifier.
* @param objectId
* the identifier of the {@link SequencingObject} to move.
* @return a status indicating the success of the move.
*/
@RequestMapping(value = "/api/samples/{sampleId}/{objectType}/{objectId}", method = RequestMethod.DELETE)
public ModelMap removeSequenceFileFromSample(@PathVariable Long sampleId, @PathVariable String objectType,
@PathVariable Long objectId) {
ModelMap modelMap = new ModelMap();
// load the project, sample and sequence file from the database
Sample s = sampleService.read(sampleId);
SequencingObject seqObject = sequencingObjectService.readSequencingObjectForSample(s, objectId);
// ask the service to remove the sample from the sequence file
sampleService.removeSequencingObjectFromSample(s, seqObject);
// respond with a link to the sample, the new location of the sequence
// file (as it is associated with the
// project)
RootResource resource = new RootResource();
resource.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(REL_SAMPLE));
resource.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).getSampleSequenceFiles(sampleId))
.withRel(REL_SAMPLE_SEQUENCE_FILES));
modelMap.addAttribute(RESTGenericController.RESOURCE_NAME, resource);
return modelMap;
}
/**
* add the forward and reverse file links and a link to the pair's sample
*
* @param pair
* The {@link SequenceFilePair} to enhance
* @param sampleId
* the id of the {@link Sample} the pair is in
* @return The {@link SequenceFilePair} with added links
*/
private static SequenceFilePair addSequenceFilePairLinks(SequenceFilePair pair, Long sampleId) {
SequenceFile forward = pair.getForwardSequenceFile();
String forwardLink = forward.getLink("self").getHref();
SequenceFile reverse = pair.getReverseSequenceFile();
String reverseLink = reverse.getLink("self").getHref();
pair.add(new Link(forwardLink, REL_PAIR_FORWARD));
pair.add(new Link(reverseLink, REL_PAIR_REVERSE));
return pair;
}
/**
* Add the links for a {@link SequencingObject} to its sample, self, to each
* individual {@link SequenceFile}
*
* @param sequencingObject
* {@link SequencingObject} to enhance
* @param sampleId
* ID of the {@link Sample} for the object
* @return the enhanced {@link SequencingObject}
*/
@SuppressWarnings("unchecked")
public static <T extends SequencingObject> T addSequencingObjectLinks(T sequencingObject, Long sampleId) {
String objectType = objectLabels.get(sequencingObject.getClass());
// link to self
sequencingObject.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequencingObject(sampleId, objectType,
sequencingObject.getId())).withSelfRel());
// link to the sample
sequencingObject.add(linkTo(methodOn(RESTProjectSamplesController.class).getSample(sampleId)).withRel(
RESTSampleSequenceFilesController.REL_SAMPLE));
// link to the individual files
for (SequenceFile file : sequencingObject.getFiles()) {
file.add(linkTo(
methodOn(RESTSampleSequenceFilesController.class).readSequenceFileForSequencingObject(sampleId,
objectType, sequencingObject.getId(), file.getId())).withSelfRel());
}
// AnalysisSubmission automatedAssembly = sequencingObject.getAutomatedAssembly();
// if (automatedAssembly != null) {
// sequencingObject
// .add(linkTo(methodOn(RESTAnalysisSubmissionController.class).getAnalysisSubmissionMinimal(automatedAssembly.getId()))
// .withRel(REL_AUTOMATED_ASSEMBLY));
sequencingObject
.add(linkTo(methodOn(RESTSampleSequenceFilesController.class).readSistrTypingForSequencingObject(sampleId, objectType, sequencingObject.getId()))
.withRel(REL_SISTR_TYPING));
// if it's a pair, add forward/reverse links
if (sequencingObject instanceof SequenceFilePair) {
sequencingObject = (T) addSequenceFilePairLinks((SequenceFilePair) sequencingObject, sampleId);
}
return sequencingObject;
}
}
|
package org.neo4j.kernel.impl.core;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.NotFoundException;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
import org.neo4j.kernel.impl.AbstractNeo4jTestCase;
import org.neo4j.kernel.impl.MyRelTypes;
public class TestNeo4jConstrains extends AbstractNeo4jTestCase
{
private String key = "testproperty";
public TestNeo4jConstrains( String testName )
{
super( testName );
}
public void setUp()
{
super.setUp();
}
public void tearDown()
{
super.tearDown();
}
public void testDeleteReferenceNodeOrLastNodeIsOk()
{
Transaction tx = getTransaction();
for ( int i = 0; i < 10; i++ )
{
getGraphDb().createNode();
}
// long numNodesPre = getNodeManager().getNumberOfIdsInUse( Node.class
// empty the DB instance
for ( Node node : getGraphDb().getAllNodes() )
{
for ( Relationship rel : node.getRelationships() )
{
rel.delete();
}
node.delete();
}
tx.success();
tx.finish();
tx = getGraphDb().beginTx();
// the DB should be empty
// long numNodesPost = getNodeManager().getNumberOfIdsInUse( Node.class
// System.out.println(String.format( "pre: %d, post: %d", numNodesPre,
// numNodesPost ));
assertFalse( getGraphDb().getAllNodes().iterator().hasNext() );
// TODO: this should be valid, fails right now!
// assertEquals( 0, numNodesPost );
try
{
getGraphDb().getReferenceNode();
fail();
}
catch ( NotFoundException nfe )
{
// should be thrown
}
tx.success();
tx.finish();
}
public void testDeleteNodeWithRel1()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
node1.createRelationshipTo( node2, MyRelTypes.TEST );
node1.delete();
try
{
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Should not validate" );
}
catch ( Exception e )
{
// good
}
setTransaction( getGraphDb().beginTx() );
}
public void testDeleteNodeWithRel2()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
node1.createRelationshipTo( node2, MyRelTypes.TEST );
node2.delete();
node1.delete();
try
{
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Should not validate" );
}
catch ( Exception e )
{
// good
}
setTransaction( getGraphDb().beginTx() );
}
public void testDeleteNodeWithRel3()
{
// make sure we can delete in wrong order
Node node0 = getGraphDb().createNode();
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Relationship rel0 = node0.createRelationshipTo( node1, MyRelTypes.TEST );
Relationship rel1 = node0.createRelationshipTo( node2, MyRelTypes.TEST );
node1.delete();
rel0.delete();
Transaction tx = getTransaction();
tx.success();
tx.finish();
setTransaction( getGraphDb().beginTx() );
node2.delete();
rel1.delete();
node0.delete();
}
public void testCreateRelOnDeletedNode()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Transaction tx = getTransaction();
tx.success();
tx.finish();
tx = getGraphDb().beginTx();
node1.delete();
try
{
node1.createRelationshipTo( node2, MyRelTypes.TEST );
fail( "Create of rel on deleted node should fail fast" );
}
catch ( Exception e )
{
}
try
{
tx.failure();
tx.finish();
// fail( "Transaction should be marked rollback" );
}
catch ( Exception e )
{ // good
}
setTransaction( getGraphDb().beginTx() );
node2.delete();
node1.delete();
}
public void testAddPropertyDeletedNode()
{
Node node = getGraphDb().createNode();
node.delete();
try
{
node.setProperty( key, new Integer( 1 ) );
fail( "Add property on deleted node should not validate" );
}
catch ( Exception e )
{
// good
}
}
public void testRemovePropertyDeletedNode()
{
Node node = getGraphDb().createNode();
node.setProperty( key, new Integer( 1 ) );
node.delete();
try
{
node.removeProperty( key );
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Change property on deleted node should not validate" );
}
catch ( Exception e )
{
}
}
public void testChangePropertyDeletedNode()
{
Node node = getGraphDb().createNode();
node.setProperty( key, new Integer( 1 ) );
node.delete();
try
{
node.setProperty( key, new Integer( 2 ) );
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Change property on deleted node should not validate" );
}
catch ( Exception e )
{
}
}
public void testAddPropertyDeletedRelationship()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST );
rel.delete();
try
{
rel.setProperty( key, new Integer( 1 ) );
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Add property on deleted rel should not validate" );
}
catch ( Exception e )
{ // good
}
node1.delete();
node2.delete();
}
public void testRemovePropertyDeletedRelationship()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST );
rel.setProperty( key, new Integer( 1 ) );
rel.delete();
try
{
rel.removeProperty( key );
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Remove property on deleted rel should not validate" );
}
catch ( Exception e )
{
}
node1.delete();
node2.delete();
}
public void testChangePropertyDeletedRelationship()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST );
rel.setProperty( key, new Integer( 1 ) );
rel.delete();
try
{
rel.setProperty( key, new Integer( 2 ) );
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Change property on deleted rel should not validate" );
}
catch ( Exception e )
{
}
node1.delete();
node2.delete();
}
public void testMultipleDeleteNode()
{
Node node1 = getGraphDb().createNode();
node1.delete();
try
{
node1.delete();
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Should not validate" );
}
catch ( Exception e )
{
}
}
public void testMultipleDeleteRelationship()
{
Node node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelTypes.TEST );
rel.delete();
node1.delete();
node2.delete();
try
{
rel.delete();
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Should not validate" );
}
catch ( Exception e )
{
}
}
public void testIllegalPropertyType()
{
Logger log = Logger.getLogger( NodeManager.class.getName() );
Level level = log.getLevel();
log.setLevel( Level.OFF );
try
{
Node node1 = getGraphDb().createNode();
try
{
node1.setProperty( key, new Object() );
fail( "Shouldn't validate" );
}
catch ( Exception e )
{ // good
}
try
{
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Shouldn't validate" );
}
catch ( Exception e )
{
} // good
setTransaction( getGraphDb().beginTx() );
try
{
getGraphDb().getNodeById( (int) node1.getId() );
fail( "Node should not exist, previous tx didn't rollback" );
}
catch ( NotFoundException e )
{
// good
}
node1 = getGraphDb().createNode();
Node node2 = getGraphDb().createNode();
Relationship rel = node1.createRelationshipTo( node2,
MyRelTypes.TEST );
try
{
rel.setProperty( key, new Object() );
fail( "Shouldn't validate" );
}
catch ( Exception e )
{ // good
}
try
{
Transaction tx = getTransaction();
tx.success();
tx.finish();
fail( "Shouldn't validate" );
}
catch ( Exception e )
{
} // good
setTransaction( getGraphDb().beginTx() );
try
{
getGraphDb().getNodeById( (int) node1.getId() );
fail( "Node should not exist, previous tx didn't rollback" );
}
catch ( NotFoundException e )
{
// good
}
try
{
getGraphDb().getNodeById( (int) node2.getId() );
fail( "Node should not exist, previous tx didn't rollback" );
}
catch ( NotFoundException e )
{
// good
}
}
finally
{
log.setLevel( level );
}
}
}
|
package org.appcelerator.titanium.proxy;
import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollFunction;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.KrollRuntime;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.AsyncResult;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.titanium.TiApplication;
import org.appcelerator.titanium.TiBaseActivity;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiDimension;
import org.appcelerator.titanium.util.TiAnimationBuilder;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.util.TiUrl;
import org.appcelerator.titanium.view.TiAnimation;
import org.appcelerator.titanium.view.TiUIView;
import android.app.Activity;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.View;
/**
* The parent class of view proxies.
*/
@Kroll.proxy(propertyAccessors={
// background properties
"backgroundImage", "backgroundRepeat", "backgroundSelectedImage",
"backgroundFocusedImage", "backgroundDisabledImage", "backgroundColor",
"backgroundSelectedColor", "backgroundFocusedColor", "backgroundDisabledColor",
"backgroundPadding", "backgroundGradient",
// border properties
"borderColor", "borderRadius", "borderWidth",
// layout / dimension (size/width/height have custom accessors)
"left", "top", "right", "bottom", "layout", "zIndex",
// others
"focusable", "touchEnabled", "visible", "enabled", "opacity",
"softKeyboardOnFocus", "transform"
})
public abstract class TiViewProxy extends KrollProxy implements Handler.Callback
{
private static final String TAG = "TiViewProxy";
private static final int MSG_FIRST_ID = KrollProxy.MSG_LAST_ID + 1;
private static final int MSG_GETVIEW = MSG_FIRST_ID + 100;
private static final int MSG_ADD_CHILD = MSG_FIRST_ID + 102;
private static final int MSG_REMOVE_CHILD = MSG_FIRST_ID + 103;
private static final int MSG_BLUR = MSG_FIRST_ID + 104;
private static final int MSG_FOCUS = MSG_FIRST_ID + 105;
private static final int MSG_SHOW = MSG_FIRST_ID + 106;
private static final int MSG_HIDE = MSG_FIRST_ID + 107;
private static final int MSG_ANIMATE = MSG_FIRST_ID + 108;
private static final int MSG_TOIMAGE = MSG_FIRST_ID + 109;
private static final int MSG_GETSIZE = MSG_FIRST_ID + 110;
private static final int MSG_GETRECT = MSG_FIRST_ID + 111;
private static final int MSG_FINISH_LAYOUT = MSG_FIRST_ID + 112;
private static final int MSG_UPDATE_LAYOUT = MSG_FIRST_ID + 113;
protected static final int MSG_LAST_ID = MSG_FIRST_ID + 999;
protected ArrayList<TiViewProxy> children;
protected WeakReference<TiViewProxy> parent;
protected TiUIView view;
protected Object pendingAnimationLock;
protected TiAnimationBuilder pendingAnimation;
private boolean isDecorView = false;
// TODO: Deprecated since Release 2.2.0
@Deprecated private AtomicBoolean layoutStarted = new AtomicBoolean();
/**
* Constructs a new TiViewProxy instance.
* @module.api
*/
public TiViewProxy()
{
pendingAnimationLock = new Object();
defaultValues.put(TiC.PROPERTY_BACKGROUND_REPEAT, false);
}
@Override
public void handleCreationDict(KrollDict options)
{
options = handleStyleOptions(options);
super.handleCreationDict(options);
//TODO eventManager.addOnEventChangeListener(this);
}
protected String getBaseUrlForStylesheet()
{
TiUrl creationUrl = getCreationUrl();
String baseUrl = creationUrl.baseUrl;
if (baseUrl == null || (baseUrl.equals("app://") && creationUrl.url.equals(""))) {
baseUrl = "app://app.js";
} else {
baseUrl = creationUrl.resolve();
}
int idx = baseUrl.lastIndexOf("/");
if (idx != -1) {
baseUrl = baseUrl.substring(idx + 1).replace(".js", "");
}
return baseUrl;
}
protected KrollDict handleStyleOptions(KrollDict options)
{
String viewId = getProxyId();
TreeSet<String> styleClasses = new TreeSet<String>();
// TODO styleClasses.add(getShortAPIName().toLowerCase());
if (options.containsKey(TiC.PROPERTY_ID)) {
viewId = TiConvert.toString(options, TiC.PROPERTY_ID);
}
if (options.containsKey(TiC.PROPERTY_CLASS_NAME)) {
String className = TiConvert.toString(options, TiC.PROPERTY_CLASS_NAME);
for (String clazz : className.split(" ")) {
styleClasses.add(clazz);
}
}
if (options.containsKey(TiC.PROPERTY_CLASS_NAMES)) {
Object c = options.get(TiC.PROPERTY_CLASS_NAMES);
if (c.getClass().isArray()) {
int length = Array.getLength(c);
for (int i = 0; i < length; i++) {
Object clazz = Array.get(c, i);
if (clazz != null) {
styleClasses.add(clazz.toString());
}
}
}
}
String baseUrl = getBaseUrlForStylesheet();
KrollDict dict = TiApplication.getInstance().getStylesheet(baseUrl, styleClasses, viewId);
if (dict.size() > 0) {
extend(dict);
}
Log.d(TAG, "trying to get stylesheet for base:" + baseUrl + ",classes:" + styleClasses + ",id:" + viewId + ",dict:"
+ dict, Log.DEBUG_MODE);
if (dict != null) {
// merge in our stylesheet details to the passed in dictionary
// our passed in dictionary takes precedence over the stylesheet
dict.putAll(options);
return dict;
}
return options;
}
public TiAnimationBuilder getPendingAnimation()
{
synchronized(pendingAnimationLock) {
return pendingAnimation;
}
}
public void clearAnimation(TiAnimationBuilder builder)
{
synchronized(pendingAnimationLock) {
if (pendingAnimation != null && pendingAnimation == builder) {
pendingAnimation = null;
}
}
}
//This handler callback is tied to the UI thread.
public boolean handleMessage(Message msg)
{
switch(msg.what) {
case MSG_GETVIEW : {
AsyncResult result = (AsyncResult) msg.obj;
result.setResult(handleGetView());
return true;
}
case MSG_ADD_CHILD : {
AsyncResult result = (AsyncResult) msg.obj;
handleAdd((TiViewProxy) result.getArg());
result.setResult(null); //Signal added.
return true;
}
case MSG_REMOVE_CHILD : {
AsyncResult result = (AsyncResult) msg.obj;
handleRemove((TiViewProxy) result.getArg());
result.setResult(null); //Signal removed.
return true;
}
case MSG_BLUR : {
handleBlur();
return true;
}
case MSG_FOCUS : {
handleFocus();
return true;
}
case MSG_SHOW : {
handleShow((KrollDict) msg.obj);
return true;
}
case MSG_HIDE : {
handleHide((KrollDict) msg.obj);
return true;
}
case MSG_ANIMATE : {
handleAnimate();
return true;
}
case MSG_TOIMAGE: {
AsyncResult result = (AsyncResult) msg.obj;
result.setResult(handleToImage());
return true;
}
case MSG_GETSIZE : {
AsyncResult result = (AsyncResult) msg.obj;
KrollDict d = null;
d = new KrollDict();
d.put(TiC.PROPERTY_X, 0);
d.put(TiC.PROPERTY_Y, 0);
if (view != null) {
View v = view.getNativeView();
if (v != null) {
TiDimension nativeWidth = new TiDimension(v.getWidth(), TiDimension.TYPE_WIDTH);
TiDimension nativeHeight = new TiDimension(v.getHeight(), TiDimension.TYPE_HEIGHT);
// TiDimension needs a view to grab the window manager, so we'll just use the decorview of the current window
View decorView = TiApplication.getAppCurrentActivity().getWindow().getDecorView();
d.put(TiC.PROPERTY_WIDTH, nativeWidth.getAsDefault(decorView));
d.put(TiC.PROPERTY_HEIGHT, nativeHeight.getAsDefault(decorView));
}
}
if (!d.containsKey(TiC.PROPERTY_WIDTH)) {
d.put(TiC.PROPERTY_WIDTH, 0);
d.put(TiC.PROPERTY_HEIGHT, 0);
}
result.setResult(d);
return true;
}
case MSG_GETRECT: {
AsyncResult result = (AsyncResult) msg.obj;
KrollDict d = null;
d = new KrollDict();
if (view != null) {
View v = view.getNativeView();
if (v != null) {
TiDimension nativeWidth = new TiDimension(v.getWidth(), TiDimension.TYPE_WIDTH);
TiDimension nativeHeight = new TiDimension(v.getHeight(), TiDimension.TYPE_HEIGHT);
TiDimension nativeLeft = new TiDimension(v.getLeft(), TiDimension.TYPE_LEFT);
TiDimension nativeTop = new TiDimension(v.getTop(), TiDimension.TYPE_TOP);
// TiDimension needs a view to grab the window manager, so we'll just use the decorview of the current window
View decorView = TiApplication.getAppCurrentActivity().getWindow().getDecorView();
d.put(TiC.PROPERTY_WIDTH, nativeWidth.getAsDefault(decorView));
d.put(TiC.PROPERTY_HEIGHT, nativeHeight.getAsDefault(decorView));
d.put(TiC.PROPERTY_X, nativeLeft.getAsDefault(decorView));
d.put(TiC.PROPERTY_Y, nativeTop.getAsDefault(decorView));
}
}
if (!d.containsKey(TiC.PROPERTY_WIDTH)) {
d.put(TiC.PROPERTY_WIDTH, 0);
d.put(TiC.PROPERTY_HEIGHT, 0);
d.put(TiC.PROPERTY_X, 0);
d.put(TiC.PROPERTY_Y, 0);
}
result.setResult(d);
return true;
}
case MSG_FINISH_LAYOUT : {
handleFinishLayout();
return true;
}
case MSG_UPDATE_LAYOUT : {
handleUpdateLayout((HashMap) msg.obj);
return true;
}
}
return super.handleMessage(msg);
}
/*
public Context getContext()
{
return getActivity();
}
*/
@Kroll.getProperty @Kroll.method
public KrollDict getRect()
{
return (KrollDict) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETRECT), getActivity());
}
@Kroll.getProperty @Kroll.method
public KrollDict getSize()
{
return (KrollDict) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETSIZE), getActivity());
}
@Kroll.getProperty @Kroll.method
public Object getWidth()
{
if (hasProperty(TiC.PROPERTY_WIDTH)) {
return getProperty(TiC.PROPERTY_WIDTH);
}
return KrollRuntime.UNDEFINED;
}
@Kroll.setProperty(retain=false) @Kroll.method
public void setWidth(Object width)
{
setPropertyAndFire(TiC.PROPERTY_WIDTH, width);
}
@Kroll.getProperty @Kroll.method
public Object getHeight()
{
if (hasProperty(TiC.PROPERTY_HEIGHT)) {
return getProperty(TiC.PROPERTY_HEIGHT);
}
return KrollRuntime.UNDEFINED;
}
@Kroll.setProperty(retain=false) @Kroll.method
public void setHeight(Object height)
{
setPropertyAndFire(TiC.PROPERTY_HEIGHT, height);
}
@Kroll.getProperty @Kroll.method
public Object getCenter()
{
Object dict = KrollRuntime.UNDEFINED;
if (hasProperty(TiC.PROPERTY_CENTER)) {
dict = getProperty(TiC.PROPERTY_CENTER);
}
return dict;
}
public void clearView()
{
if (view != null) {
view.release();
}
view = null;
}
/**
* @return the TiUIView associated with this proxy.
* @module.api
*/
public TiUIView peekView()
{
return view;
}
public void setView(TiUIView view)
{
this.view = view;
}
public TiUIView forceCreateView()
{
view = null;
return getOrCreateView();
}
/**
* Creates or retrieves the view associated with this proxy.
* @return a TiUIView instance.
* @module.api
*/
public TiUIView getOrCreateView()
{
if (activity == null || view != null) {
return view;
}
if (TiApplication.isUIThread()) {
return handleGetView();
}
return (TiUIView) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_GETVIEW), 0);
}
protected TiUIView handleGetView()
{
if (view == null) {
Log.d(TAG, "getView: " + getClass().getSimpleName(), Log.DEBUG_MODE);
Activity activity = getActivity();
view = createView(activity);
if (isDecorView) {
if (activity != null) {
((TiBaseActivity)activity).setViewProxy(view.getProxy());
} else {
Log.w(TAG, "Activity is null", Log.DEBUG_MODE);
}
}
realizeViews(view);
view.registerForTouch();
}
return view;
}
public void realizeViews(TiUIView view)
{
setModelListener(view);
// Use a copy so bundle can be modified as it passes up the inheritance
// tree. Allows defaults to be added and keys removed.
if (children != null) {
try {
for (TiViewProxy p : children) {
TiUIView cv = p.getOrCreateView();
view.add(cv);
}
} catch (ConcurrentModificationException e) {
Log.e(TAG, e.getMessage(), e);
}
}
synchronized(pendingAnimationLock) {
if (pendingAnimation != null) {
handlePendingAnimation(true);
}
}
}
public void releaseViews()
{
if (view != null) {
if (children != null) {
for (TiViewProxy p : children) {
p.releaseViews();
}
}
view.release();
view = null;
}
setModelListener(null);
KrollRuntime.suggestGC();
}
/**
* Implementing classes should use this method to create and return the appropriate view.
* @param activity the context activity.
* @return a TiUIView instance.
* @module.api
*/
public abstract TiUIView createView(Activity activity);
/**
* Adds a child to this view proxy.
* @param child The child view proxy to add.
* @module.api
*/
@Kroll.method
public void add(TiViewProxy child)
{
if (child == null) {
Log.e(TAG, "Add called with a null child");
return;
}
if (children == null) {
children = new ArrayList<TiViewProxy>();
}
if (peekView() != null) {
if (TiApplication.isUIThread()) {
handleAdd(child);
return;
}
TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_ADD_CHILD), child);
} else {
children.add(child);
child.parent = new WeakReference<TiViewProxy>(this);
}
//TODO zOrder
}
public void handleAdd(TiViewProxy child)
{
children.add(child);
child.parent = new WeakReference<TiViewProxy>(this);
if (view != null) {
child.setActivity(getActivity());
if (this instanceof DecorViewProxy) {
child.isDecorView = true;
}
TiUIView cv = child.getOrCreateView();
view.add(cv);
}
}
/**
* Removes a view from this view proxy, releasing the underlying native view if it exists.
* @param child The child to remove.
* @module.api
*/
@Kroll.method
public void remove(TiViewProxy child)
{
if (child == null) {
Log.e(TAG, "Add called with null child");
return;
}
if (peekView() != null) {
if (TiApplication.isUIThread()) {
handleRemove(child);
return;
}
TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_REMOVE_CHILD), child);
} else {
if (children != null) {
children.remove(child);
if (child.parent != null && child.parent.get() == this) {
child.parent = null;
}
}
}
}
public void handleRemove(TiViewProxy child)
{
if (children != null) {
children.remove(child);
if (view != null) {
view.remove(child.peekView());
}
if (child != null) {
child.releaseViews();
}
}
}
@Kroll.method
public void show(@Kroll.argument(optional=true) KrollDict options)
{
if (TiApplication.isUIThread()) {
handleShow(options);
} else {
getMainHandler().obtainMessage(MSG_SHOW, options).sendToTarget();
}
}
protected void handleShow(KrollDict options)
{
if (view != null) {
view.show();
setProperty(TiC.PROPERTY_VISIBLE, true);
}
}
@Kroll.method
public void hide(@Kroll.argument(optional=true) KrollDict options)
{
if (TiApplication.isUIThread()) {
handleHide(options);
} else {
getMainHandler().obtainMessage(MSG_HIDE, options).sendToTarget();
}
}
protected void handleHide(KrollDict options)
{
if (view != null) {
synchronized(pendingAnimationLock) {
if (pendingAnimation != null) {
handlePendingAnimation(false);
}
}
view.hide();
setProperty(TiC.PROPERTY_VISIBLE, false);
}
}
@Kroll.method
public void animate(Object arg, @Kroll.argument(optional=true) KrollFunction callback)
{
synchronized (pendingAnimationLock) {
if (arg instanceof HashMap) {
HashMap options = (HashMap) arg;
pendingAnimation = new TiAnimationBuilder();
pendingAnimation.applyOptions(options);
if (callback != null) {
pendingAnimation.setCallback(callback);
}
} else if (arg instanceof TiAnimation) {
TiAnimation anim = (TiAnimation) arg;
pendingAnimation = new TiAnimationBuilder();
pendingAnimation.applyAnimation(anim);
} else {
throw new IllegalArgumentException("Unhandled argument to animate: " + arg.getClass().getSimpleName());
}
handlePendingAnimation(false);
}
}
public void handlePendingAnimation(boolean forceQueue)
{
if (pendingAnimation != null && peekView() != null) {
if (forceQueue || !(TiApplication.isUIThread())) {
if (Build.VERSION.SDK_INT < TiC.API_LEVEL_HONEYCOMB) {
// Even this very small delay can help eliminate the bug
// whereby the animated view's parent suddenly becomes
// transparent (pre-honeycomb). cf. TIMOB-9813.
getMainHandler().sendEmptyMessageDelayed(MSG_ANIMATE, 10);
} else {
getMainHandler().sendEmptyMessage(MSG_ANIMATE);
}
} else {
handleAnimate();
}
}
}
protected void handleAnimate()
{
TiUIView tiv = peekView();
if (tiv != null) {
tiv.animate();
}
}
@Kroll.method
public void blur()
{
if (TiApplication.isUIThread()) {
handleBlur();
} else {
getMainHandler().sendEmptyMessage(MSG_BLUR);
}
}
protected void handleBlur()
{
if (view != null) {
view.blur();
}
}
@Kroll.method
public void focus()
{
if (TiApplication.isUIThread()) {
handleFocus();
} else {
getMainHandler().sendEmptyMessage(MSG_FOCUS);
}
}
protected void handleFocus()
{
if (view != null) {
view.focus();
}
}
@Kroll.method
public KrollDict toImage()
{
if (TiApplication.isUIThread()) {
return handleToImage();
} else {
return (KrollDict) TiMessenger.sendBlockingMainMessage(getMainHandler().obtainMessage(MSG_TOIMAGE), getActivity());
}
}
protected KrollDict handleToImage()
{
TiUIView view = getOrCreateView();
if (view == null) {
return null;
}
return view.toImage();
}
/**
* Fires an event that can optionally be "bubbled" to the parent view.
* @param eventName event to get dispatched to listeners
* @param data data to include in the event
* @param bubbles if true will send the event to the parent view after it has been dispatched to this view's listeners.
* @return true if the event was handled
*/
public boolean fireEvent(String eventName, Object data, boolean bubbles)
{
if (data == null) {
data = new KrollDict();
}
// Dispatch the event to JavaScript first before we "bubble" it to the parent view.
boolean handled = super.fireEvent(eventName, data);
if (!bubbles) {
return handled;
}
TiViewProxy parentView = getParent();
if (parentView != null) {
handled = parentView.fireEvent(eventName, data) || handled;
}
return handled;
}
/**
* Fires an event that will be bubbled to the parent view.
*/
@Override
public boolean fireEvent(String eventName, Object data)
{
// To remain compatible this override of fireEvent will always
// bubble the event to the parent view. It should eventually be deprecated
// in favor of using the fireEvent(String, Object, boolean) method.
return fireEvent(eventName, data, true);
}
/**
* @return The parent view proxy of this view proxy.
* @module.api
*/
@Kroll.getProperty @Kroll.method
public TiViewProxy getParent()
{
if (this.parent == null) {
return null;
}
return this.parent.get();
}
public void setParent(TiViewProxy parent)
{
this.parent = new WeakReference<TiViewProxy>(parent);
}
@Override
public void setActivity(Activity activity)
{
super.setActivity(activity);
if (children != null) {
for (TiViewProxy child : children) {
child.setActivity(activity);
}
}
}
/**
* @return An array of the children view proxies of this view.
* @module.api
*/
@Kroll.getProperty @Kroll.method
public TiViewProxy[] getChildren()
{
if (children == null) return new TiViewProxy[0];
return children.toArray(new TiViewProxy[children.size()]);
}
@Override
public void eventListenerAdded(String eventName, int count, KrollProxy proxy)
{
super.eventListenerAdded(eventName, count, proxy);
if (eventName.equals(TiC.EVENT_CLICK) && proxy.equals(this) && count == 1 && !(proxy instanceof TiWindowProxy)) {
if (!proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)
|| TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED))) {
setClickable(true);
}
}
}
@Override
public void eventListenerRemoved(String eventName, int count, KrollProxy proxy)
{
super.eventListenerRemoved(eventName, count, proxy);
if (eventName.equals(TiC.EVENT_CLICK) && count == 0 && proxy.equals(this) && !(proxy instanceof TiWindowProxy)) {
if (proxy.hasProperty(TiC.PROPERTY_TOUCH_ENABLED)
&& !TiConvert.toBoolean(proxy.getProperty(TiC.PROPERTY_TOUCH_ENABLED))) {
setClickable(false);
}
}
}
/**
* Return true if any view in the hierarchy has the event listener.
*/
public boolean hierarchyHasListener(String eventName)
{
boolean hasListener = hasListeners(eventName);
// Check whether the parent has the listener or not
if (!hasListener) {
TiViewProxy parent = getParent();
if (parent != null) {
boolean parentHasListener = parent.hierarchyHasListener(eventName);
hasListener = hasListener || parentHasListener;
if (hasListener) {
return hasListener;
}
}
}
return hasListener;
}
public void setClickable(boolean clickable)
{
TiUIView v = peekView();
if (v != null) {
View nv = v.getNativeView();
if (nv != null) {
nv.setClickable(clickable);
}
}
}
@Kroll.method
public void addClass(Object[] classNames)
{
// This is a pretty naive implementation right now,
// but it will work for our current needs
String baseUrl = getBaseUrlForStylesheet();
ArrayList<String> classes = new ArrayList<String>();
for (Object c : classNames) {
classes.add(TiConvert.toString(c));
}
KrollDict options = TiApplication.getInstance().getStylesheet(baseUrl, classes, null);
extend(options);
}
@Kroll.method @Kroll.getProperty
public boolean getKeepScreenOn()
{
Boolean keepScreenOn = null;
TiUIView v = peekView();
if (v != null) {
View nv = v.getNativeView();
if (nv != null) {
keepScreenOn = nv.getKeepScreenOn();
}
}
//Keep the proxy in the correct state
Object current = getProperty(TiC.PROPERTY_KEEP_SCREEN_ON);
if (current != null) {
boolean currentValue = TiConvert.toBoolean(current);
if (keepScreenOn == null) {
keepScreenOn = currentValue;
} else {
if (currentValue != keepScreenOn) {
setProperty(TiC.PROPERTY_KEEP_SCREEN_ON, keepScreenOn);
} else {
keepScreenOn = currentValue;
}
}
} else {
if (keepScreenOn == null) {
keepScreenOn = false; // Android default
}
setProperty(TiC.PROPERTY_KEEP_SCREEN_ON, keepScreenOn);
}
return keepScreenOn;
}
@Kroll.method @Kroll.setProperty(retain=false)
public void setKeepScreenOn(boolean keepScreenOn)
{
setPropertyAndFire(TiC.PROPERTY_KEEP_SCREEN_ON, keepScreenOn);
}
@Kroll.method
public KrollDict convertPointToView(KrollDict point, TiViewProxy dest)
{
if (point == null) {
throw new IllegalArgumentException("convertPointToView: point must not be null");
}
if (dest == null) {
throw new IllegalArgumentException("convertPointToView: destinationView must not be null");
}
if (!point.containsKey(TiC.PROPERTY_X)) {
throw new IllegalArgumentException("convertPointToView: required property \"x\" not found in point");
}
if (!point.containsKey(TiC.PROPERTY_Y)) {
throw new IllegalArgumentException("convertPointToView: required property \"y\" not found in point");
}
// The spec says to throw an exception if x or y cannot be converted to numbers.
// TiConvert does that automatically for us.
int x = TiConvert.toInt(point, TiC.PROPERTY_X);
int y = TiConvert.toInt(point, TiC.PROPERTY_Y);
TiUIView view = peekView();
TiUIView destView = dest.peekView();
if (view == null) {
Log.w(TAG, "convertPointToView: View has not been attached, cannot convert point");
return null;
}
if (destView == null) {
Log.w(TAG, "convertPointToView: DestinationView has not been attached, cannot convert point");
return null;
}
View nativeView = view.getNativeView();
View destNativeView = destView.getNativeView();
if (nativeView == null || nativeView.getParent() == null) {
Log.w(TAG, "convertPointToView: View has not been attached, cannot convert point");
return null;
}
if (destNativeView == null || destNativeView.getParent() == null) {
Log.w(TAG, "convertPointToView: DestinationView has not been attached, cannot convert point");
return null;
}
int viewLocation[] = new int[2];
int destLocation[] = new int[2];
nativeView.getLocationInWindow(viewLocation);
destNativeView.getLocationInWindow(destLocation);
Log.d(TAG, "nativeView location in window, x: " + viewLocation[0] + ", y: " + viewLocation[1], Log.DEBUG_MODE);
Log.d(TAG, "destNativeView location in window, x: " + destLocation[0] + ", y: " + destLocation[1], Log.DEBUG_MODE);
int pointWindowX = viewLocation[0] + x;
int pointWindowY = viewLocation[1] + y;
KrollDict destPoint = new KrollDict();
destPoint.put(TiC.PROPERTY_X, pointWindowX - destLocation[0]);
destPoint.put(TiC.PROPERTY_Y, pointWindowY - destLocation[1]);
return destPoint;
}
// TODO: Deprecated since Release 2.2.0
@Kroll.method @Deprecated
public void startLayout()
{
Log.w(TAG, "startLayout() is deprecated.", Log.DEBUG_MODE);
layoutStarted.set(true);
}
// TODO: Deprecated since Release 2.2.0
@Kroll.method @Deprecated
public void finishLayout()
{
Log.w(TAG, "finishLayout() is deprecated.", Log.DEBUG_MODE);
// Don't force a layout if startLayout() was never called
if (!isLayoutStarted()) {
return;
}
if (TiApplication.isUIThread()) {
handleFinishLayout();
} else {
getMainHandler().sendEmptyMessage(MSG_FINISH_LAYOUT);
}
layoutStarted.set(false);
}
// TODO: Deprecated since Release 2.2.0
@Kroll.method @Deprecated
public void updateLayout(Object params)
{
Log.w(TAG, "updateLayout() is deprecated.", Log.DEBUG_MODE);
HashMap<String, Object> paramsMap;
if (!(params instanceof HashMap)) {
Log.e(TAG, "Argument for updateLayout must be a dictionary");
return;
}
paramsMap = (HashMap) params;
layoutStarted.set(true);
if (TiApplication.isUIThread()) {
handleUpdateLayout(paramsMap);
} else {
getMainHandler().obtainMessage(MSG_UPDATE_LAYOUT, paramsMap).sendToTarget();
}
layoutStarted.set(false);
}
private void handleFinishLayout()
{
if (view.iszIndexChanged()) {
view.forceLayoutNativeView(true);
view.setzIndexChanged(false);
} else {
view.forceLayoutNativeView(false);
}
}
private void handleUpdateLayout(HashMap<String, Object> params)
{
for (String key : params.keySet()) {
setPropertyAndFire(key, params.get(key));
}
handleFinishLayout();
}
// TODO: Deprecated since Release 2.2.0
// This is used to check if the user has called startLayout(). We mainly use this to perform a check before running
// deprecated behavior. (i.e. performing layout when a property has changed, and the user didn't call startLayout)
@Deprecated
public boolean isLayoutStarted()
{
return layoutStarted.get();
}
}
|
package com.emc.mongoose.storage.driver.net.http.emc.s3;
import com.emc.mongoose.api.common.exception.OmgShootMyFootException;
import com.emc.mongoose.api.model.data.DataInput;
import com.emc.mongoose.api.model.io.IoType;
import com.emc.mongoose.api.model.io.task.IoTask;
import com.emc.mongoose.api.model.io.task.data.DataIoTask;
import com.emc.mongoose.api.model.item.DataItem;
import com.emc.mongoose.api.model.item.Item;
import com.emc.mongoose.api.model.storage.Credential;
import com.emc.mongoose.storage.driver.net.http.amzs3.AmzS3StorageDriver;
import com.emc.mongoose.ui.config.load.LoadConfig;
import com.emc.mongoose.ui.config.storage.StorageConfig;
import com.emc.mongoose.ui.log.LogUtil;
import com.emc.mongoose.ui.log.Loggers;
import static com.emc.mongoose.storage.driver.net.http.amzs3.AmzS3Api.HEADERS_CANONICAL;
import static com.emc.mongoose.storage.driver.net.http.amzs3.AmzS3Api.PREFIX_KEY_X_AMZ;
import static com.emc.mongoose.storage.driver.net.http.amzs3.AmzS3Api.URL_ARG_VERSIONING;
import static com.emc.mongoose.storage.driver.net.http.amzs3.AmzS3Api.VERSIONING_DISABLE_CONTENT;
import static com.emc.mongoose.storage.driver.net.http.amzs3.AmzS3Api.VERSIONING_ENABLE_CONTENT;
import static com.emc.mongoose.storage.driver.net.http.emc.base.EmcConstants.KEY_X_EMC_FILESYSTEM_ACCESS_ENABLED;
import static com.emc.mongoose.storage.driver.net.http.emc.base.EmcConstants.KEY_X_EMC_MULTIPART_COPY;
import static com.emc.mongoose.storage.driver.net.http.emc.base.EmcConstants.KEY_X_EMC_NAMESPACE;
import static com.emc.mongoose.storage.driver.net.http.emc.base.EmcConstants.PREFIX_KEY_X_EMC;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
import com.github.akurilov.commons.collection.Range;
import com.github.akurilov.commons.math.Random;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.EmptyHttpHeaders;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpStatusClass;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.AsciiString;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.Level;
import java.io.IOException;
import java.net.ConnectException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CancellationException;
public class EmcS3StorageDriver<I extends Item, O extends IoTask<I>>
extends AmzS3StorageDriver<I, O> {
private static final ThreadLocal<StringBuilder>
BUFF_CANONICAL = ThreadLocal.withInitial(StringBuilder::new);
private static final ThreadLocal<MessageDigest>
MD5_DIGEST = ThreadLocal.withInitial(DigestUtils::getMd5Digest);
private final Random rnd = new Random();
public EmcS3StorageDriver(
final String jobName, final DataInput contentSrc, final LoadConfig loadConfig,
final StorageConfig storageConfig, final boolean verifyFlag
) throws OmgShootMyFootException, InterruptedException {
super(jobName, contentSrc, loadConfig, storageConfig, verifyFlag);
}
@Override
protected String requestNewPath(final String path) {
// check the destination bucket if it exists w/ HEAD request
final String nodeAddr = storageNodeAddrs[0];
final HttpHeaders reqHeaders = new DefaultHttpHeaders();
reqHeaders.set(HttpHeaderNames.HOST, nodeAddr);
reqHeaders.set(HttpHeaderNames.CONTENT_LENGTH, 0);
reqHeaders.set(HttpHeaderNames.DATE, DATE_SUPPLIER.get());
applyDynamicHeaders(reqHeaders);
applySharedHeaders(reqHeaders);
final Credential credential = pathToCredMap.getOrDefault(path, this.credential);
applyAuthHeaders(reqHeaders, HttpMethod.HEAD, path, credential);
final FullHttpRequest checkBucketReq = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.HEAD, path, Unpooled.EMPTY_BUFFER, reqHeaders,
EmptyHttpHeaders.INSTANCE
);
final FullHttpResponse checkBucketResp;
try {
checkBucketResp = executeHttpRequest(checkBucketReq);
} catch(final InterruptedException e) {
throw new CancellationException();
} catch(final ConnectException e) {
LogUtil.exception(Level.WARN, e, "Failed to connect to the storage node");
return null;
}
boolean bucketExistedBefore = true;
if(checkBucketResp != null) {
if(HttpResponseStatus.NOT_FOUND.equals(checkBucketResp.status())) {
bucketExistedBefore = false;
} else if(!HttpStatusClass.SUCCESS.equals(checkBucketResp.status().codeClass())) {
Loggers.ERR.warn(
"The bucket checking response is: {}", checkBucketResp.status().toString()
);
}
checkBucketResp.release();
}
// create the destination bucket if it doesn't exists
if(!bucketExistedBefore) {
if(fsAccess) {
reqHeaders.add(
KEY_X_EMC_FILESYSTEM_ACCESS_ENABLED, Boolean.toString(true)
);
}
applyMetaDataHeaders(reqHeaders);
applyAuthHeaders(reqHeaders, HttpMethod.PUT, path, credential);
final FullHttpRequest putBucketReq = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.PUT, path, Unpooled.EMPTY_BUFFER, reqHeaders,
EmptyHttpHeaders.INSTANCE
);
final FullHttpResponse putBucketResp;
try {
putBucketResp = executeHttpRequest(putBucketReq);
} catch(final InterruptedException e) {
throw new CancellationException();
} catch(final ConnectException e) {
LogUtil.exception(Level.WARN, e, "Failed to connect to the storage node");
return null;
}
if(!HttpStatusClass.SUCCESS.equals(putBucketResp.status().codeClass())) {
Loggers.ERR.warn(
"The bucket creating response is: {}", putBucketResp.status().toString()
);
return null;
}
putBucketResp.release();
if(fsAccess) {
reqHeaders.remove(KEY_X_EMC_FILESYSTEM_ACCESS_ENABLED);
}
}
// check the bucket versioning state
final String bucketVersioningReqUri = path + "?" + URL_ARG_VERSIONING;
applyAuthHeaders(reqHeaders, HttpMethod.GET, bucketVersioningReqUri, credential);
final FullHttpRequest getBucketVersioningReq = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.GET, bucketVersioningReqUri, Unpooled.EMPTY_BUFFER,
reqHeaders, EmptyHttpHeaders.INSTANCE
);
final FullHttpResponse getBucketVersioningResp;
try {
getBucketVersioningResp = executeHttpRequest(getBucketVersioningReq);
} catch(final InterruptedException e) {
throw new CancellationException();
} catch(final ConnectException e) {
LogUtil.exception(Level.WARN, e, "Failed to connect to the storage node");
return null;
}
final boolean versioningEnabled;
if(!HttpStatusClass.SUCCESS.equals(getBucketVersioningResp.status().codeClass())) {
Loggers.ERR.warn(
"The bucket versioning checking response is: {}",
getBucketVersioningResp.status().toString()
);
return null;
} else {
final String content = getBucketVersioningResp
.content()
.toString(StandardCharsets.US_ASCII);
versioningEnabled = content.contains("Enabled");
}
getBucketVersioningResp.release();
final FullHttpRequest putBucketVersioningReq;
if(!versioning && versioningEnabled) {
// disable bucket versioning
reqHeaders.set(HttpHeaderNames.CONTENT_LENGTH, VERSIONING_DISABLE_CONTENT.length);
applyAuthHeaders(reqHeaders, HttpMethod.PUT, bucketVersioningReqUri, credential);
putBucketVersioningReq = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.PUT, bucketVersioningReqUri,
Unpooled.wrappedBuffer(VERSIONING_DISABLE_CONTENT).retain(), reqHeaders,
EmptyHttpHeaders.INSTANCE
);
final FullHttpResponse putBucketVersioningResp;
try {
putBucketVersioningResp = executeHttpRequest(putBucketVersioningReq);
} catch(final InterruptedException e) {
throw new CancellationException();
} catch(final ConnectException e) {
LogUtil.exception(Level.WARN, e, "Failed to connect to the storage node");
return null;
}
if(!HttpStatusClass.SUCCESS.equals(putBucketVersioningResp.status().codeClass())) {
Loggers.ERR.warn("The bucket versioning setting response is: {}",
putBucketVersioningResp.status().toString()
);
putBucketVersioningResp.release();
return null;
}
putBucketVersioningResp.release();
} else if(versioning && !versioningEnabled) {
// enable bucket versioning
reqHeaders.set(HttpHeaderNames.CONTENT_LENGTH, VERSIONING_ENABLE_CONTENT.length);
applyAuthHeaders(reqHeaders, HttpMethod.PUT, bucketVersioningReqUri, credential);
putBucketVersioningReq = new DefaultFullHttpRequest(
HttpVersion.HTTP_1_1, HttpMethod.PUT, bucketVersioningReqUri,
Unpooled.wrappedBuffer(VERSIONING_ENABLE_CONTENT).retain(), reqHeaders,
EmptyHttpHeaders.INSTANCE
);
final FullHttpResponse putBucketVersioningResp;
try {
putBucketVersioningResp = executeHttpRequest(putBucketVersioningReq);
} catch(final InterruptedException e) {
throw new CancellationException();
} catch(final ConnectException e) {
LogUtil.exception(Level.WARN, e, "Failed to connect to the storage node");
return null;
}
if(!HttpStatusClass.SUCCESS.equals(putBucketVersioningResp.status().codeClass())) {
Loggers.ERR.warn("The bucket versioning setting response is: {}",
putBucketVersioningResp.status().toString()
);
putBucketVersioningResp.release();
return null;
}
putBucketVersioningResp.release();
}
return path;
}
@Override
protected void applyMetaDataHeaders(final HttpHeaders httpHeaders) {
if(namespace != null && !namespace.isEmpty()) {
httpHeaders.set(KEY_X_EMC_NAMESPACE, namespace);
}
}
@Override
protected String getCanonical(
final HttpHeaders httpHeaders, final HttpMethod httpMethod, final String dstUriPath
) {
final StringBuilder buffCanonical = BUFF_CANONICAL.get();
buffCanonical.setLength(0); // reset/clear
buffCanonical.append(httpMethod.name());
for(final AsciiString headerName : HEADERS_CANONICAL) {
if(httpHeaders.contains(headerName)) {
for(final String headerValue: httpHeaders.getAll(headerName)) {
buffCanonical.append('\n').append(headerValue);
}
} else if(sharedHeaders != null && sharedHeaders.contains(headerName)) {
buffCanonical.append('\n').append(sharedHeaders.get(headerName));
} else {
buffCanonical.append('\n');
}
}
// x-amz-*, x-emc-*
String headerName;
Map<String, String> sortedHeaders = new TreeMap<>();
if(sharedHeaders != null) {
for(final Map.Entry<String, String> header : sharedHeaders) {
headerName = header.getKey().toLowerCase();
if(
headerName.startsWith(PREFIX_KEY_X_AMZ) ||
headerName.startsWith(PREFIX_KEY_X_EMC)
) {
sortedHeaders.put(headerName, header.getValue());
}
}
}
for(final Map.Entry<String, String> header : httpHeaders) {
headerName = header.getKey().toLowerCase();
if(headerName.startsWith(PREFIX_KEY_X_AMZ) || headerName.startsWith(PREFIX_KEY_X_EMC)) {
sortedHeaders.put(headerName, header.getValue());
}
}
for(final Map.Entry<String, String> sortedHeader : sortedHeaders.entrySet()) {
buffCanonical
.append('\n').append(sortedHeader.getKey())
.append(':').append(sortedHeader.getValue());
}
buffCanonical.append('\n');
buffCanonical.append(dstUriPath);
if(Loggers.MSG.isTraceEnabled()) {
Loggers.MSG.trace("Canonical representation:\n{}", buffCanonical);
}
return buffCanonical.toString();
}
@Override
public String toString() {
return super.toString().replace("amzs3", "emcs3");
}
@Override
protected HttpRequest getHttpRequest(final O ioTask, final String nodeAddr)
throws URISyntaxException {
if(IoType.CREATE.equals(ioTask.getIoType()) && ioTask instanceof DataIoTask) {
final DataIoTask dataIoTask = (DataIoTask) ioTask;
final List<DataItem> srcItemsToConcat = dataIoTask.getSrcItemsToConcat();
if(srcItemsToConcat != null) {
try {
return getCopyRangesRequest(dataIoTask, nodeAddr, srcItemsToConcat);
} catch(final IOException e) {
throw new AssertionError(e);
}
} else {
return super.getHttpRequest(ioTask, nodeAddr);
}
} else {
return super.getHttpRequest(ioTask, nodeAddr);
}
}
// ECS/S3 Copy Ranges API support
private final static ThreadLocal<StringBuilder>
THREAD_LOCAL_STRB = ThreadLocal.withInitial(StringBuilder::new);
private FullHttpRequest getCopyRangesRequest(
final DataIoTask dataIoTask, final String nodeAddr, final List<DataItem> srcItemsToConcat
) throws IOException {
final List<Range> fixedRanges = dataIoTask.getFixedRanges();
final int randomRangesCount = dataIoTask.getRandomRangesCount();
final DataItem dstItem = dataIoTask.getItem();
DataItem srcItem;
String srcItemPath;
long dstItemSize = 0;
// request content
final StringBuilder content = THREAD_LOCAL_STRB.get();
content.setLength(0);
content
.append("{\n\t\"content_type\": \"application/octet-stream\",\n\t\"segments\": [\n");
if(fixedRanges == null || fixedRanges.isEmpty()) {
if(randomRangesCount > 0) {
long nextSrcItemSize, srcItemCellSize, srcItemCellStartPos, rangeStart, rangeEnd;
for(int i = 0; i < srcItemsToConcat.size(); i ++) {
srcItem = srcItemsToConcat.get(i);
srcItemPath = srcItem.getName();
if(srcItemPath.charAt(0) == '/') {
srcItemPath = srcItemPath.substring(1);
}
content
.append("\t\t{\n\t\t\t\"path\": \"")
.append(srcItemPath)
.append("\",\n");
nextSrcItemSize = srcItem.size();
srcItemCellSize = nextSrcItemSize / randomRangesCount;
if(srcItemCellSize > 0) {
content.append("\t\t\t\"range\": \"");
for(int j = 0; j < randomRangesCount; j ++) {
srcItemCellStartPos = j * srcItemCellSize;
rangeStart = srcItemCellStartPos
+ rnd.nextLong(srcItemCellSize / 2);
rangeEnd = rangeStart
+ rnd.nextLong(
srcItemCellStartPos + srcItemCellSize - rangeStart - 1
);
content.append(rangeStart).append('-').append(rangeEnd);
if(j < randomRangesCount - 1) {
content.append(',');
}
dstItemSize += rangeEnd - rangeStart + 1;
}
content.append("\"\n\t\t}");
}
if(i < srcItemsToConcat.size() - 1) {
content.append(',');
}
content.append('\n');
}
} else {
for(int i = 0; i < srcItemsToConcat.size(); i ++) {
srcItem = srcItemsToConcat.get(i);
srcItemPath = srcItem.getName();
if(srcItemPath.charAt(0) == '/') {
srcItemPath = srcItemPath.substring(1);
}
content
.append("\t\t{\n\t\t\t\"path\": \"")
.append(srcItemPath)
.append("\"\n\t\t}");
if(i < srcItemsToConcat.size() - 1) {
content.append(',');
}
dstItemSize += srcItem.size();
content.append('\n');
}
}
} else {
final int n = srcItemsToConcat.size();
for(int i = 0; i < n; i ++) {
srcItem = srcItemsToConcat.get(i);
srcItemPath = srcItem.getName();
if(srcItemPath.charAt(0) == '/') {
srcItemPath = srcItemPath.substring(1);
}
content
.append("\t\t{\n\t\t\t\"path\": \"")
.append(srcItemPath)
.append("\",\n")
.append("\t\t\t\"range\": \"");
rangeListToStringBuff(fixedRanges, srcItem.size(), content);
content.append("\"\n\t\t}");
if(i < srcItemsToConcat.size() - 1) {
content.append(',');
}
content.append('\n');
}
dstItemSize = dataIoTask.getMarkedRangesSize() * n;
}
content.append("\t]\n}\n");
// set the total summary size for the destination item
dstItem.size(dstItemSize);
// request headers
final HttpHeaders httpHeaders = new DefaultHttpHeaders();
httpHeaders.set(HttpHeaderNames.HOST, nodeAddr);
httpHeaders.set(HttpHeaderNames.DATE, DATE_SUPPLIER.get());
httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, content.length());
httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON);
httpHeaders.set(KEY_X_EMC_MULTIPART_COPY, "true");
applyMetaDataHeaders(httpHeaders);
applyDynamicHeaders(httpHeaders);
applySharedHeaders(httpHeaders);
// request content and its hash (required)
final byte[] contentBytes = content.toString().getBytes();
final MessageDigest md5Digest = MD5_DIGEST.get();
md5Digest.reset();
final byte[] contentMd5Bytes = md5Digest.digest(contentBytes);
final String contentMd5EncodedHash = new String(Base64.encodeBase64(contentMd5Bytes));
httpHeaders.set(HttpHeaderNames.CONTENT_MD5, contentMd5EncodedHash);
final HttpMethod httpMethod = HttpMethod.PUT;
final String uriPath = getDataUriPath(
(I) dstItem, dataIoTask.getSrcPath(), dataIoTask.getDstPath(), IoType.CREATE
);
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(
HTTP_1_1, httpMethod, uriPath, Unpooled.wrappedBuffer(contentBytes),
httpHeaders, EmptyHttpHeaders.INSTANCE
);
// remaining request headers
applyAuthHeaders(httpHeaders, httpMethod, uriPath, dataIoTask.getCredential());
return httpRequest;
}
}
|
package org.jenkinsci.plugins.workflow.actions;
import hudson.model.Action;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
/**
* Action to add timestamp metadata to a {@link FlowNode}.
*
* @author <a href="mailto:tom.fennelly@gmail.com">tom.fennelly@gmail.com</a>
*/
public class TimingAction implements Action {
private final long startTime = System.currentTimeMillis();
public long getStartTime() {
return startTime;
}
public static long getStartTime(FlowNode flowNode) {
TimingAction timingAction = flowNode.getAction(TimingAction.class);
if (timingAction != null) {
return timingAction.getStartTime();
} else {
return 0;
}
}
@Override
public String getIconFileName() {
return null;
}
@Override
public String getDisplayName() {
return "Timing";
}
@Override
public String getUrlName() {
return null;
}
}
|
package org.cytoscape.app.internal.ui;
import static javax.swing.GroupLayout.DEFAULT_SIZE;
import static javax.swing.GroupLayout.PREFERRED_SIZE;
import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.swing.ComboBoxEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.html.HTMLDocument;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.cytoscape.app.internal.event.AppsChangedEvent;
import org.cytoscape.app.internal.event.AppsChangedListener;
import org.cytoscape.app.internal.manager.App.AppStatus;
import org.cytoscape.app.internal.manager.AppManager;
import org.cytoscape.app.internal.net.ResultsFilterer;
import org.cytoscape.app.internal.net.WebApp;
import org.cytoscape.app.internal.net.WebQuerier;
import org.cytoscape.app.internal.net.WebQuerier.AppTag;
import org.cytoscape.app.internal.task.InstallAppsFromFileTask;
import org.cytoscape.app.internal.task.InstallAppsFromWebAppTask;
import org.cytoscape.app.internal.task.ShowInstalledAppsTask;
import org.cytoscape.app.internal.ui.downloadsites.DownloadSite;
import org.cytoscape.app.internal.ui.downloadsites.DownloadSitesManager;
import org.cytoscape.app.internal.ui.downloadsites.DownloadSitesManager.DownloadSitesChangedEvent;
import org.cytoscape.app.internal.ui.downloadsites.DownloadSitesManager.DownloadSitesChangedListener;
import org.cytoscape.application.CyUserLog;
import org.cytoscape.util.swing.FileChooserFilter;
import org.cytoscape.util.swing.FileUtil;
import org.cytoscape.util.swing.LookAndFeelUtil;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskManager;
import org.cytoscape.work.TaskMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class represents the panel in the App Manager dialog's tab used for installing new apps.
*/
@SuppressWarnings("serial")
public class InstallAppsPanel extends JPanel {
private static final Logger logger = LoggerFactory.getLogger(CyUserLog.NAME);
private JPanel descriptionPanel;
private JScrollPane descriptionScrollPane;
private JSplitPane descriptionSplitPane;
private JTextPane descriptionTextPane;
private JComboBox downloadSiteComboBox;
private JLabel downloadSiteLabel;
private JTextField filterTextField;
private JButton installButton;
private JButton installFromFileButton;
private JButton manageSitesButton;
private JScrollPane resultsScrollPane;
private JTree resultsTree;
private JLabel searchAppsLabel;
private JScrollPane tagsScrollPane;
private JSplitPane tagsSplitPane;
private JTree tagsTree;
private JButton viewOnAppStoreButton;
private JFileChooser fileChooser;
private AppManager appManager;
private DownloadSitesManager downloadSitesManager;
private FileUtil fileUtil;
private TaskManager taskManager;
private Container parent;
private WebApp selectedApp;
private WebQuerier.AppTag currentSelectedAppTag;
private Set<WebApp> resultsTreeApps;
public InstallAppsPanel(
final AppManager appManager,
final DownloadSitesManager downloadSitesManager,
final FileUtil fileUtil,
final TaskManager taskManager,
final Container parent
) {
this.appManager = appManager;
this.downloadSitesManager = downloadSitesManager;
this.fileUtil = fileUtil;
this.taskManager = taskManager;
this.parent = parent;
initComponents();
tagsTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
updateResultsTree();
updateDescriptionBox();
}
});
resultsTree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
updateDescriptionBox();
}
});
setupTextFieldListener();
setupDownloadSitesChangedListener();
//queryForApps();
appManager.addAppListener(new AppsChangedListener() {
@Override
public void appsChanged(AppsChangedEvent event) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TreePath[] selectionPaths = resultsTree.getSelectionPaths();
updateDescriptionBox();
fillResultsTree(resultsTreeApps);
resultsTree.setSelectionPaths(selectionPaths);
}
});
}
});
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
queryForApps();
}
});
}
private void setupDownloadSitesChangedListener() {
downloadSitesManager.addDownloadSitesChangedListener(new DownloadSitesChangedListener() {
@Override
public void downloadSitesChanged(DownloadSitesChangedEvent downloadSitesChangedEvent) {
final DefaultComboBoxModel defaultComboBoxModel = new DefaultComboBoxModel(
new Vector<DownloadSite>(downloadSitesManager.getDownloadSites()));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
downloadSiteComboBox.setModel(defaultComboBoxModel);
}
});
}
});
}
private boolean hasTagTreeBeenPopulated = false;
// Queries the currently set app store url for available apps.
private void queryForApps() {
if (hasTagTreeBeenPopulated)
return;
final WebQuerier webQuerier = appManager.getWebQuerier();
taskManager.execute(new TaskIterator(new Task() {
// Obtain information for all available apps, then append tag information
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
taskMonitor.setTitle("Getting available apps");
taskMonitor.setStatusMessage("Obtaining apps from: "
+ webQuerier.getCurrentAppStoreUrl());
Set<WebApp> availableApps = webQuerier.getAllApps();
if (availableApps == null)
return;
// Once the information is obtained, update the tree
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// populateTree(appManager.getWebQuerier().getAllApps());
buildTagsTree();
fillResultsTree(appManager.getWebQuerier().getAllApps());
}
});
}
@Override
public void cancel() {
}
}));
}
private void initComponents() {
searchAppsLabel = new JLabel("Search:");
installFromFileButton = new JButton("Install from File...");
filterTextField = new JTextField();
descriptionSplitPane = new JSplitPane();
tagsSplitPane = new JSplitPane();
tagsScrollPane = new JScrollPane();
tagsTree = new JTree();
resultsScrollPane = new JScrollPane();
resultsTree = new JTree();
descriptionPanel = new JPanel();
descriptionScrollPane = new JScrollPane();
descriptionTextPane = new JTextPane();
viewOnAppStoreButton = new JButton("View on App Store");
installButton = new JButton("Install");
downloadSiteLabel = new JLabel("Download Site:");
downloadSiteComboBox = new JComboBox();
manageSitesButton = new JButton("Manage Sites...");
searchAppsLabel.setVisible(!LookAndFeelUtil.isAquaLAF());
filterTextField.putClientProperty("JTextField.variant", "search"); // Aqua LAF only
filterTextField.setToolTipText("To search, start typing");
installFromFileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
installFromFileButtonActionPerformed(evt);
}
});
descriptionSplitPane.setBorder(null);
descriptionSplitPane.setDividerLocation(390);
tagsSplitPane.setDividerLocation(175);
tagsSplitPane.setBorder(null);
DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode treeNode2 = new DefaultMutableTreeNode("all apps (0)");
DefaultMutableTreeNode treeNode3 = new DefaultMutableTreeNode("collections (0)");
DefaultMutableTreeNode treeNode4 = new DefaultMutableTreeNode("apps by tag");
treeNode1.add(treeNode2);
treeNode1.add(treeNode3);
treeNode1.add(treeNode4);
tagsTree.setModel(new DefaultTreeModel(treeNode1));
tagsTree.setFocusable(false);
tagsTree.setRootVisible(false);
tagsTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tagsScrollPane.setViewportView(tagsTree);
tagsSplitPane.setLeftComponent(tagsScrollPane);
treeNode1 = new DefaultMutableTreeNode("root");
resultsTree.setModel(new DefaultTreeModel(treeNode1));
resultsTree.setFocusable(false);
resultsTree.setRootVisible(false);
resultsTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
resultsScrollPane.setViewportView(resultsTree);
tagsSplitPane.setRightComponent(resultsScrollPane);
descriptionSplitPane.setLeftComponent(tagsSplitPane);
descriptionTextPane.setContentType("text/html");
descriptionTextPane.setEditable(false);
//descriptionTextPane.setText("<html>\n <head>\n\n </head>\n <body>\n <p style=\"margin-top: 0\">\n App description is displayed here.\n </p>\n </body>\n</html>\n");
descriptionTextPane.setText("");
descriptionScrollPane.setViewportView(descriptionTextPane);
final GroupLayout descriptionPanelLayout = new GroupLayout(descriptionPanel);
descriptionPanel.setLayout(descriptionPanelLayout);
descriptionPanelLayout.setHorizontalGroup(descriptionPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(descriptionScrollPane, GroupLayout.DEFAULT_SIZE, 162, Short.MAX_VALUE)
);
descriptionPanelLayout.setVerticalGroup(descriptionPanelLayout.createParallelGroup(Alignment.LEADING)
.addComponent(descriptionScrollPane, GroupLayout.DEFAULT_SIZE, 354, Short.MAX_VALUE)
);
descriptionSplitPane.setRightComponent(descriptionPanel);
viewOnAppStoreButton.setEnabled(false);
viewOnAppStoreButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
viewOnAppStoreButtonActionPerformed(evt);
}
});
installButton.setEnabled(false);
installButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
installButtonActionPerformed(evt);
}
});
downloadSiteComboBox.setModel(new DefaultComboBoxModel(new String[] { WebQuerier.DEFAULT_APP_STORE_URL }));
downloadSiteComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
downloadSiteComboBoxItemStateChanged(evt);
}
});
downloadSiteComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
downloadSiteComboBoxActionPerformed(evt);
}
});
downloadSiteComboBox.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
downloadSiteComboBoxKeyPressed(evt);
}
});
manageSitesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
manageSitesButtonActionPerformed(evt);
}
});
LookAndFeelUtil.equalizeSize(installFromFileButton, viewOnAppStoreButton, installButton);
final JSeparator sep = new JSeparator();
final GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(downloadSiteLabel)
.addComponent(downloadSiteComboBox, DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(manageSitesButton)
)
.addComponent(sep, DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(searchAppsLabel)
.addComponent(filterTextField, DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE)
)
.addComponent(descriptionSplitPane)
.addGroup(layout.createSequentialGroup()
.addComponent(installFromFileButton)
.addPreferredGap(ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
.addComponent(viewOnAppStoreButton)
.addComponent(installButton)
)
);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(downloadSiteLabel)
.addComponent(downloadSiteComboBox, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE)
.addComponent(manageSitesButton, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE)
)
.addComponent(sep, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(searchAppsLabel)
.addComponent(filterTextField, PREFERRED_SIZE, DEFAULT_SIZE, PREFERRED_SIZE)
)
.addComponent(descriptionSplitPane, DEFAULT_SIZE, 360, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(installFromFileButton)
.addComponent(viewOnAppStoreButton)
.addComponent(installButton)
)
);
// Add a key listener to the download site combo box to listen for the enter key event
final WebQuerier webQuerier = this.appManager.getWebQuerier();
downloadSiteComboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
final ComboBoxEditor editor = downloadSiteComboBox.getEditor();
final Object selectedValue = editor.getItem();
if (e.isActionKey() || e.getKeyCode() == KeyEvent.VK_ENTER) {
if (downloadSiteComboBox.getModel() instanceof DefaultComboBoxModel
&& selectedValue != null) {
final DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) downloadSiteComboBox.getModel();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
boolean selectedAlreadyInList = false;
for (int i = 0; i < comboBoxModel.getSize(); i++) {
Object listElement = comboBoxModel.getElementAt(i);
if (listElement.equals(selectedValue)) {
selectedAlreadyInList = true;
break;
}
}
if (!selectedAlreadyInList) {
comboBoxModel.insertElementAt(selectedValue, 1);
editor.setItem(selectedValue);
}
}
});
}
if (webQuerier.getCurrentAppStoreUrl() != selectedValue.toString()) {
webQuerier.setCurrentAppStoreUrl(selectedValue.toString());
queryForApps();
}
}
}
});
// Make the JTextPane render HTML using the default UI font
Font font = UIManager.getFont("Label.font");
String bodyRule = "body { font-family: " + font.getFamily() + "; " +
"font-size: " + font.getSize() + "pt; }";
((HTMLDocument) descriptionTextPane.getDocument()).getStyleSheet().addRule(bodyRule);
// Setup the TreeCellRenderer to make the app tags use the folder icon instead of the default leaf icon,
// and have it use the opened folder icon when selected
DefaultTreeCellRenderer tagsTreeCellRenderer = new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
// Make leaves use the open folder icon when selected
if (selected && leaf)
this.setIcon(getOpenIcon());
return this;
}
};
tagsTreeCellRenderer.setLeafIcon(tagsTreeCellRenderer.getDefaultClosedIcon());
tagsTree.setCellRenderer(tagsTreeCellRenderer);
}
@Override
public void addNotify() {
super.addNotify();
if (filterTextField != null)
filterTextField.requestFocusInWindow();
}
private void installFromFileButtonActionPerformed(ActionEvent evt) {
// Setup a the file filter for the open file dialog
FileChooserFilter fileChooserFilter = new FileChooserFilter(
"Jar, Zip, and Karaf Kar Files (*.jar, *.zip, *.kar)", new String[] { "jar", "zip", "kar" });
Collection<FileChooserFilter> fileChooserFilters = new LinkedList<FileChooserFilter>();
fileChooserFilters.add(fileChooserFilter);
// Show the dialog
final File[] files = fileUtil.getFiles(parent, "Choose file(s)", FileUtil.LOAD, FileUtil.LAST_DIRECTORY,
"Install", true, fileChooserFilters);
if (files != null) {
TaskIterator ti = new TaskIterator();
ti.append(new InstallAppsFromFileTask(Arrays.asList(files), appManager, true));
ti.append(new ShowInstalledAppsTask(parent));
taskManager.setExecutionContext(parent);
taskManager.execute(ti);
}
}
/**
* Attempts to insert newlines into a given string such that each line has no
* more than the specified number of characters.
*/
private String splitIntoLines(String text, int charsPerLine) {
return null;
}
private void setupTextFieldListener() {
filterTextField.getDocument().addDocumentListener(new DocumentListener() {
ResultsFilterer resultsFilterer = new ResultsFilterer();
private void showFilteredApps() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
tagsTree.clearSelection();
fillResultsTree(resultsFilterer.findMatches(filterTextField.getText(),
appManager.getWebQuerier().getAllApps()));
}
});
}
@Override
public void removeUpdate(DocumentEvent arg0) {
if (filterTextField.getText().length() != 0) {
showFilteredApps();
}
}
@Override
public void insertUpdate(DocumentEvent arg0) {
showFilteredApps();
}
@Override
public void changedUpdate(DocumentEvent arg0) {
}
});
}
private void installButtonActionPerformed(ActionEvent evt) {
final WebQuerier webQuerier = appManager.getWebQuerier();
taskManager.setExecutionContext(parent);
taskManager.execute(new TaskIterator(new InstallAppsFromWebAppTask(Collections.singletonList(selectedApp), appManager, true)));
}
private void buildTagsTree() {
WebQuerier webQuerier = appManager.getWebQuerier();
// Get all available apps and tags
Set<WebApp> availableApps = webQuerier.getAllApps();
Set<WebQuerier.AppTag> availableTags = webQuerier.getAllTags();
if(availableApps == null || availableTags == null)
return;
List<WebQuerier.AppTag> sortedTags = new LinkedList<WebQuerier.AppTag>(availableTags);
Collections.sort(sortedTags, new Comparator<WebQuerier.AppTag>() {
@Override
public int compare(AppTag tag, AppTag other) {
return other.getCount() - tag.getCount();
}
});
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode allAppsTreeNode = new DefaultMutableTreeNode("all apps"
+ " (" + availableApps.size() + ")");
root.add(allAppsTreeNode);
DefaultMutableTreeNode collectionsTreeNode = new DefaultMutableTreeNode("collections (0)");
DefaultMutableTreeNode appsByTagTreeNode = new DefaultMutableTreeNode("apps by tag");
for (final WebQuerier.AppTag appTag : sortedTags) {
if(appTag.getName().equals("collections"))
collectionsTreeNode.setUserObject(appTag);
else
appsByTagTreeNode.add(new DefaultMutableTreeNode(appTag));
}
root.add(collectionsTreeNode);
root.add(appsByTagTreeNode);
tagsTree.setModel(new DefaultTreeModel(root));
// tagsTree.expandRow(2);
currentSelectedAppTag = null;
hasTagTreeBeenPopulated = true;
}
private void updateResultsTree() {
// bild tags tree if it hasn't been populated
if(!hasTagTreeBeenPopulated)
buildTagsTree();
TreePath selectionPath = tagsTree.getSelectionPath();
// DebugHelper.print(String.valueOf(selectedNode.getUserObject()));
currentSelectedAppTag = null;
if (selectionPath != null) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
// Check if the "all apps" node is selected
if (selectedNode.getLevel() == 1
&& String.valueOf(selectedNode.getUserObject()).startsWith("all apps")) {
fillResultsTree(appManager.getWebQuerier().getAllApps());
} else if (selectedNode.getUserObject() instanceof WebQuerier.AppTag) {
WebQuerier.AppTag selectedTag = (WebQuerier.AppTag) selectedNode.getUserObject();
fillResultsTree(appManager.getWebQuerier().getAppsByTag(selectedTag.getName()));
currentSelectedAppTag = selectedTag;
} else {
// Clear tree
resultsTree.setModel(new DefaultTreeModel(null));
}
} else {
fillResultsTree(appManager.getWebQuerier().getAllApps());
// System.out.println("selection path null, not updating results tree");
}
}
private void fillResultsTree(Set<WebApp> webApps) {
if(webApps == null) {
resultsTree.setModel(new DefaultTreeModel(null));
resultsTreeApps = new HashSet<WebApp>();
return;
}
appManager.getWebQuerier().checkWebAppInstallStatus(webApps, appManager);
List<WebApp> sortedApps = new LinkedList<WebApp>(webApps);
// Sort apps by alphabetical order
Collections.sort(sortedApps, new Comparator<WebApp>() {
@Override
public int compare(WebApp webApp, WebApp other) {
return (webApp.getName().compareToIgnoreCase(other.getName()));
}
});
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode treeNode;
for (WebApp webApp : sortedApps) {
if (webApp.getCorrespondingApp() != null
&& webApp.getCorrespondingApp().getStatus() == AppStatus.INSTALLED) {
webApp.setAppListDisplayName(webApp.getFullName() + " (Installed)");
} else {
webApp.setAppListDisplayName(webApp.getFullName());
}
treeNode = new DefaultMutableTreeNode(webApp);
root.add(treeNode);
}
resultsTree.setModel(new DefaultTreeModel(root));
resultsTreeApps = new HashSet<WebApp>(webApps);
}
private void updateDescriptionBox() {
TreePath selectedPath = resultsTree.getSelectionPath();
if (selectedPath != null) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) resultsTree.getSelectionPath().getLastPathComponent();
WebApp selectedApp = (WebApp) selectedNode.getUserObject();
boolean appAlreadyInstalled = (selectedApp.getCorrespondingApp() != null
&& selectedApp.getCorrespondingApp().getStatus() == AppStatus.INSTALLED);
String text = "";
// text += "<html> <head> </head> <body hspace=\"4\" vspace=\"4\">";
text += "<html> <body hspace=\"4\" vspace=\"2\">";
// App hyperlink to web store page
// text += "<p style=\"margin-top: 0\"> <a href=\"" + selectedApp.getPageUrl() + "\">" + selectedApp.getPageUrl() + "</a> </p>";
// App name, version
text += "<b>" + selectedApp.getFullName() + "</b>";
String latestReleaseVersion = selectedApp.getReleases().get(selectedApp.getReleases().size() - 1).getReleaseVersion();
text += "<br />" + latestReleaseVersion;
if (appAlreadyInstalled) {
if (!selectedApp.getCorrespondingApp().getVersion().equalsIgnoreCase(latestReleaseVersion)) {
text += " (installed: " + selectedApp.getCorrespondingApp().getVersion() + ")";
}
}
/*
text += "<p>";
text += "<b>" + selectedApp.getFullName() + "</b>";
text += "<br />" + selectedApp.getReleases().get(selectedApp.getReleases().size() - 1).getReleaseVersion();
text += "</p>";
*/
text += "<p>";
// App image
text += "<img border=\"0\" ";
text += "src=\"" + appManager.getWebQuerier().getDefaultAppStoreUrl()
+ selectedApp.getIconUrl() + "\" alt=\"" + selectedApp.getFullName() + "\"/>";
text += "</p>";
// App description
text += "<p>";
text += (String.valueOf(selectedApp.getDescription()).equalsIgnoreCase("null") ? "App description not found." : selectedApp.getDescription());
text += "</p>";
text += "</body> </html>";
descriptionTextPane.setText(text);
this.selectedApp = selectedApp;
if (appAlreadyInstalled) {
installButton.setEnabled(false);
} else {
installButton.setEnabled(true);
}
viewOnAppStoreButton.setEnabled(true);
} else {
//descriptionTextPane.setText("App description is displayed here.");
descriptionTextPane.setText("");
this.selectedApp = null;
installButton.setEnabled(false);
viewOnAppStoreButton.setEnabled(false);
}
}
private void resetButtonActionPerformed(ActionEvent evt) {
// TODO add your handling code here:
}
private void viewOnAppStoreButtonActionPerformed(ActionEvent evt) {
if (selectedApp == null) {
return;
}
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse((new URL(selectedApp.getPageUrl())).toURI());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void downloadSiteComboBoxItemStateChanged(ItemEvent evt) {
}
private void downloadSiteComboBoxActionPerformed(ActionEvent evt) {
final Object selected = downloadSiteComboBox.getSelectedItem();
if (downloadSiteComboBox.getModel() instanceof DefaultComboBoxModel
&& selected != null) {
final DefaultComboBoxModel comboBoxModel = (DefaultComboBoxModel) downloadSiteComboBox.getModel();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
boolean selectedAlreadyInList = false;
for (int i = 0; i < comboBoxModel.getSize(); i++) {
Object listElement = comboBoxModel.getElementAt(i);
if (listElement.equals(selected)) {
selectedAlreadyInList = true;
if (i > 0) {
// comboBoxModel.removeElementAt(i);
// comboBoxModel.insertElementAt(listElement, 1);
}
break;
}
}
if (!selectedAlreadyInList) {
comboBoxModel.insertElementAt(selected, 1);
}
}
});
if (appManager.getWebQuerier().getCurrentAppStoreUrl() != selected.toString()) {
appManager.getWebQuerier().setCurrentAppStoreUrl(selected.toString());
queryForApps();
}
}
}
private void downloadSiteComboBoxKeyPressed(KeyEvent evt) {
}
private void manageSitesButtonActionPerformed(ActionEvent evt) {
if (parent instanceof AppManagerDialog) {
((AppManagerDialog) parent).showManageDownloadSitesDialog();
}
}
}
|
package org.cytoscape.tableimport.internal.tunable;
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.GroupLayout;
import javax.swing.JPanel;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle;
import org.cytoscape.model.CyTableManager;
import org.cytoscape.tableimport.internal.reader.AttributeMappingParameters;
import org.cytoscape.tableimport.internal.reader.NetworkTableMappingParameters;
import org.cytoscape.tableimport.internal.ui.ImportTablePanel;
import org.cytoscape.work.Tunable;
import org.cytoscape.work.swing.AbstractGUITunableHandler;
import org.cytoscape.tableimport.internal.util.CytoscapeServices;
import org.osgi.service.event.Event;
import java.util.Map;
import java.util.HashMap;
public class NetworkTableMappingParametersHandler extends AbstractGUITunableHandler {
private final int dialogType;
private final CyTableManager tableManager;
private ImportTablePanel importTablePanel;
private NetworkTableMappingParameters ntmp;
protected NetworkTableMappingParametersHandler(Field field,Object instance, Tunable tunable,
final int dialogType, final CyTableManager tableManager) {
super(field, instance, tunable);
this.dialogType = dialogType;
this.tableManager = tableManager;
init();
}
protected NetworkTableMappingParametersHandler(final Method getter, final Method setter, final Object instance, final Tunable tunable,
final int dialogType, final CyTableManager tableManager) {
super(getter, setter, instance, tunable);
this.dialogType = dialogType;
this.tableManager = tableManager;
init();
}
private void init(){
try {
ntmp = (NetworkTableMappingParameters) getValue();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvocationTargetException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
importTablePanel =
new ImportTablePanel(dialogType, ntmp.is,
ntmp.fileType, null,null, null, null,
null, null, null, tableManager);
final Map<String,String> props = new HashMap<String,String>();
props.put("action", "show import table dialog");
CytoscapeServices.eventAdmin.postEvent(new Event("org/cytoscape/gettingstarted", props));
} catch (Exception e) {
throw new IllegalStateException("Could not initialize ImportTablePanel.", e);
}
panel = new JPanel(new BorderLayout(10, 10));
panel.add(importTablePanel, BorderLayout.CENTER);
}
@Override
public void handle() {
try{
ntmp = importTablePanel.getNetworkTableMappingParameters();
setValue(ntmp);
final Map<String,String> props = new HashMap<String,String>();
props.put("action", "import table dialog ok");
CytoscapeServices.eventAdmin.postEvent(new Event("org/cytoscape/gettingstarted", props));
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package anabalica.github.io.meowletters.letters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
/**
* LetterChain class is a container for manipulating a sequence of Letter
* objects. In the game it represents the chain of selected letters by the user.
* Order matters. There can be valid chains (D -> E -> F -> G) and invalid
* chains (B -> C -> R).
*
* @author Ana Balica
*/
public class LetterChain implements Iterable<Letter> {
private ArrayList<Letter> chain;
public LetterChain() {
chain = new ArrayList<Letter>();
}
public LetterChain(ArrayList<Letter> chain) {
setChain(chain);
}
public ArrayList<Letter> getChain() {
return chain;
}
public Iterator<Letter> iterator() {
Iterator<Letter> letter = chain.iterator();
return letter;
}
public void setChain(ArrayList<Letter> chain) {
this.chain = chain;
}
/**
* Check if the chain is empty
*
* @return true if is empty, otherwise false
*/
public boolean isEmpty() {
return chain.isEmpty();
}
/**
* Get the size of the chain
*
* @return chain size
*/
public int size() {
return chain.size();
}
/**
* Get the i-th element from the chain
*
* @param i index of the element
* @return Letter object
*/
public Letter get(int i) {
return chain.get(i);
}
/**
* Concatenate two LetterChain(s) into one.
*
* @param letterChain LetterChain object
* @return concatenated LetterChain object
*/
public LetterChain concat(LetterChain letterChain) {
chain.addAll(letterChain.getChain());
return this;
}
/**
* Check if the chain has only consecutive Letter(s) according to the
* current alphabet.
*
* @return true if has only consecutive Letters(s), false otherwise
*/
public boolean isValid() {
int chainSize = chain.size();
if (chainSize < 2) {
return true;
}
String currentAlphabet = Alphabet.getCurrent();
if (chainSize >= currentAlphabet.length()) {
return false;
}
StringBuilder letterChain = new StringBuilder();
for (Letter letter : chain) {
letterChain.append(letter.getLetter());
}
String finalLetterChain = letterChain.toString();
return currentAlphabet.contains(finalLetterChain);
}
/**
* Add a new letter to the chain
*
* @param letter Letter object
*/
public void add(Letter letter) {
chain.add(letter);
}
/**
* Add to the beginning of the chain
*
* @param letter Letter object
*/
public void prepend(Letter letter) {
chain.add(0, letter);
}
public void remove(Letter letter) throws IllegalArgumentException{
if (!chain.contains(letter)) {
throw new IllegalArgumentException("Letter not in chain.");
}
int letter_index = chain.indexOf(letter);
int last_index = chain.size() - 1;
for (int i = last_index; i >= letter_index; i
chain.remove(i);
}
}
/**
* Wrapper for sorting the chain in ascending order.
*/
public void sort() {
Collections.sort(chain);
}
public static LetterChain generateRandomChain(int length) throws IllegalArgumentException {
if (length < 0) {
throw new IllegalArgumentException("The requested chain length can't be negative.");
}
LetterChain chain = new LetterChain();
Letter letter;
for (int i = 0; i < length; i++) {
letter = Letter.getRandomLetter();
chain.add(letter);
}
return chain;
}
public static LetterChain generateValidChain(int length) throws IllegalArgumentException {
if (length < 0) {
throw new IllegalArgumentException("The requested chain length can't be negative.");
}
if (length > Alphabet.getCurrent().length()) {
throw new IllegalArgumentException("The requested chain length exceeds the " +
"alphabet length.");
}
LetterChain chain = new LetterChain();
Letter letter = Letter.getRandomLetter();
chain.add(letter);
for (int i = 1; i < length; i++) {
Letter lastLetter = chain.get(i-1);
Letter nextLetter = lastLetter.next();
if (nextLetter != null) {
chain.add(nextLetter);
} else {
Letter firstLetter = chain.get(0);
Letter previousLetter = firstLetter.previous();
if (previousLetter != null) {
chain.prepend(previousLetter);
}
}
}
return chain;
}
/**
* Generate a letter chain that will have a specific number of consecutive letters
* and additional random letters.
*
* @param consecutiveLettersCount int number of required consecutive letters
* @param randomLettersCount int number of required random letters
* @return LetterChain object
*/
public static LetterChain generateChain(int consecutiveLettersCount, int randomLettersCount) {
if (consecutiveLettersCount == 0) {
return generateRandomChain(randomLettersCount);
}
LetterChain chain = generateValidChain(consecutiveLettersCount);
LetterChain randomChain = generateRandomChain(randomLettersCount);
return chain.concat(randomChain);
}
}
|
package org.jboss.reddeer.eclipse.test.ui.views.contentoutline;
import static org.hamcrest.MatcherAssert.assertThat;
import org.hamcrest.core.Is;
import org.jboss.reddeer.eclipse.jdt.ui.NewJavaClassWizardDialog;
import org.jboss.reddeer.eclipse.jdt.ui.NewJavaClassWizardPage;
import org.jboss.reddeer.eclipse.jdt.ui.ide.NewJavaProjectWizardDialog;
import org.jboss.reddeer.eclipse.jdt.ui.ide.NewJavaProjectWizardPage;
import org.jboss.reddeer.eclipse.jdt.ui.packageexplorer.PackageExplorer;
import org.jboss.reddeer.eclipse.ui.views.contentoutline.OutlineView;
import org.jboss.reddeer.eclipse.utils.DeleteUtils;
import org.jboss.reddeer.junit.runner.RedDeerSuite;
import org.jboss.reddeer.workbench.handler.EditorHandler;
import org.jboss.reddeer.core.exception.CoreLayerException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(RedDeerSuite.class)
public class OutlineViewTest{
private OutlineView outlineView;
private static PackageExplorer packageExplorer;
private static final String TEST_PROJECT_NAME = "OutlineViewTestProject";
@BeforeClass
public static void prepareWS() {
createJavaProject();
createJavaClass();
}
@AfterClass
public static void cleanup() {
DeleteUtils.forceProjectDeletion(packageExplorer.getProject(TEST_PROJECT_NAME),true);
}
@Test
public void testElementsInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
assertThat(outlineView.outlineElements().size(), Is.is(0));
}
@Test(expected=CoreLayerException.class)
public void testCollapseInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.collapseAll();
}
@Test(expected=CoreLayerException.class)
public void testSortInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test(expected=CoreLayerException.class)
public void testHideFieldsInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test(expected=CoreLayerException.class)
public void testHideStaticFieldsAndMethodsInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test(expected=CoreLayerException.class)
public void testHideNonPublicMembersInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test(expected=CoreLayerException.class)
public void testHideLocalTypesInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test(expected=CoreLayerException.class)
public void testLinkWithEditorInEmptyOutlineView() {
EditorHandler.getInstance().closeAll(true);
outlineView = new OutlineView();
outlineView.open();
outlineView.linkWithEditor();
}
@Test
public void testElementsInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
assertThat(outlineView.outlineElements().size(), Is.is(2));
}
@Test
public void testCollapseInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.collapseAll();
}
@Test
public void testSortInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test
public void testHideFieldsInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test
public void testHideStaticFieldsAndMethodsInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test
public void testHideNonPublicMembersInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test
public void testHideLocalTypesInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.sort();
}
@Test(expected=CoreLayerException.class)
public void testLinkWithEditorInNonEmptyOutlineView() {
openTestClass();
outlineView = new OutlineView();
outlineView.open();
outlineView.linkWithEditor();
}
private static void createJavaProject() {
NewJavaProjectWizardDialog javaProject = new NewJavaProjectWizardDialog();
javaProject.open();
NewJavaProjectWizardPage javaWizardPage = new NewJavaProjectWizardPage();
javaWizardPage.setProjectName(TEST_PROJECT_NAME);
javaProject.finish();
}
private static void createJavaClass() {
packageExplorer = new PackageExplorer();
packageExplorer.open();
packageExplorer.getProject(TEST_PROJECT_NAME).select();
NewJavaClassWizardDialog javaClassDialog = new NewJavaClassWizardDialog();
javaClassDialog.open();
NewJavaClassWizardPage wizardPage = new NewJavaClassWizardPage();
wizardPage.setName("TestClass");
wizardPage.setPackage("test");
wizardPage.setStaticMainMethod(true);
javaClassDialog.finish();
}
private void openTestClass() {
packageExplorer = new PackageExplorer();
packageExplorer.open();
packageExplorer.getProject(TEST_PROJECT_NAME).getProjectItem(
"src","test","TestClass.java").open();
}
}
|
package com.manoj.dlt.ui.activities;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import com.manoj.dlt.R;
import com.manoj.dlt.features.DeepLinkHistory;
import com.manoj.dlt.models.DeepLinkInfo;
import com.manoj.dlt.ui.adapters.DeepLinkListAdapter;
import com.manoj.dlt.utils.TextChangedListener;
import com.manoj.dlt.utils.Utilities;
import hotchemi.android.rate.AppRate;
public class DeepLinkHistoryActivity extends AppCompatActivity
{
private ListView _listView;
private EditText _deepLinkInput;
private DeepLinkHistory _history;
private DeepLinkListAdapter _adapter;
private String _previousClipboardText;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deep_link_history);
initView();
}
private void initView()
{
_deepLinkInput = (EditText) findViewById(R.id.deep_link_input);
_listView = (ListView) findViewById(R.id.deep_link_list_view);
_history = new DeepLinkHistory(this);
_adapter = new DeepLinkListAdapter(_history.getAllLinksSearchedInfo(), this);
configureListView();
configureDeepLinkInput();
findViewById(R.id.deep_link_fire).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
extractAndFireLink();
}
});
setAppropriateLayout();
}
private void configureListView()
{
_listView.setAdapter(_adapter);
_listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
{
DeepLinkInfo info = (DeepLinkInfo) _adapter.getItem(position);
setDeepLinkInputText(info.getDeepLink());
}
});
}
private void configureDeepLinkInput()
{
_deepLinkInput.requestFocus();
_deepLinkInput.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent)
{
if (shouldFireDeepLink(actionId))
{
extractAndFireLink();
return true;
} else
{
return false;
}
}
});
_deepLinkInput.addTextChangedListener(new TextChangedListener()
{
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
_adapter.updateResults(charSequence);
}
});
}
private void pasteFromClipboard()
{
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (!isProperUri(_deepLinkInput.getText().toString()) && clipboardManager.hasPrimaryClip())
{
ClipData.Item clipItem = clipboardManager.getPrimaryClip().getItemAt(0);
if (clipItem != null)
{
if (clipItem.getText() != null)
{
String clipBoardText = clipItem.getText().toString();
if (isProperUri(clipBoardText) && !clipBoardText.equals(_previousClipboardText))
{
setDeepLinkInputText(clipBoardText);
_previousClipboardText = clipBoardText;
}
} else if (clipItem.getUri() != null)
{
String clipBoardText = clipItem.getUri().toString();
if (isProperUri(clipBoardText) && !clipBoardText.equals(_previousClipboardText))
{
setDeepLinkInputText(clipBoardText);
_previousClipboardText = clipBoardText;
}
}
}
}
}
private void setAppropriateLayout()
{
if (Utilities.isAppTutorialSeen(this))
{
AppRate.showRateDialogIfMeetsConditions(this);
showDeepLinkRootView();
} else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
View tutorialView = findViewById(R.id.tutorial_layer);
tutorialView.setVisibility(View.VISIBLE);
tutorialView.setClickable(true);
tutorialView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Utilities.setAppTutorialSeen(DeepLinkHistoryActivity.this);
showDeepLinkRootView();
}
});
}
}
private void showDeepLinkRootView()
{
findViewById(R.id.tutorial_layer).setVisibility(View.GONE);
findViewById(R.id.deep_link_history_root).setVisibility(View.VISIBLE);
_deepLinkInput.requestFocus();
Utilities.showKeyboard(this);
}
public void extractAndFireLink()
{
String deepLinkUri = _deepLinkInput.getText().toString();
checkAndfireDeepLink(deepLinkUri);
}
private void checkAndfireDeepLink(String deepLinkUri) {
if (isProperUri(deepLinkUri))
{
Uri uri = Uri.parse(deepLinkUri);
Intent intent = new Intent();
intent.setData(uri);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PackageManager pm = getPackageManager();
ResolveInfo resolveInfo = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfo != null)
{
startActivity(intent);
Utilities.addResolvedInfoToHistory(deepLinkUri, resolveInfo, this);
} else
{
Utilities.raiseError(getString(R.string.error_no_activity_resolved).concat(": ").concat(deepLinkUri), this);
}
} else
{
Utilities.raiseError(getString(R.string.error_improper_uri).concat(": ").concat(deepLinkUri), this);
}
}
@Override
protected void onStart()
{
super.onStart();
_adapter.updateBaseData(_history.getAllLinksSearchedInfo());
}
@Override
protected void onResume()
{
super.onResume();
pasteFromClipboard();
}
private boolean shouldFireDeepLink(int actionId)
{
if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT)
{
return true;
}
return false;
}
private boolean isProperUri(String uriText)
{
Uri uri = Uri.parse(uriText);
if (uri.getScheme() == null || uri.getScheme().length() == 0)
{
return false;
} else if (uriText.contains("\n") || uriText.contains(" "))
{
return false;
} else
{
return true;
}
}
private void setDeepLinkInputText(String text)
{
_deepLinkInput.setText(text);
_deepLinkInput.setSelection(text.length());
}
}
|
package com.marverenic.music.player;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.os.RemoteException;
import com.marverenic.music.IPlayerService;
import com.marverenic.music.JockeyApplication;
import com.marverenic.music.data.store.ImmutablePreferenceStore;
import com.marverenic.music.data.store.PreferenceStore;
import com.marverenic.music.data.store.ReadOnlyPreferenceStore;
import com.marverenic.music.model.Song;
import com.marverenic.music.utils.ObservableQueue;
import com.marverenic.music.utils.Optional;
import com.marverenic.music.utils.Util;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Single;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;
import timber.log.Timber;
/**
* An implementation of {@link PlayerController} used in release builds to communicate with the
* media player throughout the application. This implementation uses AIDL to send commands through
* IPC to the remote player service, and gets information with a combination of AIDL to fetch data
* and BroadcastReceivers to be notified of automatic changes to the player state.
*
* This class is responsible for all communication to the remote service, including starting,
* binding, unbinding and restarting the service if it crashes.
*/
public class ServicePlayerController implements PlayerController {
private static final int POSITION_TICK_MS = 200;
private Context mContext;
private IPlayerService mBinding;
private PublishSubject<String> mErrorStream = PublishSubject.create();
private PublishSubject<String> mInfoStream = PublishSubject.create();
private final Prop<Boolean> mPlaying = new Prop<>("playing");
private final Prop<Song> mNowPlaying = new Prop<>("now playing");
private final Prop<List<Song>> mQueue = new Prop<>("queue");
private final Prop<Integer> mQueuePosition = new Prop<>("queue index");
private final Prop<Integer> mCurrentPosition = new Prop<>("seek position");
private final Prop<Integer> mDuration = new Prop<>("duration");
private final Prop<Integer> mMultiRepeatCount = new Prop<>("multi-repeat");
private final Prop<Long> mSleepTimerEndTime = new Prop<>("sleep timer");
private BehaviorSubject<Boolean> mShuffled;
private BehaviorSubject<Bitmap> mArtwork;
private Subscription mCurrentPositionClock;
private ObservableQueue<Runnable> mRequestQueue;
private Subscription mRequestQueueSubscription;
public ServicePlayerController(Context context, PreferenceStore preferenceStore) {
mContext = context;
mShuffled = BehaviorSubject.create(preferenceStore.isShuffled());
mRequestQueue = new ObservableQueue<>();
startService();
isPlaying().subscribe(
isPlaying -> {
if (isPlaying) {
startCurrentPositionClock();
} else {
stopCurrentPositionClock();
}
}, throwable -> {
Timber.e(throwable, "Failed to update current position clock");
});
}
private void startService() {
Intent serviceIntent = new Intent(mContext, PlayerService.class);
// Manually start the service to ensure that it is associated with this task and can
// appropriately set its dismiss behavior
mContext.startService(serviceIntent);
mContext.bindService(serviceIntent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBinding = IPlayerService.Stub.asInterface(service);
initAllProperties();
bindRequestQueue();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mContext.unbindService(this);
releaseAllProperties();
mBinding = null;
if (mRequestQueueSubscription != null) {
mRequestQueueSubscription.unsubscribe();
mRequestQueueSubscription = null;
}
}
}, Context.BIND_WAIVE_PRIORITY);
}
private void ensureServiceStarted() {
if (mBinding == null) {
startService();
}
}
private void bindRequestQueue() {
mRequestQueueSubscription = mRequestQueue.toObservable()
.subscribe(Runnable::run, throwable -> {
Timber.e(throwable, "Failed to process request");
// Make sure to restart the request queue, otherwise all future commands will
// be dropped
bindRequestQueue();
});
}
private void execute(Runnable command) {
ensureServiceStarted();
mRequestQueue.enqueue(command);
}
private void startCurrentPositionClock() {
if (mCurrentPositionClock != null && !mCurrentPositionClock.isUnsubscribed()) {
return;
}
mCurrentPositionClock = Observable.interval(POSITION_TICK_MS, TimeUnit.MILLISECONDS)
.observeOn(Schedulers.computation())
.subscribe(tick -> {
if (!mCurrentPosition.isSubscribedTo()) {
stopCurrentPositionClock();
} else {
mCurrentPosition.invalidate();
}
}, throwable -> {
Timber.e(throwable, "Failed to perform position tick");
});
}
private void stopCurrentPositionClock() {
if (mCurrentPositionClock != null) {
mCurrentPositionClock.unsubscribe();
mCurrentPositionClock = null;
}
}
private void releaseAllProperties() {
mPlaying.setFunction(null);
mNowPlaying.setFunction(null);
mQueue.setFunction(null);
mQueuePosition.setFunction(null);
mCurrentPosition.setFunction(null);
mDuration.setFunction(null);
mMultiRepeatCount.setFunction(null);
mSleepTimerEndTime.setFunction(null);
}
private void initAllProperties() {
mPlaying.setFunction(mBinding::isPlaying);
mNowPlaying.setFunction(mBinding::getNowPlaying);
mQueue.setFunction(mBinding::getQueue);
mQueuePosition.setFunction(mBinding::getQueuePosition);
mCurrentPosition.setFunction(mBinding::getCurrentPosition);
mDuration.setFunction(mBinding::getDuration);
mMultiRepeatCount.setFunction(mBinding::getMultiRepeatCount);
mSleepTimerEndTime.setFunction(mBinding::getSleepTimerEndTime);
invalidateAll();
}
private void invalidateAll() {
mPlaying.invalidate();
mNowPlaying.invalidate();
mQueue.invalidate();
mQueuePosition.invalidate();
mCurrentPosition.invalidate();
mDuration.invalidate();
mMultiRepeatCount.invalidate();
mSleepTimerEndTime.invalidate();
}
@Override
public Observable<String> getError() {
return mErrorStream.asObservable();
}
@Override
public Observable<String> getInfo() {
return mInfoStream.asObservable();
}
@Override
public Single<PlayerState> getPlayerState() {
return Observable.fromCallable(mBinding::getPlayerState).toSingle();
}
@Override
public void restorePlayerState(PlayerState restoreState) {
execute(() -> {
try {
mBinding.restorePlayerState(restoreState);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to restore player state");
}
});
}
@Override
public void stop() {
execute(() -> {
try {
mBinding.stop();
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to stop service");
}
});
}
@Override
public void skip() {
execute(() -> {
try {
mBinding.skip();
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to skip current track");
}
});
}
@Override
public void previous() {
execute(() -> {
try {
mBinding.previous();
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to skip backward");
}
});
}
@Override
public void togglePlay() {
execute(() -> {
try {
mBinding.togglePlay();
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to toggle playback");
}
});
}
@Override
public void play() {
execute(() -> {
try {
mBinding.play();
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to resume playback");
}
});
}
@Override
public void pause() {
execute(() -> {
try {
mBinding.pause();
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to pause playback");
}
});
}
@Override
public void updatePlayerPreferences(ReadOnlyPreferenceStore preferenceStore) {
execute(() -> {
try {
mBinding.setPreferences(new ImmutablePreferenceStore(preferenceStore));
mShuffled.onNext(preferenceStore.isShuffled());
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to update remote player preferences");
}
});
}
@Override
public void setQueue(List<Song> newQueue, int newPosition) {
execute(() -> {
try {
mBinding.setQueue(newQueue, newPosition);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to set queue");
}
});
}
@Override
public void clearQueue() {
setQueue(Collections.emptyList(), 0);
}
@Override
public void changeSong(int newPosition) {
execute(() -> {
try {
mBinding.changeSong(newPosition);
mNowPlaying.invalidate();
mQueuePosition.invalidate();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to change song");
}
});
}
@Override
public void editQueue(List<Song> queue, int newPosition) {
execute(() -> {
try {
mBinding.editQueue(queue, newPosition);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to edit queue");
}
});
}
@Override
public void queueNext(Song song) {
execute(() -> {
try {
mBinding.queueNext(song);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to queue next song");
}
});
}
@Override
public void queueNext(List<Song> songs) {
execute(() -> {
try {
mBinding.queueNextList(songs);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to queue next songs");
}
});
}
@Override
public void queueLast(Song song) {
execute(() -> {
try {
mBinding.queueLast(song);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to queue last song");
}
});
}
@Override
public void queueLast(List<Song> songs) {
execute(() -> {
try {
mBinding.queueLastList(songs);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to queue last songs");
}
});
}
@Override
public void seek(int position) {
execute(() -> {
try {
mBinding.seekTo(position);
invalidateAll();
} catch (RemoteException exception) {
Timber.e(exception, "Failed to seek");
}
});
}
@Override
public Observable<Boolean> isPlaying() {
ensureServiceStarted();
return mPlaying.getObservable();
}
@Override
public Observable<Song> getNowPlaying() {
ensureServiceStarted();
return mNowPlaying.getObservable();
}
@Override
public Observable<List<Song>> getQueue() {
ensureServiceStarted();
return mQueue.getObservable();
}
@Override
public Observable<Integer> getQueuePosition() {
ensureServiceStarted();
return mQueuePosition.getObservable();
}
@Override
public Observable<Integer> getCurrentPosition() {
ensureServiceStarted();
startCurrentPositionClock();
return mCurrentPosition.getObservable();
}
@Override
public Observable<Integer> getDuration() {
ensureServiceStarted();
return mDuration.getObservable();
}
@Override
public Observable<Boolean> isShuffleEnabled() {
ensureServiceStarted();
return mShuffled.asObservable().distinctUntilChanged();
}
@Override
public Observable<Integer> getMultiRepeatCount() {
ensureServiceStarted();
return mMultiRepeatCount.getObservable();
}
@Override
public void setMultiRepeatCount(int count) {
execute(() -> {
try {
mBinding.setMultiRepeatCount(count);
mMultiRepeatCount.setValue(count);
} catch (RemoteException exception) {
Timber.e(exception, "Failed to set multi-repeat count");
}
});
}
@Override
public Observable<Long> getSleepTimerEndTime() {
ensureServiceStarted();
return mSleepTimerEndTime.getObservable();
}
@Override
public void setSleepTimerEndTime(long timestampInMillis) {
execute(() -> {
try {
mBinding.setSleepTimerEndTime(timestampInMillis);
mSleepTimerEndTime.setValue(timestampInMillis);
} catch (RemoteException exception) {
Timber.e(exception, "Failed to set sleep-timer end time");
}
});
}
@Override
public void disableSleepTimer() {
setSleepTimerEndTime(0L);
}
@Override
public Observable<Bitmap> getArtwork() {
if (mArtwork == null) {
mArtwork = BehaviorSubject.create();
getNowPlaying()
.observeOn(Schedulers.io())
.map((Song song) -> {
if (song == null) {
return null;
}
return Util.fetchFullArt(mContext, song);
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(mArtwork::onNext, throwable -> {
Timber.e(throwable, "Failed to fetch artwork");
mArtwork.onNext(null);
});
}
return mNowPlaying.getSubject()
.map(Optional::isPresent)
.switchMap(current -> {
if (current) {
return mArtwork;
} else {
return Observable.empty();
}
});
}
/**
* A {@link BroadcastReceiver} class listening for intents with an
* {@link MusicPlayer#UPDATE_BROADCAST} action. This broadcast must be sent ordered with this
* receiver being the highest priority so that the UI can access this class for accurate
* information from the player service
*/
public static class Listener extends BroadcastReceiver {
@Inject
PlayerController mController;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getBooleanExtra(MusicPlayer.UPDATE_EXTRA_MINOR, false)) {
return;
}
if (mController == null) {
JockeyApplication.getComponent(context).inject(this);
}
if (mController instanceof ServicePlayerController) {
ServicePlayerController playerController = (ServicePlayerController) mController;
if (intent.getAction().equals(MusicPlayer.UPDATE_BROADCAST)) {
playerController.invalidateAll();
} else if (intent.getAction().equals(MusicPlayer.INFO_BROADCAST)) {
String error = intent.getExtras().getString(MusicPlayer.INFO_EXTRA_MESSAGE);
playerController.mErrorStream.onNext(error);
} else if (intent.getAction().equals(MusicPlayer.ERROR_BROADCAST)) {
String info = intent.getExtras().getString(MusicPlayer.ERROR_EXTRA_MSG);
playerController.mInfoStream.onNext(info);
}
}
}
}
private static final class Prop<T> {
private final String mName;
private final BehaviorSubject<Optional<T>> mSubject;
private final Observable<T> mObservable;
private Retriever<T> mRetriever;
public Prop(String propertyName) {
mName = propertyName;
mSubject = BehaviorSubject.create();
mObservable = mSubject.filter(Optional::isPresent)
.map(Optional::getValue)
.distinctUntilChanged();
}
public void setFunction(Retriever<T> retriever) {
mRetriever = retriever;
}
public void invalidate() {
mSubject.onNext(Optional.empty());
if (mRetriever != null) {
Observable.fromCallable(mRetriever::retrieve)
.map(Optional::ofNullable)
.subscribe(mSubject::onNext, throwable -> {
Timber.e(throwable, "Failed to fetch " + mName + " property.");
});
}
}
public boolean isSubscribedTo() {
return mSubject.hasObservers();
}
public void setValue(T value) {
mSubject.onNext(Optional.ofNullable(value));
}
protected BehaviorSubject<Optional<T>> getSubject() {
return mSubject;
}
public Observable<T> getObservable() {
return mObservable;
}
interface Retriever<T> {
T retrieve() throws Exception;
}
}
}
|
package com.cognizant.devops.platformengine.modules.dataextractor;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.cognizant.devops.platformcommons.dal.neo4j.GraphDBException;
import com.cognizant.devops.platformcommons.dal.neo4j.GraphResponse;
import com.cognizant.devops.platformcommons.dal.neo4j.Neo4jDBHandler;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/**
*
* @author Vishal Ganjare (vganjare)
*
* Entry point for correlation executor.
*
*/
public class EngineDataExtractorModule implements Job{
private static Logger log = Logger.getLogger(EngineDataExtractorModule.class);
private static boolean isDataExtractionInProgress = false;
private static final Pattern p = Pattern.compile("((?<!([A-Z]{1,10})-?)[A-Z]+-\\d+)");
private int dataBatchSize = 2000;
public void execute(JobExecutionContext context) throws JobExecutionException {
if(!isDataExtractionInProgress) {
isDataExtractionInProgress = true;
updateSCMNodesWithJiraKey();
cleanSCMNodes();
isDataExtractionInProgress = false;
}
}
private void updateSCMNodesWithJiraKey() {
Neo4jDBHandler dbHandler = new Neo4jDBHandler();
try {
String paginationCypher = "MATCH (n:SCM:DATA:RAW) where not exists(n.jiraKeyProcessed) and exists(n.commitId) return count(n) as count";
GraphResponse paginationResponse = dbHandler.executeCypherQuery(paginationCypher);
int resultCount = paginationResponse.getJson().get("results").getAsJsonArray().get(0).getAsJsonObject().get("data")
.getAsJsonArray().get(0).getAsJsonObject().get("row").getAsJsonArray().get(0).getAsInt();
while(resultCount > 0) {
long st = System.currentTimeMillis();
String scmDataFetchCypher = "MATCH (source:SCM:DATA:RAW) where not exists(source.jiraKeyProcessed) and exists(source.commitId) "
+ "WITH { uuid: source.uuid, commitId: source.commitId, message: source.message} "
+ "as data limit "+dataBatchSize+" return collect(data)";
GraphResponse response = dbHandler.executeCypherQuery(scmDataFetchCypher);
JsonArray rows = response.getJson().get("results").getAsJsonArray().get(0).getAsJsonObject().get("data")
.getAsJsonArray().get(0).getAsJsonObject().get("row").getAsJsonArray();
if(rows.isJsonNull() || rows.size() == 0) {
break;
}
JsonArray dataList = rows.get(0).getAsJsonArray();
int processedRecords = dataList.size();
String addJiraKeysCypher = "UNWIND {props} as properties MATCH (source:SCM:DATA:RAW {uuid : properties.uuid, commitId: properties.commitId}) "
+ "set source.jiraKeys = properties.jiraKeys, source.jiraKeyProcessed = true return count(source)";
String updateRawLabelCypher = "UNWIND {props} as properties MATCH (source:SCM:DATA:RAW {uuid : properties.uuid, commitId: properties.commitId}) "
+ "set source.jiraKeyProcessed = true return count(source)";
List<JsonObject> jiraKeysCypherProps = new ArrayList<JsonObject>();
List<JsonObject> updateRawLabelCypherProps = new ArrayList<JsonObject>();
JsonObject data = null;
for(JsonElement dataElem : dataList) {
JsonObject dataJson = dataElem.getAsJsonObject();
JsonElement messageElem = dataJson.get("message");
if(messageElem.isJsonPrimitive()) {
String message = messageElem.getAsString();
JsonArray jiraKeys = new JsonArray();
while(message.contains("-")) {
Matcher m = p.matcher(message);
if(m.find()) {
jiraKeys.add(m.group());
message = message.replaceAll(m.group(), "");
}else {
break;
}
}
data = new JsonObject();
data.addProperty("uuid", dataJson.get("uuid").getAsString());
data.addProperty("commitId", dataJson.get("commitId").getAsString());
if(jiraKeys.size() > 0) {
data.add("jiraKeys", jiraKeys);
jiraKeysCypherProps.add(data);
}else {
updateRawLabelCypherProps.add(data);
}
}
}
if(updateRawLabelCypherProps.size() > 0) {
JsonObject bulkCreateNodes = dbHandler.bulkCreateNodes(updateRawLabelCypherProps, null, updateRawLabelCypher);
log.debug(bulkCreateNodes);
}
if(jiraKeysCypherProps.size() > 0) {
JsonObject bulkCreateNodes = dbHandler.bulkCreateNodes(jiraKeysCypherProps, null, addJiraKeysCypher);
log.debug(bulkCreateNodes);
}
resultCount = resultCount - dataBatchSize;
log.debug("Processed "+processedRecords+" SCM records, time taken: "+(System.currentTimeMillis() - st) + " ms");
}
} catch (GraphDBException e) {
log.error("Unable to extract JIRA keys from SCM Commit messages", e);
}
}
private void cleanSCMNodes() {
Neo4jDBHandler dbHandler = new Neo4jDBHandler();
try {
int processedRecords = 1;
while(processedRecords > 0) {
long st = System.currentTimeMillis();
String scmCleanUpCypher = "MATCH (n:SCM:DATA) where not n:RAW and exists(n.jiraKeyProcessed) "
+ "WITH distinct n limit "+dataBatchSize+" remove n.jiraKeyProcessed return count(n)";
GraphResponse response = dbHandler.executeCypherQuery(scmCleanUpCypher);
processedRecords = response.getJson().get("results").getAsJsonArray().get(0).getAsJsonObject().get("data")
.getAsJsonArray().get(0).getAsJsonObject().get("row").getAsJsonArray().get(0).getAsInt();
log.debug("Processed "+processedRecords+" SCM records, time taken: "+(System.currentTimeMillis() - st) + " ms");
}
} catch (GraphDBException e) {
log.error("Unable to extract JIRA keys from SCM Commit messages", e);
}
}
}
|
package com.mikepenz.fastadapter.app;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IItem;
import com.mikepenz.fastadapter.adapters.HeaderAdapter;
import com.mikepenz.fastadapter.adapters.ItemAdapter;
import com.mikepenz.fastadapter.app.adapter.StickyHeaderAdapter;
import com.mikepenz.fastadapter.app.items.SampleItem;
import com.mikepenz.materialize.MaterializeBuilder;
import com.mikepenz.materialize.util.UIUtils;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class AdvancedSampleActivity extends AppCompatActivity {
private static final String[] headers = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
//save our FastAdapter
private FastAdapter fastAdapter;
private ItemAdapter itemAdapter;
//the ActionMode
private ActionMode actionMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
// Handle Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.sample_advanced);
//style our ui
new MaterializeBuilder().withActivity(this).build();
//create our FastAdapter
fastAdapter = new FastAdapter();
//create our adapters
final StickyHeaderAdapter stickyHeaderAdapter = new StickyHeaderAdapter();
itemAdapter = new ItemAdapter();
final HeaderAdapter headerAdapter = new HeaderAdapter();
//configure our fastAdapter
//as we provide id's for the items we want the hasStableIds enabled to speed up things
fastAdapter.setHasStableIds(true);
fastAdapter.withMultiSelect(true);
fastAdapter.withMultiSelectOnLongClick(true);
fastAdapter.withOnClickListener(new FastAdapter.OnClickListener() {
@Override
public boolean onClick(View v, int position, int relativePosition, IItem item) {
if (item instanceof SampleItem) {
if (((SampleItem) item).getSubItems() != null) {
fastAdapter.toggleCollapsible(position);
//if we are in CAB mode and there are no selections afterwards we end the CAB mode
if (actionMode != null && fastAdapter.getSelections().size() == 0) {
actionMode.finish();
}
return true;
}
}
//if we are current in CAB mode, and we remove the last selection, we want to finish the actionMode
if (actionMode != null && fastAdapter.getSelections().size() == 1 && item.isSelected()) {
actionMode.finish();
}
return false;
}
});
fastAdapter.withOnLongClickListener(new FastAdapter.OnLongClickListener() {
@Override
public boolean onLongClick(View v, int position, int relativePosition, IItem item) {
if (actionMode == null) {
//may check if actionMode is already displayed
actionMode = startSupportActionMode(new ActionBarCallBack());
findViewById(R.id.action_mode_bar).setBackgroundColor(UIUtils.getThemeColorFromAttrOrRes(AdvancedSampleActivity.this, R.attr.colorPrimary, R.color.material_drawer_primary));
//we have to select this on our own as we will consume the event
fastAdapter.select(position);
//we consume this event so the normal onClick isn't called anymore
return true;
}
return false;
}
});
//get our recyclerView and do basic setup
RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setItemAnimator(new DefaultItemAnimator());
rv.setAdapter(stickyHeaderAdapter.wrap(itemAdapter.wrap(headerAdapter.wrap(fastAdapter))));
final StickyRecyclerHeadersDecoration decoration = new StickyRecyclerHeadersDecoration(stickyHeaderAdapter);
rv.addItemDecoration(decoration);
//fill with some sample data
headerAdapter.add(new SampleItem().withName("Header").withIdentifier(1));
List<IItem> items = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
SampleItem sampleItem = new SampleItem().withName("Test " + i).withHeader(headers[i / 5]).withIdentifier(100 + i);
if (i % 10 == 0) {
List<IItem> subItems = new LinkedList<>();
for (int ii = 1; ii <= 3; ii++) {
SampleItem subItem = new SampleItem().withName("-- SubTest " + ii).withHeader(headers[i / 5]).withIdentifier(1000 + ii);
List<IItem> subSubItems = new LinkedList<>();
for (int iii = 1; iii <= 3; iii++) {
subSubItems.add(new SampleItem().withName("---- SubSubTest " + iii).withHeader(headers[i / 5]).withIdentifier(10000 + iii));
}
subItem.withSubItems(subSubItems);
subItems.add(subItem);
}
sampleItem.withSubItems(subItems);
}
items.add(sampleItem);
}
itemAdapter.add(items);
//so the headers are aware of changes
stickyHeaderAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
decoration.invalidateHeaders();
}
});
//init cache with the added items, this is useful for shorter lists with many many different view types (at least 4 or more
//new RecyclerViewCacheUtil().withCacheSize(2).apply(rv, items);
//restore selections (this has to be done after the items were added
fastAdapter.withSavedInstanceState(savedInstanceState);
//set the back arrow in the toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the adapter to the bundel
outState = fastAdapter.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle the click on the back arrow click
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Our ActionBarCallBack to showcase the CAB
*/
class ActionBarCallBack implements ActionMode.Callback {
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
fastAdapter.deleteAllSelectedItems();
//finish the actionMode
mode.finish();
return true;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(UIUtils.getThemeColorFromAttrOrRes(AdvancedSampleActivity.this, R.attr.colorPrimaryDark, R.color.material_drawer_primary_dark));
}
mode.getMenuInflater().inflate(R.menu.cab, menu);
//as we are now in the actionMode a single click is fine for multiSelection
fastAdapter.withMultiSelectOnLongClick(false);
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
//after we are done with the actionMode we fallback to longClick for multiselect
fastAdapter.withMultiSelectOnLongClick(true);
//actionMode end. deselect everything
fastAdapter.deselect();
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
}
}
|
package eu.bcvsolutions.idm.core.api.service;
import eu.bcvsolutions.idm.core.api.dto.IdmContractGuaranteeDto;
import eu.bcvsolutions.idm.core.api.dto.filter.IdmContractGuaranteeFilter;
import eu.bcvsolutions.idm.core.api.script.ScriptEnabled;
import eu.bcvsolutions.idm.core.security.api.service.AuthorizableService;
public interface IdmContractGuaranteeService extends
EventableDtoService<IdmContractGuaranteeDto, IdmContractGuaranteeFilter>,
AuthorizableService<IdmContractGuaranteeDto>,
ScriptEnabled {
}
|
package com.tasomaniac.openwith.resolver;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;
import com.karumi.headerrecyclerview.HeaderRecyclerViewAdapter;
import com.tasomaniac.openwith.R;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import timber.log.Timber;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.M;
public class ResolveListAdapter extends HeaderRecyclerViewAdapter<ResolveListAdapter.ViewHolder, ResolveListAdapter.Header, DisplayResolveInfo, Void> {
private static final Intent BROWSER_INTENT;
static {
BROWSER_INTENT = new Intent();
BROWSER_INTENT.setAction(Intent.ACTION_VIEW);
BROWSER_INTENT.addCategory(Intent.CATEGORY_BROWSABLE);
BROWSER_INTENT.setData(Uri.parse("http:"));
}
protected boolean mShowExtended;
private final int mIconDpi;
private Intent mIntent;
private ResolveInfo mLastChosen;
private final LayoutInflater mInflater;
protected List<DisplayResolveInfo> mList;
private int mLastChosenPosition = -1;
private boolean mFilterLastUsed;
private PackageManager mPm;
private Map<String, UsageStats> mStats;
private static final long USAGE_STATS_PERIOD = 1000 * 60 * 60 * 24 * 14;
private ChooserHistory mHistory;
private final Context mContext;
private final String mCallerPackage;
private HashMap<String, Integer> mPriorities;
public ResolveListAdapter(Context context,
ChooserHistory history,
Intent intent,
String callerPackage,
ResolveInfo lastChosen,
boolean filterLastUsed) {
final ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
mIconDpi = am.getLauncherLargeIconDensity();
if (SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
UsageStatsManager mUsm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
final long sinceTime = System.currentTimeMillis() - USAGE_STATS_PERIOD;
mStats = mUsm.queryAndAggregateUsageStats(sinceTime, System.currentTimeMillis());
}
mPm = context.getPackageManager();
mInflater = LayoutInflater.from(context);
mList = new ArrayList<>();
mContext = context;
mHistory = history;
mIntent = intent;
mCallerPackage = callerPackage;
mLastChosen = lastChosen;
mFilterLastUsed = filterLastUsed;
rebuildList();
}
public void setPriorityItems(String... packageNames) {
if (packageNames == null || packageNames.length == 0) {
mPriorities = null;
rebuildList();
return;
}
int size = packageNames.length;
mPriorities = new HashMap<>(size);
for (int i = 0; i < size; i++) {
// position 0 should have highest priority,
// starting with 1 for lowest priority.
mPriorities.put(packageNames[0], size - i + 1);
}
rebuildList();
}
public void handlePackagesChanged() {
rebuildList();
notifyDataSetChanged();
}
public DisplayResolveInfo getFilteredItem() {
if (mFilterLastUsed && mLastChosenPosition >= 0) {
// Not using getItem since it offsets to dodge this position for the list
return mList.get(mLastChosenPosition);
}
return null;
}
public int getFilteredPosition() {
if (mFilterLastUsed && mLastChosenPosition >= 0) {
return mLastChosenPosition;
}
return AbsListView.INVALID_POSITION;
}
public boolean hasFilteredItem() {
return mFilterLastUsed && mLastChosenPosition >= 0;
}
@TargetApi(Build.VERSION_CODES.M)
protected void rebuildList() {
mList.clear();
int flag;
flag = SDK_INT >= M ? PackageManager.MATCH_ALL : PackageManager.MATCH_DEFAULT_ONLY;
flag = flag | (mFilterLastUsed ? PackageManager.GET_RESOLVED_FILTER : 0);
List<ResolveInfo> currentResolveList = new ArrayList<>();
currentResolveList.addAll(mPm.queryIntentActivities(mIntent, flag));
if (SDK_INT >= M) {
addBrowsersToList(currentResolveList, flag);
}
//Remove the components from the caller
if (!TextUtils.isEmpty(mCallerPackage)) {
removePackageFromList(mCallerPackage, currentResolveList);
}
int N;
if ((N = currentResolveList.size()) > 0) {
// Only display the first matches that are either of equal
// priority or have asked to be default options.
ResolveInfo r0 = currentResolveList.get(0);
for (int i = 1; i < N; i++) {
ResolveInfo ri = currentResolveList.get(i);
if (r0.priority != ri.priority ||
r0.isDefault != ri.isDefault) {
while (i < N) {
currentResolveList.remove(i);
N
}
}
}
//If there is no left, return
if (N <= 0) {
return;
}
if (N > 1) {
Comparator<ResolveInfo> rComparator =
new ResolverComparator(mContext, mIntent);
Collections.sort(currentResolveList, rComparator);
}
// Check for applications with same name and use application name or
// package name if necessary
r0 = currentResolveList.get(0);
int start = 0;
CharSequence r0Label = r0.loadLabel(mPm);
mShowExtended = false;
for (int i = 1; i < N; i++) {
if (r0Label == null) {
r0Label = r0.activityInfo.packageName;
}
ResolveInfo ri = currentResolveList.get(i);
CharSequence riLabel = ri.loadLabel(mPm);
if (riLabel == null) {
riLabel = ri.activityInfo.packageName;
}
if (riLabel.equals(r0Label)) {
continue;
}
processGroup(currentResolveList, start, (i - 1), r0, r0Label);
r0 = ri;
r0Label = riLabel;
start = i;
}
// Process last group
processGroup(currentResolveList, start, (N - 1), r0, r0Label);
}
}
private void removePackageFromList(final String packageName, List<ResolveInfo> currentResolveList) {
List<ResolveInfo> infosToRemoved = new ArrayList<>();
for (ResolveInfo info : currentResolveList) {
if (info.activityInfo.packageName.equals(packageName)) {
infosToRemoved.add(info);
}
}
currentResolveList.removeAll(infosToRemoved);
}
private void addBrowsersToList(List<ResolveInfo> currentResolveList, int flag) {
final int initialSize = currentResolveList.size();
List<ResolveInfo> browsers = queryBrowserIntentActivities(flag);
for (ResolveInfo browser : browsers) {
boolean browserFound = false;
for (int i = 0; i < initialSize; i++) {
ResolveInfo info = currentResolveList.get(i);
if (info.activityInfo.packageName.equals(browser.activityInfo.packageName)) {
browserFound = true;
break;
}
}
if (!browserFound) {
currentResolveList.add(browser);
}
}
}
private List<ResolveInfo> queryBrowserIntentActivities(int flags) {
return mPm.queryIntentActivities(BROWSER_INTENT, flags);
}
private void processGroup(List<ResolveInfo> rList, int start, int end, ResolveInfo ro,
CharSequence roLabel) {
// Process labels from start to i
int num = end - start + 1;
if (num == 1) {
// No duplicate labels. Use label for entry at start
addResolveInfo(new DisplayResolveInfo(ro, roLabel, null));
updateLastChosenPosition(ro);
} else {
mShowExtended = true;
boolean usePkg = false;
CharSequence startApp = ro.activityInfo.applicationInfo.loadLabel(mPm);
if (startApp == null) {
usePkg = true;
}
if (!usePkg) {
// Use HashSet to track duplicates
HashSet<CharSequence> duplicates =
new HashSet<>();
duplicates.add(startApp);
for (int j = start + 1; j <= end; j++) {
ResolveInfo jRi = rList.get(j);
CharSequence jApp = jRi.activityInfo.applicationInfo.loadLabel(mPm);
if ((jApp == null) || (duplicates.contains(jApp))) {
usePkg = true;
break;
} else {
duplicates.add(jApp);
}
}
// Clear HashSet for later use
duplicates.clear();
}
for (int k = start; k <= end; k++) {
ResolveInfo add = rList.get(k);
if (usePkg) {
// Use application name for all entries from start to end-1
addResolveInfo(new DisplayResolveInfo(add, roLabel,
add.activityInfo.packageName));
} else {
// Use package name for all entries from start to end-1
addResolveInfo(new DisplayResolveInfo(add, roLabel,
add.activityInfo.applicationInfo.loadLabel(mPm)));
}
updateLastChosenPosition(add);
}
}
}
private void updateLastChosenPosition(ResolveInfo info) {
if (mLastChosen != null
&& mLastChosen.activityInfo.packageName.equals(info.activityInfo.packageName)
&& mLastChosen.activityInfo.name.equals(info.activityInfo.name)) {
mLastChosenPosition = mList.size() - 1;
}
}
private void addResolveInfo(DisplayResolveInfo dri) {
mList.add(dri);
}
public ResolveInfo resolveInfoForPosition(int position, boolean filtered) {
return displayResolveInfoForPosition(position, filtered).ri;
}
public Intent intentForPosition(int position, boolean filtered) {
DisplayResolveInfo dri = displayResolveInfoForPosition(position, filtered);
return intentForDisplayResolveInfo(dri);
}
DisplayResolveInfo displayResolveInfoForPosition(int position, boolean filtered) {
return filtered ? getItem(position) : mList.get(position);
}
@Override
public int getItemCount() {
int result = mList.size();
if (mFilterLastUsed && mLastChosenPosition >= 0) {
result
}
result += getHeaderViewsCount();
return result;
}
@Override
public DisplayResolveInfo getItem(int position) {
position -= getHeaderViewsCount();
if (position < 0) {
return null;
}
if (mFilterLastUsed && mLastChosenPosition >= 0 && position >= mLastChosenPosition) {
position++;
}
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public int getHeaderViewsCount() {
return hasHeader() ? 1 : 0;
}
@Override
protected ViewHolder onCreateHeaderViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(mInflater
.inflate(R.layout.resolver_different_item_header, parent, false));
}
@Override
protected void onBindHeaderViewHolder(ViewHolder holder, int position) {
}
@Override
protected ViewHolder onCreateFooterViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
protected void onBindFooterViewHolder(ViewHolder holder, int position) {
}
@Override
public ViewHolder onCreateItemViewHolder(ViewGroup viewGroup, int i) {
return new ViewHolder(mInflater
.inflate(R.layout.resolve_list_item, viewGroup, false));
}
@Override
public void onBindItemViewHolder(ViewHolder holder, final int position) {
final DisplayResolveInfo info = getItem(position);
holder.text.setText(info.displayLabel);
if (holder.text2 != null) {
if (mShowExtended) {
holder.text2.setVisibility(View.VISIBLE);
holder.text2.setText(info.extendedInfo);
} else {
holder.text2.setVisibility(View.GONE);
}
}
if (holder.icon != null) {
if (info.displayIcon == null) {
new LoadIconTask().execute(info);
}
holder.icon.setImageDrawable(info.displayIcon);
}
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.text1)
public TextView text;
@Nullable @Bind(R.id.text2)
public TextView text2;
@Nullable @Bind(R.id.icon)
public ImageView icon;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
private class LoadIconTask extends AsyncTask<DisplayResolveInfo, Void, DisplayResolveInfo> {
@Override
protected DisplayResolveInfo doInBackground(DisplayResolveInfo... params) {
final DisplayResolveInfo info = params[0];
if (info.displayIcon == null) {
info.displayIcon = loadIconForResolveInfo(mPm, info.ri, mIconDpi);
}
return info;
}
@Override
protected void onPostExecute(DisplayResolveInfo info) {
notifyDataSetChanged();
}
}
public static Drawable loadIconForResolveInfo(PackageManager mPm, ResolveInfo ri, int mIconDpi) {
Drawable dr;
try {
if (ri.resolvePackageName != null && ri.icon != 0) {
dr = getIcon(mPm.getResourcesForApplication(ri.resolvePackageName), ri.icon, mIconDpi);
if (dr != null) {
return dr;
}
}
final int iconRes = ri.getIconResource();
if (iconRes != 0) {
dr = getIcon(mPm.getResourcesForApplication(ri.activityInfo.packageName), iconRes, mIconDpi);
if (dr != null) {
return dr;
}
}
} catch (PackageManager.NameNotFoundException e) {
Timber.e(e, "Couldn't find resources for package");
}
return ri.loadIcon(mPm);
}
private static Drawable getIcon(Resources res, int resId, int mIconDpi) {
Drawable result;
try {
//noinspection deprecation
result = res.getDrawableForDensity(resId, mIconDpi);
} catch (Resources.NotFoundException e) {
result = null;
}
return result;
}
class ResolverComparator implements Comparator<ResolveInfo> {
private final Collator mCollator;
private final boolean mHttp;
public ResolverComparator(Context context, Intent intent) {
mCollator = Collator.getInstance(context.getResources().getConfiguration().locale);
String scheme = intent.getScheme();
mHttp = "http".equals(scheme) || "https".equals(scheme);
}
@Override
public int compare(ResolveInfo lhs, ResolveInfo rhs) {
if (mHttp) {
// Special case: we want filters that match URI paths/schemes to be
// ordered before others. This is for the case when opening URIs,
// to make native apps go above browsers.
final boolean lhsSpecific = isSpecificUriMatch(lhs.match);
final boolean rhsSpecific = isSpecificUriMatch(rhs.match);
if (lhsSpecific != rhsSpecific) {
return lhsSpecific ? -1 : 1;
}
}
if (mHistory != null) {
int leftCount = mHistory.get(lhs.activityInfo.packageName);
int rightCount = mHistory.get(rhs.activityInfo.packageName);
if (leftCount != rightCount) {
return rightCount - leftCount;
}
}
if (mPriorities != null) {
int leftPriority = getPriority(lhs);
int rightPriority = getPriority(rhs);
if (leftPriority != rightPriority) {
return rightPriority - leftPriority;
}
}
if (mStats != null) {
final long timeDiff =
getPackageTimeSpent(rhs.activityInfo.packageName) -
getPackageTimeSpent(lhs.activityInfo.packageName);
if (timeDiff != 0) {
return timeDiff > 0 ? 1 : -1;
}
}
CharSequence sa = lhs.loadLabel(mPm);
if (sa == null) sa = lhs.activityInfo.name;
CharSequence sb = rhs.loadLabel(mPm);
if (sb == null) sb = rhs.activityInfo.name;
return mCollator.compare(sa.toString(), sb.toString());
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private long getPackageTimeSpent(String packageName) {
if (mStats != null) {
final UsageStats stats = mStats.get(packageName);
if (stats != null) {
return stats.getTotalTimeInForeground();
}
}
return 0;
}
private int getPriority(ResolveInfo lhs) {
final Integer integer = mPriorities.get(lhs.activityInfo.packageName);
return integer != null ? integer : 0;
}
}
Intent intentForDisplayResolveInfo(DisplayResolveInfo dri) {
Intent intent = new Intent(mIntent);
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT
| Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
if (dri.ri != null) {
ActivityInfo ai = dri.ri.activityInfo;
intent.setComponent(new ComponentName(
ai.applicationInfo.packageName, ai.name));
}
return intent;
}
static boolean isSpecificUriMatch(int match) {
match = match & IntentFilter.MATCH_CATEGORY_MASK;
return match >= IntentFilter.MATCH_CATEGORY_HOST
&& match <= IntentFilter.MATCH_CATEGORY_PATH;
}
public static class Header {}
}
|
package org.eclipse.birt.report.designer.internal.ui.views.actions;
import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory;
import org.eclipse.birt.report.designer.internal.ui.command.CommandUtils;
import org.eclipse.birt.report.designer.internal.ui.util.Policy;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.util.DNDUtil;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.ColumnHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DataSourceHandle;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.EmbeddedImageHandle;
import org.eclipse.birt.report.model.api.GridHandle;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.ListGroupHandle;
import org.eclipse.birt.report.model.api.ListHandle;
import org.eclipse.birt.report.model.api.ParameterGroupHandle;
import org.eclipse.birt.report.model.api.ReportItemHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.TemplateElementHandle;
import org.eclipse.birt.report.model.api.ThemeHandle;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.MeasureGroupHandle;
import org.eclipse.birt.report.model.api.olap.MeasureHandle;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.NotEnabledException;
import org.eclipse.core.commands.NotHandledException;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.gef.ui.actions.Clipboard;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
/**
* Copy action
*/
public class CopyAction extends AbstractViewAction
{
private static final String DEFAULT_TEXT = Messages.getString( "CopyAction.text" ); //$NON-NLS-1$
/**
* Create a new copy action with given selection and default text
*
* @param selectedObject
* the selected object,which cannot be null
*
*/
public CopyAction( Object selectedObject )
{
this( selectedObject, DEFAULT_TEXT );
}
/**
* Create a new copy action with given selection and text
*
* @param selectedObject
* the selected object,which cannot be null
* @param text
* the text of the action
*/
public CopyAction( Object selectedObject, String text )
{
super( selectedObject, text );
ISharedImages shareImages = PlatformUI.getWorkbench( )
.getSharedImages( );
setImageDescriptor( shareImages.getImageDescriptor( ISharedImages.IMG_TOOL_COPY ) );
setDisabledImageDescriptor( shareImages.getImageDescriptor( ISharedImages.IMG_TOOL_COPY_DISABLED ) );
setAccelerator( SWT.CTRL | 'C' );
}
/**
* Runs this action. Copies the content. Each action implementation must
* define the steps needed to carry out this action. The default
* implementation of this method in <code>Action</code> does nothing.
*/
public void run( )
{
if ( Policy.TRACING_ACTIONS )
{
System.out.println( "Copy action >> Copy " + getSelection( ) ); //$NON-NLS-1$
}
// Object cloneElements = DNDUtil.cloneSource( getSelection( ) );
// Clipboard.getDefault( ).setContents( cloneElements );
try
{
CommandUtils.executeCommand( "org.eclipse.birt.report.designer.ui.command.copyAction" );
}
catch ( ExecutionException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( NotDefinedException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( NotEnabledException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch ( NotHandledException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#isEnabled()
*/
public boolean isEnabled( )
{
if ( canCopy( getSelection( ) ) )
return super.isEnabled( );
return false;
}
// this function is from DNDUtil.handleValidateDragInOutline( Object
// selection )
public boolean canCopy( Object selection )
{
if ( selection instanceof StructuredSelection )
{
return canCopy( ( (StructuredSelection) selection ).toArray( ) );
}
if ( selection instanceof Object[] )
{
Object[] array = (Object[]) selection;
if ( array.length == 0 )
{
return false;
}
if ( array[0] instanceof ColumnHandle
&& ( (ColumnHandle) array[0] ).getRoot( ) != null )
{
boolean bool = false;
int columnNumber = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( array[0] )
.getColumnNumber( );
Object parent = ( (ColumnHandle) array[0] ).getContainer( );
if ( parent instanceof TableHandle )
{
bool = ( (TableHandle) parent ).canCopyColumn( columnNumber );
}
else if ( parent instanceof GridHandle )
{
bool = ( (GridHandle) parent ).canCopyColumn( columnNumber );
}
if ( bool && array.length == 1 )
{
return true;
}
if ( bool && array[1] instanceof CellHandle )
{
return true;
}
return false;
}
for ( int i = 0; i < array.length; i++ )
{
if ( DNDUtil.checkContainerExists( array[i], array ) )
continue;
if ( !canCopy( array[i] ) )
return false;
}
return true;
}
// if ( selection instanceof ReportElementModel )
// return canCopy( ( (ReportElementModel) selection ).getSlotHandle( ) );
if ( selection instanceof SlotHandle )
{
SlotHandle slot = (SlotHandle) selection;
DesignElementHandle handle = slot.getElementHandle( );
return slot.getContents( ).size( ) > 0
&& ( handle instanceof ListHandle || handle instanceof ListGroupHandle );
}
if ( selection instanceof ColumnHandle
&& ( (ColumnHandle) selection ).getRoot( ) != null )
{
int columnNumber = HandleAdapterFactory.getInstance( )
.getColumnHandleAdapter( selection )
.getColumnNumber( );
Object parent = ( (ColumnHandle) selection ).getContainer( );
if ( parent instanceof TableHandle )
{
return ( (TableHandle) parent ).canCopyColumn( columnNumber );
}
else if ( parent instanceof GridHandle )
{
return ( (GridHandle) parent ).canCopyColumn( columnNumber );
}
}
return selection instanceof ReportItemHandle
|| selection instanceof DataSetHandle
|| selection instanceof DataSourceHandle
|| selection instanceof ScalarParameterHandle
|| selection instanceof ParameterGroupHandle
|| selection instanceof GroupHandle
|| selection instanceof StyleHandle
|| selection instanceof ThemeHandle
|| selection instanceof EmbeddedImageHandle
|| selection instanceof TemplateElementHandle
|| selection instanceof CubeHandle
|| selection instanceof LevelHandle
|| selection instanceof MeasureHandle
|| selection instanceof DimensionHandle
|| selection instanceof MeasureGroupHandle;
}
}
|
package org.eclipse.birt.report.designer.ui.dialogs;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import org.eclipse.birt.core.data.DataType;
import org.eclipse.birt.core.format.DateFormatter;
import org.eclipse.birt.core.format.NumberFormatter;
import org.eclipse.birt.core.format.StringFormatter;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.views.data.DataSetItemModel;
import org.eclipse.birt.report.designer.data.ui.dataset.DataSetUIUtil;
import org.eclipse.birt.report.designer.internal.ui.dialogs.BaseDialog;
import org.eclipse.birt.report.designer.internal.ui.util.DataSetManager;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.widget.ComboBoxCellEditor;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.actions.NewDataSetAction;
import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.model.api.CachedMetaDataHandle;
import org.eclipse.birt.report.model.api.CascadingParameterGroupHandle;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.DesignEngine;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ScalarParameterHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.command.NameException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import com.ibm.icu.util.ULocale;
/**
* Cascading Parameter Dialog.
*/
public class CascadingParametersDialog extends BaseDialog
{
private static final String LABEL_PROMPT_TEXT = Messages.getString( "CascadingParametersDialog.label.promptText" ); //$NON-NLS-1$
private static final String LABEL_SELECT_DISPLAY_COLUMN = Messages.getString( "CascadingParametersDialog.label.select.displayColumn" ); //$NON-NLS-1$
private static final String LABEL_VALUES = Messages.getString( "CascadingParametersDialog.label.values" ); //$NON-NLS-1$
private static final String LABEL_LIST_LIMIT = Messages.getString( "CascadingParametersDialog.label.listLimit" ); //$NON-NLS-1$
private static final String LABEL_GROUP_GENERAL = Messages.getString( "CascadingParametersDialog.label.group.general" ); //$NON-NLS-1$
private static final String LABEL_CASCADING_PARAMETER_NAME = Messages.getString( "CascadingParametersDialog.label.cascadingParam.name" ); //$NON-NLS-1$
private static final String LABEL_DATA_SETS = Messages.getString( "CascadingParametersDialog.label.dataSets" ); //$NON-NLS-1$
private static final String LABEL_BUTTON_CREATE_NEW_DATASET = Messages.getString( "CascadingParametersDialog.label.button.createNew.dataset" ); //$NON-NLS-1$
private static final String LABEL_PARAMETERS = Messages.getString( "CascadingParametersDialog.label.parameters" ); //$NON-NLS-1$
private static final String LABEL_GROUP_PROPERTIES = Messages.getString( "CascadingParametersDialog.label.group.properties" ); //$NON-NLS-1$
private static final String LABEL_PARAM_NAME = Messages.getString( "CascadingParametersDialog.label.param.name" ); //$NON-NLS-1$
private static final String LABEL_DATA_TYPE = Messages.getString( "CascadingParametersDialog.label.dataType" ); //$NON-NLS-1$
private static final String LABEL_DISPLAY_TYPE = Messages.getString( "CascadingParametersDialog.label.displayType" ); //$NON-NLS-1$
private static final String LABEL_DEFAULT_VALUE = Messages.getString( "CascadingParametersDialog.label.defaultValue" ); //$NON-NLS-1$
private static final String LABEL_GROUP_MORE_OPTIONS = Messages.getString( "CascadingParametersDialog.label.group.moreOptions" ); //$NON-NLS-1$
private static final String LABEL_HELP_TEXT = Messages.getString( "CascadingParametersDialog.label.helpText" ); //$NON-NLS-1$
private static final String LABEL_FORMAT_AS = Messages.getString( "CascadingParametersDialog.label.formatAs" ); //$NON-NLS-1$
private static final String LABEL_CHANGE_FORMAT_BUTTON = Messages.getString( "CascadingParametersDialog.label.button.changeFormat" ); //$NON-NLS-1$
private static final String LABEL_PREVIEW_WITH_FORMAT = Messages.getString( "CascadingParametersDialog.label.preview" ); //$NON-NLS-1$
private static final String LABEL_CREATE_NEW_PARAMETER = Messages.getString( "CascadingParametersDialog.label.createNewParam" ); //$NON-NLS-1$
private static final String LABEL_SELECT_A_VALUE_COLUMN = Messages.getString( "CascadingParametersDialog.label.selecteValueColumn" ); //$NON-NLS-1$
private static final String LABEL_NO_COLUMN_AVAILABLE = Messages.getString( "CascadingParametersDialog.Label.NoColumnAvailable" ); //$NON-NLS-1$
private static final String BUTTON_ALLOW_NULL_VALUE = Messages.getString( "CascadingParametersDialog.Button.AllowNull" ); //$NON-NLS-1$
private static final String COLUMN_NAME = "Name"; //$NON-NLS-1$
private static final String COLUMN_VALUE = "Value"; //$NON-NLS-1$
private static final String COLUMN_DISPLAY_TEXT = "Display Text"; //$NON-NLS-1$
private static final String COLUMN_NAME_LABEL = Messages.getString( "CascadingParametersDialog.label.column.name" ); //$NON-NLS-1$
private static final String COLUMN_VALUE_LABEL = Messages.getString( "CascadingParametersDialog.label.column.value" ); //$NON-NLS-1$
private static final String COLUMN_DISPLAY_TEXT_LABEL = Messages.getString( "CascadingParametersDialog.label.column.displayText" ); //$NON-NLS-1$
private static final String PARAM_CONTROL_LIST = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX
+ "/List"; //$NON-NLS-1$
private static final String PARAM_CONTROL_COMBO = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX
+ "/Combo"; //$NON-NLS-1$
private static final String DISPLAY_NAME_CONTROL_LIST = Messages.getString( "CascadingParametersDialog.display.controlType.listBox" ); //$NON-NLS-1$
private static final String DISPLAY_NAME_CONTROL_COMBO = Messages.getString( "CascadingParametersDialog.display.controlType.comboBox" ); //$NON-NLS-1$
private static final double DEFAULT_PREVIEW_NUMBER = Double.parseDouble( "1234.56" ); //$NON-NLS-1$
private static final String DEFAULT_PREVIEW_STRING = Messages.getString( "CascadingParametersDialog.default.preview.string" ); //$NON-NLS-1$
private static final String ERROR_TITLE_INVALID_LIST_LIMIT = Messages.getString( "ParameterDialog.ErrorTitle.InvalidListLimit" ); //$NON-NLS-1$
private static final String ERROR_MSG_INVALID_LIST_LIMIT = Messages.getString( "ParameterDialog.ErrorMessage.InvalidListLimit" ); //$NON-NLS-1$
private Group optionsGroup;
private Group propertiesGroup;
private Text cascadingNameEditor;
private Text paramNameEditor;
private Text helpTextEditor;
private Text defaultValueEditor;
private Text formatField;
private Text listLimit;
private Text promptText;
private Combo dataSetsCombo;
private Combo dataTypeChooser;
private Combo displayTypeChooser;
private Button createDSButton;
private Button changeFormat;
private Label previewLable;
private Table table;
private TableViewer valueTable;
private CellEditor[] cellEditors;
private static IChoiceSet dataType = DesignEngine.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_PARAM_TYPE );
private CascadingParameterGroupHandle inputParameterGroup;
private DataSetHandle dataSet;
private ScalarParameterHandle selectedParameter;
// private ArrayList inputParameters = new ArrayList( );
protected ScalarParameterHandle newParameter = null;
private String defaultValue;
private String formatPattern;
private String formatCategroy;
private boolean loading = true;
private Button allowNull;
/**
*
* Constructor.
*
* @param parentShell
* @param title
*/
public CascadingParametersDialog( Shell parentShell, String title )
{
super( parentShell, title );
}
/**
* Constructor.
*
* @param title
*/
public CascadingParametersDialog( String title )
{
super( title );
}
protected Control createDialogArea( Composite parent )
{
Composite composite = (Composite) super.createDialogArea( parent );
GridData data = new GridData( );
data.widthHint = 550;
composite.setLayoutData( data );
createGeneralPart( composite );
createDynamicParamsPart( composite );
createPropertiesPart( composite );
createOptionsPart( composite );
return composite;
}
private void createGeneralPart( Composite parent )
{
Group group = new Group( parent, SWT.NULL );
group.setText( LABEL_GROUP_GENERAL );
group.setLayout( new GridLayout( 2, false ) );
group.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Label label = new Label( group, SWT.NULL );
label.setText( LABEL_CASCADING_PARAMETER_NAME );
cascadingNameEditor = new Text( group, SWT.BORDER );
cascadingNameEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
private void createDynamicParamsPart( Composite parent )
{
Composite comp = new Composite( parent, SWT.NULL );
GridLayout layout = new GridLayout( 3, false );
layout.marginHeight = 0;
layout.marginWidth = 0;
comp.setLayout( layout );
comp.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( comp, LABEL_DATA_SETS );
dataSetsCombo = new Combo( comp, SWT.READ_ONLY );
GridData data = new GridData( );
data.widthHint = 120;
dataSetsCombo.setLayoutData( data );
dataSetsCombo.setItems( getDataSets( ) );
dataSetsCombo.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
dataSet = getDataSet( dataSetsCombo.getText( ) );
refreshValueTable( );
updateButtons( );
}
} );
createDSButton = new Button( comp, SWT.PUSH );
createDSButton.setText( LABEL_BUTTON_CREATE_NEW_DATASET );
createDSButton.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
new NewDataSetAction( ).run( );
refreshDataSets( );
}
} );
Label label = new Label( comp, SWT.NULL );
label.setText( LABEL_PARAMETERS );
data = new GridData( );
data.horizontalSpan = 3;
label.setLayoutData( data );
table = new Table( comp, SWT.FULL_SELECTION
| SWT.HIDE_SELECTION
| SWT.BORDER );
data = new GridData( GridData.FILL_HORIZONTAL );
data.horizontalSpan = 3;
data.heightHint = 100;
table.setLayoutData( data );
table.setLinesVisible( true );
table.setHeaderVisible( true );
table.addKeyListener( new KeyAdapter( ) {
public void keyReleased( KeyEvent e )
{
// If Delete pressed, delete the selected row
if ( e.keyCode == SWT.DEL )
{
deleteRow( );
}
}
} );
int[] columnWidths = new int[]{
180, 145, 145,
};
String[] columnProps = new String[]{
COLUMN_NAME, COLUMN_VALUE, COLUMN_DISPLAY_TEXT
};
String[] columnLabels = new String[]{
COLUMN_NAME_LABEL,
COLUMN_VALUE_LABEL,
COLUMN_DISPLAY_TEXT_LABEL
};
cellEditors = new CellEditor[]{
new TextCellEditor( table ),
new ComboBoxCellEditor( table, new String[0], SWT.READ_ONLY ),
new ComboBoxCellEditor( table, new String[0], SWT.READ_ONLY ),
};
for ( int i = 0; i < columnProps.length; i++ )
{
TableColumn column = new TableColumn( table, SWT.LEFT );
column.setResizable( true );
column.setText( columnLabels[i] );
column.setWidth( columnWidths[i] );
}
valueTable = new TableViewer( table );
valueTable.setCellEditors( cellEditors );
valueTable.setColumnProperties( columnProps );
valueTable.setContentProvider( contentProvider );
valueTable.setLabelProvider( labelProvider );
valueTable.setCellModifier( cellModifier );
valueTable.addSelectionChangedListener( new ISelectionChangedListener( ) {
public void selectionChanged( SelectionChangedEvent event )
{
ISelection selection = event.getSelection( );
Object param = ( (StructuredSelection) selection ).getFirstElement( );
if ( param != selectedParameter )
{
if ( param instanceof ScalarParameterHandle )
{
try
{
saveParameterProperties( );
selectedParameter = (ScalarParameterHandle) param;
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
valueTable.setSelection( new StructuredSelection( selectedParameter ) );
}
refreshParameterProperties( );
updateButtons( );
}
}
}
} );
}
private void createPropertiesPart( Composite parent )
{
propertiesGroup = new Group( parent, SWT.NULL );
propertiesGroup.setText( LABEL_GROUP_PROPERTIES );
propertiesGroup.setLayout( new GridLayout( 2, false ) );
propertiesGroup.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( propertiesGroup, LABEL_PARAM_NAME );
paramNameEditor = new Text( propertiesGroup, SWT.BORDER );
paramNameEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
paramNameEditor.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
valueTable.refresh( selectedParameter );
}
} );
createLabel( propertiesGroup, LABEL_PROMPT_TEXT );
promptText = new Text( propertiesGroup, SWT.BORDER );
promptText.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( propertiesGroup, LABEL_DATA_TYPE );
dataTypeChooser = new Combo( propertiesGroup, SWT.DROP_DOWN
| SWT.READ_ONLY );
dataTypeChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
dataTypeChooser.setItems( ChoiceSetFactory.getDisplayNamefromChoiceSet( dataType ) );
dataTypeChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
if ( selectedParameter != null
&& selectedParameter != newParameter )
{
changeDataType( dataType.findChoiceByDisplayName( dataTypeChooser.getText( ) )
.getName( ) );
try
{
selectedParameter.setDataType( dataType.findChoiceByDisplayName( dataTypeChooser.getText( ) )
.getName( ) );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
}
}
} );
createLabel( propertiesGroup, LABEL_DISPLAY_TYPE );
displayTypeChooser = new Combo( propertiesGroup, SWT.DROP_DOWN
| SWT.READ_ONLY );
displayTypeChooser.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
displayTypeChooser.setItems( new String[]{
DISPLAY_NAME_CONTROL_LIST, DISPLAY_NAME_CONTROL_COMBO
} );
displayTypeChooser.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
if ( selectedParameter != null
&& selectedParameter != newParameter )
{
try
{
String newControlType = getSelectedDisplayType( );
if ( PARAM_CONTROL_COMBO.equals( newControlType ) )
{
newControlType = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX;
selectedParameter.setMustMatch( true );
}
else if ( PARAM_CONTROL_LIST.equals( newControlType ) )
{
newControlType = DesignChoiceConstants.PARAM_CONTROL_LIST_BOX;
selectedParameter.setMustMatch( false );
}
else
{
selectedParameter.setProperty( ScalarParameterHandle.MUCH_MATCH_PROP,
null );
}
selectedParameter.setControlType( newControlType );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
}
}
} );
createLabel( propertiesGroup, LABEL_DEFAULT_VALUE );
defaultValueEditor = new Text( propertiesGroup, SWT.BORDER );
defaultValueEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
}
private void createOptionsPart( Composite parent )
{
optionsGroup = new Group( parent, SWT.NULL );
optionsGroup.setText( LABEL_GROUP_MORE_OPTIONS );
optionsGroup.setLayout( new GridLayout( 2, false ) );
optionsGroup.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( optionsGroup, LABEL_HELP_TEXT );
helpTextEditor = new Text( optionsGroup, SWT.BORDER );
helpTextEditor.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Label lable = new Label( optionsGroup, SWT.NULL );
lable.setText( LABEL_FORMAT_AS );
lable.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_BEGINNING ) );
Composite formatArea = new Composite( optionsGroup, SWT.NONE );
formatArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, false ) );
formatArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
formatField = new Text( formatArea, SWT.BORDER
| SWT.SINGLE
| SWT.READ_ONLY );
formatField.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
changeFormat = new Button( formatArea, SWT.PUSH );
changeFormat.setText( LABEL_CHANGE_FORMAT_BUTTON );
setButtonLayoutData( changeFormat );
changeFormat.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
popupFormatBuilder( true );
}
} );
Group preview = new Group( formatArea, SWT.NULL );
preview.setText( LABEL_PREVIEW_WITH_FORMAT );
preview.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
preview.setLayout( new GridLayout( ) );
previewLable = new Label( preview, SWT.CENTER
| SWT.HORIZONTAL
| SWT.VIRTUAL );
previewLable.setText( "" ); //$NON-NLS-1$
previewLable.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
createLabel( optionsGroup, LABEL_LIST_LIMIT );
Composite composite = new Composite( optionsGroup, SWT.NULL );
composite.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, true ) );
composite.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
Composite limitArea = new Composite( composite, SWT.NULL );
limitArea.setLayout( UIUtil.createGridLayoutWithoutMargin( 2, true ) );
limitArea.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
listLimit = new Text( limitArea, SWT.BORDER );
GridData gridData = new GridData( );
gridData.widthHint = 80;
listLimit.setLayoutData( gridData );
listLimit.addVerifyListener( new VerifyListener( ) {
public void verifyText( VerifyEvent e )
{
e.doit = ( "0123456789\0\b\u007f".indexOf( e.character ) != -1 );
}
} );
listLimit.addModifyListener( new ModifyListener( ) {
private String oldValue = ""; //$NON-NLS-1$
public void modifyText( ModifyEvent e )
{
try
{
if ( !StringUtil.isBlank( listLimit.getText( ) ) )
{
Integer.parseInt( listLimit.getText( ) );
oldValue = listLimit.getText( );
}
}
catch ( NumberFormatException e1 )
{
ExceptionHandler.openErrorMessageBox( ERROR_TITLE_INVALID_LIST_LIMIT,
MessageFormat.format( ERROR_MSG_INVALID_LIST_LIMIT,
new Object[]{
Integer.toString( Integer.MAX_VALUE )
} ) );
listLimit.setText( oldValue );
}
}
} );
new Label( limitArea, SWT.NONE ).setText( LABEL_VALUES );
allowNull = new Button( composite, SWT.CHECK );
allowNull.setText( BUTTON_ALLOW_NULL_VALUE );
allowNull.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
allowNull.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
if ( selectedParameter != null
&& selectedParameter != newParameter )
{
try
{
selectedParameter.setAllowNull( allowNull.getSelection( ) );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
}
}
} );
}
private void createLabel( Composite parent, String content )
{
Label label = new Label( parent, SWT.NONE );
setLabelLayoutData( label );
if ( content != null )
{
label.setText( content );
}
}
private void setLabelLayoutData( Control control )
{
GridData gd = new GridData( GridData.VERTICAL_ALIGN_BEGINNING );
gd.widthHint = 100;
control.setLayoutData( gd );
}
// set input for dialog
public void setInput( Object input )
{
Assert.isNotNull( input );
Assert.isLegal( input instanceof CascadingParameterGroupHandle );
inputParameterGroup = (CascadingParameterGroupHandle) input;
}
// initiate dialog
protected boolean initDialog( )
{
dataSet = inputParameterGroup.getDataSet( );
if ( dataSet != null )
{
dataSetsCombo.setText( "" + dataSet.getName( ) ); //$NON-NLS-1$
}
else
{
dataSetsCombo.select( 0 );
dataSet = getDataSet( dataSetsCombo.getText( ) );
}
cascadingNameEditor.setText( inputParameterGroup.getName( ) );
valueTable.setInput( inputParameterGroup );
refreshParameterProperties( );
updateButtons( );
return true;
}
// ok pressed
protected void okPressed( )
{
try
{
saveParameterProperties( );
inputParameterGroup.setName( cascadingNameEditor.getText( ) );
inputParameterGroup.setDataSet( dataSet );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
refreshParameterProperties( );
return;
}
setResult( inputParameterGroup );
super.okPressed( );
}
private void deleteRow( )
{
int index = valueTable.getTable( ).getSelectionIndex( );
ScalarParameterHandle choice = (ScalarParameterHandle) ( (IStructuredSelection) valueTable.getSelection( ) ).getFirstElement( );
if ( choice == null )
{
return;
}
try
{
inputParameterGroup.getParameters( ).drop( choice );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
return;
}
refreshValueTable( );
index
if ( index < 0 && valueTable.getTable( ).getItemCount( ) > 1 )
{
index = 0;
}
StructuredSelection selection = null;
if ( index != -1 )
{
selection = new StructuredSelection( valueTable.getTable( )
.getItem( index )
.getData( ) );
}
else
{
selection = StructuredSelection.EMPTY;
}
valueTable.setSelection( selection );
}
private void refreshDataSets( )
{
String selectedDataSetName = dataSetsCombo.getText( );
String[] oldList = dataSetsCombo.getItems( );
String[] newDataSets = ChoiceSetFactory.getDataSets( );
if ( !Arrays.asList( oldList ).equals( Arrays.asList( newDataSets ) ) )
{
dataSetsCombo.setItems( newDataSets );
dataSetsCombo.setText( selectedDataSetName );
}
}
private String[] getDataSets( )
{
return ChoiceSetFactory.getDataSets( );
}
private DataSetHandle getDataSet( String name )
{
if ( name == null )
{
return null;
}
String value = name;
DataSetHandle dataSet = null;
if ( value != null )
{
dataSet = SessionHandleAdapter.getInstance( )
.getReportDesignHandle( )
.findDataSet( value );
}
return dataSet;
}
private String[] getDataSetColumns( )
{
return getDataSetColumns( null );
}
private String[] getDataSetColumns( ScalarParameterHandle handle )
{
if ( dataSet == null )
{
return new String[0];
}
DataSetItemModel[] models = DataSetManager.getCurrentInstance( )
.getColumns( dataSet, false );
if ( models == null )
{
return new String[0];
}
ArrayList valueList = new ArrayList( models.length );
for ( int i = 0; i < models.length; i++ )
{
if ( handle == null || matchDataType( handle, models[i] ) )
{
valueList.add( models[i].getName( ) );
}
}
return (String[]) valueList.toArray( new String[0] );
}
private void setCellEditorItems( )
{
( (ComboBoxCellEditor) cellEditors[1] ).setItems( getDataSetColumns( selectedParameter ) );
( (ComboBoxCellEditor) cellEditors[2] ).setItems( getDataSetColumns( ) );
}
private IStructuredContentProvider contentProvider = new IStructuredContentProvider( ) {
public Object[] getElements( Object inputElement )
{
ArrayList elementsList = new ArrayList( inputParameterGroup.getParameters( )
.getContents( ) );
for ( Iterator iter = elementsList.iterator( ); iter.hasNext( ); )
{
ScalarParameterHandle handle = (ScalarParameterHandle) iter.next( );
String[] columns = getDataSetColumns( handle );
boolean found = false;
for ( int i = 0; i < columns.length; i++ )
{
if ( DEUtil.getColumnExpression( columns[i] )
.equals( handle.getValueExpr( ) ) )
{
found = true;
break;
}
}
if ( !found )
{
try
{
handle.setValueExpr( null );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
if ( newParameter == null )
{
newParameter = DesignElementFactory.getInstance( )
.newScalarParameter( null ); //$NON-NLS-1$
try
{
newParameter.setControlType( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX );
newParameter.setValueType( DesignChoiceConstants.PARAM_VALUE_TYPE_DYNAMIC );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
elementsList.add( newParameter );
return elementsList.toArray( );
}
public void dispose( )
{
}
public void inputChanged( Viewer viewer, Object oldInput,
Object newInput )
{
}
};
private ITableLabelProvider labelProvider = new ITableLabelProvider( ) {
public Image getColumnImage( Object element, int columnIndex )
{
return null;
}
public String getColumnText( Object element, int columnIndex )
{
String value = null;
ScalarParameterHandle paramHandle = null;
if ( element instanceof ScalarParameterHandle )
{
paramHandle = (ScalarParameterHandle) element;
}
if ( paramHandle == newParameter )
{
if ( columnIndex == 0 )
{
value = LABEL_CREATE_NEW_PARAMETER;
}
else if ( columnIndex == 1 )
{
value = LABEL_SELECT_A_VALUE_COLUMN;
}
}
else
{
switch ( columnIndex )
{
case 0 :
{
if ( paramHandle != newParameter )
{
String paramName;
if ( paramHandle != selectedParameter )
{
paramName = paramHandle.getName( );
}
else
{
paramName = paramNameEditor.getText( ).trim( );
}
value = getDummyText( paramHandle ) + paramName;
}
break;
}
case 1 :
{
if ( paramHandle.getValueExpr( ) != null )
{
value = getColumnName( paramHandle.getValueExpr( ) );
}
else if ( getDataSetColumns( paramHandle ).length > 0 )
{
value = LABEL_SELECT_A_VALUE_COLUMN;
}
else
{
value = LABEL_NO_COLUMN_AVAILABLE;
}
break;
}
case 2 :
{
value = getColumnName( paramHandle.getLabelExpr( ) );
if ( value == null )
{
if ( getDataSetColumns( ).length > 0 )
{
value = LABEL_SELECT_DISPLAY_COLUMN;
}
else
{
value = LABEL_NO_COLUMN_AVAILABLE;
}
}
break;
}
}
}
if ( value == null )
{
value = ""; //$NON-NLS-1$
}
return value;
}
private String getDummyText( Object element )
{
String dummyText = ""; //$NON-NLS-1$
int index = getTableIndex( element );
for ( int i = 0; i < index; i++ )
{
dummyText += " "; //$NON-NLS-1$
}
return dummyText;
}
public void addListener( ILabelProviderListener listener )
{
}
public void dispose( )
{
}
public boolean isLabelProperty( Object element, String property )
{
return false;
}
public void removeListener( ILabelProviderListener listener )
{
}
};
private ICellModifier cellModifier = new ICellModifier( ) {
public boolean canModify( Object element, String property )
{
if ( element != selectedParameter )
{
return false;
}
if ( element == newParameter )
{
if ( !property.equals( COLUMN_VALUE ) )
{
return false;
}
}
else if ( property.equals( COLUMN_NAME ) )
{
return false;
}
if ( property.equals( COLUMN_VALUE ) )
{
if ( getDataSetColumns( (ScalarParameterHandle) element ).length == 0 )
{
return false;
}
}
setCellEditorItems( );
return true;
}
public Object getValue( Object element, String property )
{
if ( element instanceof ScalarParameterHandle )
{
ScalarParameterHandle parameter = (ScalarParameterHandle) element;
String value = null;
if ( COLUMN_NAME.equals( property ) )
{
if ( element == newParameter )
{
value = ""; //$NON-NLS-1$
}
else
{
value = parameter.getName( );
}
}
else if ( COLUMN_VALUE.equals( property ) )
{
value = getColumnName( parameter.getValueExpr( ) );
}
else if ( COLUMN_DISPLAY_TEXT.equals( property ) )
{
value = getColumnName( parameter.getLabelExpr( ) );
}
if ( value == null )
{
value = ""; //$NON-NLS-1$
}
return value;
}
return ""; //$NON-NLS-1$
}
public void modify( Object element, String property, Object value )
{
Object actualElement = ( (TableItem) element ).getData( );
try
{
saveParameterProperties( );
}
catch ( SemanticException e1 )
{
// TODO Auto-generated catch block
e1.printStackTrace( );
}
if ( COLUMN_NAME.equals( property ) )
{
try
{
if ( actualElement == newParameter )
{
( (ScalarParameterHandle) actualElement ).setName( newParameter.getName( ) );
}
else
{
( (ScalarParameterHandle) actualElement ).setName( (String) value );
}
}
catch ( NameException e )
{
ExceptionHandler.handle( e );
}
}
else if ( COLUMN_VALUE.equals( property ) )
{
try
{
( (ScalarParameterHandle) actualElement ).setValueExpr( DEUtil.getColumnExpression( (String) value ) );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
else if ( COLUMN_DISPLAY_TEXT.equals( property ) )
{
try
{
( (ScalarParameterHandle) actualElement ).setLabelExpr( DEUtil.getColumnExpression( (String) value ) );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
if ( actualElement == newParameter )
{
if ( newParameter.getValueExpr( ) != null
&& newParameter.getValueExpr( ).trim( ).length( ) > 0 )
{
try
{
inputParameterGroup.getParameters( ).add( newParameter );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
return;
}
clearNewParameter( );
}
}
refreshValueTable( );
refreshParameterProperties( );
updateButtons( );
}
};
private void clearNewParameter( )
{
newParameter = null;
}
protected int getTableIndex( Object element )
{
Object[] input = ( (IStructuredContentProvider) valueTable.getContentProvider( ) ).getElements( valueTable.getInput( ) );
int index = 0;
if ( element != newParameter )
{
for ( int i = 0; i < input.length; i++ )
{
if ( element == input[i] )
{
index = i;
break;
}
}
}
return index;
}
private void refreshValueTable( )
{
if ( valueTable != null && !valueTable.getTable( ).isDisposed( ) )
{
valueTable.refresh( );
}
}
private void refreshParameterProperties( )
{
if ( selectedParameter == null || selectedParameter == newParameter )
{
clearParamProperties( );
setControlEnabled( false );
return;
}
loading = true;
setControlEnabled( true );
paramNameEditor.setText( selectedParameter.getName( ) );
if ( selectedParameter.getPromptText( ) == null )
{
promptText.setText( "" ); //$NON-NLS-1$
}
else
{
promptText.setText( selectedParameter.getPromptText( ) );
}
dataTypeChooser.setText( dataType.findChoice( selectedParameter.getDataType( ) )
.getDisplayName( ) );
if ( getInputDisplayName( ) == null )
{
displayTypeChooser.clearSelection( ); //$NON-NLS-1$
}
else
{
displayTypeChooser.setText( getInputDisplayName( ) );
}
defaultValue = selectedParameter.getDefaultValue( );
if ( defaultValue == null )
{
defaultValueEditor.setText( "" ); //$NON-NLS-1$
}
else
{
defaultValueEditor.setText( defaultValue );
}
helpTextEditor.setText( UIUtil.convertToGUIString( selectedParameter.getHelpText( ) ) );
if ( selectedParameter.getPropertyHandle( ScalarParameterHandle.LIST_LIMIT_PROP )
.isSet( ) )
{
listLimit.setText( String.valueOf( selectedParameter.getListlimit( ) ) );
}
else
{
listLimit.setText( "" ); //$NON-NLS-1$
}
allowNull.setSelection( selectedParameter.allowNull( ) );
changeDataType( selectedParameter.getDataType( ) );
loading = false;
}
private void clearParamProperties( )
{
paramNameEditor.setText( "" ); //$NON-NLS-1$
promptText.setText( "" ); //$NON-NLS-1$
dataTypeChooser.select( -1 );
displayTypeChooser.select( -1 );
defaultValueEditor.setText( "" ); //$NON-NLS-1$
helpTextEditor.setText( "" ); //$NON-NLS-1$
formatField.setText( "" ); //$NON-NLS-1$
listLimit.setText( "" ); //$NON-NLS-1$
previewLable.setText( "" ); //$NON-NLS-1$
allowNull.setSelection( false );
}
private void setControlEnabled( boolean enable )
{
paramNameEditor.setEnabled( enable );
promptText.setEnabled( enable );
dataTypeChooser.setEnabled( enable );
displayTypeChooser.setEnabled( enable );
defaultValueEditor.setEnabled( enable );
helpTextEditor.setEnabled( enable );
formatField.setEnabled( enable );
listLimit.setEnabled( enable );
changeFormat.setEnabled( enable );
}
private void changeDataType( String type )
{
initFormatField( type );
refreshValueTable( );
updateButtons( );
}
private void initFormatField( String selectedDataType )
{
IChoiceSet choiceSet = getFormatChoiceSet( selectedDataType );
if ( choiceSet == null )
{
formatCategroy = formatPattern = null;
}
else
{
if ( !loading || selectedParameter.getFormat( ) == null )
{
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( selectedDataType ) )
{
formatCategroy = choiceSet.findChoice( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED )
.getName( );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( selectedDataType ) )
{
formatCategroy = choiceSet.findChoice( DesignChoiceConstants.DATETIEM_FORMAT_TYPE_UNFORMATTED )
.getName( );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( selectedDataType )
|| DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( selectedDataType ) )
{
formatCategroy = choiceSet.findChoice( DesignChoiceConstants.NUMBER_FORMAT_TYPE_UNFORMATTED )
.getName( );
}
formatPattern = null;
}
else
{
formatCategroy = getCategroy( selectedParameter.getFormat( ) );
formatPattern = getPattern( selectedParameter.getFormat( ) );
}
}
updateFormatField( );
}
private String getInputDisplayName( )
{
String displayName = null;
if ( DesignChoiceConstants.PARAM_CONTROL_LIST_BOX.equals( selectedParameter.getControlType( ) ) )
{
if ( selectedParameter.isMustMatch( ) )
{
displayName = DISPLAY_NAME_CONTROL_COMBO;
}
else
{
displayName = DISPLAY_NAME_CONTROL_LIST;
}
}
return displayName;
}
private IChoiceSet getFormatChoiceSet( String type )
{
IChoiceSet choiceSet = null;
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) )
{
choiceSet = DesignEngine.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_STRING_FORMAT_TYPE );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) )
{
choiceSet = DesignEngine.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_DATETIME_FORMAT_TYPE );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type )
|| DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) )
{
choiceSet = DesignEngine.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_NUMBER_FORMAT_TYPE );
}
return choiceSet;
}
private String getSelectedDataType( )
{
String type = null;
if ( StringUtil.isBlank( dataTypeChooser.getText( ) ) )
{
if ( selectedParameter != null )
{
type = selectedParameter.getDataType( );
}
else
{
type = DesignChoiceConstants.PARAM_TYPE_STRING;
}
}
else
{
IChoice choice = dataType.findChoiceByDisplayName( dataTypeChooser.getText( ) );
type = choice.getName( );
}
return type;
}
/**
* Gets the internal name of the control type from the display name
*/
private String getSelectedDisplayType( )
{
String displayText = displayTypeChooser.getText( );
if ( displayText.length( ) == 0 )
{
return null;
}
if ( DISPLAY_NAME_CONTROL_COMBO.equals( displayText ) )
{
return PARAM_CONTROL_COMBO;
}
if ( DISPLAY_NAME_CONTROL_LIST.equals( displayText ) )
{
return PARAM_CONTROL_LIST;
}
return null;
}
private void popupFormatBuilder( boolean refresh )
{
String type = getSelectedDataType( );
int style;
if ( DesignChoiceConstants.PARAM_TYPE_BOOLEAN.equals( type ) )
{
return;
}
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) )
{
style = FormatBuilder.STRING;
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) )
{
style = FormatBuilder.DATETIME;
}
else
{
style = FormatBuilder.NUMBER;
}
FormatBuilder formatBuilder = new FormatBuilder( style );
formatBuilder.setInputFormat( formatCategroy, formatPattern );
// formatBuilder.setPreviewText( defaultValue );
if ( formatBuilder.open( ) == OK )
{
formatCategroy = getCategroy( (String) formatBuilder.getResult( ) );
formatPattern = getPattern( (String) formatBuilder.getResult( ) );
updateFormatField( );
}
}
private void updateFormatField( )
{
String displayFormat;
IChoiceSet choiceSet = getFormatChoiceSet( getSelectedDataType( ) );
if ( choiceSet == null )
{// Boolean type;
displayFormat = DesignEngine.getMetaDataDictionary( )
.getChoiceSet( DesignChoiceConstants.CHOICE_STRING_FORMAT_TYPE )
.findChoice( DesignChoiceConstants.STRING_FORMAT_TYPE_UNFORMATTED )
.getDisplayName( );
}
else
{
displayFormat = choiceSet.findChoice( formatCategroy )
.getDisplayName( );
if ( formatPattern != null )
{
displayFormat += ": " + formatPattern; //$NON-NLS-1$
}
}
formatField.setText( "" + displayFormat ); //$NON-NLS-1$
changeFormat.setEnabled( choiceSet != null );
if ( selectedParameter != null )
{
try
{
doPreview( formatPattern == null ? formatCategroy
: formatPattern );
String format = formatCategroy;
if ( formatPattern != null )
{
format += ":" + formatPattern; //$NON-NLS-1$
}
selectedParameter.setFormat( format );
}
catch ( SemanticException e1 )
{
ExceptionHandler.handle( e1 );
}
}
}
private void doPreview( String pattern )
{
String type = getSelectedDataType( );
String formatStr = ""; //$NON-NLS-1$
if ( DesignChoiceConstants.PARAM_TYPE_STRING.equals( type ) )
{
formatStr = new StringFormatter( pattern, ULocale.getDefault( ) ).format( DEFAULT_PREVIEW_STRING );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( type ) )
{
formatStr = new DateFormatter( pattern ).format( new Date( ) );
}
else if ( DesignChoiceConstants.PARAM_TYPE_DECIMAL.equals( type )
|| DesignChoiceConstants.PARAM_TYPE_FLOAT.equals( type ) )
{
formatStr = new NumberFormatter( pattern ).format( DEFAULT_PREVIEW_NUMBER );
}
previewLable.setText( formatStr );
}
private String getCategroy( String formatString )
{
if ( formatString != null )
{
return formatString.split( ":" )[0]; // NON-NLS-1$ //$NON-NLS-1$
}
return null;
}
private String getPattern( String formatString )
{
if ( formatString != null )
{
int index = formatString.indexOf( ':' ); // NON-NLS-1$
if ( index == -1 )
{
return null;
}
return formatString.substring( index + 1 );
}
return null;
}
private String getColumnName( String value )
{
// DataSetItemModel[] models = DataSetManager.getCurrentInstance( )
// .getColumns( dataSet, true );
// if ( value != null )
// for ( int i = 0; i < models.length; i++ )
// if ( value.equalsIgnoreCase( DEUtil.getColumnExpression(
// models[i].getName( ) ) ) )
// return models[i].getName( );
CachedMetaDataHandle cmdh = null;
try
{
cmdh = DataSetUIUtil.getCachedMetaDataHandle( dataSet );
}
catch ( SemanticException e )
{
}
if ( cmdh != null )
{
for ( Iterator iter = cmdh.getResultSet( ).iterator( ); iter.hasNext( ); )
{
ResultSetColumnHandle element = (ResultSetColumnHandle) iter.next( );
if ( DEUtil.getColumnExpression( element.getColumnName( ) )
.equalsIgnoreCase( value ) )
{
return element.getColumnName( );
}
}
}
return null;
}
private void updateButtons( )
{
boolean okEnable = true;
if ( dataSet == null )
{
okEnable = false;
}
else
{
Iterator iter = inputParameterGroup.getParameters( ).iterator( );
if ( !iter.hasNext( ) )
{
okEnable = false;
}
else
{
int count = 0;
while ( iter.hasNext( ) )
{
Object obj = iter.next( );
if ( obj instanceof ScalarParameterHandle )
{
ScalarParameterHandle param = (ScalarParameterHandle) obj;
count++;
if ( param.getValueExpr( ) == null )
{
okEnable = false;
break;
}
}
}
okEnable &= ( count != 0 );
}
}
getOkButton( ).setEnabled( okEnable );
}
private boolean matchDataType( ScalarParameterHandle handle,
DataSetItemModel column )
{
if ( column.getDataType( ) == DataType.UNKNOWN_TYPE )
{
return false;
}
String type = handle.getDataType( );
if ( handle == selectedParameter )
{
type = getSelectedDataType( );
}
if ( type.equals( DesignChoiceConstants.PARAM_TYPE_STRING ) )
{
return true;
}
switch ( column.getDataType( ) )
{
case DataType.BOOLEAN_TYPE :
return type.equals( DesignChoiceConstants.PARAM_TYPE_BOOLEAN );
case DataType.INTEGER_TYPE :
return type.equals( DesignChoiceConstants.PARAM_TYPE_DECIMAL )
|| type.equals( DesignChoiceConstants.PARAM_TYPE_FLOAT );
case DataType.DATE_TYPE :
return type.equals( DesignChoiceConstants.PARAM_TYPE_DATETIME );
case DataType.DECIMAL_TYPE :
return type.equals( DesignChoiceConstants.PARAM_TYPE_DECIMAL )
|| type.equals( DesignChoiceConstants.PARAM_TYPE_FLOAT );
case DataType.DOUBLE_TYPE :
return type.equals( DesignChoiceConstants.PARAM_TYPE_FLOAT );
}
return false;
}
private void saveParameterProperties( ) throws SemanticException
{
if ( selectedParameter != null && selectedParameter != newParameter )
{
selectedParameter.setPromptText( UIUtil.convertToModelString( promptText.getText( ),
false ) );
selectedParameter.setHelpText( UIUtil.convertToModelString( helpTextEditor.getText( ),
true ) );
selectedParameter.setDefaultValue( UIUtil.convertToModelString( defaultValueEditor.getText( ),
true ) );
if ( StringUtil.isBlank( listLimit.getText( ) ) )
{
selectedParameter.setProperty( ScalarParameterHandle.LIST_LIMIT_PROP,
null );
}
else
{
selectedParameter.setListlimit( Integer.parseInt( listLimit.getText( ) ) );
}
selectedParameter.setAllowNull( allowNull.getSelection( ) );
selectedParameter.setName( UIUtil.convertToModelString( paramNameEditor.getText( ),
true ) );
refreshValueTable( );
};
}
}
|
package nerd.tuxmobil.fahrplan.congress;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import nerd.tuxmobil.fahrplan.congress.FahrplanContract.LecturesTable;
import nerd.tuxmobil.fahrplan.congress.FahrplanContract.LecturesTable.Columns;
public class DateFieldValidation {
final protected SQLiteOpenHelper mLecturesDatabase;
final protected List<ValidationError> mValidationErrors;
public DateFieldValidation(Context context) {
mLecturesDatabase = new LecturesDBOpenHelper(context);
mValidationErrors = new ArrayList<ValidationError>();
}
/**
* Returns a list of validation errors or null.
*/
public List<ValidationError> getValidationErrors() {
return mValidationErrors;
}
/**
* Prints all validation errors.
*/
public void printValidationErrors() {
for (ValidationError validationError : mValidationErrors) {
MyApp.LogDebug(getClass().getName(), validationError.toString());
}
}
/**
* Returns true if the time stamps in the "date" fields of
* each "event" are within a valid time range.
* The time range is defined by the "date" attribute of
* the "day" fields. Otherwise false is returned.
*/
public boolean validate() {
SQLiteDatabase db = mLecturesDatabase.getReadableDatabase();
Cursor lectureCursor = null;
try {
// Order by "date" column relying on that the date formatted
// in reverse order: yyyy-MM-dd'T'HH:mm:ssZ
lectureCursor = db.query(
LecturesTable.NAME, null, null, null, null, null, Columns.DATE);
if (lectureCursor.getCount() == 0) return true;
// Prepare time range (first day)
lectureCursor.moveToFirst();
int dateColumnIndex = lectureCursor.getColumnIndex(Columns.DATE);
String firstDateString = lectureCursor.getString(dateColumnIndex);
Date firstDate = DateHelper.getDate(firstDateString, "yyyy-MM-dd");
String formattedFirstDate = DateHelper.getFormattedDate(firstDate);
// Prepare time range (last day)
lectureCursor.moveToLast();
String lastDateString = lectureCursor.getString(dateColumnIndex);
Date lastDate = DateHelper.getDate(lastDateString, "yyyy-MM-dd");
// Increment date by one day since events also happen on the last day
// and no time information is given - only the pure date.
lastDate = DateHelper.shiftByDays(lastDate, 1);
String formattedLastDate = DateHelper.getFormattedDate(lastDate);
// Check if the time stamp in <date> is within the time range (first : last day)
// defined by "date" attribute in the <day> nodes.
lectureCursor.moveToFirst();
while (!lectureCursor.isAfterLast()) {
validateEvent(lectureCursor, firstDate, lastDate,
formattedFirstDate, formattedLastDate);
lectureCursor.moveToNext();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (lectureCursor != null) {
lectureCursor.close();
}
db.close();
}
// Evaluate validation
MyApp.LogDebug(getClass().getName(),
"Validation result for <date> field: " + mValidationErrors.size() + " errors.");
return mValidationErrors.isEmpty();
}
private void validateEvent(Cursor lectureCursor, Date firstDate, Date lastDate,
String formattedFirstDate, String formattedLastDate) {
long dateUtcInMilliseconds = lectureCursor.getLong(
lectureCursor.getColumnIndex(LecturesTable.Columns.DATE_UTC));
Date dateUtc = new Date();
dateUtc.setTime(dateUtcInMilliseconds);
Date[] dateRange = new Date[]{firstDate, lastDate};
if (!DateHelper.dateIsWithinRange(dateUtc, dateRange)) {
String eventId = lectureCursor.getString(
lectureCursor.getColumnIndex(LecturesTable.Columns.EVENT_ID));
String formattedDateUtc = DateHelper.getFormattedDate(dateUtc);
String errorMessage = "Field <date> " + formattedDateUtc + " of event "
+ eventId +
" exceeds range: [ " + formattedFirstDate + " : " + formattedLastDate
+ " ]";
ValidationError error = new ValidationError(errorMessage);
mValidationErrors.add(error);
}
}
}
|
package org.cnodejs.android.md.display.adapter;
import android.app.Activity;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import org.cnodejs.android.md.R;
import org.cnodejs.android.md.display.activity.LoginActivity;
import org.cnodejs.android.md.display.activity.UserDetailActivity;
import org.cnodejs.android.md.display.widget.CNodeWebView;
import org.cnodejs.android.md.display.widget.ThemeUtils;
import org.cnodejs.android.md.display.widget.ToastUtils;
import org.cnodejs.android.md.model.api.ApiClient;
import org.cnodejs.android.md.model.api.DefaultToastCallback;
import org.cnodejs.android.md.model.entity.Reply;
import org.cnodejs.android.md.model.entity.Result;
import org.cnodejs.android.md.model.entity.Topic;
import org.cnodejs.android.md.model.entity.TopicWithReply;
import org.cnodejs.android.md.model.storage.LoginShared;
import org.cnodejs.android.md.util.FormatUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;
public class TopicAdapter extends RecyclerView.Adapter<TopicAdapter.ViewHolder> {
private static final int TYPE_HEADER = 0;
private static final int TYPE_REPLY = 1;
private final Activity activity;
private final LayoutInflater inflater;
private TopicWithReply topic;
private boolean isHeaderShow = false; // falseheader
public interface OnAtClickListener {
void onAt(String loginName);
}
private final OnAtClickListener onAtClickListener;
public TopicAdapter(@NonNull Activity activity, @NonNull OnAtClickListener onAtClickListener) {
this.activity = activity;
inflater = LayoutInflater.from(activity);
this.onAtClickListener = onAtClickListener;
}
public void setTopic(TopicWithReply topic) {
this.topic = topic;
isHeaderShow = false;
}
@Override
public int getItemCount() {
return topic == null ? 0 : topic.getReplyList().size() + 1;
}
@Override
public int getItemViewType(int position) {
if (topic != null && position != 0) {
return TYPE_REPLY;
} else {
return TYPE_HEADER;
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_HEADER:
return new HeaderViewHolder(inflater.inflate(R.layout.activity_topic_item_header, parent, false));
default: // TYPE_REPLY
return new ReplyViewHolder(inflater.inflate(R.layout.activity_topic_item_reply, parent, false));
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
switch (getItemViewType(position)) {
case TYPE_HEADER:
holder.update(position);
break;
default: // TYPE_REPLY
holder.update(position - 1);
break;
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
protected ViewHolder(View itemView) {
super(itemView);
}
protected void update(int position) {}
}
public class HeaderViewHolder extends ViewHolder {
@Bind(R.id.topic_item_header_tv_title)
protected TextView tvTitle;
@Bind(R.id.topic_item_header_icon_good)
protected View iconGood;
@Bind(R.id.topic_item_header_img_avatar)
protected ImageView imgAvatar;
@Bind(R.id.topic_item_header_tv_tab)
protected TextView tvTab;
@Bind(R.id.topic_item_header_tv_login_name)
protected TextView tvLoginName;
@Bind(R.id.topic_item_header_tv_create_time)
protected TextView tvCreateTime;
@Bind(R.id.topic_item_header_tv_visit_count)
protected TextView tvVisitCount;
@Bind(R.id.topic_item_header_btn_favorite)
protected ImageView btnFavorite;
@Bind(R.id.topic_item_header_web_content)
protected CNodeWebView webContent;
@Bind(R.id.topic_item_header_layout_no_reply)
protected ViewGroup layoutNoReply;
public HeaderViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void update(int position) {
if (!isHeaderShow) {
tvTitle.setText(topic.getTitle());
iconGood.setVisibility(topic.isGood() ? View.VISIBLE : View.GONE);
Glide.with(activity).load(topic.getAuthor().getAvatarUrl()).placeholder(R.drawable.image_placeholder).dontAnimate().into(imgAvatar);
tvTab.setText(topic.isTop() ? R.string.tab_top : topic.getTab().getNameId());
tvTab.setBackgroundDrawable(ThemeUtils.getThemeAttrDrawable(activity, topic.isTop() ? R.attr.referenceBackgroundAccent : R.attr.referenceBackgroundNormal));
tvTab.setTextColor(topic.isTop() ? Color.WHITE : ThemeUtils.getThemeAttrColor(activity, android.R.attr.textColorSecondary));
tvLoginName.setText(topic.getAuthor().getLoginName());
tvCreateTime.setText(FormatUtils.getRecentlyTimeText(topic.getCreateAt()) + "");
tvVisitCount.setText(topic.getVisitCount() + "");
btnFavorite.setImageResource(topic.isCollect() ? R.drawable.ic_favorite_theme_24dp : R.drawable.ic_favorite_outline_grey600_24dp);
// WebView
webContent.loadRenderedContent(topic.getHandleContent());
isHeaderShow = true;
}
layoutNoReply.setVisibility(topic.getReplyList().size() > 0 ? View.GONE : View.VISIBLE);
}
@OnClick(R.id.topic_item_header_img_avatar)
protected void onBtnAvatarClick() {
UserDetailActivity.startWithTransitionAnimation(activity, topic.getAuthor().getLoginName(), imgAvatar, topic.getAuthor().getAvatarUrl());
}
@OnClick(R.id.topic_item_header_btn_favorite)
protected void onBtnFavoriteClick() {
if (topic != null) {
if (LoginActivity.startForResultWithAccessTokenCheck(activity)) {
if (topic.isCollect()) {
decollectTopicAsyncTask(topic, btnFavorite);
} else {
collectTopicAsyncTask(topic, btnFavorite);
}
}
}
}
}
private void collectTopicAsyncTask(@NonNull final TopicWithReply topic, @NonNull final ImageView btnFavorite) {
Call<Result> call = ApiClient.service.collectTopic(LoginShared.getAccessToken(activity), topic.getId());
call.enqueue(new DefaultToastCallback<Result>(activity) {
@Override
public boolean onResultOk(Response<Result> response, Result result) {
if (!activity.isFinishing()) {
topic.setCollect(true);
btnFavorite.setImageResource(R.drawable.ic_favorite_theme_24dp);
}
return false;
}
});
}
private void decollectTopicAsyncTask(@NonNull final TopicWithReply topic, @NonNull final ImageView btnFavorite) {
Call<Result> call = ApiClient.service.decollectTopic(LoginShared.getAccessToken(activity), topic.getId());
call.enqueue(new DefaultToastCallback<Result>(activity) {
@Override
public boolean onResultOk(Response<Result> response, Result result) {
if (!activity.isFinishing()) {
topic.setCollect(false);
btnFavorite.setImageResource(R.drawable.ic_favorite_outline_grey600_24dp);
}
return false;
}
});
}
public class ReplyViewHolder extends ViewHolder {
@Bind(R.id.topic_item_reply_img_avatar)
protected ImageView imgAvatar;
@Bind(R.id.topic_item_reply_tv_login_name)
protected TextView tvLoginName;
@Bind(R.id.topic_item_reply_tv_index)
protected TextView tvIndex;
@Bind(R.id.topic_item_reply_tv_create_time)
protected TextView tvCreateTime;
@Bind(R.id.topic_item_reply_btn_ups)
protected TextView btnUps;
@Bind(R.id.topic_item_reply_web_content)
protected CNodeWebView webContent;
@Bind(R.id.topic_item_reply_icon_deep_line)
protected View iconDeepLine;
@Bind(R.id.topic_item_reply_icon_shadow_gap)
protected View iconShadowGap;
private Reply reply;
private int position = -1;
public ReplyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void update(int position) {
this.position = position;
reply = topic.getReplyList().get(position);
Glide.with(activity).load(reply.getAuthor().getAvatarUrl()).placeholder(R.drawable.image_placeholder).dontAnimate().into(imgAvatar);
tvLoginName.setText(reply.getAuthor().getLoginName());
tvIndex.setText(position + 1 + "");
tvCreateTime.setText(FormatUtils.getRecentlyTimeText(reply.getCreateAt()));
btnUps.setText(String.valueOf(reply.getUpList().size()));
btnUps.setCompoundDrawablesWithIntrinsicBounds(reply.getUpList().contains(LoginShared.getId(activity)) ? R.drawable.ic_thumb_up_theme_24dp : R.drawable.ic_thumb_up_grey600_24dp, 0, 0, 0);
iconDeepLine.setVisibility(position == topic.getReplyList().size() - 1 ? View.GONE : View.VISIBLE);
iconShadowGap.setVisibility(position == topic.getReplyList().size() - 1 ? View.VISIBLE : View.GONE);
// WebView
webContent.loadRenderedContent(reply.getHandleContent());
}
@OnClick(R.id.topic_item_reply_img_avatar)
protected void onBtnAvatarClick() {
UserDetailActivity.startWithTransitionAnimation(activity, reply.getAuthor().getLoginName(), imgAvatar, reply.getAuthor().getAvatarUrl());
}
@OnClick(R.id.topic_item_reply_btn_ups)
protected void onBtnUpsClick() {
if (LoginActivity.startForResultWithAccessTokenCheck(activity)) {
if (reply.getAuthor().getLoginName().equals(LoginShared.getLoginName(activity))) {
ToastUtils.with(activity).show(R.string.can_not_up_yourself_reply);
} else {
upReplyAsyncTask(this);
}
}
}
@OnClick(R.id.topic_item_reply_btn_at)
protected void onBtnAtClick() {
if (LoginActivity.startForResultWithAccessTokenCheck(activity)) {
onAtClickListener.onAt(reply.getAuthor().getLoginName());
}
}
}
private void upReplyAsyncTask(final ReplyViewHolder holder) {
final int position = holder.position;
final Reply reply = holder.reply;
Call<Result.UpReply> call = ApiClient.service.upReply(holder.reply.getId(), LoginShared.getAccessToken(activity));
call.enqueue(new DefaultToastCallback<Result.UpReply>(activity) {
@Override
public boolean onResultOk(Response<Result.UpReply> response, Result.UpReply result) {
if (!activity.isFinishing()) {
if (result.getAction() == Reply.UpAction.up) {
reply.getUpList().add(LoginShared.getId(activity));
} else if (result.getAction() == Reply.UpAction.down) {
reply.getUpList().remove(LoginShared.getId(activity));
}
if (position == holder.position) {
holder.btnUps.setText(String.valueOf(holder.reply.getUpList().size()));
holder.btnUps.setCompoundDrawablesWithIntrinsicBounds(holder.reply.getUpList().contains(LoginShared.getId(activity)) ? R.drawable.ic_thumb_up_theme_24dp : R.drawable.ic_thumb_up_grey600_24dp, 0, 0, 0);
}
}
return false;
}
});
}
}
|
package org.fossasia.pslab.fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import org.fossasia.pslab.PSLabApplication;
import org.fossasia.pslab.R;
import org.fossasia.pslab.communication.ScienceLab;
import org.fossasia.pslab.others.EditTextWidget;
import org.fossasia.pslab.others.ScienceLabCommon;
import java.util.HashMap;
import java.util.Map;
public class ControlFragmentAdvanced extends Fragment {
private ScienceLab scienceLab;
private Map<String, Integer> state = new HashMap<>();
public static ControlFragmentAdvanced newInstance() {
return new ControlFragmentAdvanced();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scienceLab = ScienceLabCommon.scienceLab;
state.put("SQR1", 0);
state.put("SQR2", 0);
state.put("SQR3", 0);
state.put("SQR4", 0);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_control_advanced, container, false);
Button buttonControlAdvanced1 = (Button) view.findViewById(R.id.button_control_advanced1);
Button buttonControlAdvanced2 = (Button) view.findViewById(R.id.button_control_advanced2);
final EditText etWidgetControlAdvanced1 = (EditText) view.findViewById(R.id.etwidget_control_advanced1);
final EditText etWidgetControlAdvanced2 = (EditText) view.findViewById(R.id.etwidget_control_advanced2);
final EditText etWidgetControlAdvanced3 = (EditText) view.findViewById(R.id.etwidget_control_advanced3);
final EditText etWidgetControlAdvanced4 = (EditText) view.findViewById(R.id.etwidget_control_advanced4);
final EditText etWidgetControlAdvanced5 = (EditText) view.findViewById(R.id.etwidget_control_advanced5);
final EditText etWidgetControlAdvanced6 = (EditText) view.findViewById(R.id.etwidget_control_advanced6);
final EditText etWidgetControlAdvanced7 = (EditText) view.findViewById(R.id.etwidget_control_advanced7);
final EditText etWidgetControlAdvanced8 = (EditText) view.findViewById(R.id.etwidget_control_advanced8);
final EditText etWidgetControlAdvanced9 = (EditText) view.findViewById(R.id.etwidget_control_advanced9);
final EditText etWidgetControlAdvanced10 = (EditText) view.findViewById(R.id.etwidget_control_advanced10);
final EditText etWidgetControlAdvanced11 = (EditText) view.findViewById(R.id.etwidget_control_advanced11);
final Spinner spinnerControlAdvanced1 = (Spinner) view.findViewById(R.id.spinner_control_advanced1);
final Spinner spinnerControlAdvanced2 = (Spinner) view.findViewById(R.id.spinner_control_advanced2);
CheckBox checkBoxControlAdvanced1 = (CheckBox) view.findViewById(R.id.checkbox_control_advanced1);
CheckBox checkBoxControlAdvanced2 = (CheckBox) view.findViewById(R.id.checkbox_control_advanced2);
CheckBox checkBoxControlAdvanced3 = (CheckBox) view.findViewById(R.id.checkbox_control_advanced3);
CheckBox checkBoxControlAdvanced4 = (CheckBox) view.findViewById(R.id.checkbox_control_advanced4);
etWidgetControlAdvanced1.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced2.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced3.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced4.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced5.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced6.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced7.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced8.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced9.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced10.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced11.setInputType(InputType.TYPE_NULL);
etWidgetControlAdvanced1.setText("10.0");
etWidgetControlAdvanced2.setText("10.0");
etWidgetControlAdvanced3.setText("10.0");
etWidgetControlAdvanced4.setText("0.0");
etWidgetControlAdvanced5.setText("0.0");
etWidgetControlAdvanced6.setText("0.0");
etWidgetControlAdvanced7.setText("0.0");
etWidgetControlAdvanced8.setText("0.0");
etWidgetControlAdvanced9.setText("0.0");
etWidgetControlAdvanced10.setText("0.0");
etWidgetControlAdvanced11.setText("0.0");
etWidgetControlAdvanced1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced1, 1.0, 10.0, 5000.0);
}
});
etWidgetControlAdvanced1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced1, 1.0, 10.0, 5000.0);
}
}
});
etWidgetControlAdvanced2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced2, 1.0, 10.0, 5000.0);
}
});
etWidgetControlAdvanced2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced2, 1.0, 10.0, 5000.0);
}
}
});
etWidgetControlAdvanced3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced3, 1.0, 0.0, 360.0);
}
});
etWidgetControlAdvanced3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced3, 1.0, 0.0, 360.0);
}
}
});
etWidgetControlAdvanced4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced4, 0.1, 0.0, 1.0);
}
});
etWidgetControlAdvanced4.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced4, 0.1, 0.0, 1.0);
}
}
});
etWidgetControlAdvanced5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced5, 1.0, 0.0, 360.0);
}
});
etWidgetControlAdvanced5.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced5, 1.0, 0.0, 360.0);
}
}
});
etWidgetControlAdvanced6.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced6, 0.1, 0.0, 1.0);
}
});
etWidgetControlAdvanced6.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced6, 0.1, 0.0, 1.0);
}
}
});
etWidgetControlAdvanced7.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced7, 1.0, 0.0, 360.0);
}
});
etWidgetControlAdvanced7.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced7, 1.0, 0.0, 360.0);
}
}
});
etWidgetControlAdvanced8.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced8, 0.1, 0.0, 1.0);
}
});
etWidgetControlAdvanced8.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced8, 0.1, 0.0, 1.0);
}
}
});
etWidgetControlAdvanced9.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced9, 1.0, 0.0, 360.0);
}
});
etWidgetControlAdvanced9.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced9, 1.0, 0.0, 360.0);
}
}
});
etWidgetControlAdvanced10.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced10, 0.1, 0.0, 1.0);
}
});
etWidgetControlAdvanced10.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced10, 0.1, 0.0, 1.0);
}
}
});
etWidgetControlAdvanced11.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
showInputDialog(etWidgetControlAdvanced11, 1.0, 10.0, 5000.0);
}
});
etWidgetControlAdvanced11.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showInputDialog(etWidgetControlAdvanced11, 1.0, 10.0, 5000.0);
}
}
});
buttonControlAdvanced1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Double frequencyW1 = Double.valueOf(etWidgetControlAdvanced1.getText().toString());
Double frequencyW2 = Double.valueOf(etWidgetControlAdvanced2.getText().toString());
int phase = Integer.valueOf(etWidgetControlAdvanced3.getText().toString());
String wavetypeW1 = spinnerControlAdvanced1.getSelectedItem().toString();
String wavetypeW2 = spinnerControlAdvanced2.getSelectedItem().toString();
if ("SINE".equals(wavetypeW1) && scienceLab.isConnected())
scienceLab.setSine1(frequencyW1);
else if ("SQUARE".equals(wavetypeW1) && scienceLab.isConnected())
scienceLab.setSqr1(frequencyW1, -1, false);
if ("SINE".equals(wavetypeW2) && scienceLab.isConnected())
scienceLab.setSine2(frequencyW2);
else if ("SQUARE".equals(wavetypeW2) && scienceLab.isConnected())
scienceLab.setSqr2(frequencyW2, -1);
} catch (NumberFormatException e) {
etWidgetControlAdvanced1.setText("0");
etWidgetControlAdvanced2.setText("0");
etWidgetControlAdvanced3.setText("0");
}
}
});
buttonControlAdvanced2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
double phase2 = Double.valueOf(etWidgetControlAdvanced5.getText().toString());
double phase3 = Double.valueOf(etWidgetControlAdvanced7.getText().toString());
double phase4 = Double.valueOf(etWidgetControlAdvanced9.getText().toString());
double dutyCycle1 = Double.valueOf(etWidgetControlAdvanced4.getText().toString());
double dutyCycle2 = Double.valueOf(etWidgetControlAdvanced6.getText().toString());
double dutyCycle3 = Double.valueOf(etWidgetControlAdvanced8.getText().toString());
double dutyCycle4 = Double.valueOf(etWidgetControlAdvanced10.getText().toString());
double frequency = Double.valueOf(etWidgetControlAdvanced11.getText().toString());
if (scienceLab.isConnected())
scienceLab.sqrPWM(frequency, dutyCycle1, phase2, dutyCycle2, phase3, dutyCycle3,
phase4, dutyCycle4, true);
} catch (NumberFormatException e) {
etWidgetControlAdvanced4.setText("0");
etWidgetControlAdvanced5.setText("0");
etWidgetControlAdvanced6.setText("0");
etWidgetControlAdvanced7.setText("0");
etWidgetControlAdvanced8.setText("0");
etWidgetControlAdvanced9.setText("0");
etWidgetControlAdvanced10.setText("0");
etWidgetControlAdvanced11.setText("0");
}
}
});
checkBoxControlAdvanced1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) state.put("SQR1", 1);
else state.put("SQR1", 0);
if (scienceLab.isConnected())
scienceLab.setState(state);
}
});
checkBoxControlAdvanced2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) state.put("SQR2", 1);
else state.put("SQR2", 0);
if (scienceLab.isConnected())
scienceLab.setState(state);
}
});
checkBoxControlAdvanced3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) state.put("SQR3", 1);
else state.put("SQR3", 0);
if (scienceLab.isConnected())
scienceLab.setState(state);
}
});
checkBoxControlAdvanced4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) state.put("SQR4", 1);
else state.put("SQR4", 0);
if (scienceLab.isConnected())
scienceLab.setState(state);
}
});
return view;
}
private void showInputDialog(final EditText et, final double leastCount, final double minima, final double maxima) {
LayoutInflater li = LayoutInflater.from(getContext());
View promptsView = li.inflate(R.layout.dialog_input_edit_text_widget, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
alertDialogBuilder.setView(promptsView);
final EditTextWidget userInput =
(EditTextWidget) promptsView.findViewById(R.id.editTextDialogUserInput);
userInput.init(getContext(), leastCount, minima, maxima);
userInput.setText(et.getText().toString());
alertDialogBuilder
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
String input = userInput.getText();
if (Double.valueOf(input) > maxima) {
input = String.valueOf(maxima);
Toast.makeText(getContext(), "The Maximum value for this field is " + maxima, Toast.LENGTH_SHORT).show();
}
if (Double.valueOf(input) < minima) {
input = String.valueOf(minima);
Toast.makeText(getContext(), "The Minimum value for this field is " + minima, Toast.LENGTH_SHORT).show();
}
et.setText(input);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
@Override
public void onDestroyView() {
super.onDestroyView();
((PSLabApplication)getActivity().getApplication()).refWatcher.watch(this, ControlFragmentAdvanced.class.getSimpleName());
}
}
|
package radoslav.yordanov.quizgames.controller;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import radoslav.yordanov.quizgames.QuizGamesApplication;
import radoslav.yordanov.quizgames.R;
public class MainActivity extends AppCompatActivity {
private int timedQuiz;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.activity_main, new MainFragment());
ft.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
if (QuizGamesApplication.userRoleId != 1) {
MenuItem add = menu.findItem(R.id.add);
add.setVisible(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.logout:
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage(getResources().getString(R.string.logoutAsk));
dialog.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
appPreferences.edit().putInt(QuizGamesApplication.USER_ID_PREF, -1).apply();
appPreferences.edit().putInt(QuizGamesApplication.USER_ROLE_ID, -1).apply();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
});
dialog.setNegativeButton(getResources().getString(R.string.no), null);
dialog.show();
return true;
case R.id.add:
Intent intent = new Intent(MainActivity.this, AddQuizActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPlayClick(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
ft.replace(R.id.activity_main, new QuizTimeFragment());
ft.addToBackStack("quizTime");
ft.commit();
}
public void onTopScoresClick(View view) {
Intent intent = new Intent(this, TopScoresActivity.class);
startActivity(intent);
}
public void onAboutClick(View view) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
ft.replace(R.id.activity_main, new AboutFragment());
ft.addToBackStack("quiz");
ft.commit();
}
public void onCarsQuizClick(View view) {
Intent intent = new Intent(this, QuizActivity.class);
intent.putExtra(QuizActivity.EXTRA_quizType, "cars");
intent.putExtra(QuizActivity.EXTRA_timed, timedQuiz);
startActivity(intent);
// overridePendingTransition(R.anim.enter, R.anim.exit);
}
public void onLogosQuizClick(View view) {
Intent intent = new Intent(this, QuizActivity.class);
intent.putExtra(QuizActivity.EXTRA_quizType, "logos");
intent.putExtra(QuizActivity.EXTRA_timed, timedQuiz);
startActivity(intent);
}
public void onCitiesQuizClick(View view) {
Intent intent = new Intent(this, QuizActivity.class);
intent.putExtra(QuizActivity.EXTRA_quizType, "cities");
intent.putExtra(QuizActivity.EXTRA_timed, timedQuiz);
startActivity(intent);
}
public void onTimeLimitClick(View view) {
timedQuiz = 1;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
ft.replace(R.id.activity_main, new QuizSelectionFragment());
ft.addToBackStack("quizSelection");
ft.commit();
}
public void onNoLimitClick(View view) {
timedQuiz = 0;
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
ft.replace(R.id.activity_main, new QuizSelectionFragment());
ft.addToBackStack("quizSelection");
ft.commit();
}
}
|
package com.ilscipio.scipio.cms.control;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.transaction.Transaction;
import com.ibm.icu.util.Calendar;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import com.ilscipio.scipio.ce.webapp.control.util.AccessTokenProvider;
import com.ilscipio.scipio.ce.webapp.control.util.AccessTokenProvider.EventHandler;
import com.ilscipio.scipio.cms.content.CmsPage;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.transaction.TransactionUtil;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
/**
* Generates and cleanups access tokens for CMS, mainly for preview mode.
* <p>
* Added 2018-05-06.
*/
public class CmsAccessHandler implements HttpSessionListener {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static final int TOKEN_EXPIRY = UtilProperties.getPropertyAsInteger("cms", "cms.access.token.expiry", 60 * 60 * 24); // in seconds
private static final int TOKEN_HALFLIFE = UtilProperties.getPropertyAsInteger("cms", "cms.access.token.halfLife", 60 * 60 * 6); // in seconds
// 2020-03-12: This is now only used to generate new tokens, otherwise the token is handled in DB.
private static final AccessTokenProvider<GenericValue> tokenProvider = AccessTokenProvider.newAccessTokenProvider(new EventHandler<GenericValue>() {});
public CmsAccessHandler() {
}
public static String getAccessTokenString(HttpServletRequest request, CmsPage cmsPage, String cmsPagePath) {
if(UtilValidate.isNotEmpty(cmsPage) && UtilValidate.isNotEmpty(cmsPage.getId())){
GenericValue tokenRecord = getOrCreateUserAccessToken(UtilHttp.getSessionUserLogin(request), cmsPage.getId(), null, true);
return (tokenRecord != null) ? tokenRecord.getString("token") : null;
}
return null;
}
private static GenericValue getOrCreateUserAccessToken(GenericValue userLogin, String pageId, Timestamp nowTimestamp, boolean deleteExpired) {
if (userLogin == null) {
return null;
}
Delegator delegator = userLogin.getDelegator();
if (nowTimestamp == null) {
nowTimestamp = UtilDateTime.nowTimestamp();
}
String userId = userLogin.getString("userLoginId");
List<GenericValue> tokens = delegator.from("CmsAccessToken").where("userId", userId, "pageId", pageId).queryListSafe();
if (UtilValidate.isNotEmpty(tokens)) {
GenericValue activeToken = null;
List<GenericValue> expiredTokens = null;
for(GenericValue token : tokens) {
if (activeToken == null && isActiveAccessToken(token, nowTimestamp, TOKEN_HALFLIFE)) { // for token generation, use half-life
activeToken = token;
if (!deleteExpired) {
return activeToken;
}
} else if (deleteExpired && !isActiveAccessToken(token, nowTimestamp, TOKEN_EXPIRY)) {
if (expiredTokens == null) {
expiredTokens = new ArrayList<>();
}
expiredTokens.add(token);
}
}
if (expiredTokens != null) {
// delete expired tokens, in separate transaction to not affect screens
String errMsg = "removing " + expiredTokens.size() + " expired access tokens for user '"
+ userId + "'" + (pageId != null ? " for page '" + pageId + "'" : "");
Debug.logInfo("Cms: getOrCreateUserAccessToken: " + errMsg, module);
final List<GenericValue> expiredTokensFinal = expiredTokens;
try {
TransactionUtil.doNewTransaction(new Callable<Object>() {
@Override
public Object call() throws Exception {
return delegator.removeAll(expiredTokensFinal);
}
}, "Cms: Error " + errMsg, 0, true);
} catch (Exception e) {
Debug.logError(e, module);
}
}
}
try {
GenericValue tokenRecord = delegator.makeValue("CmsAccessToken",
"token", tokenProvider.newTokenString(), "userId", userId, "pageId", pageId, "createdDate", nowTimestamp);
return delegator.createSetNextSeqId(tokenRecord);
} catch (GenericEntityException e) {
Debug.logError(e, "Cms: Access Token: Could not create user access token for user '" + userId + "', page '" + pageId + "'", module);
return null;
}
}
public static boolean isValidAccessToken(HttpServletRequest request, Delegator delegator, String cmsPagePath, String paramToken) {
return isValidAccessToken(delegator, cmsPagePath, paramToken);
}
public static boolean isValidAccessToken(Delegator delegator, String cmsPagePath, String paramToken) {
if (paramToken == null || paramToken.isEmpty()) {
return false;
}
// TODO: REVIEW: Here we can query only by token and not by pageId because the page is not yet known,
// but this has minimal impact on security because the pageId is mostly needed to provide variety in token strings rather than bind to any specific page.
// If we try to do the pageId here it may cause complications for process mappings in the future.
GenericValue tokenRecord = delegator.from("CmsAccessToken").where("token", paramToken).queryOneSafe();
if (tokenRecord == null) {
return false;
}
if (!isActiveAccessToken(tokenRecord, UtilDateTime.nowTimestamp(), TOKEN_EXPIRY)) { // for token validation, use expiry
Debug.logWarning("Cms: Access Token: Expired token '" + tokenRecord.get("tokenId") + "' accessed; denying", module);
return false;
}
return true;
}
private static boolean isActiveAccessToken(GenericValue tokenRecord, Timestamp nowTimestamp, int maxTime) {
return (nowTimestamp.getTime() - tokenRecord.getTimestamp("createdDate").getTime()) < (maxTime * 1000);
}
public static String cleanupUserAccessTokens(HttpServletRequest request, HttpServletResponse response) {
cleanupUserAccessTokens(UtilHttp.getSessionUserLogin(request), null, null);
return "success";
}
public static void cleanupUserAccessTokens(GenericValue userLogin, String pageId, Timestamp nowTimestamp) {
if (userLogin == null) {
return;
}
Delegator delegator = userLogin.getDelegator();
if (nowTimestamp == null) {
nowTimestamp = UtilDateTime.nowTimestamp();
}
String userId = userLogin.getString("userLoginId");
List<EntityCondition> conds = UtilMisc.toList(EntityCondition.makeCondition("userId", userId),
EntityCondition.makeCondition("createdDate", EntityOperator.LESS_THAN, UtilDateTime.adjustTimestamp(nowTimestamp, Calendar.SECOND, -TOKEN_EXPIRY)));
if (pageId != null) {
conds.add(EntityCondition.makeCondition("pageId", userLogin.get("pageId")));
}
List<GenericValue> tokens = delegator.from("CmsAccessToken").where(conds).queryListSafe();
if (UtilValidate.isEmpty(tokens)) {
return;
}
Debug.logInfo("Cms: cleanupUserAccessTokens: Removing " + tokens.size() + " expired access tokens for user '"
+ userId + "'" + (pageId != null ? " for page '" + pageId + "'" : ""), module);
try {
delegator.removeAll(tokens);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
@Override
public void sessionCreated(HttpSessionEvent se) {
// nothing useful is in the session at this point
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
}
}
|
package se.chalmers.pd.playlistmanager;
import java.util.ArrayList;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.widget.SearchView;
public class MainActivity extends FragmentActivity implements AndroidSpotifyMetadata.Callback, ApplicationController.Callback, QueryTextListener.Callback {
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private ApplicationController controller;
private LoadingDialogFragment loadingFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Track> searchTracks = new ArrayList<Track>();
ArrayList<Track> playlistTracks = new ArrayList<Track>();
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), searchTracks, playlistTracks, this);
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(sectionsPagerAdapter);
controller = new ApplicationController(this, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(this.getComponentName()));
searchView.setOnQueryTextListener(new QueryTextListener(this, this));
return super.onCreateOptionsMenu(menu);
}
@Override
public void onSearchBegin() {
loadingFragment = LoadingDialogFragment.newInstance();
loadingFragment.show(getFragmentManager(), "LoadingFragment");
}
@Override
public void onSearchResult(ArrayList<Track> tracks) {
loadingFragment.dismiss();
viewPager.setCurrentItem(SectionsPagerAdapter.FIRST_PAGE, true);
sectionsPagerAdapter.updateResults(tracks);
}
public void onTrackSelected(Track track) {
switch (viewPager.getCurrentItem()) {
case SectionsPagerAdapter.FIRST_PAGE:
controller.addTrack(track);
break;
case SectionsPagerAdapter.SECOND_PAGE:
break;
}
}
@Override
public void onUpdatePlaylist(Track track) {
sectionsPagerAdapter.updatePlaylist(track);
}
public void onPlayerAction(Action action) {
controller.performAction(action);
// FIXME: handle action from player fragment
// FIXME: refactor all actions to use Action
}
}
|
package gov.nih.nci.cagrid.portal.portlet.credmgr;
import gov.nih.nci.cagrid.portal.portlet.PortalPortletIntegrationTestBase;
/**
* User: kherm
*
* @author kherm manav.kher@semanticbits.com
*/
public class CredentialManagerFacadeSystemTest extends PortalPortletIntegrationTestBase {
public CredentialManagerFacade credentialManagerFacade;
public void testCreds() {
assertNotNull(credentialManagerFacade.listIdPs());
}
public CredentialManagerFacade getCredentialManagerFacade() {
return credentialManagerFacade;
}
public void setCredentialManagerFacade(CredentialManagerFacade credentialManagerFacade) {
this.credentialManagerFacade = credentialManagerFacade;
}
}
|
package org.eclipse.birt.chart.ui.swt.wizard.format.series;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.attribute.LegendItemType;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.component.impl.SeriesImpl;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.composites.ExternalizedTextEditorComposite;
import org.eclipse.birt.chart.ui.swt.wizard.TreeCompoundTask;
import org.eclipse.birt.chart.ui.swt.wizard.format.SubtaskSheetImpl;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.util.LiteralHelper;
import org.eclipse.birt.chart.util.NameSet;
import org.eclipse.birt.chart.util.PluginSettings;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TreeItem;
/**
* "Series" subtask. Attention: the series layout order must be consistent with
* series items in the naviagor tree.
*
*/
public class SeriesSheetImpl extends SubtaskSheetImpl
implements
SelectionListener
{
private static Hashtable htSeriesNames = null;
private transient Combo cmbColorBy;
private transient Cursor curHand = null;
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.ISheet#getComponent(org.eclipse.swt.widgets.Composite)
*/
public void getComponent( Composite parent )
{
final int COLUMN_NUMBER = 5;
cmpContent = new Composite( parent, SWT.NONE );
{
GridLayout glContent = new GridLayout( COLUMN_NUMBER, false );
glContent.horizontalSpacing = 20;
cmpContent.setLayout( glContent );
GridData gd = new GridData( GridData.FILL_BOTH );
cmpContent.setLayoutData( gd );
}
new Label( cmpContent, SWT.NONE ).setText( Messages.getString( "ChartSheetImpl.Label.ColorBy" ) ); //$NON-NLS-1$
cmbColorBy = new Combo( cmpContent, SWT.DROP_DOWN | SWT.READ_ONLY );
{
GridData gridData = new GridData( );
gridData.horizontalSpan = COLUMN_NUMBER - 1;
cmbColorBy.setLayoutData( gridData );
NameSet ns = LiteralHelper.legendItemTypeSet;
cmbColorBy.setItems( ns.getDisplayNames( ) );
cmbColorBy.select( ns.getSafeNameIndex( getChart( ).getLegend( )
.getItemType( )
.getName( ) ) );
cmbColorBy.addSelectionListener( this );
}
Label separator = new Label( cmpContent, SWT.SEPARATOR | SWT.HORIZONTAL );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
// gd.horizontalIndent = -5;
gd.horizontalSpan = COLUMN_NUMBER;
separator.setLayoutData( gd );
}
Label lblSeries = new Label( cmpContent, SWT.NONE );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
lblSeries.setLayoutData( gd );
lblSeries.setFont( JFaceResources.getBannerFont( ) );
lblSeries.setText( Messages.getString( "SeriesSheetImpl.Label.Series" ) ); //$NON-NLS-1$
}
Label lblTitle = new Label( cmpContent, SWT.NONE );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
lblTitle.setLayoutData( gd );
lblTitle.setFont( JFaceResources.getBannerFont( ) );
lblTitle.setText( Messages.getString( "SeriesSheetImpl.Label.Title" ) ); //$NON-NLS-1$
}
Label lblType = new Label( cmpContent, SWT.NONE );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
lblType.setLayoutData( gd );
lblType.setFont( JFaceResources.getBannerFont( ) );
lblType.setText( Messages.getString( "SeriesSheetImpl.Label.Type" ) ); //$NON-NLS-1$
}
Label lblVisible = new Label( cmpContent, SWT.NONE );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
lblVisible.setLayoutData( gd );
lblVisible.setFont( JFaceResources.getBannerFont( ) );
lblVisible.setText( Messages.getString( "SeriesSheetImpl.Label.Visible" ) ); //$NON-NLS-1$
}
Label lblStack = new Label( cmpContent, SWT.NONE );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
lblStack.setLayoutData( gd );
lblStack.setFont( JFaceResources.getBannerFont( ) );
lblStack.setText( Messages.getString( "SeriesSheetImpl.Label.Stacked" ) ); //$NON-NLS-1$
}
List seriesDefns = ChartUIUtil.getBaseSeriesDefinitions( getChart( ) );
int treeIndex = 0;
for ( int i = 0; i < seriesDefns.size( ); i++ )
{
new SeriesOptionChoser( ( (SeriesDefinition) seriesDefns.get( i ) ),
getChart( ) instanceof ChartWithAxes
? Messages.getString( "SeriesSheetImpl.Label.CategoryXSeries" ) : Messages.getString( "SeriesSheetImpl.Label.CategoryBaseSeries" ), //$NON-NLS-1$ //$NON-NLS-2$
i,
treeIndex++ ).placeComponents( cmpContent );
}
seriesDefns = ChartUIUtil.getOrthogonalSeriesDefinitions( getChart( ),
-1 );
for ( int i = 0; i < seriesDefns.size( ); i++ )
{
String text = getChart( ) instanceof ChartWithAxes
? Messages.getString( "SeriesSheetImpl.Label.ValueYSeries" ) : Messages.getString( "SeriesSheetImpl.Label.ValueOrthogonalSeries" ); //$NON-NLS-1$ //$NON-NLS-2$
new SeriesOptionChoser( ( (SeriesDefinition) seriesDefns.get( i ) ),
( seriesDefns.size( ) == 1 ? text
: ( text + " - " + ( i + 1 ) ) ) + ":", i, treeIndex++ ).placeComponents( cmpContent ); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void onShow( Object context, Object container )
{
super.onShow( context, container );
curHand = new Cursor( Display.getDefault( ), SWT.CURSOR_HAND );
}
public Object onHide( )
{
curHand.dispose( );
return super.onHide( );
}
private class SeriesOptionChoser
implements
SelectionListener,
Listener,
MouseListener,
MouseTrackListener
{
private transient SeriesDefinition seriesDefn;
private transient String seriesName;
private transient Label lblSeries;
private transient ExternalizedTextEditorComposite txtTitle;
private transient Combo cmbTypes;
private transient Button btnVisible;
private transient Button btnStack;
private transient int iSeriesDefinitionIndex = 0;
// Index of tree item in the navigator tee
private transient int treeIndex = 0;
public SeriesOptionChoser( SeriesDefinition seriesDefn,
String seriesName, int iSeriesDefinitionIndex, int treeIndex )
{
this.seriesDefn = seriesDefn;
this.seriesName = seriesName;
this.iSeriesDefinitionIndex = iSeriesDefinitionIndex;
this.treeIndex = treeIndex;
}
public void placeComponents( Composite parent )
{
Series series = seriesDefn.getDesignTimeSeries();
lblSeries = new Label( parent, SWT.NONE );
{
GridData gd = new GridData( );
lblSeries.setLayoutData( gd );
lblSeries.setText( seriesName );
lblSeries.setForeground( Display.getDefault( )
.getSystemColor( SWT.COLOR_DARK_BLUE ) );
lblSeries.addMouseListener( this );
lblSeries.addMouseTrackListener( this );
}
List keys = null;
if ( getContext( ).getUIServiceProvider( ) != null )
{
keys = getContext( ).getUIServiceProvider( )
.getRegisteredKeys( );
}
txtTitle = new ExternalizedTextEditorComposite( parent,
SWT.BORDER | SWT.SINGLE,
-1,
-1,
keys,
getContext( ).getUIServiceProvider( ),
series.getSeriesIdentifier( ).toString( ) );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
txtTitle.setLayoutData( gd );
txtTitle.addListener( this );
}
cmbTypes = new Combo( parent, SWT.DROP_DOWN | SWT.READ_ONLY );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
cmbTypes.setLayoutData( gd );
cmbTypes.addSelectionListener( this );
}
btnVisible = new Button( parent, SWT.CHECK );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
btnVisible.setLayoutData( gd );
btnVisible.setSelection( series.isVisible( ) );
btnVisible.setEnabled( !series.getClass( )
.isAssignableFrom( SeriesImpl.class ) );
btnVisible.addSelectionListener( this );
}
btnStack = new Button( parent, SWT.CHECK );
{
GridData gd = new GridData( );
gd.horizontalAlignment = SWT.CENTER;
btnStack.setLayoutData( gd );
btnStack.setEnabled( series.canBeStacked( ) );
btnStack.setSelection( series.isStacked( ) );
btnStack.addSelectionListener( this );
}
populateLists( seriesDefn.getDesignTimeSeries( ) );
}
public void widgetSelected( SelectionEvent e )
{
Series series = seriesDefn.getDesignTimeSeries();
if ( e.getSource( ).equals( cmbTypes ) )
{
if ( seriesDefn.getDesignTimeSeries( )
.canParticipateInCombination( ) )
{
// Get a new series of the selected type by using as much
// information as possible from the existing series
Series newSeries = getNewSeries( cmbTypes.getText( ),
series );
newSeries.eAdapters( ).addAll( seriesDefn.eAdapters( ) );
seriesDefn.getSeries( ).set( 0, newSeries );
}
}
else if ( e.getSource( ).equals( btnVisible ) )
{
series.setVisible( btnVisible.getSelection( ) );
}
else if ( e.getSource( ).equals( btnStack ) )
{
series.setStacked( btnStack.getSelection( ) );
}
}
private Series getNewSeries( String sSeriesName, Series oldSeries )
{
try
{
Class seriesClass = Class.forName( (String) htSeriesNames.get( sSeriesName ) );
Method createMethod = seriesClass.getDeclaredMethod( "create", new Class[]{} ); //$NON-NLS-1$
Series series = (Series) createMethod.invoke( seriesClass,
new Object[]{} );
setIgnoreNotifications( true );
series.translateFrom( oldSeries,
iSeriesDefinitionIndex,
getChart( ) );
setIgnoreNotifications( false );
return series;
}
catch ( Exception e )
{
e.printStackTrace( );
}
return null;
}
public void widgetDefaultSelected( SelectionEvent e )
{
// TODO Auto-generated method stub
}
public void handleEvent( Event event )
{
if ( event.widget.equals( txtTitle ) )
{
seriesDefn.getDesignTimeSeries( )
.setSeriesIdentifier( txtTitle.getText( ) );
}
}
private void populateLists( Series series )
{
// Populate Series Types List
if ( series.canParticipateInCombination( ) )
{
try
{
populateSeriesTypes( PluginSettings.instance( )
.getRegisteredSeries( ), series );
}
catch ( ChartException e )
{
e.printStackTrace( );
}
}
else
{
String seriesName = PluginSettings.instance( )
.getSeriesDisplayName( series.getClass( ).getName( ) );
cmbTypes.add( seriesName );
cmbTypes.select( 0 );
}
}
private void populateSeriesTypes( String[] allSeriesTypes, Series series )
{
for ( int i = 0; i < allSeriesTypes.length; i++ )
{
try
{
Class seriesClass = Class.forName( allSeriesTypes[i] );
Method createMethod = seriesClass.getDeclaredMethod( "create", new Class[]{} ); //$NON-NLS-1$
Series newSeries = (Series) createMethod.invoke( seriesClass,
new Object[]{} );
if ( htSeriesNames == null )
{
htSeriesNames = new Hashtable( 20 );
}
String sDisplayName = PluginSettings.instance( )
.getSeriesDisplayName( allSeriesTypes[i] );
htSeriesNames.put( sDisplayName, allSeriesTypes[i] );
if ( newSeries.canParticipateInCombination( ) )
{
cmbTypes.add( sDisplayName );
if ( allSeriesTypes[i].equals( series.getClass( )
.getName( ) ) )
{
cmbTypes.select( cmbTypes.getItemCount( ) - 1 );
}
}
}
catch ( Exception e )
{
e.printStackTrace( );
}
}
}
public void mouseDoubleClick( MouseEvent e )
{
// TODO Auto-generated method stub
}
public void mouseDown( MouseEvent e )
{
switchTo( treeIndex );
}
public void mouseUp( MouseEvent e )
{
}
public void mouseEnter( MouseEvent e )
{
lblSeries.setCursor( curHand );
}
public void mouseExit( MouseEvent e )
{
lblSeries.setCursor( null );
}
public void mouseHover( MouseEvent e )
{
// TODO Auto-generated method stub
}
private void switchTo( int index )
{
if ( getParentTask( ) instanceof TreeCompoundTask )
{
TreeCompoundTask compoundTask = (TreeCompoundTask) getParentTask( );
TreeItem currentItem = compoundTask.getNavigatorTree( )
.getSelection( )[0];
TreeItem[] children = currentItem.getItems( );
if ( index < children.length )
{
// Switch to specified subtask
compoundTask.switchToTreeItem( children[index] );
}
}
}
}
public void widgetSelected( SelectionEvent e )
{
if ( e.widget.equals( cmbColorBy ) )
{
getChart( ).getLegend( )
.setItemType( LegendItemType.get( LiteralHelper.legendItemTypeSet.getNameByDisplayName( cmbColorBy.getText( ) ) ) );
}
}
public void widgetDefaultSelected( SelectionEvent e )
{
// TODO Auto-generated method stub
}
}
|
package org.opencb.commons.datastore.mongodb;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Projections;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryParam;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MongoDBQueryUtils {
@Deprecated
private static final String REGEX_SEPARATOR = "(\\w+|\\^)";
private static final Pattern OPERATION_STRING_PATTERN = Pattern.compile("^(!=?|!?=?~|==?|=?\\^|=?\\$)([^=<>~!]+.*)$");
private static final Pattern OPERATION_NUMERIC_PATTERN = Pattern.compile("^(<=?|>=?|!=|!?=?~|==?)([^=<>~!]+.*)$");
private static final Pattern OPERATION_BOOLEAN_PATTERN = Pattern.compile("^(!=|!?=?~|==?)([^=<>~!]+.*)$");
public static final String OR = ",";
public static final String AND = ";";
public static final String IS = ":";
public enum LogicalOperator {
AND,
OR;
}
public enum ComparisonOperator {
EQUALS,
NOT_EQUALS,
IN,
NOT_IN,
ALL,
// String comparators
EQUAL_IGNORE_CASE,
STARTS_WITH, // The regular expression will look for "=^" or "^" at the beginning.
ENDS_WITH, // The regular expression will look for "=$" or "$" at the beginning.
REGEX, // The regular expression will look for "=~" or "~" at the beginning.
TEXT,
// Numeric comparators
GREATER_THAN,
GREATER_THAN_EQUAL,
LESS_THAN,
LESS_THAN_EQUAL;
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query) {
return createFilter(mongoDbField, queryParam, query, QueryParam.Type.TEXT, ComparisonOperator.EQUALS, LogicalOperator.OR);
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type) {
return createFilter(mongoDbField, queryParam, query, type, ComparisonOperator.EQUALS, LogicalOperator.OR);
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type,
ComparisonOperator comparator) {
return createFilter(mongoDbField, queryParam, query, type, comparator, LogicalOperator.OR);
}
public static Bson createFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type,
ComparisonOperator comparator, LogicalOperator operator) {
Bson filter = null;
if (query != null && query.containsKey(queryParam)) {
switch (type) {
case TEXT:
case TEXT_ARRAY:
filter = createFilter(mongoDbField, query.getAsStringList(queryParam, getLogicalSeparator(operator)), comparator,
operator);
break;
case INTEGER:
case INTEGER_ARRAY:
filter = createFilter(mongoDbField, query.getAsLongList(queryParam, getLogicalSeparator(operator)), comparator,
operator);
break;
case DECIMAL:
case DECIMAL_ARRAY:
filter = createFilter(mongoDbField, query.getAsDoubleList(queryParam, getLogicalSeparator(operator)), comparator,
operator);
break;
case BOOLEAN:
filter = createFilter(mongoDbField, query.getBoolean(queryParam), comparator);
break;
default:
break;
}
}
return filter;
}
private static String getLogicalSeparator(LogicalOperator operator) {
return (operator != null && operator.equals(LogicalOperator.AND)) ? AND : OR;
}
public static Bson createAutoFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type)
throws NumberFormatException {
Bson filter = null;
if (query != null && query.containsKey(queryParam)) {
List<String> values = query.getAsStringList(queryParam);
LogicalOperator operator = LogicalOperator.OR;
if (values.size() == 1) {
operator = checkOperator(values.get(0));
}
filter = createAutoFilter(mongoDbField, queryParam, query, type, operator);
}
return filter;
}
public static Bson createAutoFilter(String mongoDbField, String queryParam, Query query, QueryParam.Type type, LogicalOperator operator)
throws NumberFormatException {
List<String> queryParamList = query.getAsStringList(queryParam, getLogicalSeparator(operator));
List<Bson> bsonList = new ArrayList<>(queryParamList.size());
for (String queryItem : queryParamList) {
Matcher matcher = getPattern(type).matcher(queryItem);
String op = "";
String queryValueString = queryItem;
if (matcher.find()) {
op = matcher.group(1);
queryValueString = matcher.group(2);
}
ComparisonOperator comparator = getComparisonOperator(op, type);
switch (type) {
case STRING:
case TEXT:
case TEXT_ARRAY:
bsonList.add(createFilter(mongoDbField, queryValueString, comparator));
break;
case INTEGER:
case INTEGER_ARRAY:
bsonList.add(createFilter(mongoDbField, Integer.parseInt(queryValueString), comparator));
break;
case DOUBLE:
case DECIMAL:
case DECIMAL_ARRAY:
bsonList.add(createFilter(mongoDbField, Double.parseDouble(queryValueString), comparator));
break;
case BOOLEAN:
bsonList.add(createFilter(mongoDbField, Boolean.parseBoolean(queryValueString), comparator));
break;
default:
break;
}
}
Bson filter;
if (bsonList.size() == 0) {
filter = Filters.size(queryParam, 0);
} else if (bsonList.size() == 1) {
filter = bsonList.get(0);
} else {
if (operator.equals(LogicalOperator.OR)) {
filter = Filters.or(bsonList);
} else {
filter = Filters.and(bsonList);
}
}
return filter;
}
public static <T> Bson createFilter(String mongoDbField, T queryValue) {
return createFilter(mongoDbField, queryValue, ComparisonOperator.EQUALS);
}
public static <T> Bson createFilter(String mongoDbField, T queryValue, ComparisonOperator comparator) {
Bson filter = null;
if (queryValue != null) {
if (queryValue instanceof String) {
switch (comparator) {
case EQUALS:
filter = Filters.eq(mongoDbField, queryValue);
break;
case NOT_EQUALS:
filter = Filters.ne(mongoDbField, queryValue);
break;
case EQUAL_IGNORE_CASE:
filter = Filters.regex(mongoDbField, queryValue.toString(), "i");
break;
case STARTS_WITH:
filter = Filters.regex(mongoDbField, "^" + queryValue + "*");
break;
case ENDS_WITH:
filter = Filters.regex(mongoDbField, "*" + queryValue + "$");
break;
case REGEX:
filter = Filters.regex(mongoDbField, queryValue.toString());
break;
case TEXT:
filter = Filters.text(String.valueOf(queryValue));
break;
default:
break;
}
} else {
switch (comparator) {
case EQUALS:
filter = Filters.eq(mongoDbField, queryValue);
break;
case NOT_EQUALS:
filter = Filters.ne(mongoDbField, queryValue);
break;
case GREATER_THAN:
filter = Filters.gt(mongoDbField, queryValue);
break;
case GREATER_THAN_EQUAL:
filter = Filters.gte(mongoDbField, queryValue);
break;
case LESS_THAN:
filter = Filters.lt(mongoDbField, queryValue);
break;
case LESS_THAN_EQUAL:
filter = Filters.lte(mongoDbField, queryValue);
break;
default:
break;
}
}
}
return filter;
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues) {
return createFilter(mongoDbField, queryValues, ComparisonOperator.EQUALS, LogicalOperator.OR);
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues, LogicalOperator operator) {
return createFilter(mongoDbField, queryValues, ComparisonOperator.EQUALS, operator);
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues, ComparisonOperator comparator) {
return createFilter(mongoDbField, queryValues, comparator, LogicalOperator.OR);
}
public static <T> Bson createFilter(String mongoDbField, List<T> queryValues, ComparisonOperator comparator, LogicalOperator operator) {
Bson filter = null;
if (queryValues != null && queryValues.size() > 0) {
if (comparator.equals(ComparisonOperator.IN) || comparator.equals(ComparisonOperator.NOT_IN)
|| comparator.equals(ComparisonOperator.ALL)) {
switch (comparator) {
case IN:
filter = Filters.in(mongoDbField, queryValues);
break;
case NOT_IN:
filter = Filters.nin(mongoDbField, queryValues);
break;
case ALL:
filter = Filters.all(mongoDbField, queryValues);
break;
default:
break;
}
} else {
// If there is only on element in the array then it does not make sense to create an OR or AND filter
if (queryValues.size() == 1) {
filter = createFilter(mongoDbField, queryValues.get(0), comparator);
} else {
List<Bson> bsonList = new ArrayList<>(queryValues.size());
for (T queryItem : queryValues) {
Bson filter1 = createFilter(mongoDbField, queryItem, comparator);
if (filter1 != null) {
bsonList.add(filter1);
}
}
if (operator.equals(LogicalOperator.OR)) {
filter = Filters.or(bsonList);
} else {
filter = Filters.and(bsonList);
}
}
}
}
return filter;
}
public static LogicalOperator checkOperator(String value) throws IllegalArgumentException {
boolean containsOr = value.contains(OR);
boolean containsAnd = value.contains(AND);
if (containsAnd && containsOr) {
throw new IllegalArgumentException("Cannot merge AND and OR operators in the same query filter.");
} else if (containsAnd && !containsOr) {
return LogicalOperator.AND;
} else if (containsOr && !containsAnd) {
return LogicalOperator.OR;
} else { // !containsOr && !containsAnd
return null;
}
}
public static List<Bson> createGroupBy(Bson query, String groupByField, String idField, boolean count) {
if (groupByField == null || groupByField.isEmpty()) {
return new ArrayList<>();
}
if (groupByField.contains(",")) {
// call to multiple createGroupBy if commas are present
return createGroupBy(query, Arrays.asList(groupByField.split(",")), idField, count);
} else {
Bson match = Aggregates.match(query);
Bson project = Aggregates.project(Projections.include(groupByField, idField));
Bson group;
if (count) {
group = Aggregates.group("$" + groupByField, Accumulators.sum("count", 1));
} else {
group = Aggregates.group("$" + groupByField, Accumulators.addToSet("features", "$" + idField));
}
return Arrays.asList(match, project, group);
}
}
public static List<Bson> createGroupBy(Bson query, List<String> groupByField, String idField, boolean count) {
if (groupByField == null || groupByField.isEmpty()) {
return new ArrayList<>();
}
if (groupByField.size() == 1) {
// if only one field then we call to simple createGroupBy
return createGroupBy(query, groupByField.get(0), idField, count);
} else {
Bson match = Aggregates.match(query);
// add all group-by fields to the projection together with the aggregation field name
List<String> groupByFields = new ArrayList<>(groupByField);
groupByFields.add(idField);
Bson project = Aggregates.project(Projections.include(groupByFields));
// _id document creation to have the multiple id
Document id = new Document();
for (String s : groupByField) {
id.append(s, "$" + s);
}
Bson group;
if (count) {
group = Aggregates.group(id, Accumulators.sum("count", 1));
} else {
group = Aggregates.group(id, Accumulators.addToSet("features", "$" + idField));
}
return Arrays.asList(match, project, group);
}
}
public static ComparisonOperator getComparisonOperator(String op, QueryParam.Type type) {
ComparisonOperator comparator = null;
if (op != null && op.isEmpty()) {
comparator = ComparisonOperator.EQUALS;
} else {
switch (type) {
case STRING:
case TEXT:
case TEXT_ARRAY:
switch(op) {
case "=":
case "==":
comparator = ComparisonOperator.EQUALS;
break;
case "!":
case "!=":
comparator = ComparisonOperator.NOT_EQUALS;
break;
case "~":
case "=~":
comparator = ComparisonOperator.REGEX;
break;
case "^":
case "=^":
comparator = ComparisonOperator.STARTS_WITH;
break;
case "$":
case "=$":
comparator = ComparisonOperator.ENDS_WITH;
break;
default:
throw new IllegalStateException("Unknown string query operation " + op);
}
break;
case INTEGER:
case INTEGER_ARRAY:
case DOUBLE:
case DECIMAL:
case DECIMAL_ARRAY:
switch(op) {
case "=":
case "==":
comparator = ComparisonOperator.EQUALS;
break;
case ">":
comparator = ComparisonOperator.GREATER_THAN;
break;
case ">=":
comparator = ComparisonOperator.GREATER_THAN_EQUAL;
break;
case "<":
comparator = ComparisonOperator.LESS_THAN;
break;
case "<=":
comparator = ComparisonOperator.LESS_THAN_EQUAL;
break;
case "!=":
comparator = ComparisonOperator.NOT_EQUALS;
break;
default:
throw new IllegalStateException("Unknown numerical query operation " + op);
}
break;
case BOOLEAN:
switch(op) {
case "=":
case "==":
comparator = ComparisonOperator.EQUALS;
break;
case "!=":
comparator = ComparisonOperator.NOT_EQUALS;
break;
default:
throw new IllegalStateException("Unknown boolean query operation " + op);
}
break;
default:
break;
}
}
return comparator;
}
protected static Pattern getPattern(QueryParam.Type type) {
Pattern pattern = null;
switch (type) {
case STRING:
case TEXT:
case TEXT_ARRAY:
pattern = OPERATION_STRING_PATTERN;
break;
case INTEGER:
case INTEGER_ARRAY:
case DOUBLE:
case DECIMAL:
case DECIMAL_ARRAY:
pattern = OPERATION_NUMERIC_PATTERN;
break;
case BOOLEAN:
pattern = OPERATION_BOOLEAN_PATTERN;
break;
default:
break;
}
return pattern;
}
}
|
package org.intermine.bio.web.logic;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.bio.util.OrganismRepository;
import org.intermine.bio.web.model.ChromosomeInfo;
import org.intermine.bio.web.model.GenomicRegion;
import org.intermine.bio.web.model.GenomicRegionSearchConstraint;
import org.intermine.bio.web.struts.GenomicRegionSearchForm;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.metadata.ConstraintOp;
import org.intermine.metadata.Model;
import org.intermine.metadata.StringUtil;
import org.intermine.model.bio.Organism;
import org.intermine.model.bio.SequenceFeature;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryObjectReference;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.OrderDirection;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.WebUtil;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.session.SessionMethods;
import org.json.JSONObject;
/**
* A class to provide genomic region search services in general.
*
* @author Fengyuan Hu
*/
public class GenomicRegionSearchService
{
private InterMineAPI interMineAPI = null;
private Model model = null;
private ObjectStore objectStore = null;
private Properties webProperties = null;
private Profile profile = null;
private WebConfig webConfig = null;
private Map<String, String> classDescrs = null;
private static String orgFeatureJSONString = "";
private static final String GENOMIC_REGION_SEARCH_OPTIONS_DEFAULT =
"genomic_region_search_options_default";
private static final String GENOMIC_REGION_SEARCH_RESULTS_DEFAULT =
"genomic_region_search_results_default";
private static final int READ_AHEAD_CHARS = 10000;
private GenomicRegionSearchConstraint grsc = null;
private static Set<String> featureTypesInOrgs = null;
private static Map<String, List<String>> featureTypeToSOTermMap = null;
private static Map<String, Integer> orgTaxonIdMap = null;
private List<String> selectionInfo = new ArrayList<String>();
private static final String CHROMOSOME_LOCATION_MISSING =
"Chromosome location information is missing";
private static final Logger LOG = Logger.getLogger(GenomicRegionSearchService.class);
/**
* Constructor
*/
public GenomicRegionSearchService() {
}
/**
* To set globally used variables.
* @param request HttpServletRequest
*/
public void init (HttpServletRequest request) {
this.webProperties = SessionMethods.getWebProperties(
request.getSession().getServletContext());
this.webConfig = SessionMethods.getWebConfig(request);
this.interMineAPI = SessionMethods.getInterMineAPI(request.getSession());
this.profile = SessionMethods.getProfile(request.getSession());
this.model = this.interMineAPI.getModel();
this.objectStore = this.interMineAPI.getObjectStore();
this.classDescrs = (Map<String, String>) request.getSession()
.getServletContext().getAttribute("classDescriptions");
}
/**
* To call the queryOrganismAndSequenceFeatureTypes method in
* GenomicRegionSearchQueryRunner.
*
* @return a JSON string
* @throws Exception e
*/
public String setupWebData() throws Exception {
long startTime = System.currentTimeMillis();
// By default, query all organisms in the database
// pre defined organism short names can be read out from web.properties
String presetOrganisms = webProperties.getProperty(
"genomicRegionSearch.defaultOrganisms");
List<String> orgList = new ArrayList<String>();
Set<String> chrOrgSet = getChromosomeInfomationMap().keySet();
if (chrOrgSet == null || chrOrgSet.size() == 0) {
return CHROMOSOME_LOCATION_MISSING;
} else {
if (presetOrganisms == null || "".equals(presetOrganisms)) {
orgList = new ArrayList<String>(chrOrgSet);
} else {
// e.g. presetCollection [f,b,a], orgFromDBCollection [g,a,e,f]
// results => [f,a] + [e,g] = [f,a,e,g]
// some items in preset organisms will be removed if chro information not available
List<String> presetOrgList = Arrays.asList(presetOrganisms
.split(","));
List<String> trimedPresetOrgList = new ArrayList<String>();
for (String s : presetOrgList) {
if (!"".equals(s.trim())) {
trimedPresetOrgList.add(s.trim());
}
}
// Don't remove any items from chrOrgSet, just make a copy
Set<String> chrOrgSetCopy = new TreeSet<String>();
for (String s : chrOrgSet) {
chrOrgSetCopy.add(s);
}
for (String o : trimedPresetOrgList) {
if (chrOrgSet.contains(o)) {
chrOrgSetCopy.remove(o);
}
}
trimedPresetOrgList.retainAll(chrOrgSet);
orgList.addAll(trimedPresetOrgList);
orgList.addAll(chrOrgSetCopy);
}
}
// Exclude preset feature types (global) to display
// Data should be comma separated class names
String excludedFeatureTypes = webProperties.getProperty(
"genomicRegionSearch.featureTypesExcluded.global");
List<String> excludedFeatureTypeList = new ArrayList<String>();
if (excludedFeatureTypes == null || "".equals(excludedFeatureTypes)) {
excludedFeatureTypeList = null;
} else {
excludedFeatureTypeList = Arrays.asList(excludedFeatureTypes.split("[, ]+"));
}
if ("".equals(orgFeatureJSONString)) {
String retval = prepareWebData(orgList, excludedFeatureTypeList);
LOG.info("REGIONS INIT total time:" + (System.currentTimeMillis() - startTime) + "ms");
return retval;
} else {
return orgFeatureJSONString;
}
}
private String prepareWebData(List<String> orgList, List<String> excludedFeatureTypeList) {
long startTime = System.currentTimeMillis();
Query q = new Query();
q.setDistinct(true);
QueryClass qcOrg = new QueryClass(Organism.class);
QueryClass qcFeature = new QueryClass(SequenceFeature.class);
QueryField qfOrgName = new QueryField(qcOrg, "shortName");
QueryField qfFeatureClass = new QueryField(qcFeature, "class");
q.addToSelect(qfOrgName);
q.addToSelect(qfFeatureClass);
q.addFrom(qcOrg);
q.addFrom(qcFeature);
q.addToOrderBy(qfOrgName, "ascending");
ConstraintSet constraints = new ConstraintSet(ConstraintOp.AND);
q.setConstraint(constraints);
// SequenceFeature.organism = Organism
QueryObjectReference organism = new QueryObjectReference(qcFeature,
"organism");
ContainsConstraint ccOrg = new ContainsConstraint(organism,
ConstraintOp.CONTAINS, qcOrg);
constraints.addConstraint(ccOrg);
// constraints.addConstraint(new BagConstraint(qfOrgName,
// ConstraintOp.IN, orgList));
int batchSize = 100000;
Results results = objectStore.execute(q, batchSize, true, true, true);
// Parse results data to a map
Map<String, Set<String>> resultsMap = new LinkedHashMap<String, Set<String>>();
Set<String> featureTypeSet = new LinkedHashSet<String>();
// TODO this will be very slow when query too many features
if (results == null || results.size() < 0) {
return "";
} else {
for (Iterator<?> iter = results.iterator(); iter.hasNext();) {
ResultsRow<?> row = (ResultsRow<?>) iter.next();
String org = (String) row.get(0);
@SuppressWarnings("rawtypes")
// TODO exception - feature type is NULL
String featureType = ((Class) row.get(1)).getSimpleName();
if (!"Chromosome".equals(featureType) && orgList.contains(org)) {
if (resultsMap.size() < 1) {
featureTypeSet.add(featureType);
resultsMap.put(org, featureTypeSet);
} else {
if (resultsMap.keySet().contains(org)) {
resultsMap.get(org).add(featureType);
} else {
Set<String> s = new LinkedHashSet<String>();
s.add(featureType);
resultsMap.put(org, s);
}
}
}
}
}
LOG.info("REGIONS INIT - organism feature types query took: "
+ (System.currentTimeMillis() - startTime) + "ms");
// Get all feature types
for (Set<String> ftSet : resultsMap.values()) {
// Exclude some feature types
if (excludedFeatureTypeList != null) {
ftSet.removeAll(excludedFeatureTypeList);
}
if (featureTypesInOrgs == null) {
featureTypesInOrgs = new HashSet<String>();
featureTypesInOrgs.addAll(ftSet);
}
}
getFeatureTypeToSOTermMap();
getOrganismToTaxonMap();
// Parse data to JSON string
List<Object> ft = new ArrayList<Object>();
List<Object> gb = new ArrayList<Object>();
Map<String, Object> ma = new LinkedHashMap<String, Object>();
for (Entry<String, Set<String>> e : resultsMap.entrySet()) {
Map<String, Object> mft = new LinkedHashMap<String, Object>();
Map<String, Object> mgb = new LinkedHashMap<String, Object>();
mft.put("organism", e.getKey());
List<Object> featureTypeAndDespMapList = new ArrayList<Object>();
for (String className : e.getValue()) {
Map<String, String> featureTypeAndDespMap = new LinkedHashMap<String, String>();
// String soTermDes = "description not avaliable";
// List<String> soInfo = featureTypeToSOTermMap.get(className);
// if (soInfo != null) {
// soTermDes = featureTypeToSOTermMap.get(className).get(1);
String des = "description not avaliable";
if (featureTypeToSOTermMap.containsKey(className)) {
des = featureTypeToSOTermMap.get(className).get(1);
} else {
des = (classDescrs.get(className) == null) ? "description not avaliable"
: classDescrs.get(className);
des = des.replaceAll("'", "'");
des = des.replaceAll("\"", """);
}
featureTypeAndDespMap.put("featureType", className);
featureTypeAndDespMap.put("description", des);
featureTypeAndDespMapList.add(featureTypeAndDespMap);
}
mft.put("features", featureTypeAndDespMapList);
ft.add(mft);
mgb.put("organism", e.getKey());
mgb.put("genomeBuild",
(OrganismGenomeBuildLookup
.getGenomeBuildbyOrgansimAbbreviation(e.getKey()) == null)
? "not available"
: OrganismGenomeBuildLookup
.getGenomeBuildbyOrgansimAbbreviation(e
.getKey()));
gb.add(mgb);
}
ma.put("organisms", orgList);
ma.put("genomeBuilds", gb);
ma.put("featureTypes", ft);
JSONObject jo = new JSONObject(ma);
// Note: JSONObject toString will replace \' to \\', so don't convert it before the method
// was called. Replace "\" in java -> "\\\\"
String preDataStr = jo.toString();
// preDataStr = preDataStr.replaceAll("'", "\\\\'");
return preDataStr;
}
/**
* Get the name of customized options javascript, by default, it is named
* "genomic_region_search_options_default.js"
*
* @return the name of options javascript name
*/
public String getOptionsJavascript() {
String optionsJavascriptName = webProperties
.getProperty("genomicRegionSearch.optionsJavascript");
if (optionsJavascriptName == null || "".equals(optionsJavascriptName)) {
optionsJavascriptName = GENOMIC_REGION_SEARCH_OPTIONS_DEFAULT;
}
return optionsJavascriptName;
}
/**
* Get the name of customized results javascript
*
* @return the name of results page
*/
public String getResultsJavascript() {
String resultsJavascriptName = webProperties
.getProperty("genomicRegionSearch.resultsJavascript");
if (resultsJavascriptName == null || "".equals(resultsJavascriptName)) {
resultsJavascriptName = GENOMIC_REGION_SEARCH_RESULTS_DEFAULT;
}
return resultsJavascriptName;
}
/**
* Get the name of customized options CSS
*
* @return the name of options css
*/
public String getOptionsCss() {
String optionsCssName = webProperties.getProperty(
"genomicRegionSearch.optionsCss");
if (optionsCssName == null || "".equals(optionsCssName)) {
optionsCssName = GENOMIC_REGION_SEARCH_OPTIONS_DEFAULT;
}
return optionsCssName;
}
/**
* Get the name of customized results CSS
*
* @return the name of results css
*/
public String getResultsCss() {
String resultsCssName = webProperties.getProperty(
"genomicRegionSearch.resultsCss");
if (resultsCssName == null || "".equals(resultsCssName)) {
resultsCssName = GENOMIC_REGION_SEARCH_RESULTS_DEFAULT;
}
return resultsCssName;
}
/**
* To parse form data
*
* @param grsForm GenomicRegionSearchForm
* @return genomic region search constraint
* @throws Exception e
*/
public ActionMessage parseGenomicRegionSearchForm(
GenomicRegionSearchForm grsForm) throws Exception {
grsc = new GenomicRegionSearchConstraint();
ActionMessage actmsg = parseBasicInput(grsForm);
if (actmsg != null) {
return actmsg;
}
return null;
}
/**
*
* @param grsForm GenomicRegionSearchForm
* @return ActionMessage
* @throws Exception e
*/
public ActionMessage parseBasicInput(GenomicRegionSearchForm grsForm) throws Exception {
// Parse form
String organism = (String) grsForm.get("organism");
String[] featureTypes = (String[]) grsForm.get("featureTypes");
String whichInput = (String) grsForm.get("whichInput");
String dataFormat = (String) grsForm.get("dataFormat");
FormFile formFile = (FormFile) grsForm.get("fileInput");
String pasteInput = (String) grsForm.get("pasteInput");
String extendedRegionSize = (String) grsForm.get("extendedRegionSize");
// Organism
grsc.setOrgName(organism);
if (Integer.parseInt(extendedRegionSize) < 0) {
throw new Exception(
"extendedRegionSize can't be a negative value: "
+ extendedRegionSize);
} else {
grsc.setExtededRegionSize(Integer.parseInt(extendedRegionSize));
}
selectionInfo.add("<b>Selected organism: </b><i>" + organism + "</i>");
// Feature types
if (featureTypes == null) {
return new ActionMessage("genomicRegionSearch.spanFieldSelection",
"feature types");
}
Set<Class<?>> ftSet = getFeatureTypes(featureTypes, extendedRegionSize);
grsc.setFeatureTypes(ftSet);
// File parsing
BufferedReader reader = null;
/*
* FormFile used from Struts works a bit strangely. 1. Although the file
* does't exist formFile.getInputStream() doesn't throw
* FileNotFoundException. 2. When user specified empty file path or very
* invalid file path, like file path not starting at '/' then
* formFile.getFileName() returns empty string.
*/
if ("paste".equals(whichInput)) {
if (pasteInput != null && pasteInput.length() != 0) {
String trimmedText = pasteInput.trim();
if (trimmedText.length() == 0) {
return new ActionMessage("genomicRegionSearch.noSpanPaste");
}
reader = new BufferedReader(new StringReader(trimmedText));
} else {
return new ActionMessage("genomicRegionSearch.noSpanFile");
}
} else if ("file".equals(whichInput)) {
if (formFile != null && formFile.getFileName() != null
&& formFile.getFileName().length() > 0) {
String mimetype = formFile.getContentType();
if (!"application/octet-stream".equals(mimetype)
&& !mimetype.startsWith("text")) {
return new ActionMessage("genomicRegionSearch.isNotText", mimetype);
}
if (formFile.getFileSize() == 0) {
return new ActionMessage("genomicRegionSearch.noSpanFileOrEmpty");
}
try {
reader = new BufferedReader(new InputStreamReader(
formFile.getInputStream()));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
return new ActionMessage("genomicRegionSearch.spanInputType");
}
if (reader == null) {
return new ActionMessage("genomicRegionSearch.spanInputType");
}
// Validate text format
try {
reader.mark(READ_AHEAD_CHARS);
} catch (IOException e) {
e.printStackTrace();
}
char[] buf = new char[READ_AHEAD_CHARS];
int read;
Set<String> spanStringSet = new LinkedHashSet<String>();
try {
read = reader.read(buf, 0, READ_AHEAD_CHARS);
for (int i = 0; i < read; i++) {
if (buf[i] == 0) {
return new ActionMessage("genomicRegionSearch.isNotText", "binary");
}
}
reader.reset();
// Remove duplication
String thisLine;
while ((thisLine = reader.readLine()) != null) {
spanStringSet.add(thisLine);
}
} catch (IOException e) {
e.printStackTrace();
}
// Parse uploaded spans to an arraylist; handle empty content and non-integer spans
// Tab delimited format: "chr(tab)start(tab)end" or "chr:start..end"
List<GenomicRegion> spanList = new ArrayList<GenomicRegion>();
for (String spanStr : spanStringSet) {
// The first time to create GenomicRegion object and set ExtendedRegionSize
GenomicRegion aSpan = new GenomicRegion();
aSpan.setOrganism(grsc.getOrgName());
aSpan.setExtendedRegionSize(grsc.getExtendedRegionSize());
// Use regular expression to validate user's input:
// "chr:start..end" - [^:]+:\d+\.{2,}\d+
String ddotsRegex = "^[^:]+: ?\\d+(,\\d+)*\\.{2}\\d+(,\\d+)*$";
// "chr:start..end:tag"
String ddotstagRegex = "^[^:]+: ?\\d+(,\\d+)*\\.{2}\\d+(,\\d+)*: ?\\d+$";
// "chr:start-end" - [^:]+:\d+\-\d+
String tabRegex = "^[^\\t\\s]+\\t\\d+(,\\d+)*\\t\\d+(,\\d+)*";
// "chr(tab)start(tab)end" - [^\t]+\t\d+\t\d+
String dashRegex = "^[^:]+: ?\\d+(,\\d+)*\\-\\d+(,\\d+)*$";
// "chr:singlePosition" - [^:]+:[\d]+$
String snpRegex = "^[^:]+: ?\\d+(,\\d+)*$";
String emptyLine = "^\\s*$";
if (Pattern.matches(ddotsRegex, spanStr)) {
spanStr = spanStr.contains(",") ? spanStr.replaceAll(",", "") : spanStr;
aSpan.setChr((spanStr.split(":"))[0]);
String[] spanItems = (spanStr.split(":"))[1].split("\\..");
String start = spanItems[0].trim();
if ("isInterBaseCoordinate".equals(dataFormat)) {
aSpan.setStart(Integer.valueOf(start) + 1);
} else {
aSpan.setStart(Integer.valueOf(start));
}
aSpan.setEnd(Integer.valueOf(spanItems[1]));
} else if (Pattern.matches(ddotstagRegex, spanStr)) {
spanStr = spanStr.contains(",") ? spanStr.replaceAll(",", "") : spanStr;
aSpan.setChr((spanStr.split(":"))[0]);
String[] spanItems = (spanStr.split(":"))[1].split("\\..");
String start = spanItems[0].trim();
if ("isInterBaseCoordinate".equals(dataFormat)) {
aSpan.setStart(Integer.valueOf(start) + 1);
} else {
aSpan.setStart(Integer.valueOf(start));
}
aSpan.setEnd(Integer.valueOf(spanItems[1]));
aSpan.setTag(Integer.valueOf((spanStr.split(":"))[2]));
} else if (Pattern.matches(tabRegex, spanStr)) {
spanStr = spanStr.contains(",") ? spanStr.replaceAll(",", "") : spanStr;
String[] spanItems = spanStr.split("\t");
aSpan.setChr(spanItems[0]);
if ("isInterBaseCoordinate".equals(dataFormat)) {
aSpan.setStart(Integer.valueOf(spanItems[1]) + 1);
} else {
aSpan.setStart(Integer.valueOf(spanItems[1]));
}
aSpan.setEnd(Integer.valueOf(spanItems[2]));
} else if (Pattern.matches(dashRegex, spanStr)) {
spanStr = spanStr.contains(",") ? spanStr.replaceAll(",", "") : spanStr;
aSpan.setChr((spanStr.split(":"))[0]);
String[] spanItems = (spanStr.split(":"))[1].split("-");
String start = spanItems[0].trim();
if ("isInterBaseCoordinate".equals(dataFormat)) {
aSpan.setStart(Integer.valueOf(start) + 1);
} else {
aSpan.setStart(Integer.valueOf(start));
}
aSpan.setEnd(Integer.valueOf(spanItems[1]));
} else if (Pattern.matches(snpRegex, spanStr)) {
spanStr = spanStr.contains(",") ? spanStr.replaceAll(",", "") : spanStr;
aSpan.setChr((spanStr.split(":"))[0]);
String start = (spanStr.split(":"))[1].trim();
if ("isInterBaseCoordinate".equals(dataFormat)) {
aSpan.setStart(Integer.valueOf(start) + 1);
} else {
aSpan.setStart(Integer.valueOf(start));
}
aSpan.setEnd(Integer.valueOf((spanStr.split(":"))[1].trim()));
} else {
if (!Pattern.matches(emptyLine, spanStr)) {
return new ActionMessage(
"genomicRegionSearch.spanInWrongformat", spanStr);
}
}
spanList.add(aSpan);
}
grsc.setGenomicRegionList(spanList);
return null;
}
private Set<Class<?>> getFeatureTypes(String[] featureTypes,
String extendedRegionSize) {
// featureTypes in this case are (the last bit of) class instead of
// featuretype in the db table; gain the full name by Model.getQualifiedTypeName(className)
Set<Class<?>> ftSet = new HashSet<Class<?>>();
for (String f : featureTypes) {
ClassDescriptor cld = model.getClassDescriptorByName(f);
ftSet.add(cld.getType());
// get all subclasses
for (ClassDescriptor subCld : model.getAllSubs(cld)) {
ftSet.add(subCld.getType());
}
}
String ftString = "";
for (String aFeaturetype : featureTypes) {
aFeaturetype = WebUtil.formatPath(aFeaturetype, interMineAPI, webConfig);
ftString = ftString + aFeaturetype + ", ";
}
selectionInfo.add("<b>Selected feature types: </b>"
+ ftString.substring(0, ftString.lastIndexOf(", ")));
if (Integer.parseInt(extendedRegionSize) > 0) {
if (Integer.parseInt(extendedRegionSize) >= 1000
&& Integer.parseInt(extendedRegionSize) < 1000000) {
selectionInfo.add("<b>Extend Regions: </b>"
+ new DecimalFormat("#.##").format(Integer
.parseInt(extendedRegionSize) / 1000) + " kbp");
} else if (Integer.parseInt(extendedRegionSize) >= 1000000) {
selectionInfo.add("<b>Extend Regions: </b>"
+ new DecimalFormat("#.##").format(Integer
.parseInt(extendedRegionSize) / 1000000) + " Mbp");
} else {
selectionInfo.add("<b>Extend Regions: </b>" + extendedRegionSize + "bp");
}
}
return ftSet;
}
/**
* To prepare queries for genomic regions
*
* @return a list of prepared queries for genomic regions
*/
public Map<GenomicRegion, Query> createQueryList() {
return GenomicRegionSearchUtil.createQueryList(
grsc.getGenomicRegionList(),
grsc.getExtendedRegionSize(),
grsc.getOrgName(),
grsc.getFeatureTypes());
}
/**
* @return the grsc
*/
public GenomicRegionSearchConstraint getConstraint() {
return this.grsc;
}
/**
* Get chromosome information as in a map, keys are lowercased chromosome ids
* @return chrInfoMap
*/
public Map<String, Map<String, ChromosomeInfo>> getChromosomeInfomationMap() {
return GenomicRegionSearchQueryRunner.getChromosomeInfo(interMineAPI);
}
/**
*
* @return featureTypeToSOTermMap
*/
public Map<String, List<String>> getFeatureTypeToSOTermMap() {
if (featureTypeToSOTermMap == null) {
long startTime = System.currentTimeMillis();
featureTypeToSOTermMap = GenomicRegionSearchQueryRunner
.getFeatureAndSOInfo(interMineAPI, classDescrs);
if (!(featureTypesInOrgs.size() == featureTypeToSOTermMap.size() && featureTypesInOrgs
.containsAll(featureTypeToSOTermMap.keySet()))) {
Map<String, List<String>> newFeatureTypeToSOTermMap =
new HashMap<String, List<String>>();
for (String ft : featureTypesInOrgs) {
if (featureTypeToSOTermMap.keySet().contains(ft)) {
newFeatureTypeToSOTermMap.put(ft,
featureTypeToSOTermMap.get(ft));
} else {
List<String> ftInfo = new ArrayList<String>();
ftInfo.add(ft);
String des = (classDescrs.get(ft) == null) ? "description not avaliable"
: classDescrs.get(ft);
des = des.replaceAll("'", "'");
des = des.replaceAll("\"", """);
ftInfo.add(des);
newFeatureTypeToSOTermMap.put(ft, ftInfo);
}
}
featureTypeToSOTermMap = newFeatureTypeToSOTermMap;
LOG.info("REGIONS INIT - getFeatureTypeToSoTermMap() took: "
+ (System.currentTimeMillis() - startTime) + "ms");
}
}
return featureTypeToSOTermMap;
}
/**
*
* @return orgTaxonIdMap
*/
public Map<String, Integer> getOrganismToTaxonMap() {
if (orgTaxonIdMap == null) {
orgTaxonIdMap = GenomicRegionSearchQueryRunner.getTaxonInfo(interMineAPI,
profile);
}
return orgTaxonIdMap;
}
/**
* Validate input genomic regions
*
* @return resultMap
* @throws Exception with error message
*/
public Map<String, List<GenomicRegion>> validateGenomicRegions() throws Exception {
/* the Map has two key-value mappings
* PASS-ArrayList<passedSpan>
* ERROR-ArrayList<errorSpan>
*/
Map<String, List<GenomicRegion>> resultMap = new HashMap<String, List<GenomicRegion>>();
List<GenomicRegion> passedSpanList = new ArrayList<GenomicRegion>();
List<GenomicRegion> errorSpanList = new ArrayList<GenomicRegion>();
Map<String, ChromosomeInfo> chrInfo = getChromosomeInfomationMap().get(grsc.getOrgName());
if (chrInfo == null) { // this should not happen
throw new Exception("ChromosomeInfo map should not be null");
}
// Create passedSpanList
for (GenomicRegion gr : grsc.getGenomicRegionList()) {
// User input could be x instead of X for human chromosome, converted to lowercase
ChromosomeInfo ci = null;
String chr = gr.getChr().toLowerCase();
if (chrInfo.containsKey(chr)) {
ci = chrInfo.get(chr);
} else {
if (chr.startsWith("chr")) { // UCSC format
if (chrInfo.containsKey(chr.substring(3))) {
ci = chrInfo.get(chr.substring(3));
} else {
continue;
}
} else {
continue;
}
}
if (gr.getStart() > gr.getEnd()) {
GenomicRegion newSpan = new GenomicRegion();
newSpan.setChr(ci.getChrPID()); // converted to the right case
if (gr.getEnd() < 1) {
newSpan.setStart(1);
} else {
newSpan.setStart(gr.getEnd());
}
newSpan.setEnd(gr.getStart());
newSpan.setExtendedRegionSize(0);
newSpan.setOrganism(grsc.getOrgName());
passedSpanList.add(newSpan);
} else {
gr.setChr(ci.getChrPID());
if (gr.getStart() < 1) {
gr.setStart(1);
}
passedSpanList.add(gr);
}
}
// make errorSpanList
errorSpanList.addAll(grsc.getGenomicRegionList());
errorSpanList.removeAll(passedSpanList);
resultMap.put("pass", passedSpanList);
resultMap.put("error", errorSpanList);
return resultMap;
}
/**
* The message passed to results page
*
* @return resultMessages
*/
public List<String> getSelectionInformation() {
return this.selectionInfo;
}
/**
* Get organism for GenomicRegionSearchAjaxAction use.
*
* @param spanUUIDString uuid
* @param spanConstraintMap map of contraints
* @return the organism
*/
public String getGenomicRegionOrganismConstraint(String spanUUIDString,
Map<GenomicRegionSearchConstraint, String> spanConstraintMap) {
for (Entry<GenomicRegionSearchConstraint, String> e : spanConstraintMap
.entrySet()) {
if (e.getValue().equals(spanUUIDString)) {
return e.getKey().getOrgName();
}
}
return null;
}
/**
* Get flanking size for GenomicRegionSearchAjaxAction use.
*
* @param spanUUIDString uuid
* @param spanConstraintMap map of contraints
* @return the flanking size
*/
public int getGenomicRegionExtendedSizeConstraint(String spanUUIDString,
Map<GenomicRegionSearchConstraint, String> spanConstraintMap) {
for (Entry<GenomicRegionSearchConstraint, String> e : spanConstraintMap
.entrySet()) {
if (e.getValue().equals(spanUUIDString)) {
return e.getKey().getExtendedRegionSize();
}
}
return 0;
}
/**
* Get a set of ids of a span's overlap features. for
* GenomicRegionSearchAjaxAction use.
*
* @param grInfo a genomic region in string array
* @param resultMap map of search results
* @return String feature ids joined by comma
* @throws Exception with error message
*/
public Set<Integer> getGenomicRegionOverlapFeaturesAsSet(String grInfo,
Map<GenomicRegion, List<List<String>>> resultMap) throws Exception {
Set<Integer> featureIdSet = new LinkedHashSet<Integer>();
GenomicRegion grToExport = GenomicRegionSearchUtil
.generateGenomicRegions(Arrays.asList(new String[] {grInfo}))
.get(0);
for (List<String> sf : resultMap.get(grToExport)) {
// the first element (0) is InterMine Id, second (1) is PID
featureIdSet.add(Integer.valueOf(sf.get(0)));
}
return featureIdSet;
}
/**
* Get a set of ids of a span's overlap features by given feature type. for
* GenomicRegionSearchAjaxAction use.
*
* @param grInfo a genomic region in string array
* @param resultMap map of search results
* @param featureType e.g. Gene
* @return String feature ids joined by comma
* @throws Exception with error message
*/
public Set<Integer> getGenomicRegionOverlapFeaturesByType(String grInfo,
Map<GenomicRegion, List<List<String>>> resultMap, String featureType) throws Exception {
Set<Integer> featureIdSet = new LinkedHashSet<Integer>();
GenomicRegion grToExport = GenomicRegionSearchUtil
.generateGenomicRegions(Arrays.asList(new String[] {grInfo}))
.get(0);
for (List<String> sf : resultMap.get(grToExport)) {
// the first element (0) is InterMine Id, second (1) is PID, 4 featureType
if (sf.get(3).equals(featureType)) {
featureIdSet.add(Integer.valueOf(sf.get(0)));
}
}
return featureIdSet;
}
/**
* Get a set of ids of all span's overlap features by given feature type. for
* GenomicRegionSearchAjaxAction use.
*
* @param resultMap map of search results
* @param featureType e.g. Gene
* @return String feature ids joined by comma
*/
public Set<Integer> getAllGenomicRegionOverlapFeaturesByType(
Map<GenomicRegion, List<List<String>>> resultMap, String featureType) {
Set<Integer> featureIdSet = new LinkedHashSet<Integer>();
for (Entry<GenomicRegion, List<List<String>>> e : resultMap.entrySet()) {
if (e.getValue() != null) {
for (List<String> sf : e.getValue()) {
if (sf.get(3).equals(featureType)) { // 3 featureType
featureIdSet.add(Integer.valueOf(sf.get(0))); // 0 id
}
}
}
}
return featureIdSet;
}
/**
* Get a comma separated string of a span's overlap features. for
* GenomicRegionSearchAjaxAction use.
*
* @param grInfo a genomic region in string array
* @param resultMap map of search results
* @return String feature ids joined by comma
* @throws Exception with error message
*/
public String getGenomicRegionOverlapFeaturesAsString(String grInfo,
Map<GenomicRegion, List<List<String>>> resultMap) throws Exception {
Set<Integer> featureSet = getGenomicRegionOverlapFeaturesAsSet(grInfo, resultMap);
return StringUtil.join(featureSet, ",");
}
/**
* Check whether the results have empty features. for
* GenomicRegionSearchAjaxAction use.
*
* @param resultMap map of search results
* @return String "hasFeature" or "emptyFeature"
*/
public String isEmptyFeature(
Map<GenomicRegion, List<List<String>>> resultMap) {
for (List<List<String>> l : resultMap.values()) {
if (l != null) {
return "hasFeature";
}
}
return "emptyFeature";
}
/**
* Generate a html string with all feature type for list creation.
*
* @param resultMap map of search results
* @return a html string
*/
public String generateCreateListHtml(Map<GenomicRegion, List<List<String>>> resultMap) {
Set<String> ftSet = new TreeSet<String>();
for (List<List<String>> l : resultMap.values()) {
if (l != null) {
for (List<String> feature : l) {
ftSet.add(feature.get(3)); // the 3rd is feature type
}
}
}
String clHtml = " or Create List by feature type:"
+ "<select id=\"all-regions\" style=\"margin: 4px 3px\">";
for (String ft : ftSet) {
clHtml += "<option value=\"" + ft + "\">"
+ WebUtil.formatPath(ft, interMineAPI, webConfig)
+ "</option>";
}
clHtml += "</select>";
clHtml += "<button onClick=\"javascript:createList('all','all-regions');\">Go</button>";
return clHtml;
}
/**
* Convert result map to HTML string.
*
* @param resultMap resultMap
* @param resultStat result statistics
* @param genomicRegionList spanList
* @param fromIdx offsetStart
* @param toIdx offsetEnd
* @param session the current session
* @return a String of HTML
*/
public String convertResultMapToHTML(
Map<GenomicRegion, List<List<String>>> resultMap,
Map<GenomicRegion, Map<String, Integer>> resultStat,
List<GenomicRegion> genomicRegionList, int fromIdx, int toIdx,
HttpSession session) {
// TODO hard coded count limit
int maxRecordCutOff = 1000;
if (webProperties.getProperty("genomicRegionSearch.maxRecordCutOff") != null) {
maxRecordCutOff = Integer.valueOf(webProperties
.getProperty("genomicRegionSearch.maxRecordCutOff"));
}
String baseURL = webProperties.getProperty("webapp.baseurl");
String path = webProperties.getProperty("webapp.path");
String galaxyDisplay = webProperties.getProperty("galaxy.display");
String exportChromosomeSegment = webProperties
.getProperty("genomicRegionSearch.exportChromosomeSegment");
List<GenomicRegion> subGenomicRegionList = genomicRegionList.subList(fromIdx, toIdx + 1);
// start to build the html for results table
StringBuffer sb = new StringBuffer();
//TODO use HTML Template
sb.append("<thead><tr valign=\"middle\">");
sb.append("<th align=\"center\">Genome Region</th>");
sb.append("<th align=\"center\">Feature</th>");
sb.append("<th align=\"center\">Feature Type</th>");
sb.append("<th align=\"center\">Location</th>");
sb.append("</tr></thead>");
sb.append("<tbody>");
for (GenomicRegion s : subGenomicRegionList) {
List<List<String>> features = resultMap.get(s);
Map<String, Integer> stat = resultStat.get(s);
String ftHtml = "";
Set<String> ftSet = null;
Map<String, Integer> aboveCutOffFeatureTypeMap = null;
if (stat != null) {
// get list of featureTypes
ftHtml = categorizeFeatureTypes(stat.keySet(), s);
ftSet = getFeatureTypeSetInAlphabeticalOrder(stat.keySet());
aboveCutOffFeatureTypeMap = new LinkedHashMap<String, Integer>();
int topCount = stat.values().iterator().next();
if (topCount >= maxRecordCutOff) {
for (Entry<String, Integer> e : stat.entrySet()) {
if (e.getValue() > maxRecordCutOff) {
aboveCutOffFeatureTypeMap.put(e.getKey(), e.getValue());
} else {
break;
}
}
}
}
String span = s.getExtendedRegionSize() == 0 ? s
.getOriginalRegion() : s.getExtendedRegion();
/*
* order: 0.id
* 1.feature PID
* 2.symbol
* 3.feature type
* 4.chr
* 5.start
* 6.end
* see query fields in createQueryList method
*/
if (features != null) {
if (aboveCutOffFeatureTypeMap == null || aboveCutOffFeatureTypeMap.size() == 0) {
int length = features.size();
addFirstFeatures(baseURL, path, galaxyDisplay,
exportChromosomeSegment, sb, s, features, ftHtml,
ftSet, span, length);
for (int i = 1; i < length; i++) {
addFeaturesAboveCutoff(baseURL, path, sb, features, i);
}
} else { // some feature sizes are over cutoff
int length = addFeaturesAboveCutoff(galaxyDisplay,
exportChromosomeSegment, sb, s, features, ftHtml,
ftSet, aboveCutOffFeatureTypeMap, span);
parseFeaturesAboveCutoff(sb, s, aboveCutOffFeatureTypeMap);
parseFeaturesBelowCutoff(baseURL, path, sb, features,
aboveCutOffFeatureTypeMap, length);
}
} else {
sb.append("<tr><td><b>"
+ span
+ "</b></td><td colspan='3'><i>No overlap features found</i></td></tr>");
}
}
sb.append("</tbody>");
return sb.toString();
}
private void addFirstFeatures(String baseURL, String path,
String galaxyDisplay, String exportChromosomeSegment,
StringBuffer sb, GenomicRegion s, List<List<String>> features,
String ftHtml, Set<String> ftSet, String span, int length) {
List<String> firstFeature = features.get(0);
String firstId = firstFeature.get(0);
String firstPid = firstFeature.get(1);
String firstSymbol = firstFeature.get(2);
String firstFeatureType = firstFeature.get(3); // Class name
String firstChr = firstFeature.get(4);
String firstStart = firstFeature.get(5);
String firstEnd = firstFeature.get(6);
String loc = firstChr + ":" + firstStart + ".." + firstEnd;
// translatedClassName
String firstSoTerm = WebUtil.formatPath(firstFeatureType, interMineAPI,
webConfig);
String firstSoTermDes = firstFeatureType;
if (featureTypeToSOTermMap.get(firstFeatureType) != null) {
firstSoTermDes = featureTypeToSOTermMap.get(firstFeatureType).get(1);
}
// firstSoTermDes = firstSoTermDes.replaceAll("'", "\\\\'");
sb.append("<tr><td valign='top' rowspan='" + length + "'>");
if (isJBrowseEnabled()) {
sb.append("<b><a title='view region in genome browser' "
+ "target='genome-browser' href='"
+ generateJBrowseURL(s)
+ "'>" + span + "</a></b>");
} else {
sb.append("<b>" + span + "</b>");
}
if (!"false".equals(exportChromosomeSegment)) {
sb.append("<span style=\"padding: 10px;\">"
+ "<a href='javascript: exportFeatures(\""
+ s.getFullRegionInfo()
+ "\", \"\", \"chrSeg\");'><img title=\"export chromosome "
+ "region as FASTA\" class=\"fasta\" "
+ "src=\"model/images/fasta.gif\"></a></span>");
}
sb.append("<br>");
if (s.getExtendedRegionSize() != 0) {
String os = s.getOriginalRegion();
sb.append("<i>Original input: " + os + "</i><br>");
}
String facet = "SequenceFeature";
if (ftSet != null) {
if (ftSet.size() == 1) {
facet = ftSet.iterator().next();
}
}
sb.append("<div style='align:center; padding:8px 0 4px 0;'>"
+ "<span class='tab export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"tab\");'></a></span>"
+ "<span class='csv export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"csv\");'></a></span>"
+ "<span class='gff3 export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"gff3\");'></a></span>"
+ "<span class='fasta export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"sequence\");'></a></span>"
+ "<span class='bed export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"bed\");'></a></span>");
// Display galaxy export
if (!"false".equals(galaxyDisplay)) {
sb.append("<span class='galaxy export-region'><a href='javascript: "
+ "exportToGalaxy(\"" + s.getFullRegionInfo() + "\");'></a></span>");
}
sb.append("</div>");
// Add create list by feature types link
sb.append(ftHtml);
// // Add JBrowse link
// if (isJBrowseEnabled()) {
// sb.append("<div><a target='genome-browser' href='"
// + generateJBrowseURL(s)
// + "'>View in genome bowser</a></div>");
sb.append("</td>");
sb.append("<td><a target='' title='' href='" + baseURL + "/" + path
+ "/report.do?id=" + firstId + "'>");
if ((firstSymbol == null || "".equals(firstSymbol))
&& (firstPid == null || "".equals(firstPid))) {
sb.append("<i>unknown identifier</i>");
} else if ((firstSymbol == null || "".equals(firstSymbol))
&& (firstPid != null && "".equals(firstPid))) {
sb.append("<span style='font-size: 11px;'>" + firstPid
+ "</span>");
} else if ((firstSymbol != null && "".equals(firstSymbol))
&& (firstPid == null || "".equals(firstPid))) {
sb.append("<strong>" + firstSymbol + "</strong>");
} else {
sb.append("<strong>" + firstSymbol + "</strong>")
.append(" ")
.append("<span style='font-size: 11px;'>"
+ firstPid + "</span>");
}
sb.append("</a></td><td>" + firstSoTerm
+ "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='"
+ firstSoTerm + ": " + firstSoTermDes.replaceAll("'", "\\\\'")
+ "';document.getElementById('ctxHelpDiv').style.display='';"
+ "window.scrollTo(0, 0);return false\" title=\"" + firstSoTermDes
+ "\"><img class=\"tinyQuestionMark\" "
+ "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>"
+ "</td><td>" + loc + "</td></tr>");
}
private int addFeaturesAboveCutoff(String galaxyDisplay,
String exportChromosomeSegment, StringBuffer sb, GenomicRegion s,
List<List<String>> features, String ftHtml, Set<String> ftSet,
Map<String, Integer> aboveCutOffFeatureTypeMap, String span) {
int length = features.size();
String firstFeatureType = aboveCutOffFeatureTypeMap.keySet().iterator().next();
// translatedClassName
String firstSoTerm = WebUtil.formatPath(firstFeatureType, interMineAPI,
webConfig);
String firstSoTermDes = firstFeatureType;
if (featureTypeToSOTermMap.get(firstFeatureType) != null) {
firstSoTermDes = featureTypeToSOTermMap.get(firstFeatureType).get(1);
}
// firstSoTermDes = firstSoTermDes.replaceAll("'", "\\\\'");
// row span is smaller than the feature size
int totalDupCount = 0;
for (String ft : aboveCutOffFeatureTypeMap.keySet()) {
totalDupCount = totalDupCount + aboveCutOffFeatureTypeMap.get(ft);
}
int rowSpan = length - totalDupCount
+ aboveCutOffFeatureTypeMap.size();
sb.append("<tr><td valign='top' rowspan='" + rowSpan + "'>");
if (isJBrowseEnabled()) {
sb.append("<b><a title='view region in genome browser' "
+ "target='genome-browser' href='"
+ generateJBrowseURL(s)
+ "'>" + span + "</a></b>");
} else {
sb.append("<b>" + span + "</b>");
}
if (!"false".equals(exportChromosomeSegment)) {
sb.append("<span style=\"padding: 10px;\">"
+ "<a href='javascript: exportFeatures(\""
+ s.getFullRegionInfo()
+ "\", \"\", \"chrSeg\");'><img title=\"export chromosome "
+ "region as FASTA\" class=\"fasta\" "
+ "src=\"model/images/fasta.gif\"></a></span>");
}
sb.append("<br>");
if (s.getExtendedRegionSize() != 0) {
String os = s.getOriginalRegion();
sb.append("<i>Original input: " + os + "</i><br>");
}
String facet = "SequenceFeature";
if (ftSet != null) {
if (ftSet.size() == 1) {
facet = ftSet.iterator().next();
}
}
sb.append("<div style='align:center; padding:8px 0 4px 0;'>"
+ "<span class='tab export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"tab\");'></a></span>"
+ "<span class='csv export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"csv\");'></a></span>"
+ "<span class='gff3 export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"gff3\");'></a></span>"
+ "<span class='fasta export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"sequence\");'></a></span>"
+ "<span class='bed export-region'><a href='javascript: "
+ "exportFeatures(\"" + s.getFullRegionInfo() + "\", " + "\""
+ facet + "\", \"bed\");'></a></span>");
// Display galaxy export
if (!"false".equals(galaxyDisplay)) {
sb.append("<span class='galaxy export-region'><a href='javascript: "
+ "exportToGalaxy(\"" + s.getFullRegionInfo() + "\");'></a></span>");
}
sb.append("</div>");
// Add create list by feature types link
sb.append(ftHtml);
// // Add JBrowse link
// if (isJBrowseEnabled()) {
// sb.append("<div><a target='genome-browser' href='"
// + generateJBrowseURL(s)
// + "'>View in genome bowser</a></div>");
sb.append("</td>");
int firstRecordCount = aboveCutOffFeatureTypeMap.get(firstFeatureType);
sb.append("<td colspan='3'><b>" + firstRecordCount + "</b> "
+ firstSoTerm
+ "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='"
+ firstSoTerm + ": " + firstSoTermDes.replaceAll("'", "\\\\'")
+ "';document.getElementById('ctxHelpDiv').style.display='';"
+ "window.scrollTo(0, 0);return false\" title=\"" + firstSoTermDes
+ "\"><img class=\"tinyQuestionMark\" "
+ "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>"
+ " records (too many to display all), "
+ "please <a href=\"javascript: createList('"
+ s.getFullRegionInfo() + "', " + null + ", '"
+ firstFeatureType
+ "');\">create a list</a>");
if (hasJBrowseTrack(firstFeatureType)) {
String jbrowseUrl = generateJBrowseURL(s, Arrays.asList(firstFeatureType));
sb.append(" or <a target='genome-browser' href='"
+ jbrowseUrl + "'>view in JBrowse</a>");
}
sb.append("</td></tr>");
return length;
}
private void addFeaturesAboveCutoff(String baseURL, String path,
StringBuffer sb, List<List<String>> features, int i) {
String id = features.get(i).get(0);
String pid = features.get(i).get(1);
String symbol = features.get(i).get(2);
String featureType = features.get(i).get(3);
String chr = features.get(i).get(4);
String start = features.get(i).get(5);
String end = features.get(i).get(6);
String soTerm = WebUtil.formatPath(featureType, interMineAPI,
webConfig);
String soTermDes = featureType;
if (featureTypeToSOTermMap.get(featureType) != null) {
soTermDes = featureTypeToSOTermMap.get(featureType).get(1);
}
// soTermDes = soTermDes.replaceAll("'", "\\\\'");
String location = chr + ":" + start + ".." + end;
sb.append("<tr><td><a target='' title='' href='"
+ baseURL + "/" + path + "/report.do?id=" + id + "'>");
if ((symbol == null || "".equals(symbol))
&& (pid == null || "".equals(pid))) {
sb.append("<i>unknown identifier</i>");
} else if ((symbol == null || "".equals(symbol))
&& (pid != null && "".equals(pid))) {
sb.append("<span style='font-size: 11px;'>" + pid
+ "</span>");
} else if ((symbol != null && "".equals(symbol))
&& (pid == null || "".equals(pid))) {
sb.append("<strong>" + symbol + "</strong>");
} else {
sb.append("<strong>" + symbol + "</strong>")
.append(" ")
.append("<span style='font-size: 11px;'>"
+ pid + "</span>");
}
sb.append("</a></td><td>"
+ soTerm
+ "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='"
+ soTerm + ": " + soTermDes.replaceAll("'", "\\\\'")
+ "';document.getElementById('ctxHelpDiv').style.display='';"
+ "window.scrollTo(0, 0);return false\" title=\"" + soTermDes
+ "\"><img class=\"tinyQuestionMark\" "
+ "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>"
+ "</td><td>" + location + "</td></tr>");
}
private void parseFeaturesBelowCutoff(String baseURL, String path,
StringBuffer sb, List<List<String>> features,
Map<String, Integer> aboveCutOffFeatureTypeMap, int length) {
for (int i = 0; i < length; i++) {
String id = features.get(i).get(0);
String pid = features.get(i).get(1);
String symbol = features.get(i).get(2);
String featureType = features.get(i).get(3);
String chr = features.get(i).get(4);
String start = features.get(i).get(5);
String end = features.get(i).get(6);
String soTerm = WebUtil.formatPath(featureType, interMineAPI,
webConfig);
String soTermDes = featureType;
if (featureTypeToSOTermMap.get(featureType) != null) {
soTermDes = featureTypeToSOTermMap.get(featureType).get(1);
}
// soTermDes = soTermDes.replaceAll("'", "\\\\'");
String location = chr + ":" + start + ".." + end;
if (!aboveCutOffFeatureTypeMap.keySet().contains(featureType)) {
sb.append("<tr><td><a target='' title='' href='"
+ baseURL + "/" + path + "/report.do?id=" + id + "'>");
if ((symbol == null || "".equals(symbol))
&& (pid == null || "".equals(pid))) {
sb.append("<i>unknown identifier</i>");
} else if ((symbol == null || "".equals(symbol))
&& (pid != null && "".equals(pid))) {
sb.append("<span style='font-size: 11px;'>" + pid
+ "</span>");
} else if ((symbol != null && "".equals(symbol))
&& (pid == null || "".equals(pid))) {
sb.append("<strong>" + symbol + "</strong>");
} else {
sb.append("<strong>" + symbol + "</strong>")
.append(" ")
.append("<span style='font-size: 11px;'>"
+ pid + "</span>");
}
sb.append("</a></td><td>"
+ soTerm
+ "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='"
+ soTerm + ": " + soTermDes.replaceAll("'", "\\\\'")
+ "';document.getElementById('ctxHelpDiv').style.display='';"
+ "window.scrollTo(0, 0);return false\" title=\"" + soTermDes
+ "\"><img class=\"tinyQuestionMark\" "
+ "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>"
+ "</td><td>" + location + "</td></tr>");
}
}
}
private void parseFeaturesAboveCutoff(StringBuffer sb, GenomicRegion s,
Map<String, Integer> aboveCutOffFeatureTypeMap) {
if (aboveCutOffFeatureTypeMap.size() > 1) {
List<String> aboveCutOffFeatureTypeList = new ArrayList<String>(
aboveCutOffFeatureTypeMap.keySet());
for (int i = 1; i < aboveCutOffFeatureTypeList.size(); i++) {
String featureType = aboveCutOffFeatureTypeList.get(i);
String soTerm = WebUtil.formatPath(featureType, interMineAPI,
webConfig);
String soTermDes = featureType;
if (featureTypeToSOTermMap.get(featureType) != null) {
soTermDes = featureTypeToSOTermMap.get(featureType).get(1);
}
// soTermDes = soTermDes.replaceAll("'", "\\\\'");
int recordCount = aboveCutOffFeatureTypeMap.get(featureType);
sb.append("<tr><td colspan='3'><b>" + recordCount + "</b> "
+ soTerm
+ "<a onclick=\"document.getElementById('ctxHelpTxt').innerHTML='"
+ soTerm + ": " + soTermDes.replaceAll("'", "\\\\'")
+ "';document.getElementById('ctxHelpDiv').style.display='';"
+ "window.scrollTo(0, 0);return false\" title=\"" + soTermDes
+ "\"><img class=\"tinyQuestionMark\" "
+ "src=\"images/icons/information-small-blue.png\" alt=\"?\"></a>"
+ " records (too many to display all), "
+ "please <a href=\"javascript: createList('"
+ s.getFullRegionInfo() + "', " + null + ", '"
+ featureType
+ "');\">create a list</a></td></tr>");
}
}
}
/**
* Get all feature types from a list of sequence features
* @param featureSet a set of feature types (class names) in a special order
* @param s GenomicRegion
* @return A html string with a dropdown list of feature types
*/
public String categorizeFeatureTypes(Set<String> featureSet, GenomicRegion s) {
String id = s.getChr() + "-" + s.getStart() + "-" + s.getEnd();
Set<String> ftSet = getFeatureTypeSetInAlphabeticalOrder(featureSet);
if (ftSet == null) {
return "";
} else {
String ftHtml = "<div>Create List by"
+ "<select id=\"" + id + "\" style=\"margin: 4px 3px\">";
for (String ft : ftSet) {
ftHtml += "<option value=\"" + ft + "\">"
+ WebUtil.formatPath(ft, interMineAPI, webConfig)
+ "</option>";
}
ftHtml += "</select>";
ftHtml += "<button onClick=\"javascript: createList('" + s.getFullRegionInfo()
+ "', '" + id + "');\">Go</button>";
ftHtml += "</div>";
return ftHtml;
}
}
/**
* Get all feature types in a TresSet
*
* @param featureSet a set of feature types (class names) in a special order
* @return a set of feature types of a genomic region in alphabetical order
*/
public Set<String> getFeatureTypeSetInAlphabeticalOrder(Set<String> featureSet) {
return new TreeSet<String>(featureSet);
}
/**
* Calculate the number of matched bases.
*
* @param gr a GenomicRegion object
* @param r a list of attributes
* @return matched base count as String
*/
protected String getMatchedBaseCount(GenomicRegion gr, List<String> r) {
int spanStart = gr.getStart();
int spanEnd = gr.getEnd();
int featureStart = Integer.valueOf(r.get(3));
int featureEnd = Integer.valueOf(r.get(4));
int matchedBaseCount = 0;
if (featureStart <= spanStart && featureEnd >= spanStart
&& featureEnd <= spanEnd) {
matchedBaseCount = featureEnd - spanStart + 1;
}
if (featureStart >= spanStart && featureStart <= spanEnd
&& featureEnd >= spanEnd) {
matchedBaseCount = spanEnd - featureStart + 1;
}
if (featureStart >= spanStart && featureEnd <= spanEnd) {
matchedBaseCount = featureEnd - featureStart + 1;
}
if (featureStart <= spanStart && featureEnd >= spanEnd) {
matchedBaseCount = spanEnd - spanStart + 1;
}
return String.valueOf(matchedBaseCount);
}
/**
* A flexiable way of setting query fields.
*
* @param featureIds set of feature intermine ids
* @param featureType feature class name
* @param views user defined views in web.properties
* @param sortOrder user defined sortOrder in web.properties
* @return a pathquery
*/
public PathQuery getExportFeaturesQuery(Set<Integer> featureIds,
String featureType, Set<String> views, List<String> sortOrder) {
PathQuery q = new PathQuery(model);
String path = featureType;
if (views == null) {
q.addView(path + ".primaryIdentifier");
q.addView(path + ".symbol");
q.addView(path + ".chromosomeLocation.locatedOn.primaryIdentifier");
q.addView(path + ".chromosomeLocation.start");
q.addView(path + ".chromosomeLocation.end");
q.addView(path + ".organism.name");
q.addOrderBy(path + ".chromosomeLocation.start", OrderDirection.ASC);
} else {
for (String view : views) {
q.addView(view.trim().replace("{0}", path));
}
String orderPath = sortOrder.get(0);
String direction = sortOrder.get(1);
if ("asc".equals(direction)) {
q.addOrderBy(orderPath.trim().replace("{0}", path), OrderDirection.ASC);
} else if ("desc".equals(direction)) {
q.addOrderBy(orderPath.trim().replace("{0}", path), OrderDirection.DESC);
}
}
q.addConstraint(Constraints.inIds(featureType, featureIds), "A");
return q;
}
/**
*
* @param organisms set of org names
* @return set of taxonIds
*/
public Set<Integer> getTaxonIds(Set<String> organisms) {
Set<Integer> taxIds = new HashSet<Integer>();
for (String org : organisms) {
taxIds.add(this.getOrganismToTaxonMap().get(org));
}
return taxIds;
}
/**
* Test if jbrowse is enabled
* @return boolean
*/
public boolean isJBrowseEnabled() {
String display = webProperties.getProperty("genomicRegionSearch.jbrowse.display");
if (display != null) {
display = display.trim();
if ("true".equals(display)) {
return true;
}
}
return false;
}
/**
* Get jbrowse track information from web.properties
* @return a map: key - feature type, value - track name
*/
public Map<String, String> getJBrowseTracks() {
String jbTracks = webProperties.getProperty("genomicRegionSearch.jbrowse.tracks").trim();
if (jbTracks == null || "".equals(jbTracks)) {
return null;
} else {
String[] tracks = jbTracks.split("\\|");
Map<String, String> trackMap = new HashMap<String, String>();
for (String track : tracks) {
trackMap.put(track.split(":")[1], track.split(":")[0]);
}
return trackMap;
}
}
/**
* Test if jbrowse has a track regards to a feature type
* @param featureType a feature type
* @return boolean
*/
public boolean hasJBrowseTrack(String featureType) {
if (isJBrowseEnabled() && getJBrowseTracks().get(featureType.toLowerCase()) != null) {
return true;
}
return false;
}
/**
* Generated a jbrowse url
* @param s a GenomicRegion object
* @param featureTypes list of feature types
* @return a string representing jbrowse url
*/
public String generateJBrowseURL(GenomicRegion s, List<String> featureTypes) {
int taxonId = OrganismRepository.getOrganismRepository()
.getOrganismDataByShortName(s.getOrganism()).getTaxonId();
String orgPrefix = webProperties.getProperty(
"genomicRegionSearch.jbrowse." + taxonId).trim();
String chrPattern = webProperties.getProperty(
"genomicRegionSearch.jbrowse.chrPattern").trim();
chrPattern = chrPattern.replace("{0}", orgPrefix);
chrPattern = chrPattern.replace("{1}", s.getChr());
String jbrowseBaseUrl = webProperties.getProperty("genomicRegionSearch.jbrowse.url").trim();
String jbUrl;
if (s.getExtendedRegionSize() == 0) {
jbUrl = jbrowseBaseUrl + "?loc=" + chrPattern + ":" + s.getStart()
+ ".." + s.getEnd();
} else {
jbUrl = jbrowseBaseUrl + "?loc=" + chrPattern + ":"
+ s.getExtendedStart() + ".." + s.getExtendedEnd();
}
List<String> tracks = new ArrayList<String>();
Map<String, String> trackMap = getJBrowseTracks();
if (trackMap != null) {
if (featureTypes == null) {
tracks = new ArrayList<String>(trackMap.values());
} else {
for (String featureType : featureTypes) {
if (trackMap.keySet().contains(featureType.toLowerCase())) {
tracks.add(trackMap.get(featureType.toLowerCase()));
}
}
}
if (tracks.size() > 0) {
jbUrl = jbUrl + "&tracks=" + StringUtil.join(tracks, ",");
}
}
return jbUrl;
}
/**
* A wrapper of generateJBrowseURL(GenomicRegion s, List<String> featureTypes)
* @param s GenomicRegion
* @return jbrowse url
*/
public String generateJBrowseURL(GenomicRegion s) {
return generateJBrowseURL(s, null);
}
}
|
package org.geomajas.plugin.deskmanager.client.gwt.manager.common;
import com.google.gwt.core.client.GWT;
import com.smartgwt.client.types.Overflow;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.types.TitleOrientation;
import com.smartgwt.client.util.BooleanCallback;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Slider;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;
import org.geomajas.configuration.client.ClientLayerInfo;
import org.geomajas.configuration.client.ClientRasterLayerInfo;
import org.geomajas.configuration.client.ClientVectorLayerInfo;
import org.geomajas.configuration.client.ClientWidgetInfo;
import org.geomajas.gwt.client.util.WidgetLayout;
import org.geomajas.plugin.deskmanager.client.gwt.manager.editor.LayerWidgetEditor;
import org.geomajas.plugin.deskmanager.client.gwt.manager.editor.VectorLayerWidgetEditor;
import org.geomajas.plugin.deskmanager.client.gwt.manager.editor.WidgetEditor;
import org.geomajas.plugin.deskmanager.client.gwt.manager.editor.WidgetEditorFactory;
import org.geomajas.plugin.deskmanager.client.gwt.manager.editor.WidgetEditorFactoryRegistry;
import org.geomajas.plugin.deskmanager.client.gwt.manager.i18n.ManagerMessages;
import org.geomajas.plugin.deskmanager.client.gwt.manager.service.SensibleScaleConverter;
import org.geomajas.plugin.deskmanager.client.gwt.manager.util.ExpertSldEditorHelper;
import org.geomajas.plugin.deskmanager.domain.dto.LayerDto;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Configuration window for individual layers.
*
* @author Oliver May
* @author Kristof Heirwegh
*/
public class LayerConfigurationWindow extends Window {
private static final ManagerMessages MESSAGES = GWT.create(ManagerMessages.class);
private static final int TABSET_WIDTH = 600;
private static final int TABSET_HEIGHT = 300;
private static final int FORMITEM_WIDTH = 300;
public static final String FLD_NAME = "Name";
private LayerDto layer;
private BooleanCallback callback;
private DynamicForm form;
private TextItem label;
private CheckboxItem publicLayer;
private CheckboxItem defaultVisible;
private TextItem minScale;
private TextItem maxScale;
private TabSet tabset;
private TabSet widgetTabset;
private List<WidgetEditorHandler> widgetEditors = new ArrayList<WidgetEditorHandler>();
private ExpertSldEditorHelper styleHelper;
private Slider opacitySlider;
/**
* Construct a layer configuration window.
*
* @param layerDto
* @param callback returns true if saved, false if canceled.
*/
public LayerConfigurationWindow(LayerDto layerDto, BooleanCallback callback) {
this.layer = layerDto;
this.callback = callback;
setAutoSize(true);
setCanDragReposition(true);
setCanDragResize(false);
setKeepInParentRect(true);
setOverflow(Overflow.HIDDEN);
setAutoCenter(true);
setTitle(MESSAGES.layerConfigurationConfigureLayer());
setShowCloseButton(false);
setShowMinimizeButton(false);
setShowMaximizeButton(false);
setIsModal(true);
setShowModalMask(true);
tabset = new TabSet();
tabset.setWidth(TABSET_WIDTH);
tabset.setHeight(TABSET_HEIGHT);
tabset.addTab(createSettingsTab());
ClientLayerInfo config = layerDto.getClientLayerInfo() == null ? layer.getReferencedLayerInfo() : layer
.getClientLayerInfo();
if (config instanceof ClientVectorLayerInfo) {
tabset.addTab(createVectorLayerStyleTab());
styleHelper = new ExpertSldEditorHelper((ClientVectorLayerInfo) config);
} else if (config instanceof ClientRasterLayerInfo) {
tabset.addTab(createRasterStyleTab((ClientRasterLayerInfo) config));
}
widgetTabset = new TabSet();
widgetTabset.setTabBarPosition(Side.LEFT);
widgetTabset.setWidth100();
widgetTabset.setHeight100();
widgetTabset.setOverflow(Overflow.HIDDEN);
widgetTabset.setTabBarThickness(100);
Tab tab = new Tab(MESSAGES.geodeskDetailTabWidgets());
tab.setPane(widgetTabset);
tabset.addTab(tab);
HLayout buttons = new HLayout(10);
IButton save = new IButton(MESSAGES.saveButtonText());
save.setIcon(WidgetLayout.iconSave);
save.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
saved();
}
});
IButton cancel = new IButton(MESSAGES.cancelButtonText());
cancel.setIcon(WidgetLayout.iconCancel);
cancel.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
cancelled();
}
});
IButton restore = new IButton(MESSAGES.resetButtonText());
restore.setIcon(WidgetLayout.iconReset);
restore.setTooltip(MESSAGES.resetButtonTooltip());
restore.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
restored();
}
});
buttons.addMember(save);
buttons.addMember(cancel);
buttons.addMember(new LayoutSpacer());
buttons.addMember(restore);
VLayout vl = new VLayout(10);
vl.setMargin(10);
vl.addMember(tabset);
vl.addMember(buttons);
addItem(vl);
}
private Tab createRasterStyleTab(final ClientRasterLayerInfo config) {
Tab tab = new Tab(MESSAGES.layerConfigurationLayerStyle());
VLayout vl = new VLayout(10);
vl.setMargin(10);
opacitySlider = new Slider(MESSAGES.layerConfigurationOpacity());
opacitySlider.setMinValue(0);
opacitySlider.setMaxValue(100);
opacitySlider.setVertical(false);
if (config.getStyle() != null && !"".equals(config.getStyle())) {
try {
opacitySlider.setValue(Float.parseFloat(config.getStyle()) * 100);
} catch (NumberFormatException e) {
opacitySlider.setValue(100);
}
}
vl.addMember(opacitySlider);
tab.setPane(vl);
return tab;
}
private Tab createSettingsTab() {
Tab tab = new Tab(MESSAGES.layerConfigurationLayerProperties());
form = new DynamicForm();
form.setIsGroup(true);
form.setGroupTitle(MESSAGES.layerConfigurationLayerProperties());
form.setPadding(5);
form.setWidth100();
form.setHeight100();
form.setAutoFocus(true); /* Set focus on first field */
form.setNumCols(2);
form.setTitleOrientation(TitleOrientation.LEFT);
label = new TextItem(FLD_NAME);
label.setTitle(MESSAGES.layerConfigurationName());
label.setRequired(true);
label.setWidth(FORMITEM_WIDTH);
label.setWrapTitle(false);
label.setTooltip(MESSAGES.layerConfigurationNameTooltip());
publicLayer = new CheckboxItem();
publicLayer.setTitle(MESSAGES.layerConfigurationPublicLayer());
publicLayer.setDisabled(true); // altijd readonly hier
publicLayer.setWrapTitle(false);
defaultVisible = new CheckboxItem();
defaultVisible.setTitle(MESSAGES.layerConfigurationLayerVisibleByDefault());
defaultVisible.setWrapTitle(false);
defaultVisible.setTooltip(MESSAGES.layerConfigurationLayerVisibleByDefaultTooltip());
minScale = new TextItem();
minScale.setTitle(MESSAGES.layerConfigurationMinimumScale());
minScale.setWidth(FORMITEM_WIDTH / 2);
minScale.setWrapTitle(false);
minScale.setTooltip(MESSAGES.layerConfigurationMinimumScaleTooltip());
minScale.setValidators(new ScaleValidator());
maxScale = new TextItem();
maxScale.setTitle(MESSAGES.layerConfigurationMaximumScale());
maxScale.setWidth(FORMITEM_WIDTH / 2);
maxScale.setWrapTitle(false);
maxScale.setValidators(new ScaleValidator());
maxScale.setTooltip(MESSAGES.layerConfigurationMaximumScaleTooltip());
form.setFields(label, publicLayer, defaultVisible, minScale, maxScale);
tab.setPane(form);
return tab;
}
private Tab createVectorLayerStyleTab() {
Tab tab = new Tab(MESSAGES.layerConfigurationLayerStyle());
VLayout vl = new VLayout(10);
vl.setMargin(10);
IButton openStyleEditor = new IButton(MESSAGES.layerConfigExpertEditorBtn());
openStyleEditor.setIcon(WidgetLayout.iconEdit);
openStyleEditor.setAutoFit(true);
openStyleEditor.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
styleHelper.showExpertStyleEditor();
}
});
vl.addMember(openStyleEditor);
tab.setPane(vl);
return tab;
}
public void show() {
form.clearValues();
publicLayer.setValue(layer.getLayerModel().isPublic());
ClientLayerInfo cli = layer.getClientLayerInfo();
if (cli == null) {
// If layerInfo not set (yet), copy from model.
cli = layer.getReferencedLayerInfo();
}
label.setValue(cli.getLabel());
defaultVisible.setValue(cli.isVisible());
minScale.setValue(SensibleScaleConverter.scaleToString(cli.getMinimumScale()));
maxScale.setValue(SensibleScaleConverter.scaleToString(cli.getMaximumScale()));
clearWidgetTabs();
loadWidgetTabs(layer);
super.show();
}
private void cancelled() {
hide();
destroy();
if (callback != null) {
callback.execute(false);
}
}
private void saved() {
if (form.validate()) {
if (layer.getClientLayerInfo() == null) {
layer.setClientLayerInfo(layer.getReferencedLayerInfo()); // clone??
}
ClientLayerInfo cli = layer.getClientLayerInfo();
cli.setLayerInfo(null);
cli.setVisible(defaultVisible.getValueAsBoolean());
cli.setLabel(label.getValueAsString());
cli.setMinimumScale(SensibleScaleConverter.stringToScale(minScale.getValueAsString()));
cli.setMaximumScale(SensibleScaleConverter.stringToScale(maxScale.getValueAsString()));
if (cli instanceof ClientRasterLayerInfo && opacitySlider != null) {
float opacityValue = opacitySlider.getValue() / 100;
((ClientRasterLayerInfo) cli).setStyle(String.valueOf(opacityValue));
} else if (cli instanceof ClientVectorLayerInfo && styleHelper != null) {
styleHelper.apply((ClientVectorLayerInfo) cli);
}
for (WidgetEditorHandler h : widgetEditors) {
h.save(layer);
}
hide();
destroy();
if (callback != null) {
callback.execute(true);
}
}
}
@Override
public void destroy() {
if (styleHelper != null) {
styleHelper.destroy();
}
super.destroy();
}
private void restored() {
if (layer.getClientLayerInfo() != null || !layer.getWidgetInfo().isEmpty()) {
SC.ask(MESSAGES.layerConfigConfirmRestoreTitle(), MESSAGES.layerConfigConfirmRestoreText(),
new BooleanCallback() {
public void execute(Boolean value) {
if (value) {
layer.setClientLayerInfo(null);
layer.getWidgetInfo().clear();
hide();
callback.execute(true);
}
}
});
}
}
/** Clear all custom widget tabs from the last blueprint. */
private void clearWidgetTabs() {
for (Tab tab : widgetTabset.getTabs()) {
widgetTabset.removeTab(tab);
}
widgetEditors.clear();
}
/**
* Load all widget editors that are available on this blueprints user application, and add them to the tabset.
*
* @param layerDto the basegeodesk.
*/
private void loadWidgetTabs(LayerDto layerDto) {
for (String key : WidgetEditorFactoryRegistry.getLayerRegistry().getWidgetEditors().keySet()) {
addWidgetTab(WidgetEditorFactoryRegistry.getMapRegistry().get(key), layerDto.getWidgetInfo(), layerDto);
}
}
/**
* Add a widget editor tab to the tabset for a given editor factory, set of widget info's (where one of will be
* edited by the editor) and a base geodesk that could provide extra context to the editor.
*
* @param editorFactory the editor factory
* @param widgetInfos all the widget infos
* @param layerDto the layer model
*/
private void addWidgetTab(final WidgetEditorFactory editorFactory, final Map<String, ClientWidgetInfo> widgetInfos,
final LayerDto layerDto) {
if (editorFactory != null) {
Tab tab = new Tab(editorFactory.getName());
final WidgetEditor editor = editorFactory.createEditor();
if (editor instanceof LayerWidgetEditor) {
((LayerWidgetEditor) editor).setLayer(layerDto.getLayerModel());
// in case instanceof VectorLayerWidgetEditor, only add a tab for vector layers
// and add clientLayerInfo to the editor,
if (editor instanceof VectorLayerWidgetEditor) {
final VectorLayerWidgetEditor vectorLayerWidgetEditor =
(VectorLayerWidgetEditor) editor;
if (layerDto.getClientLayerInfo() instanceof ClientVectorLayerInfo) {
vectorLayerWidgetEditor.setClientVectorLayerInfo(
(ClientVectorLayerInfo) layerDto.getClientLayerInfo());
} else {
// layer is raster, so don't add this editor as a tab.
return;
}
}
}
editor.setWidgetConfiguration(widgetInfos.get(editorFactory.getKey()));
// Create tab layout
VLayout layout = new VLayout();
layout.setMargin(5);
widgetEditors.add(new WidgetEditorHandler() {
@Override
public void save(LayerDto layer) {
layer.getWidgetInfo().put(editorFactory.getKey(), editor.getWidgetConfiguration());
}
});
layout.addMember(editor.getCanvas());
tab.setPane(layout);
widgetTabset.addTab(tab);
}
}
/**
* Interface for handling widget editors.
*
* @author Oliver May
*/
private interface WidgetEditorHandler {
/**
* Set the correct information in the layer dto.
*
* @param layer the layer dto
*/
void save(LayerDto layer);
}
}
|
// IT Innovation Centre of Gamma House, Enterprise Road,
// Chilworth Science Park, Southampton, SO16 7NS, UK.
// or reproduced in whole or in part in any manner or form or in or
// on any media by any person other than in accordance with the terms
// of the Licence Agreement supplied with the software, or otherwise
// PURPOSE, except where stated in the Licence Agreement supplied with
// the software.
// Created Date : 06-Feb-2013
// Created for Project : EXPERIMEDIA
package uk.ac.soton.itinnovation.experimedia.arch.ecc.dash.views.liveMetrics;
import uk.ac.soton.itinnovation.experimedia.arch.ecc.edm.spec.mon.dao.IReportDAO;
import uk.ac.soton.itinnovation.robust.cat.core.components.viewEngine.spec.uif.mvc.IUFView;
import uk.ac.soton.itinnovation.robust.cat.core.components.viewEngine.spec.uif.types.UFAbstractEventManager;
import uk.ac.soton.itinnovation.experimedia.arch.ecc.common.logging.spec.*;
import uk.ac.soton.itinnovation.experimedia.arch.ecc.common.dataModel.metrics.*;
import uk.ac.soton.itinnovation.experimedia.arch.ecc.common.dataModel.monitor.EMClient;
import uk.ac.soton.itinnovation.experimedia.arch.ecc.common.dataModel.provenance.PROVStatement;
import uk.ac.soton.itinnovation.experimedia.arch.ecc.dash.views.liveMetrics.visualizers.*;
import org.vaadin.artur.icepush.ICEPush;
import java.util.*;
public class LiveMonitorController extends UFAbstractEventManager
implements LiveMonitorViewListener
{
private final IECCLogger liveMonLogger = Logger.getLogger( LiveMonitorController.class );
private final Object updateViewLock = new Object();
private LiveMonitorView liveMonitorView;
private transient HashMap<UUID, MSUpdateInfo> measurementUpdates;
private transient HashSet<UUID> activeMSVisuals;
private transient IReportDAO expReportAccessor;
private transient ICEPush icePusher;
public LiveMonitorController( ICEPush pusher )
{
super();
icePusher = pusher;
measurementUpdates = new HashMap<UUID, MSUpdateInfo>();
activeMSVisuals = new HashSet<UUID>();
createView();
}
public void initialse( IReportDAO dao )
{ expReportAccessor = dao; }
public void processLiveMetricData( EMClient client, Report report ) throws Exception
{
// Safety first
if ( report == null || client == null ) throw new Exception( "Live monitoring metric parameters were null" );
if ( expReportAccessor == null ) throw new Exception( "Live monitoring control has not been initialised" );
// Check to see if we have anything useful store, and try store
if ( sanitiseMetricReport(report) )
{
try
{ expReportAccessor.saveMeasurements( report ); }
catch ( Exception e ) { throw e; }
// Remove measurements we've already displayed 'live'
removeOldMeasurements( report );
// Display (if we have an active display and there is still data)
if ( report.getNumberOfMeasurements() > 0 )
synchronized ( updateViewLock )
{
UUID msID = report.getMeasurementSet().getID();
if ( activeMSVisuals.contains(msID) )
{
MeasurementSet ms = report.getMeasurementSet();
liveMonitorView.updateMetricVisual( msID, ms );
if ( icePusher !=null ) icePusher.push();
}
}
}
}
public void processLivePROVData( EMClient client, PROVStatement statement ) throws Exception
{
if ( client == null || statement == null ) throw new Exception( "Live monitoring provenance parameters were null" );
liveMonLogger.info( "Got PROV statement from: " + statement.getCopyOfDate().toString() );
// More to do here later
}
public IUFView getLiveView()
{ return liveMonitorView; }
public void reset()
{
activeMSVisuals.clear();
liveMonitorView.resetView();
}
public void shutDown()
{
icePusher = null;
}
public void addliveView( EMClient client, Entity entity, Attribute attribute,
Collection<MeasurementSet> mSets )
{
if ( client != null && attribute != null && mSets != null )
{
Iterator<MeasurementSet> msIt = mSets.iterator();
while ( msIt.hasNext() )
{
MeasurementSet ms = msIt.next();
UUID msID = ms.getID();
Metric metric = ms.getMetric();
BaseMetricVisual visual = null;
if ( !activeMSVisuals.contains(msID) )
{
switch ( ms.getMetric().getMetricType() )
{
case NOMINAL :
visual = new NominalValuesSnapshotVisual( attribute.getName(),
metric.getUnit().getName(),
metric.getMetricType().name(),
msID ); break;
case ORDINAL :
case INTERVAL:
visual = new RawDataVisual( attribute.getName(),
metric.getUnit().getName(),
metric.getMetricType().name(),
msID ); break;
case RATIO :
visual = new NumericTimeSeriesVisual( attribute.getName(),
metric.getUnit().getName(),
metric.getMetricType().name(),
msID ); break;
}
if ( visual != null )
synchronized ( updateViewLock )
{
liveMonitorView.addMetricVisual( client.getName(),
entity.getName(),
attribute.getName(),
msID, visual );
activeMSVisuals.add( msID );
}
}
}
}
}
public void removeClientLiveView( EMClient client )
{
if ( client != null )
{
// Remove all known measurement sets from view
Set<MetricGenerator> msGens = client.getCopyOfMetricGenerators();
if ( !msGens.isEmpty() )
{
Map<UUID, MeasurementSet> mSets = MetricHelper.getAllMeasurementSets( msGens );
Iterator<MeasurementSet> msIt = mSets.values().iterator();
synchronized ( updateViewLock )
{
while ( msIt.hasNext() )
{
UUID msID = msIt.next().getID();
activeMSVisuals.remove( msID );
liveMonitorView.removeMetricVisual( msID );
}
if ( icePusher !=null ) icePusher.push();
}
}
}
}
@Override
public void onRemoveVisualClicked( UUID msID )
{
if ( msID != null )
{
synchronized ( updateViewLock )
{
activeMSVisuals.remove( msID );
liveMonitorView.removeMetricVisual( msID );
if ( icePusher !=null ) icePusher.push();
}
}
}
private void createView()
{
liveMonitorView = new LiveMonitorView();
liveMonitorView.addListener( this );
}
private void removeOldMeasurements( Report report )
{
if ( report != null )
{
MeasurementSet ms = report.getMeasurementSet();
if ( ms != null )
{
Set<Measurement> targetMeasurements = ms.getMeasurements();
if ( targetMeasurements != null && !targetMeasurements.isEmpty() )
{
// Measurements we're going to ditch (because we've got them) to be recored here
HashSet<Measurement> oldMeasurements = new HashSet<Measurement>();
UUID msID = ms.getID();
// Get latest measurement (if one does not exist, create a dummy measurement)
MSUpdateInfo lastRecent = measurementUpdates.get( msID );
if ( lastRecent == null )
{
Date date = new Date();
date.setTime( 0 );
lastRecent = new MSUpdateInfo( date, UUID.randomUUID() );
}
MSUpdateInfo mostRecentInfo = lastRecent;
// Find old measurements (if any)
Iterator<Measurement> mIt = targetMeasurements.iterator();
while( mIt.hasNext() )
{
Measurement m = mIt.next();
Date mDate = m.getTimeStamp();
if ( mostRecentInfo.lastUpdate.after(mDate) ||
mostRecentInfo.lastMeasurementID.equals(m.getUUID()) ) // If it is an old or repeated
oldMeasurements.add( m ); // measurement, we don't want it
else
mostRecentInfo = new MSUpdateInfo( mDate, m.getUUID() );
}
// Remove old measurements
mIt = oldMeasurements.iterator();
while ( mIt.hasNext() )
targetMeasurements.remove( mIt.next() );
// Update measurement count and recency
report.setNumberOfMeasurements( targetMeasurements.size() );
measurementUpdates.remove( msID );
measurementUpdates.put( msID, mostRecentInfo );
}
else report.setNumberOfMeasurements( 0 );
}
else report.setNumberOfMeasurements( 0 );
}
}
private boolean sanitiseMetricReport( Report reportOUT )
{
if ( reportOUT.getNumberOfMeasurements() == 0 ) return false;
MeasurementSet ms = reportOUT.getMeasurementSet();
if ( ms == null ) return false;
Metric metric = ms.getMetric();
if ( metric == null ) return false;
MetricType mt = metric.getMetricType();
// Sanitise data
MeasurementSet cleanSet = new MeasurementSet( ms, false );
for ( Measurement m : ms.getMeasurements() )
{
String val = m.getValue();
switch ( mt )
{
case NOMINAL:
case ORDINAL:
if ( val != null && !val.isEmpty() ) cleanSet.addMeasurement( m ); break;
case INTERVAL:
case RATIO:
{
if ( val != null )
{
try
{
// Make sure we have a sensible number
Double dVal = Double.parseDouble(val);
if ( !dVal.isNaN() && !dVal.isInfinite() )
cleanSet.addMeasurement( m );
}
catch( Exception ex ) { /*Not INTERVAL OR RATIO, so don't include*/ }
}
} break;
}
}
// Use update report with clean measurement set
reportOUT.setMeasurementSet( cleanSet );
reportOUT.setNumberOfMeasurements( cleanSet.getMeasurements().size() );
return true;
}
private class MSUpdateInfo
{
final Date lastUpdate;
final UUID lastMeasurementID;
public MSUpdateInfo( Date update, UUID measurementID )
{
lastUpdate = update;
lastMeasurementID = measurementID;
}
}
}
|
package com.dianping.cat.consumer;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
import org.unidal.helper.Threads;
import org.unidal.helper.Threads.Task;
import org.unidal.lookup.ContainerHolder;
import org.unidal.lookup.annotation.Inject;
import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.analysis.MessageAnalyzer;
import com.dianping.cat.analysis.MessageAnalyzerManager;
import com.dianping.cat.analysis.PeriodStrategy;
import com.dianping.cat.analysis.PeriodTask;
import com.dianping.cat.consumer.problem.ProblemAnalyzer;
import com.dianping.cat.consumer.top.TopAnalyzer;
import com.dianping.cat.consumer.transaction.TransactionAnalyzer;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.MessageProducer;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.io.DefaultMessageQueue;
import com.dianping.cat.message.spi.MessageQueue;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.core.MessageConsumer;
import com.dianping.cat.statistic.ServerStatisticManager;
public class RealtimeConsumer extends ContainerHolder implements MessageConsumer, Initializable, LogEnabled {
private static final long MINUTE = 60 * 1000L;
private static int QUEUE_SIZE = 200000;
@Inject
private MessageAnalyzerManager m_analyzerManager;
@Inject
private ServerStatisticManager m_serverStateManager;
private Map<String, Integer> m_errorTimeDomains = new HashMap<String, Integer>();
private Logger m_logger;
private PeriodManager m_periodManager;
private long m_networkError;
private long m_duration = 60 * MINUTE;
private long m_extraTime = 3 * MINUTE;
@Override
public void consume(MessageTree tree) {
try {
m_periodManager.waitUntilStarted();
} catch (InterruptedException e) {
// ignore it
}
long timestamp = tree.getMessage().getTimestamp();
Period period = m_periodManager.findPeriod(timestamp);
if (period != null) {
period.distribute(tree);
} else {
m_serverStateManager.addNetworkTimeError(1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
String domain = tree.getDomain();
Integer size = m_errorTimeDomains.get(domain);
if (size == null) {
size = 1;
} else {
size++;
}
m_errorTimeDomains.put(domain, size);
m_networkError++;
if (m_networkError % (CatConstants.ERROR_COUNT * 10) == 0) {
m_logger.error("Error network time:" + m_errorTimeDomains);
m_logger.error("The timestamp of message is out of range, IGNORED! "
+ sdf.format(new Date(tree.getMessage().getTimestamp())) + " " + tree.getDomain() + " "
+ tree.getIpAddress());
}
}
}
public void doCheckpoint() throws IOException {
MessageProducer cat = Cat.getProducer();
Transaction t = cat.newTransaction("Checkpoint", getClass().getSimpleName());
try {
long currentStartTime = getCurrentStartTime();
Period period = m_periodManager.findPeriod(currentStartTime);
for (MessageAnalyzer analyzer : period.getAnalzyers()) {
try {
analyzer.doCheckpoint(false);
} catch (Exception e) {
Cat.logError(e);
}
}
try {
// wait dump analyzer store completed
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
// ignore
}
t.setStatus(Message.SUCCESS);
} catch (RuntimeException e) {
cat.logError(e);
t.setStatus(e);
} finally {
t.complete();
}
}
@Override
public void enableLogging(Logger logger) {
m_logger = logger;
}
public MessageAnalyzer getCurrentAnalyzer(String name) {
long currentStartTime = getCurrentStartTime();
Period period = m_periodManager.findPeriod(currentStartTime);
return period.getAnalyzer(name);
}
private long getCurrentStartTime() {
long now = System.currentTimeMillis();
long time = now - now % m_duration;
return time;
}
public MessageAnalyzer getLastAnalyzer(String name) {
long lastStartTime = getCurrentStartTime() - m_duration;
Period period = m_periodManager.findPeriod(lastStartTime);
return period == null ? null : period.getAnalyzer(name);
}
@Override
public void initialize() throws InitializationException {
m_periodManager = new PeriodManager();
Threads.forGroup("Cat").start(m_periodManager);
}
class Period {
private long m_startTime;
private long m_endTime;
private List<PeriodTask> m_tasks;
public Period(long startTime, long endTime) {
List<String> names = m_analyzerManager.getAnalyzerNames();
m_startTime = startTime;
m_endTime = endTime;
m_tasks = new ArrayList<PeriodTask>(names.size());
Map<String, MessageAnalyzer> analyzers = new LinkedHashMap<String, MessageAnalyzer>();
for (String name : names) {
MessageAnalyzer analyzer = m_analyzerManager.getAnalyzer(name, startTime);
MessageQueue queue = new DefaultMessageQueue(QUEUE_SIZE);
PeriodTask task = new PeriodTask(m_serverStateManager, analyzer, queue, startTime);
analyzers.put(name, analyzer);
task.enableLogging(m_logger);
m_tasks.add(task);
}
// hack for dependency
MessageAnalyzer top = analyzers.get(TopAnalyzer.ID);
MessageAnalyzer transaction = analyzers.get(TransactionAnalyzer.ID);
MessageAnalyzer problem = analyzers.get(ProblemAnalyzer.ID);
if (top != null) {
((TopAnalyzer) top).setTransactionAnalyzer((TransactionAnalyzer) transaction);
((TopAnalyzer) top).setProblemAnalyzer((ProblemAnalyzer) problem);
}
}
public void distribute(MessageTree tree) {
m_serverStateManager.addMessageTotal(tree.getDomain(), 1);
for (PeriodTask task : m_tasks) {
task.enqueue(tree);
}
}
public void finish() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = new Date(m_startTime);
Date endDate = new Date(m_endTime - 1);
m_logger.info(String.format("Finishing %s tasks in period [%s, %s]", m_tasks.size(), df.format(startDate),
df.format(endDate)));
Cat.setup(null);
MessageProducer cat = Cat.getProducer();
Transaction t = cat.newTransaction("Checkpoint", "RealtimeConsumer");
try {
for (PeriodTask task : m_tasks) {
task.finish();
}
t.setStatus(Message.SUCCESS);
} catch (Throwable e) {
cat.logError(e);
t.setStatus(e);
} finally {
t.complete();
m_logger.info(String.format("Finished %s tasks in period [%s, %s]", m_tasks.size(), df.format(startDate),
df.format(endDate)));
}
Cat.reset();
}
public MessageAnalyzer getAnalyzer(String name) {
List<String> names = m_analyzerManager.getAnalyzerNames();
int index = names.indexOf(name);
if (index >= 0) {
PeriodTask task = m_tasks.get(index);
return task.getAnalyzer();
}
return null;
}
public List<MessageAnalyzer> getAnalzyers() {
List<MessageAnalyzer> analyzers = new ArrayList<MessageAnalyzer>(m_tasks.size());
for (PeriodTask task : m_tasks) {
analyzers.add(task.getAnalyzer());
}
return analyzers;
}
public boolean isIn(long timestamp) {
return timestamp >= m_startTime && timestamp < m_endTime;
}
public void start() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
m_logger.info(String.format("Starting %s tasks in period [%s, %s]", m_tasks.size(),
df.format(new Date(m_startTime)), df.format(new Date(m_endTime - 1))));
for (PeriodTask task : m_tasks) {
Threads.forGroup("Cat-RealtimeConsumer").start(task);
}
}
}
class PeriodManager implements Task {
private PeriodStrategy m_strategy;
private List<Period> m_periods = new ArrayList<Period>();
private boolean m_active;
private CountDownLatch m_latch;
public PeriodManager() {
m_strategy = new PeriodStrategy(m_duration, m_extraTime, m_extraTime);
m_active = true;
m_latch = new CountDownLatch(1);
}
public void waitUntilStarted() throws InterruptedException {
m_latch.await();
}
private void endPeriod(long startTime) {
int len = m_periods.size();
for (int i = 0; i < len; i++) {
Period period = m_periods.get(i);
if (period.isIn(startTime)) {
period.finish();
m_periods.remove(i);
break;
}
}
}
public Period findPeriod(long timestamp) {
for (Period period : m_periods) {
if (period.isIn(timestamp)) {
return period;
}
}
return null;
}
@Override
public String getName() {
return "RealtimeConsumer-PeriodManager";
}
@Override
public void run() {
long startTime = m_strategy.next(System.currentTimeMillis());
// for current period
try {
startPeriod(startTime);
m_latch.countDown();
while (m_active) {
try {
long now = System.currentTimeMillis();
long value = m_strategy.next(now);
if (value > 0) {
startPeriod(value);
} else if (value < 0) {
// last period is over,make it asynchronous
Threads.forGroup("Cat").start(new EndTaskThread(-value));
}
} catch (Throwable e) {
Cat.logError(e);
}
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
break;
}
}
} catch (Exception e) {
Cat.logError(e);
}
}
@Override
public void shutdown() {
m_active = false;
}
private void startPeriod(long startTime) {
long endTime = startTime + m_strategy.getDuration();
Period period = new Period(startTime, endTime);
m_periods.add(period);
period.start();
}
private class EndTaskThread implements Task {
private long m_startTime;
public EndTaskThread(long startTime) {
m_startTime = startTime;
}
@Override
public void run() {
endPeriod(m_startTime);
}
@Override
public String getName() {
return "End-Consumer-Task";
}
@Override
public void shutdown() {
}
}
}
}
|
package org.eclipse.birt.report.engine.api;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import org.eclipse.birt.report.engine.EngineCase;
import org.eclipse.birt.report.engine.api.impl.Image;
import org.eclipse.birt.report.model.api.IResourceLocator;
public class HTMLCompleteImageHandlerTest extends EngineCase
{
protected IReportEngine engine = null;
protected IReportRunnable runnable = null;
protected static final String REPORT_DESIGN_RESOURCE = "org/eclipse/birt/report/engine/api/HTMLCompleteImageHandlerTest.rptdesign";
protected static final String REPORT_DESIGN = "HTMLCompleteImageHandlerTest.rptdesign";
public void setUp( ) throws Exception
{
removeFile( REPORT_DESIGN );
copyResource( REPORT_DESIGN_RESOURCE, REPORT_DESIGN );
engine = createReportEngine( );
runnable = engine.openReportDesign( REPORT_DESIGN );
}
public void tearDown( )
{
// shut down the engine.
if ( engine != null )
{
engine.shutdown( );
}
removeFile( REPORT_DESIGN );
}
/**
* API test on HTMLCompleteImageHandler.onDocImage( ) method. This method is
* not implemented so far, so the default return value is *null*
*/
public void testOnDocImage( )
{
HTMLCompleteImageHandler handler = new HTMLCompleteImageHandler( );
String result = handler.onDocImage( null, null );
assertNull( result );
}
/**
* API test on HTMLCompleteImageHandler.onURLImage( ) method. This test get
* a connection for the web specified by the URL
*/
public void testOnURLImage( )
{
try
{
final String ACTU_IMG_URL = "http:
HTMLRenderContext context = new HTMLRenderContext( );
context.setImageDirectory( "" );
Image image = new Image( ACTU_IMG_URL );
HTMLCompleteImageHandler handler = new HTMLCompleteImageHandler( );
String urlString = handler.onURLImage( image, context );
URL url = runnable.getDesignHandle( ).getModule( ).findResource(
urlString, IResourceLocator.IMAGE );
InputStream inputStream = url.openConnection( ).getInputStream( );
int availableBytes = inputStream.available( );
assert ( availableBytes > 0 );
}
catch ( Exception ex )
{
ex.printStackTrace( );
fail( );
}
}
public void testOnFileImage( )
{
// todo
}
public void testoOnCustomImage( )
{
// todo
}
/**
* API test on HTMLCompleteImageHandler.onDesignImage( ) method
*/
public void testOnDesignImage( )
{
HTMLRenderContext context = new HTMLRenderContext( );
context.setImageDirectory( "" );
Image image = (Image) runnable.getImage( "img.jpg" );
RenderOptionBase option = new RenderOptionBase( );
image.setRenderOption( option );
HTMLCompleteImageHandler imageHandler = new HTMLCompleteImageHandler( );
String resultPath = imageHandler.onDesignImage( image, context );
assertTrue( isFilePathLegal( resultPath ) );
}
private boolean isFilePathLegal( String filePath )
{
try
{
URL fileURL = new URL( filePath );
return fileURL.openStream( ) != null;
}
catch ( Exception ex )
{
// DO NOTHING
}
return false;
}
}
|
package br.net.mirante.singular.exemplos.emec.credenciamentoescolagoverno.form;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import com.google.common.base.Predicates;
import br.net.mirante.singular.form.SIComposite;
import br.net.mirante.singular.form.SIList;
import br.net.mirante.singular.form.SInfoType;
import br.net.mirante.singular.form.SInstance;
import br.net.mirante.singular.form.STypeComposite;
import br.net.mirante.singular.form.STypeList;
import br.net.mirante.singular.form.TypeBuilder;
import br.net.mirante.singular.form.type.core.STypeDecimal;
import br.net.mirante.singular.form.type.core.STypeInteger;
import br.net.mirante.singular.form.type.core.STypeString;
import br.net.mirante.singular.form.type.country.brazil.STypeCEP;
import br.net.mirante.singular.form.view.SViewByBlock;
import br.net.mirante.singular.form.view.SViewListByMasterDetail;
import br.net.mirante.singular.form.view.SViewListByTable;
@SInfoType(spackage = SPackageCredenciamentoEscolaGoverno.class)
public class STypePDI extends STypeComposite<SIComposite>{
private static final List<String> TIPOS_RECEITA = Arrays.asList("Anuidade / Mensalidade(+)", "Bolsas(-)", "Diversos(+)", "Financiamentos(+)", "Inadimplência(-)", "Serviços(+)", "Taxas(+)");
@Override
protected void onLoadType(TypeBuilder tb) {
super.onLoadType(tb);
addPerfilInstitucional();
addProjetoPedagogico();
addImplantacaoInstituicao();
addOrganizacaoDidaticopedagogica();
addPerfilCorpoDocente();
addOrganizacaoAdministrativa();
addInfraestruturaInstalacoesAcademicas();
addAtendimentoPessoasNecessidadesEspeciais();
addAtoAutorizativoCriacao();
addDemonstrativoCapacidadeSustentabilidadeFinanceira();
addOutros();
// cria um bloco por campo
setView(SViewByBlock::new)
.newBlock("1 Perfil Institucional").add("perfilInstitucional")
.newBlock("2 Projeto Pedagógico da Instituição").add("projetoPedagogicoInstituicao")
.newBlock("3 Implantação de Desenvolvimento da Instituição - Programa de Abertura de Cursos de Pós Graduação").add("implantacaoInstituicao")
.newBlock("4 Organização didatico-pedagógica da Instituição").add("organizacaoDidaticopedagogicaInstituicao")
.newBlock("5 Perfil do corpo docente e técnico-administrativo").add("perfilCorpoDocenteETecnicoAdministrativo")
.newBlock("6 Organização Administrativa da Instituição").add("organizacaoAdministrativa")
.newBlock("7 Infra-estrutura e Instalações Acadêmicas").add("infraestruturaInstalacoesAcademicas")
.newBlock("8 Atendimento de Pessoas com Necessidades Especiais").add("atendimentoPessoasNecessidadesEspeciais")
.newBlock("9 Ato autorizativo anterior ou ato de criação").add("atoAutorizativoCriacao")
.newBlock("10 Demonstrativo de Capacidade e Sustentabilidade Financeira").add("demonstrativoCapacidadeSustentabilidadeFinanceira")
.newBlock("11 Outros").add("outros");
}
private void addPerfilInstitucional() {
final STypeComposite<SIComposite> perfilInstitucional = this.addFieldComposite("perfilInstitucional");
perfilInstitucional.addFieldInteger("anoInicioPDI", true).asAtr().label("Ano de Início do PDI");
perfilInstitucional.addFieldInteger("anoFimPDI", true).asAtr().label("Ano de Fim do PDI");
perfilInstitucional.addFieldString("historicoDesenvolvimentoInstituicao", true)
.withTextAreaView().asAtr().label("Histórico e desenvolvimento da Instituição de Ensino");
perfilInstitucional.addFieldString("missaoObjetivosMetas", true)
.withTextAreaView().asAtr().label("Missão, objetivos e metas da Instituição, na sua área de atuação");
}
private void addProjetoPedagogico() {
this.addFieldString("projetoPedagogicoInstituicao", true)
.withTextAreaView()
.asAtrBootstrap().maxColPreference();
}
private void addImplantacaoInstituicao() {
final STypeComposite<SIComposite> implantacaoInstituicao = this.addFieldComposite("implantacaoInstituicao");
implantacaoInstituicao.addFieldListOf("cursosPrevistos", STypeCurso.class)
.withView(SViewListByMasterDetail::new)
.asAtr().label("Cursos Previstos").itemLabel("Curso Previsto");
}
private void addOrganizacaoDidaticopedagogica() {
this.addFieldString("organizacaoDidaticopedagogicaInstituicao", true)
.withTextAreaView().asAtr().label("Organização didatico-pedagógica da Instituição")
.asAtrBootstrap().maxColPreference();
}
private void addPerfilCorpoDocente() {
final STypeComposite<SIComposite> perfilCorpoDocenteETecnicoAdministrativo = this.addFieldComposite("perfilCorpoDocenteETecnicoAdministrativo");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("corpoTecnicoAdministrativo", true)
.withTextAreaView().asAtr().label("Corpo técnico-administrativo");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("cronogramaExpansaoCorpoTecnicoAdministrativo", true)
.withTextAreaView().asAtr().label("Crongrama de expansão do corpo técnico-administrativo");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("cronogramaExpansaoCorpoDocente", true)
.withTextAreaView().asAtr().label("Crongrama de expansão do corpo docente");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("criteriosSelecaoContratacaoProfessores", true)
.withTextAreaView().asAtr().label("Critérios de seleção e contratação dos professores");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("politicasQualificacaoPlanoCarreira", true)
.withTextAreaView().asAtr().label("Políticas de qualificação e plano de carreira do corpo docente");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("requisitosTitulacaoExperienciaProfissional", true)
.withTextAreaView().asAtr().label("Requisitos de titulação e experiência profissional do corpo docente");
perfilCorpoDocenteETecnicoAdministrativo.addFieldString("regimeTrabalhoProcedimentosSubstituicaoEventualProfessores", true)
.withTextAreaView().asAtr().label("Regime de trabalho e procedimentos de substituição eventual de professores");
}
private void addOrganizacaoAdministrativa() {
final STypeComposite<SIComposite> organizacaoAdministrativa = this.addFieldComposite("organizacaoAdministrativa");
organizacaoAdministrativa.addFieldString("estruturaOrganizacionalIES", true)
.withTextAreaView().asAtr().label("Estrutura OrganizacionalIES");
organizacaoAdministrativa.addFieldString("procedimentosAtendimentosAlunos", true)
.withTextAreaView().asAtr().label("Procedimentos de atendimento dos alunos");
organizacaoAdministrativa.addFieldString("procedimentoAutoavaliacaoInstitucional", true)
.withTextAreaView().asAtr().label("Procedimento de auto-avaliação Institucional");
}
private void addInfraestruturaInstalacoesAcademicas() {
final STypeComposite<SIComposite> infraestruturaInstalacoesAcademicas = this.addFieldComposite("infraestruturaInstalacoesAcademicas");
final STypeList<STypeComposite<SIComposite>, SIComposite> enderecoes = infraestruturaInstalacoesAcademicas.addFieldListOfComposite("enderecoes", "encereco");
enderecoes.withView(SViewListByMasterDetail::new)
.asAtr().label("Endereços").itemLabel("Endereço");
final STypeComposite<SIComposite> endereco = enderecoes.getElementsType();
endereco.addFieldString("endereco").asAtr().required().label("Endereço");
endereco.addField("cep", STypeCEP.class);
}
private void addAtendimentoPessoasNecessidadesEspeciais() {
this.addFieldString("atendimentoPessoasNecessidadesEspeciais", true)
.withTextAreaView().asAtr().label("Plano de promoção de acessibilidade e atendimento prioritário, imediato e diferenciado para utilização, "
+ "com segurança e autonomia, total ou assistida, dos espaços, mobiliários e equipamentos urbanos, das edificações, dos serviços de transporte, dos dispositivos, "
+ "sistemas e meios de comunicação e informação, serviços de tradutor e intérprete de Língua Brasileira de Sinais - LIBRAS")
.asAtrBootstrap().maxColPreference();
}
private void addAtoAutorizativoCriacao() {
final STypeComposite<SIComposite> atoAutorizativoCriacao = this.addFieldComposite("atoAutorizativoCriacao");
atoAutorizativoCriacao.addFieldString("tipoDocumento", true)
.withRadioView().selectionOf("Ata", "Decreto", "Decreto-lei", "Lei", "Medida Provisória", "Parecer", "Portaria", "Resolução")
.asAtr().label("Tipo de Documento")
.asAtrBootstrap().maxColPreference();
atoAutorizativoCriacao.addFieldInteger("numeroDocumento", true)
.asAtr().label("Nº do Documento")
.asAtrBootstrap().colPreference(3);
atoAutorizativoCriacao.addFieldDate("dataDocumento", true)
.asAtr().label("Data do Documento")
.asAtrBootstrap().colPreference(3);
atoAutorizativoCriacao.addFieldDate("dataPublicacao", true)
.asAtr().label("Data de Publicação")
.asAtrBootstrap().colPreference(3);
atoAutorizativoCriacao.addFieldDate("dataCriacao", true)
.asAtr().label("Data de Criação")
.asAtrBootstrap().colPreference(3);
atoAutorizativoCriacao.addFieldAttachment("atoAutorizativoAnterior").asAtr().label("Ato autorizativo anterior");
}
private void addDemonstrativoCapacidadeSustentabilidadeFinanceira() {
final STypeComposite<SIComposite> demonstrativoCapacidadeSustentabilidadeFinanceira = this.addFieldComposite("demonstrativoCapacidadeSustentabilidadeFinanceira");
final STypeList<STypeComposite<SIComposite>, SIComposite> demonstrativos = demonstrativoCapacidadeSustentabilidadeFinanceira.addFieldListOfComposite("demonstrativos", "demonstrativo");
final STypeComposite<SIComposite> demonstrativo = demonstrativos.getElementsType();
final STypeInteger ano = demonstrativo.addFieldInteger("ano", true);
ano.asAtr().displayString("Demonstrativo Financeiro ${ano}").enabled(false);
final STypeList<STypeComposite<SIComposite>, SIComposite> receitas = demonstrativo.addFieldListOfComposite("receitas", "receita");
receitas.setView(SViewListByTable::new).disableNew().disableDelete();
final STypeString tipoReceita = receitas.getElementsType().addFieldString("tipo", true);
tipoReceita.asAtr().enabled(false);
final STypeDecimal valorReceita = receitas.getElementsType().addFieldDecimal("valor", true);
demonstrativo.withInitListener(ins -> {
final Optional<SIList<SIComposite>> lista = ins.findNearest(receitas);
for (String tipo : TIPOS_RECEITA) {
lista.get().addNew().findNearest(tipoReceita).get().setValue(tipo);
}
});
demonstrativoCapacidadeSustentabilidadeFinanceira.withInitListener(ins -> {
final Optional<SIList<SIComposite>> lista = ins.findNearest(demonstrativos);
for (int i = 0; i < 5; i++) {
final SIComposite siComposite = lista.get().addNew();
siComposite.findNearest(ano).get().setValue(LocalDate.now().getYear() + i);
}
});
demonstrativos.withView(
new SViewListByMasterDetail()
.col("Ano", "${ano}")
.col("Receitas", ins -> {
final Optional<SIList<SIComposite>> lista = ins.findNearest(receitas);
BigDecimal total = lista.get().stream().map(siComposite -> siComposite.findNearest(valorReceita).get().getValue())
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
return total.toString();
})
.col("Despesas", "Tipo de referência")
.col("Total Geral", "Tipo de referência")
.disableNew().disableDelete())
.asAtr().label("Demonstrativos").itemLabel("Demonstrativo");
}
private void addOutros() {
this.addFieldString("outros", true)
.withTextAreaView()
.asAtrBootstrap().maxColPreference();
}
}
|
package com.crowdfire.cfalertdialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.StringRes;
import android.support.annotation.StyleRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatDialog;
import android.support.v7.widget.CardView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.crowdfire.cfalertdialog.utils.DeviceUtil;
import com.crowdfire.cfalertdialog.views.CFPushButton;
import java.util.ArrayList;
import java.util.List;
public class CFAlertDialog extends AppCompatDialog {
// region ENUMS
public enum CFAlertActionStyle{
DEFAULT,
NEGATIVE,
POSITIVE;
}
public enum CFAlertActionAlignment {
START,
END,
CENTER,
JUSTIFIED;
}
public enum CFAlertBackgroundStyle {
PLAIN,
BLUR;
}
// endregion
private DialogParams params;
private RelativeLayout cfDialogBackground;
private LinearLayout cfDialogHeaderLinearLayout, buttonContainerLinearLayout,
cfDialogFooterLinearLayout, iconTitleContainer, selectableItemsContainer;
private CardView dialogCardView;
private TextView dialogTitleTextView, dialogMessageTextView;
private ImageView cfDialogIconImageView;
private CFAlertDialog(Context context) {
super(context, R.style.CFDialog);
}
private CFAlertDialog(Context context, int theme) {
super(context, theme);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate the view
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.cfalert_layout, null);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(view);
// Setup the dialog
bindSubviews(view);
populateDialog(params);
// Adjust the dialog width
adjustDialogWidth();
// Set the size to adjust when keyboard shown
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
// Disable the view initially
setEnabled(false);
}
public void setCFDialogBackgroundColor(int color){
cfDialogBackground.setBackgroundColor(color);
}
@Override
public void show() {
super.show();
// Perform the present animation
startPresentAnimation();
}
@Override
public void dismiss() {
// Disable the view when being dismissed
setEnabled(false);
// Perform the dismiss animation and after that dismiss the dialog
Animation dismissAnimation = getDismissAnimation(params.dialogGravity);
dismissAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
CFAlertDialog.super.dismiss();
}
});
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
dialogCardView.startAnimation(dismissAnimation);
}
public void setEnabled(boolean enabled) {
setViewEnabled(cfDialogBackground, enabled);
}
private void bindSubviews(View view) {
cfDialogBackground = ((RelativeLayout) view.findViewById(R.id.cfdialog_background));
dialogCardView = (CardView) view.findViewById(R.id.cfdialog_cardview);
cfDialogHeaderLinearLayout = (LinearLayout) view.findViewById(R.id.alert_header_container);
dialogTitleTextView = (TextView) view.findViewById(R.id.tv_dialog_title);
iconTitleContainer = (LinearLayout) view.findViewById(R.id.icon_title_container);
cfDialogIconImageView = (ImageView) view.findViewById(R.id.cfdialog_icon_imageview);
dialogMessageTextView = (TextView) view.findViewById(R.id.tv_dialog_content_desc);
buttonContainerLinearLayout = (LinearLayout) view.findViewById(R.id.alert_buttons_container);
cfDialogFooterLinearLayout = (LinearLayout) view.findViewById(R.id.alert_footer_container);
selectableItemsContainer = (LinearLayout) view.findViewById(R.id.alert_selection_items_container);
}
private void populateDialog(final DialogParams params) {
// Background
getWindow().setBackgroundDrawableResource(android.R.color.transparent);
if (params.backgroundStyle == CFAlertBackgroundStyle.BLUR) {
// TODO: Add blur background effect
}
else {
cfDialogBackground.setBackgroundColor(params.backgroundColor);
}
cfDialogBackground.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (params.cancelable) {
dismiss();
}
}
});
// Icon
if (params.iconDrawableId != -1) {
setIcon(params.iconDrawableId);
} else if (params.iconDrawable != null) {
setIcon(params.iconDrawable);
} else { setIcon(null); }
// Title
setTitle(params.title);
// Message
setMessage(params.message);
// Cancel
setCancelable(params.cancelable);
// Buttons
populateButtons(params.context, params.buttons);
// Dialog position
setDialogGravity(params.dialogGravity);
// Text gravity
setTextGravity(params.textGravity);
// Image/Header
if (params.contentImageDrawableId != -1) {
setContentImageDrawable(params.contentImageDrawableId);
} else if (params.contentImageDrawable != null) {
setContentImageDrawable(params.contentImageDrawable);
} else if (params.headerView != null) {
setHeaderView(params.headerView);
} else if (params.headerViewId != -1) {
setHeaderView(params.headerViewId);
}
// Footer
if (params.footerView != null) {
setFooterView(params.footerView);
} else if (params.footerViewId != -1) {
setFooterView(params.footerViewId);
}
// Selection items
if (params.items != null && params.items.length > 0) {
setItems(params.items, params.onItemClickListener);
} else if (params.multiSelectItems != null && params.multiSelectItems.length > 0) {
setMultiSelectItems(params.multiSelectItems, params.multiSelectedItems, params.onMultiChoiceClickListener);
} else if (params.singleSelectItems != null && params.singleSelectItems.length > 0) {
setSingleSelectItems(params.singleSelectItems, params.singleSelectedItem, params.onSingleItemClickListener);
} else {
selectableItemsContainer.removeAllViews();
}
}
private void adjustDialogWidth() {
int margin = (int)getContext().getResources().getDimension(R.dimen.cfdialog_outer_margin);
int width = DeviceUtil.getScreenWidth(getContext()) - (2 * margin);
width = Math.min(width, (int) getContext().getResources().getDimension(R.dimen.cfdialog_maxwidth));
RelativeLayout.LayoutParams cardViewLayoutParams = new RelativeLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
cardViewLayoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
cardViewLayoutParams.setMargins(margin, margin, margin, margin);
dialogCardView.setLayoutParams(cardViewLayoutParams);
}
private void startPresentAnimation() {
Animation presentAnimation = getPresentAnimation(params.dialogGravity);
presentAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
alertPresented();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
dialogCardView.startAnimation(presentAnimation);
}
private void alertPresented() {
setEnabled(true);
}
private void setDialogParams(DialogParams params) {
this.params = params;
}
@Override
public void setTitle(CharSequence title) {
if (TextUtils.isEmpty(title)) {
dialogTitleTextView.setVisibility(View.GONE);
if (cfDialogIconImageView.getVisibility() == View.GONE) {
iconTitleContainer.setVisibility(View.GONE);
}
} else {
dialogTitleTextView.setText(title);
dialogTitleTextView.setVisibility(View.VISIBLE);
iconTitleContainer.setVisibility(View.VISIBLE);
}
}
@Override
public void setTitle(int titleId) {
setTitle(getContext().getString(titleId));
}
public void setMessage(CharSequence message) {
if (TextUtils.isEmpty(message)) {
dialogMessageTextView.setVisibility(View.GONE);
} else {
dialogMessageTextView.setText(message);
dialogMessageTextView.setVisibility(View.VISIBLE);
}
}
public void setMessage(int messageId) {
setMessage(getContext().getString(messageId));
}
/**
* @param dialogGravity @see android.view.Gravity
*/
public void setDialogGravity(int dialogGravity) {
if (dialogGravity != -1) {
cfDialogBackground.setGravity(dialogGravity);
}
}
/**
* @param textGravity @see android.view.Gravity
*/
public void setTextGravity(int textGravity) {
((LinearLayout.LayoutParams) iconTitleContainer.getLayoutParams()).gravity = textGravity;
dialogMessageTextView.setGravity(textGravity);
}
/**
* @param headerView pass null to remove header
*/
public void setHeaderView(View headerView) {
cfDialogHeaderLinearLayout.removeAllViews();
if (headerView != null) {
cfDialogHeaderLinearLayout.addView(headerView);
cfDialogHeaderLinearLayout.setVisibility(View.VISIBLE);
} else {
cfDialogHeaderLinearLayout.setVisibility(View.GONE);
}
fixDialogPadding();
}
public void setHeaderView(@LayoutRes int headerResId) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(headerResId, null);
setHeaderView(view);
}
public void setIcon(@DrawableRes int iconDrawableId) {
setIcon(ContextCompat.getDrawable(getContext(), iconDrawableId));
}
public void setIcon(Drawable iconDrawable) {
if (iconDrawable == null) {
cfDialogIconImageView.setVisibility(View.GONE);
if (dialogTitleTextView.getVisibility() == View.GONE) {
iconTitleContainer.setVisibility(View.GONE);
}
} else {
cfDialogIconImageView.setVisibility(View.VISIBLE);
iconTitleContainer.setVisibility(View.VISIBLE);
cfDialogIconImageView.setImageDrawable(iconDrawable);
}
}
/**
* @param imageDrawableId value -1 will remove image
*/
public void setContentImageDrawable(@DrawableRes int imageDrawableId) {
setContentImageDrawable(ContextCompat.getDrawable(getContext(), imageDrawableId));
}
public void setContentImageDrawable(Drawable imageDrawable) {
if (imageDrawable != null) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.cfdialog_imageview_header, cfDialogHeaderLinearLayout).findViewById(R.id.cfdialog_imageview_content);
imageView.setImageDrawable(imageDrawable);
imageView.setTag(111);
cfDialogHeaderLinearLayout.setVisibility(View.VISIBLE);
} else {
for (int i = 0; i < cfDialogHeaderLinearLayout.getChildCount(); i++) {
View view = cfDialogHeaderLinearLayout.getChildAt(i);
if (view instanceof ImageView && (int) view.getTag() == 111) {
cfDialogHeaderLinearLayout.removeView(view);
cfDialogHeaderLinearLayout.setVisibility(View.GONE);
break;
}
}
}
}
/**
* @param footerView pass null to remove header
*/
public void setFooterView(View footerView) {
cfDialogFooterLinearLayout.removeAllViews();
if (footerView != null) {
cfDialogFooterLinearLayout.addView(footerView);
cfDialogFooterLinearLayout.setVisibility(View.VISIBLE);
} else {
cfDialogFooterLinearLayout.setVisibility(View.GONE);
}
fixDialogPadding();
}
public void setFooterView(@LayoutRes int footerResId) {
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(footerResId, null);
setFooterView(view);
}
private void fixDialogPadding() {
int topPadding, bottomPadding;
if (cfDialogFooterLinearLayout.getChildCount() == 0) {
bottomPadding = (int) getContext().getResources().getDimension(R.dimen.cfdialog_footer_top_margin_half);
} else {
bottomPadding = 0;
}
if (cfDialogHeaderLinearLayout.getChildCount() == 0) {
topPadding = (int) getContext().getResources().getDimension(R.dimen.cfdialog_header_bottom_margin_half);
} else {
topPadding = 0;
}
dialogCardView.setContentPadding(0, topPadding, 0, bottomPadding);
}
private void setViewEnabled(ViewGroup layout, boolean enabled) {
layout.setEnabled(enabled);
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
if (child instanceof ViewGroup) {
setViewEnabled((ViewGroup) child, enabled);
} else {
child.setEnabled(enabled);
}
}
}
private void populateButtons(Context context, List<CFAlertActionButton> buttons) {
buttonContainerLinearLayout.removeAllViews();
if (buttons.size() > 0) {
for (int i = 0; i < buttons.size(); i++) {
View buttonView = createButton(context, buttons.get(i));
buttonContainerLinearLayout.addView(buttonView);
}
buttonContainerLinearLayout.setVisibility(View.VISIBLE);
} else {
buttonContainerLinearLayout.setVisibility(View.GONE);
}
}
private View createButton(Context context, final CFAlertActionButton actionButton) {
CFPushButton button = new CFPushButton(context, null, R.style.CFDialog_Button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
actionButton.onClickListener.onClick(CFAlertDialog.this, 0);
}
});
setButtonLayout(button, actionButton);
button.setText(actionButton.buttonText);
setButtonColors(button, actionButton);
return button;
}
private void setButtonLayout(View buttonView, CFAlertActionButton actionButton) {
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
;
switch (actionButton.alignment) {
case JUSTIFIED:
buttonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
break;
case START:
buttonParams.gravity = Gravity.START;
break;
case CENTER:
buttonParams.gravity = Gravity.CENTER;
break;
case END:
buttonParams.gravity = Gravity.END;
break;
}
int margin = ((int) buttonView.getResources().getDimension(R.dimen.cfdialog_internal_spacing_half));
buttonParams.setMargins(margin, margin, margin, margin);
buttonView.setLayoutParams(buttonParams);
int padding = ((int) buttonView.getResources().getDimension(R.dimen.cfdialog_button_padding));
buttonView.setPadding(padding, padding, padding, padding);
}
private void setButtonColors(TextView button, CFAlertActionButton actionButton) {
if (actionButton.backgroundDrawable != null) {
setButtonBackgroundColor(button, actionButton.backgroundDrawable);
} else if (actionButton.backgroundDrawableId != -1) {
setButtonBackgroundColor(button, ContextCompat.getDrawable(getContext(), actionButton.backgroundDrawableId));
}
if (actionButton.textColor != null) {
button.setTextColor(actionButton.textColor);
} else if (actionButton.textColorListId != -1) {
button.setTextColor(ContextCompat.getColorStateList(getContext(), actionButton.textColorListId));
}
}
private void setButtonBackgroundColor(TextView button, Drawable backgroundDrawable) {
if (Build.VERSION.SDK_INT > 16) {
button.setBackground(backgroundDrawable);
} else {
button.setBackgroundDrawable(backgroundDrawable);
}
}
public void setItems(String[] items, final OnClickListener onClickListener) {
if (items != null && items.length > 0) {
selectableItemsContainer.removeAllViews();
selectableItemsContainer.setVisibility(View.VISIBLE);
for (int i = 0; i < items.length; i++) {
String item = items[i];
View view = getLayoutInflater().inflate(R.layout.cfdialog_selectable_item_layout, null);
TextView itemTextView = (TextView) view.findViewById(R.id.cfdialog_selectable_item_textview);
itemTextView.setText(item);
final int position = i;
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (onClickListener != null) {
onClickListener.onClick(CFAlertDialog.this, position);
}
}
});
selectableItemsContainer.addView(view);
}
} else {
selectableItemsContainer.setVisibility(View.GONE);
}
}
public void setMultiSelectItems(String[] multiSelectItems, boolean[] selectedItems, final OnMultiChoiceClickListener onMultiChoiceClickListener) {
if (multiSelectItems != null && multiSelectItems.length > 0) {
if (selectedItems.length != multiSelectItems.length) {
throw new IllegalArgumentException("multi select items and boolean array size not equal");
}
selectableItemsContainer.removeAllViews();
selectableItemsContainer.setVisibility(View.VISIBLE);
for (int i = 0; i < multiSelectItems.length; i++) {
String item = multiSelectItems[i];
View view = getLayoutInflater().inflate(R.layout.cfdialog_multi_select_item_layout, null);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.cfdialog_multi_select_item_checkbox);
checkBox.setText(item);
checkBox.setChecked(selectedItems[i]);
final int position = i;
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (onMultiChoiceClickListener != null) {
onMultiChoiceClickListener.onClick(CFAlertDialog.this, position, isChecked);
}
}
});
selectableItemsContainer.addView(view);
}
} else {
selectableItemsContainer.setVisibility(View.GONE);
}
}
public void setSingleSelectItems(String[] singleSelectItems, int selectedItem, final OnClickListener onClickListener) {
if (singleSelectItems != null && singleSelectItems.length > 0) {
selectableItemsContainer.removeAllViews();
selectableItemsContainer.setVisibility(View.VISIBLE);
RadioGroup radioGroup = (RadioGroup) getLayoutInflater().inflate(R.layout.cfdialog_single_select_item_layout, selectableItemsContainer)
.findViewById(R.id.cfstage_single_select_radio_group);
radioGroup.removeAllViews();
for (int i = 0; i < singleSelectItems.length; i++) {
String item = singleSelectItems[i];
RadioButton radioButton = (RadioButton) getLayoutInflater().inflate(R.layout.cfdialog_single_select_radio_button_layout, null);
radioButton.setText(item);
radioButton.setId(i);
final int position = i;
if (position == selectedItem) {
radioButton.setChecked(true);
}
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked && onClickListener != null) {
onClickListener.onClick(CFAlertDialog.this, position);
}
}
});
radioGroup.addView(radioButton);
((LinearLayout.LayoutParams) radioButton.getLayoutParams()).leftMargin =
((LinearLayout.LayoutParams) radioButton.getLayoutParams()).rightMargin =
(int) getContext().getResources().getDimension(R.dimen.cfdialog_padding);
}
} else {
selectableItemsContainer.setVisibility(View.GONE);
}
}
public void setElevation(float elevation) {
dialogCardView.setCardElevation(elevation);
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
//cfDialogFooterLinearLayout.removeAllViews();
//cfDialogHeaderLinearLayout.removeAllViews();
}
// region Animation helper methods
private Animation getPresentAnimation(int gravity) {
switch (gravity) {
case Gravity.TOP:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_present_top);
case Gravity.CENTER:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_present_center);
case Gravity.BOTTOM:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_present_bottom);
default:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_present_center);
}
}
private Animation getDismissAnimation(int gravity) {
switch (gravity) {
case Gravity.TOP:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_dismiss_top);
case Gravity.CENTER:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_dismiss_center);
case Gravity.BOTTOM:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_dismiss_bottom);
default:
return AnimationUtils.loadAnimation(params.context, R.anim.dialog_dismiss_center);
}
}
// endregion
public static class Builder {
private DialogParams params;
public Builder(Context context) {
params = new DialogParams();
setDefaultParams();
this.params.context = context;
}
public Builder(Context context, @StyleRes int theme) {
params = new DialogParams();
setDefaultParams();
this.params.context = context;
this.params.theme = theme;
}
private void setDefaultParams() {
this.params.theme = R.style.CFDialog;
this.params.backgroundStyle = CFAlertBackgroundStyle.PLAIN;
this.params.backgroundColor = Color.TRANSPARENT;
}
public Builder setBackgroundStyle(CFAlertBackgroundStyle backgroundStyle) {
this.params.backgroundStyle = backgroundStyle;
return this;
}
public Builder setBackgroundResource(@ColorRes int backgroundResource) {
this.params.backgroundColor = ResourcesCompat.getColor(this.params.context.getResources(), backgroundResource, null);
return this;
}
public Builder setBackgroundColor(@ColorInt int backgroundColor) {
this.params.backgroundColor = backgroundColor;
return this;
}
public Builder setMessage(CharSequence message) {
this.params.message = message;
return this;
}
public Builder setTitle(CharSequence title) {
this.params.title = title;
return this;
}
public Builder setMessage(@StringRes int messageId) {
this.params.message = params.context.getString(messageId);
return this;
}
public Builder setTitle(@StringRes int titleId) {
this.params.title = params.context.getString(titleId);
return this;
}
public Builder setContentImageDrawable(@DrawableRes int contentImageDrawableId) {
this.params.contentImageDrawableId = contentImageDrawableId;
this.params.contentImageDrawable = null;
return this;
}
public Builder setContentImageDrawable(Drawable contentImageDrawable) {
this.params.contentImageDrawable = contentImageDrawable;
this.params.contentImageDrawableId = -1;
return this;
}
public Builder setIcon(@DrawableRes int iconDrawableId) {
this.params.iconDrawableId = iconDrawableId;
this.params.iconDrawable = null;
return this;
}
public Builder setIcon(Drawable iconDrawable) {
this.params.iconDrawable = iconDrawable;
this.params.iconDrawableId = -1;
return this;
}
public Builder onDismissListener(OnDismissListener onDismissListener) {
this.params.onDismissListener = onDismissListener;
return this;
}
/**
* @param dialogGravity @see android.view.Gravity
*/
public Builder setDialogVerticalGravity(int dialogGravity) {
this.params.dialogGravity = dialogGravity;
return this;
}
/**
* @param textGravity @see android.view.Gravity
*/
public Builder setTextGravity(int textGravity) {
this.params.textGravity = textGravity;
return this;
}
public Builder addButton(String buttonText, CFAlertActionStyle style, CFAlertActionAlignment alignment, OnClickListener onClickListener) {
CFAlertActionButton button = new CFAlertActionButton(buttonText, style, alignment, onClickListener);
this.params.buttons.add(button);
return this;
}
public Builder setItems(String[] items, OnClickListener onItemClickListener) {
params.items = items;
params.onItemClickListener = onItemClickListener;
return this;
}
public Builder setMultiChoiceItems(String[] items, boolean[] selectedItems, OnMultiChoiceClickListener onMultiChoiceClickListener) {
params.multiSelectItems = items;
params.multiSelectedItems = selectedItems;
params.onMultiChoiceClickListener = onMultiChoiceClickListener;
return this;
}
public Builder setSingleChoiceItems(String[] items, int selectedItem, OnClickListener onItemClickListener) {
params.singleSelectItems = items;
params.singleSelectedItem = selectedItem;
params.onSingleItemClickListener = onItemClickListener;
return this;
}
public Builder setHeaderView(View headerView) {
this.params.headerView = headerView;
this.params.headerViewId = -1;
return this;
}
public Builder setHeaderView(@LayoutRes int headerViewId) {
this.params.headerViewId = headerViewId;
this.params.headerView = null;
return this;
}
public Builder setFooterView(View footerView) {
this.params.footerView = footerView;
this.params.footerViewId = -1;
return this;
}
public Builder setFooterView(@LayoutRes int footerViewId) {
this.params.footerViewId = footerViewId;
this.params.footerView = null;
return this;
}
/**
* default is true
*
* @param cancelable
*/
public Builder setCancelable(boolean cancelable) {
this.params.cancelable = cancelable;
return this;
}
public CFAlertDialog create() {
CFAlertDialog cfAlertDialog;
if (params.theme == 0) {
cfAlertDialog = new CFAlertDialog(params.context);
} else {
cfAlertDialog = new CFAlertDialog(params.context, params.theme);
}
cfAlertDialog.setOnDismissListener(params.onDismissListener);
cfAlertDialog.setDialogParams(params);
return cfAlertDialog;
}
public CFAlertDialog show() {
final CFAlertDialog dialog = create();
dialog.show();
return dialog;
}
}
private static class DialogParams {
private Context context;
private CFAlertBackgroundStyle backgroundStyle = CFAlertBackgroundStyle.PLAIN;
private @ColorInt int backgroundColor = -1;
private CharSequence message, title;
private int theme = R.style.CFDialog,
dialogGravity = Gravity.CENTER,
textGravity = Gravity.LEFT,
iconDrawableId = -1,
contentImageDrawableId = -1;
private View headerView, footerView;
private int headerViewId = -1, footerViewId = -1;
private Drawable contentImageDrawable, iconDrawable;
private List<CFAlertActionButton> buttons = new ArrayList<>();
private OnDismissListener onDismissListener;
private boolean cancelable = true;
private String[] multiSelectItems;
private String[] items;
private String[] singleSelectItems;
private boolean[] multiSelectedItems;
private int singleSelectedItem = -1;
private OnClickListener onItemClickListener;
private OnClickListener onSingleItemClickListener;
private OnMultiChoiceClickListener onMultiChoiceClickListener;
}
private static class CFAlertActionButton {
private String buttonText;
private DialogInterface.OnClickListener onClickListener;
private ColorStateList textColor;
private CFAlertActionStyle style;
private CFAlertActionAlignment alignment = CFAlertActionAlignment.JUSTIFIED;
private Drawable backgroundDrawable;
private int textColorListId = -1, backgroundDrawableId = -1;
public CFAlertActionButton(String buttonText, CFAlertActionStyle style, CFAlertActionAlignment alignment, OnClickListener onClickListener) {
this.buttonText = buttonText;
this.onClickListener = onClickListener;
this.style = style;
this.alignment = alignment;
this.backgroundDrawableId = getBackgroundDrawable(style);
}
private @DrawableRes int getBackgroundDrawable(CFAlertActionStyle style) {
@DrawableRes int backgroundDrawable = 0;
switch (style) {
case NEGATIVE:
backgroundDrawable = R.drawable.cfdialog_negative_button_background_drawable;
break;
case POSITIVE:
backgroundDrawable = R.drawable.cfdialog_positive_button_background_drawable;
break;
case DEFAULT:
backgroundDrawable = R.drawable.cfdialog_default_button_background_drawable;
break;
}
return backgroundDrawable;
}
}
}
|
package org.ovirt.engine.ui.uicommonweb.models.clusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.ovirt.engine.core.common.businessentities.AdditionalFeature;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.MigrateOnErrorOptions;
import org.ovirt.engine.core.common.businessentities.SerialNumberPolicy;
import org.ovirt.engine.core.common.businessentities.ServerCpu;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.SupportedAdditionalClusterFeature;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VmRngDevice;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.ConfigurationValues;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.scheduling.ClusterPolicy;
import org.ovirt.engine.core.common.scheduling.PolicyUnit;
import org.ovirt.engine.core.common.utils.ObjectUtils;
import org.ovirt.engine.core.common.utils.Pair;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.FilteredListModel;
import org.ovirt.engine.ui.uicommonweb.models.HasEntity;
import org.ovirt.engine.ui.uicommonweb.models.HasValidatedTabs;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.TabName;
import org.ovirt.engine.ui.uicommonweb.models.ValidationCompleteEvent;
import org.ovirt.engine.ui.uicommonweb.models.vms.SerialNumberPolicyModel;
import org.ovirt.engine.ui.uicommonweb.models.vms.key_value.KeyValueModel;
import org.ovirt.engine.ui.uicommonweb.validation.HostWithProtocolAndPortAddressValidation;
import org.ovirt.engine.ui.uicommonweb.validation.I18NNameValidation;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.LengthValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.IEventListener;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
public class ClusterModel extends EntityModel<VDSGroup> implements HasValidatedTabs {
private Map<Guid, PolicyUnit> policyUnitMap;
private ListModel<ClusterPolicy> clusterPolicy;
private Map<Guid, Network> defaultManagementNetworkCache = new HashMap<>();
private Boolean detached;
private ListModel<String> glusterTunedProfile;
public ListModel<String> getGlusterTunedProfile() {
return glusterTunedProfile;
}
public void setGlusterTunedProfile(ListModel<String> glusterTunedProfile) {
this.glusterTunedProfile = glusterTunedProfile;
}
public ListModel<ClusterPolicy> getClusterPolicy() {
return clusterPolicy;
}
public void setClusterPolicy(ListModel<ClusterPolicy> clusterPolicy) {
this.clusterPolicy = clusterPolicy;
}
private KeyValueModel customPropertySheet;
public KeyValueModel getCustomPropertySheet() {
return customPropertySheet;
}
public void setCustomPropertySheet(KeyValueModel customPropertySheet) {
this.customPropertySheet = customPropertySheet;
}
private int privateServerOverCommit;
public int getServerOverCommit() {
return privateServerOverCommit;
}
public void setServerOverCommit(int value) {
privateServerOverCommit = value;
}
private int privateDesktopOverCommit;
public int getDesktopOverCommit() {
return privateDesktopOverCommit;
}
public void setDesktopOverCommit(int value) {
privateDesktopOverCommit = value;
}
private int privateDefaultMemoryOvercommit;
public int getDefaultMemoryOvercommit() {
return privateDefaultMemoryOvercommit;
}
public void setDefaultMemoryOvercommit(int value) {
privateDefaultMemoryOvercommit = value;
}
private boolean privateIsEdit;
public boolean getIsEdit() {
return privateIsEdit;
}
public void setIsEdit(boolean value) {
privateIsEdit = value;
}
private boolean isCPUinitialized = false;
private boolean privateIsNew;
public boolean getIsNew() {
return privateIsNew;
}
public void setIsNew(boolean value) {
privateIsNew = value;
}
private String privateOriginalName;
public String getOriginalName() {
return privateOriginalName;
}
public void setOriginalName(String value) {
privateOriginalName = value;
}
private Guid privateClusterId;
public Guid getClusterId() {
return privateClusterId;
}
public void setClusterId(Guid value) {
privateClusterId = value;
}
private EntityModel<String> privateName;
public EntityModel<String> getName() {
return privateName;
}
public void setName(EntityModel<String> value) {
privateName = value;
}
private EntityModel<String> privateDescription;
public EntityModel<String> getDescription() {
return privateDescription;
}
public void setDescription(EntityModel<String> value) {
privateDescription = value;
}
private EntityModel<String> privateComment;
public EntityModel<String> getComment() {
return privateComment;
}
public void setComment(EntityModel<String> value) {
privateComment = value;
}
private ListModel<StoragePool> privateDataCenter;
public ListModel<StoragePool> getDataCenter() {
return privateDataCenter;
}
public void setDataCenter(ListModel<StoragePool> value) {
privateDataCenter = value;
}
private ListModel<Network> managementNetwork;
public void setManagementNetwork(ListModel<Network> managementNetwork) {
this.managementNetwork = managementNetwork;
}
public ListModel<Network> getManagementNetwork() {
return managementNetwork;
}
private FilteredListModel<ServerCpu> privateCPU;
public FilteredListModel<ServerCpu> getCPU() {
return privateCPU;
}
public void setCPU(FilteredListModel<ServerCpu> value) {
privateCPU = value;
}
private EntityModel<Boolean> rngRandomSourceRequired;
public EntityModel<Boolean> getRngRandomSourceRequired() {
return rngRandomSourceRequired;
}
public void setRngRandomSourceRequired(EntityModel<Boolean> rngRandomSourceRequired) {
this.rngRandomSourceRequired = rngRandomSourceRequired;
}
private EntityModel<Boolean> rngHwrngSourceRequired;
public EntityModel<Boolean> getRngHwrngSourceRequired() {
return rngHwrngSourceRequired;
}
public void setRngHwrngSourceRequired(EntityModel<Boolean> rngHwrngSourceRequired) {
this.rngHwrngSourceRequired = rngHwrngSourceRequired;
}
private ListModel<Version> privateVersion;
public ListModel<Version> getVersion() {
return privateVersion;
}
public void setVersion(ListModel<Version> value) {
privateVersion = value;
}
private ListModel<ArchitectureType> privateArchitecture;
public ListModel<ArchitectureType> getArchitecture() {
return privateArchitecture;
}
public void setArchitecture(ListModel<ArchitectureType> value) {
privateArchitecture = value;
}
private boolean allowClusterWithVirtGlusterEnabled;
public boolean getAllowClusterWithVirtGlusterEnabled() {
return allowClusterWithVirtGlusterEnabled;
}
public void setAllowClusterWithVirtGlusterEnabled(boolean value) {
allowClusterWithVirtGlusterEnabled = value;
if (allowClusterWithVirtGlusterEnabled != value) {
allowClusterWithVirtGlusterEnabled = value;
onPropertyChanged(new PropertyChangedEventArgs("AllowClusterWithVirtGlusterEnabled")); //$NON-NLS-1$
}
}
private EntityModel<Boolean> privateEnableOvirtService;
public EntityModel<Boolean> getEnableOvirtService() {
return privateEnableOvirtService;
}
public void setEnableOvirtService(EntityModel<Boolean> value) {
this.privateEnableOvirtService = value;
}
private EntityModel<Boolean> privateEnableGlusterService;
public EntityModel<Boolean> getEnableGlusterService() {
return privateEnableGlusterService;
}
public void setEnableGlusterService(EntityModel<Boolean> value) {
this.privateEnableGlusterService = value;
}
private ListModel<List<AdditionalFeature>> additionalClusterFeatures;
public ListModel<List<AdditionalFeature>> getAdditionalClusterFeatures() {
return additionalClusterFeatures;
}
public void setAdditionalClusterFeatures(ListModel<List<AdditionalFeature>> additionalClusterFeatures) {
this.additionalClusterFeatures = additionalClusterFeatures;
}
private EntityModel<Boolean> isImportGlusterConfiguration;
public EntityModel<Boolean> getIsImportGlusterConfiguration() {
return isImportGlusterConfiguration;
}
public void setIsImportGlusterConfiguration(EntityModel<Boolean> value) {
this.isImportGlusterConfiguration = value;
}
private EntityModel<String> glusterHostAddress;
public EntityModel<String> getGlusterHostAddress() {
return glusterHostAddress;
}
public void setGlusterHostAddress(EntityModel<String> glusterHostAddress) {
this.glusterHostAddress = glusterHostAddress;
}
private EntityModel<String> glusterHostFingerprint;
public EntityModel<String> getGlusterHostFingerprint() {
return glusterHostFingerprint;
}
public void setGlusterHostFingerprint(EntityModel<String> glusterHostFingerprint) {
this.glusterHostFingerprint = glusterHostFingerprint;
}
private Boolean isFingerprintVerified;
public Boolean isFingerprintVerified() {
return isFingerprintVerified;
}
public void setIsFingerprintVerified(Boolean value) {
this.isFingerprintVerified = value;
}
private EntityModel<String> glusterHostPassword;
public EntityModel<String> getGlusterHostPassword() {
return glusterHostPassword;
}
public void setGlusterHostPassword(EntityModel<String> glusterHostPassword) {
this.glusterHostPassword = glusterHostPassword;
}
private EntityModel<Integer> privateOptimizationNone;
public EntityModel<Integer> getOptimizationNone() {
return privateOptimizationNone;
}
public void setOptimizationNone(EntityModel<Integer> value) {
privateOptimizationNone = value;
}
private EntityModel<Integer> privateOptimizationForServer;
public EntityModel<Integer> getOptimizationForServer() {
return privateOptimizationForServer;
}
public void setOptimizationForServer(EntityModel<Integer> value) {
privateOptimizationForServer = value;
}
private EntityModel<Integer> privateOptimizationForDesktop;
public EntityModel<Integer> getOptimizationForDesktop() {
return privateOptimizationForDesktop;
}
public void setOptimizationForDesktop(EntityModel<Integer> value) {
privateOptimizationForDesktop = value;
}
private EntityModel<Integer> privateOptimizationCustom;
public EntityModel<Integer> getOptimizationCustom() {
return privateOptimizationCustom;
}
public void setOptimizationCustom(EntityModel<Integer> value) {
privateOptimizationCustom = value;
}
private EntityModel<Boolean> privateOptimizationNone_IsSelected;
public EntityModel<Boolean> getOptimizationNone_IsSelected() {
return privateOptimizationNone_IsSelected;
}
public void setOptimizationNone_IsSelected(EntityModel<Boolean> value) {
privateOptimizationNone_IsSelected = value;
}
private EntityModel<Boolean> privateOptimizationForServer_IsSelected;
public EntityModel<Boolean> getOptimizationForServer_IsSelected() {
return privateOptimizationForServer_IsSelected;
}
public void setOptimizationForServer_IsSelected(EntityModel<Boolean> value) {
privateOptimizationForServer_IsSelected = value;
}
private EntityModel<Boolean> privateOptimizationForDesktop_IsSelected;
public EntityModel<Boolean> getOptimizationForDesktop_IsSelected() {
return privateOptimizationForDesktop_IsSelected;
}
public void setOptimizationForDesktop_IsSelected(EntityModel<Boolean> value) {
privateOptimizationForDesktop_IsSelected = value;
}
private EntityModel<Boolean> privateOptimizationCustom_IsSelected;
public EntityModel<Boolean> getOptimizationCustom_IsSelected() {
return privateOptimizationCustom_IsSelected;
}
public void setOptimizationCustom_IsSelected(EntityModel<Boolean> value) {
privateOptimizationCustom_IsSelected = value;
}
private EntityModel<Boolean> privateCountThreadsAsCores;
public EntityModel<Boolean> getCountThreadsAsCores() {
return privateCountThreadsAsCores;
}
public void setCountThreadsAsCores(EntityModel<Boolean> value) {
privateCountThreadsAsCores = value;
}
private EntityModel<Boolean> privateVersionSupportsCpuThreads;
public EntityModel<Boolean> getVersionSupportsCpuThreads() {
return privateVersionSupportsCpuThreads;
}
public void setVersionSupportsCpuThreads(EntityModel<Boolean> value) {
privateVersionSupportsCpuThreads = value;
}
/**
* Mutually exclusive Resilience policy radio button
* @see #privateMigrateOnErrorOption_YES
* @see #privateMigrateOnErrorOption_HA_ONLY
*/
private EntityModel<Boolean> privateMigrateOnErrorOption_NO;
public EntityModel<Boolean> getMigrateOnErrorOption_NO() {
return privateMigrateOnErrorOption_NO;
}
public void setMigrateOnErrorOption_NO(EntityModel<Boolean> value) {
privateMigrateOnErrorOption_NO = value;
}
/**
* Mutually exclusive Resilience policy radio button
* @see #privateMigrateOnErrorOption_NO
* @see #privateMigrateOnErrorOption_HA_ONLY
*/
private EntityModel<Boolean> privateMigrateOnErrorOption_YES;
public EntityModel<Boolean> getMigrateOnErrorOption_YES() {
return privateMigrateOnErrorOption_YES;
}
public void setMigrateOnErrorOption_YES(EntityModel<Boolean> value) {
privateMigrateOnErrorOption_YES = value;
}
/**
* Mutually exclusive Resilience policy radio button
* @see #privateMigrateOnErrorOption_YES
* @see #privateMigrateOnErrorOption_NO
*/
private EntityModel<Boolean> privateMigrateOnErrorOption_HA_ONLY;
public EntityModel<Boolean> getMigrateOnErrorOption_HA_ONLY() {
return privateMigrateOnErrorOption_HA_ONLY;
}
public void setMigrateOnErrorOption_HA_ONLY(EntityModel<Boolean> value) {
privateMigrateOnErrorOption_HA_ONLY = value;
}
private EntityModel<Boolean> enableKsm;
public EntityModel<Boolean> getEnableKsm() {
return enableKsm;
}
public void setEnableKsm(EntityModel<Boolean> enableKsm) {
this.enableKsm = enableKsm;
}
private ListModel<KsmPolicyForNuma> ksmPolicyForNumaSelection;
public ListModel<KsmPolicyForNuma> getKsmPolicyForNumaSelection() {
return ksmPolicyForNumaSelection;
}
private void setKsmPolicyForNumaSelection(ListModel<KsmPolicyForNuma> value) {
ksmPolicyForNumaSelection = value;
}
private EntityModel<Boolean> enableBallooning;
public EntityModel<Boolean> getEnableBallooning() {
return enableBallooning;
}
public void setEnableBallooning(EntityModel<Boolean> enableBallooning) {
this.enableBallooning = enableBallooning;
}
private EntityModel<Boolean> optimizeForUtilization;
public EntityModel<Boolean> getOptimizeForUtilization() {
return optimizeForUtilization;
}
public void setOptimizeForUtilization(EntityModel<Boolean> optimizeForUtilization) {
this.optimizeForUtilization = optimizeForUtilization;
}
private EntityModel<Boolean> optimizeForSpeed;
public EntityModel<Boolean> getOptimizeForSpeed() {
return optimizeForSpeed;
}
public void setOptimizeForSpeed(EntityModel<Boolean> optimizeForSpeed) {
this.optimizeForSpeed = optimizeForSpeed;
}
private EntityModel<Boolean> guarantyResources;
public EntityModel<Boolean> getGuarantyResources() {
return guarantyResources;
}
public void setGuarantyResources(EntityModel<Boolean> guarantyResources) {
this.guarantyResources = guarantyResources;
}
private EntityModel<Boolean> allowOverbooking;
public EntityModel<Boolean> getAllowOverbooking() {
return allowOverbooking;
}
public void setAllowOverbooking(EntityModel<Boolean> allowOverbooking) {
this.allowOverbooking = allowOverbooking;
}
private SerialNumberPolicyModel serialNumberPolicy;
public SerialNumberPolicyModel getSerialNumberPolicy() {
return serialNumberPolicy;
}
public void setSerialNumberPolicy(SerialNumberPolicyModel serialNumberPolicy) {
this.serialNumberPolicy = serialNumberPolicy;
}
private EntityModel<String> spiceProxy;
public EntityModel<String> getSpiceProxy() {
return spiceProxy;
}
public void setSpiceProxy(EntityModel<String> spiceProxy) {
this.spiceProxy = spiceProxy;
}
private EntityModel<Boolean> spiceProxyEnabled;
public EntityModel<Boolean> getSpiceProxyEnabled() {
return spiceProxyEnabled;
}
public void setSpiceProxyEnabled(EntityModel<Boolean> spiceProxyEnabled) {
this.spiceProxyEnabled = spiceProxyEnabled;
}
private MigrateOnErrorOptions migrateOnErrorOption = MigrateOnErrorOptions.values()[0];
public MigrateOnErrorOptions getMigrateOnErrorOption() {
if (getMigrateOnErrorOption_NO().getEntity() == true) {
return MigrateOnErrorOptions.NO;
}
else if (getMigrateOnErrorOption_YES().getEntity() == true) {
return MigrateOnErrorOptions.YES;
}
else if (getMigrateOnErrorOption_HA_ONLY().getEntity() == true) {
return MigrateOnErrorOptions.HA_ONLY;
}
return MigrateOnErrorOptions.YES;
}
public void setMigrateOnErrorOption(MigrateOnErrorOptions value) {
if (migrateOnErrorOption != value) {
migrateOnErrorOption = value;
// webadmin use.
switch (migrateOnErrorOption) {
case NO:
getMigrateOnErrorOption_NO().setEntity(true);
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
break;
case YES:
getMigrateOnErrorOption_NO().setEntity(false);
getMigrateOnErrorOption_YES().setEntity(true);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
break;
case HA_ONLY:
getMigrateOnErrorOption_NO().setEntity(false);
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(true);
break;
default:
break;
}
onPropertyChanged(new PropertyChangedEventArgs("MigrateOnErrorOption")); //$NON-NLS-1$
}
}
private boolean privateisResiliencePolicyTabAvailable;
public boolean getisResiliencePolicyTabAvailable() {
return privateisResiliencePolicyTabAvailable;
}
public void setisResiliencePolicyTabAvailable(boolean value) {
privateisResiliencePolicyTabAvailable = value;
}
public boolean getIsResiliencePolicyTabAvailable() {
return getisResiliencePolicyTabAvailable();
}
public void setIsResiliencePolicyTabAvailable(boolean value) {
if (getisResiliencePolicyTabAvailable() != value) {
setisResiliencePolicyTabAvailable(value);
onPropertyChanged(new PropertyChangedEventArgs("IsResiliencePolicyTabAvailable")); //$NON-NLS-1$
}
}
private EntityModel<Boolean> enableOptionalReason;
public EntityModel<Boolean> getEnableOptionalReason() {
return enableOptionalReason;
}
public void setEnableOptionalReason(EntityModel<Boolean> value) {
this.enableOptionalReason = value;
}
private EntityModel<Boolean> enableHostMaintenanceReason;
public EntityModel<Boolean> getEnableHostMaintenanceReason() {
return enableHostMaintenanceReason;
}
public void setEnableHostMaintenanceReason(EntityModel<Boolean> value) {
this.enableHostMaintenanceReason = value;
}
private EntityModel<Boolean> privateEnableTrustedService;
private EntityModel<Boolean> privateEnableHaReservation;
public EntityModel<Boolean> getEnableHaReservation() {
return privateEnableHaReservation;
}
public void setEnableHaReservation(EntityModel<Boolean> value) {
this.privateEnableHaReservation = value;
}
public EntityModel<Boolean> getEnableTrustedService() {
return privateEnableTrustedService;
}
public void setEnableTrustedService(EntityModel<Boolean> value) {
this.privateEnableTrustedService = value;
}
public int getMemoryOverCommit() {
if (getOptimizationNone_IsSelected().getEntity()) {
return getOptimizationNone().getEntity();
}
if (getOptimizationForServer_IsSelected().getEntity()) {
return getOptimizationForServer().getEntity();
}
if (getOptimizationForDesktop_IsSelected().getEntity()) {
return getOptimizationForDesktop().getEntity();
}
if (getOptimizationCustom_IsSelected().getEntity()) {
return getOptimizationCustom().getEntity();
}
return AsyncDataProvider.getInstance().getClusterDefaultMemoryOverCommit();
}
public String getSchedulerOptimizationInfoMessage() {
return ConstantsManager.getInstance()
.getMessages()
.schedulerOptimizationInfo(AsyncDataProvider.getInstance().getOptimizeSchedulerForSpeedPendingRequests());
}
public String getAllowOverbookingInfoMessage() {
return ConstantsManager.getInstance()
.getMessages()
.schedulerAllowOverbookingInfo(AsyncDataProvider.getInstance().getSchedulerAllowOverbookingPendingRequestsThreshold());
}
public void setMemoryOverCommit(int value) {
getOptimizationNone_IsSelected().setEntity(value == getOptimizationNone().getEntity());
getOptimizationForServer_IsSelected().setEntity(value == getOptimizationForServer().getEntity());
getOptimizationForDesktop_IsSelected().setEntity(value == getOptimizationForDesktop().getEntity());
if (!getOptimizationNone_IsSelected().getEntity()
&& !getOptimizationForServer_IsSelected().getEntity()
&& !getOptimizationForDesktop_IsSelected().getEntity()) {
getOptimizationCustom().setIsAvailable(true);
getOptimizationCustom().setEntity(value);
getOptimizationCustom_IsSelected().setIsAvailable(true);
getOptimizationCustom_IsSelected().setEntity(true);
}
}
private EntityModel<Boolean> fencingEnabledModel;
public EntityModel<Boolean> getFencingEnabledModel() {
return fencingEnabledModel;
}
public void setFencingEnabledModel(EntityModel<Boolean> fencingEnabledModel) {
this.fencingEnabledModel = fencingEnabledModel;
}
private EntityModel<Boolean> skipFencingIfSDActiveEnabled;
public EntityModel<Boolean> getSkipFencingIfSDActiveEnabled() {
return skipFencingIfSDActiveEnabled;
}
public void setSkipFencingIfSDActiveEnabled(EntityModel<Boolean> skipFencingIfSDActiveEnabled) {
this.skipFencingIfSDActiveEnabled = skipFencingIfSDActiveEnabled;
}
private EntityModel<Boolean> skipFencingIfConnectivityBrokenEnabled;
public EntityModel<Boolean> getSkipFencingIfConnectivityBrokenEnabled() {
return skipFencingIfConnectivityBrokenEnabled;
}
public void setSkipFencingIfConnectivityBrokenEnabled(EntityModel<Boolean> skipFencingIfConnectivityBrokenEnabled) {
this.skipFencingIfConnectivityBrokenEnabled = skipFencingIfConnectivityBrokenEnabled;
}
private ListModel<Integer> hostsWithBrokenConnectivityThreshold;
public ListModel<Integer> getHostsWithBrokenConnectivityThreshold() {
return hostsWithBrokenConnectivityThreshold;
}
public void setHostsWithBrokenConnectivityThreshold(ListModel<Integer> value) {
hostsWithBrokenConnectivityThreshold = value;
}
private ListModel<Boolean> autoConverge;
public ListModel<Boolean> getAutoConverge() {
return autoConverge;
}
public void setAutoConverge(ListModel<Boolean> autoConverge) {
this.autoConverge = autoConverge;
}
private ListModel<Boolean> migrateCompressed;
public ListModel<Boolean> getMigrateCompressed() {
return migrateCompressed;
}
public void setMigrateCompressed(ListModel<Boolean> migrateCompressed) {
this.migrateCompressed = migrateCompressed;
}
public ClusterModel() {
super();
ListModel<KsmPolicyForNuma> ksmPolicyForNumaSelection = new ListModel<KsmPolicyForNuma>();
ksmPolicyForNumaSelection.setItems(Arrays.asList(KsmPolicyForNuma.values()));
setKsmPolicyForNumaSelection(ksmPolicyForNumaSelection);
}
public void initTunedProfiles() {
this.startProgress(null);
Frontend.getInstance().runQuery(VdcQueryType.GetGlusterTunedProfiles, new VdcQueryParametersBase(), new AsyncQuery(new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ClusterModel.this.stopProgress();
List<String> glusterTunedProfiles = new ArrayList<>();
if (((VdcQueryReturnValue) returnValue).getSucceeded()) {
glusterTunedProfiles.addAll((List<String>)(((VdcQueryReturnValue) returnValue).getReturnValue()));
}
glusterTunedProfile.setItems(glusterTunedProfiles, glusterTunedProfile.getSelectedItem());
glusterTunedProfile.setIsAvailable(glusterTunedProfile.getItems().size() > 0);
}
}));
}
public void init(final boolean isEdit) {
setIsEdit(isEdit);
setName(new EntityModel<String>());
setDescription(new EntityModel<String>());
setComment(new EntityModel<String>());
setEnableTrustedService(new EntityModel<Boolean>(false));
setEnableHaReservation(new EntityModel<Boolean>(false));
setEnableOptionalReason(new EntityModel<Boolean>(false));
getEnableOptionalReason().setIsAvailable(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly));
setEnableHostMaintenanceReason(new EntityModel<Boolean>(false));
setAllowClusterWithVirtGlusterEnabled(true);
setGlusterTunedProfile(new ListModel<String>());
AsyncDataProvider.getInstance().getAllowClusterWithVirtGlusterEnabled(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
setAllowClusterWithVirtGlusterEnabled((Boolean) returnValue);
}
}));
setEnableOvirtService(new EntityModel<Boolean>());
setEnableGlusterService(new EntityModel<Boolean>());
setAdditionalClusterFeatures(new ListModel<List<AdditionalFeature>>());
List<List<AdditionalFeature>> additionalFeatures = new ArrayList<List<AdditionalFeature>>();
additionalFeatures.add(Collections.<AdditionalFeature> emptyList());
getAdditionalClusterFeatures().setItems(additionalFeatures, null);
setSpiceProxyEnabled(new EntityModel<Boolean>());
getSpiceProxyEnabled().setEntity(false);
getSpiceProxyEnabled().getEntityChangedEvent().addListener(this);
setSpiceProxy(new EntityModel<String>());
getSpiceProxy().setIsChangeable(false);
setFencingEnabledModel(new EntityModel<Boolean>());
getFencingEnabledModel().setEntity(true);
getFencingEnabledModel().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
updateFencingPolicyContent(getVersion() == null ? null : getVersion().getSelectedItem());
}
});
setSkipFencingIfSDActiveEnabled(new EntityModel<Boolean>());
getSkipFencingIfSDActiveEnabled().setEntity(true);
setSkipFencingIfConnectivityBrokenEnabled(new EntityModel<Boolean>());
getSkipFencingIfConnectivityBrokenEnabled().setEntity(true);
setEnableOvirtService(new EntityModel<Boolean>());
setEnableGlusterService(new EntityModel<Boolean>());
setSerialNumberPolicy(new SerialNumberPolicyModel());
setAutoConverge(new ListModel<Boolean>());
getAutoConverge().setItems(Arrays.asList(null, true, false));
setMigrateCompressed(new ListModel<Boolean>());
getMigrateCompressed().setItems(Arrays.asList(null, true, false));
getEnableOvirtService().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
refreshAdditionalClusterFeaturesList();
if (!getAllowClusterWithVirtGlusterEnabled() && getEnableOvirtService().getEntity()) {
getEnableGlusterService().setEntity(Boolean.FALSE);
}
getEnableGlusterService().setIsChangeable(true);
getEnableTrustedService().setEntity(false);
if (getEnableOvirtService().getEntity() != null
&& getEnableOvirtService().getEntity()) {
if (getEnableGlusterService().getEntity() != null
&& !getEnableGlusterService().getEntity()) {
getEnableTrustedService().setIsChangeable(true);
}
else {
getEnableTrustedService().setIsChangeable(false);
}
}
else {
getEnableTrustedService().setIsChangeable(false);
}
}
});
getEnableOvirtService().setEntity(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly));
getEnableOvirtService().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.VirtOnly
&& ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly));
setRngRandomSourceRequired(new EntityModel<Boolean>());
getRngRandomSourceRequired().setIsAvailable(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly));
setRngHwrngSourceRequired(new EntityModel<Boolean>());
getRngHwrngSourceRequired().setIsAvailable(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly));
initImportCluster(isEdit);
getEnableGlusterService().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
refreshAdditionalClusterFeaturesList();
if (!getAllowClusterWithVirtGlusterEnabled() && getEnableGlusterService().getEntity()) {
getEnableOvirtService().setEntity(Boolean.FALSE);
}
if (!isEdit
&& getEnableGlusterService().getEntity() != null
&& getEnableGlusterService().getEntity()) {
getIsImportGlusterConfiguration().setIsAvailable(true);
getGlusterHostAddress().setIsAvailable(true);
getGlusterHostFingerprint().setIsAvailable(true);
getGlusterHostPassword().setIsAvailable(true);
}
else {
getIsImportGlusterConfiguration().setIsAvailable(false);
getIsImportGlusterConfiguration().setEntity(false);
getGlusterHostAddress().setIsAvailable(false);
getGlusterHostFingerprint().setIsAvailable(false);
getGlusterHostPassword().setIsAvailable(false);
}
if (getEnableGlusterService().getEntity() != null
&& getEnableGlusterService().getEntity()) {
getEnableTrustedService().setEntity(false);
getEnableTrustedService().setIsChangeable(false);
}
else {
if (getEnableOvirtService().getEntity() != null
&& getEnableOvirtService().getEntity()) {
getEnableTrustedService().setIsChangeable(true);
}
else {
getEnableTrustedService().setIsChangeable(false);
}
}
getGlusterTunedProfile().setIsAvailable(getEnableGlusterService().getEntity());
if (getEnableGlusterService().getEntity()) {
initTunedProfiles();
}
}
});
getEnableTrustedService().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
if (getEnableTrustedService().getEntity() != null
&& getEnableTrustedService().getEntity()) {
getEnableGlusterService().setEntity(false);
getEnableGlusterService().setIsChangeable(false);
}
else {
getEnableGlusterService().setIsChangeable(true);
}
}
});
getEnableGlusterService().setEntity(ApplicationModeHelper.getUiMode() == ApplicationMode.GlusterOnly);
getEnableGlusterService().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly
&& ApplicationModeHelper.isModeSupported(ApplicationMode.GlusterOnly));
getGlusterTunedProfile().setIsAvailable(getEnableGlusterService().getEntity());
setOptimizationNone(new EntityModel<Integer>());
setOptimizationForServer(new EntityModel<Integer>());
setOptimizationForDesktop(new EntityModel<Integer>());
setOptimizationCustom(new EntityModel<Integer>());
EntityModel<Boolean> tempVar = new EntityModel<Boolean>();
tempVar.setEntity(false);
setOptimizationNone_IsSelected(tempVar);
getOptimizationNone_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel<Boolean> tempVar2 = new EntityModel<Boolean>();
tempVar2.setEntity(false);
setOptimizationForServer_IsSelected(tempVar2);
getOptimizationForServer_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel<Boolean> tempVar3 = new EntityModel<Boolean>();
tempVar3.setEntity(false);
setOptimizationForDesktop_IsSelected(tempVar3);
getOptimizationForDesktop_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel<Boolean> tempVar4 = new EntityModel<Boolean>();
tempVar4.setEntity(false);
tempVar4.setIsAvailable(false);
setOptimizationCustom_IsSelected(tempVar4);
getOptimizationCustom_IsSelected().getEntityChangedEvent().addListener(this);
EntityModel<Boolean> tempVar5 = new EntityModel<Boolean>();
tempVar5.setEntity(false);
setMigrateOnErrorOption_YES(tempVar5);
getMigrateOnErrorOption_YES().getEntityChangedEvent().addListener(this);
EntityModel<Boolean> tempVar6 = new EntityModel<Boolean>();
tempVar6.setEntity(false);
setMigrateOnErrorOption_NO(tempVar6);
getMigrateOnErrorOption_NO().getEntityChangedEvent().addListener(this);
EntityModel<Boolean> tempVar7 = new EntityModel<Boolean>();
tempVar7.setEntity(false);
setMigrateOnErrorOption_HA_ONLY(tempVar7);
getMigrateOnErrorOption_HA_ONLY().getEntityChangedEvent().addListener(this);
// KSM feature
setEnableKsm(new EntityModel<Boolean>());
getEnableKsm().setEntity(false);
getKsmPolicyForNumaSelection().setIsChangeable(false);
getEnableKsm().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
if (getEnableKsm().getEntity() == null){
return;
}
if (getEnableKsm().getEntity() == true){
getKsmPolicyForNumaSelection().setIsChangeable(true);
}
if (getEnableKsm().getEntity() == false){
getKsmPolicyForNumaSelection().setIsChangeable(false);
}
}
});
setEnableBallooning(new EntityModel<Boolean>());
getEnableBallooning().setEntity(false);
// Optimization methods:
// default value =100;
setDefaultMemoryOvercommit(AsyncDataProvider.getInstance().getClusterDefaultMemoryOverCommit());
setCountThreadsAsCores(new EntityModel<Boolean>(AsyncDataProvider.getInstance().getClusterDefaultCountThreadsAsCores()));
setVersionSupportsCpuThreads(new EntityModel<Boolean>(true));
setOptimizeForUtilization(new EntityModel<Boolean>());
setOptimizeForSpeed(new EntityModel<Boolean>());
getOptimizeForUtilization().setEntity(true);
getOptimizeForSpeed().setEntity(false);
getOptimizeForUtilization().getEntityChangedEvent().addListener(this);
getOptimizeForSpeed().getEntityChangedEvent().addListener(this);
setGuarantyResources(new EntityModel<Boolean>());
setAllowOverbooking(new EntityModel<Boolean>());
getGuarantyResources().setEntity(true);
getAllowOverbooking().setEntity(false);
getAllowOverbooking().getEntityChangedEvent().addListener(this);
getGuarantyResources().getEntityChangedEvent().addListener(this);
boolean overbookingSupported = AsyncDataProvider.getInstance().getScheudulingAllowOverbookingSupported();
getAllowOverbooking().setIsAvailable(overbookingSupported);
if (overbookingSupported) {
getOptimizeForSpeed().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
Boolean entity = getOptimizeForSpeed().getEntity();
if (entity) {
getGuarantyResources().setEntity(true);
}
getAllowOverbooking().setIsChangeable(!entity);
}
});
getAllowOverbooking().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
Boolean entity = getAllowOverbooking().getEntity();
if (entity) {
getOptimizeForUtilization().setEntity(true);
}
getOptimizeForSpeed().setIsChangeable(!entity);
}
});
}
setHostsWithBrokenConnectivityThreshold(new ListModel<Integer>());
getHostsWithBrokenConnectivityThreshold().setIsAvailable(true);
getHostsWithBrokenConnectivityThreshold().getSelectedItemChangedEvent().addListener(this);
initHostsWithBrokenConnectivityThreshold();
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
ClusterModel clusterModel = (ClusterModel) model;
clusterModel.setDesktopOverCommit((Integer) result);
AsyncQuery _asyncQuery1 = new AsyncQuery();
_asyncQuery1.setModel(clusterModel);
_asyncQuery1.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model1, Object result1) {
ClusterModel clusterModel1 = (ClusterModel) model1;
clusterModel1.setServerOverCommit((Integer) result1);
// temp is used for conversion purposes
EntityModel temp;
temp = clusterModel1.getOptimizationNone();
temp.setEntity(clusterModel1.getDefaultMemoryOvercommit());
// res1, res2 is used for conversion purposes.
boolean res1 = clusterModel1.getDesktopOverCommit() != clusterModel1.getDefaultMemoryOvercommit();
boolean res2 = clusterModel1.getServerOverCommit() != clusterModel1.getDefaultMemoryOvercommit();
temp = clusterModel1.getOptimizationNone_IsSelected();
setIsSelected(res1 && res2);
temp.setEntity(getIsSelected());
temp = clusterModel1.getOptimizationForServer();
temp.setEntity(clusterModel1.getServerOverCommit());
temp = clusterModel1.getOptimizationForServer_IsSelected();
temp.setEntity(clusterModel1.getServerOverCommit() == clusterModel1.getDefaultMemoryOvercommit());
temp = clusterModel1.getOptimizationForDesktop();
temp.setEntity(clusterModel1.getDesktopOverCommit());
temp = clusterModel1.getOptimizationForDesktop_IsSelected();
temp.setEntity(clusterModel1.getDesktopOverCommit() == clusterModel1.getDefaultMemoryOvercommit());
temp = clusterModel1.getOptimizationCustom();
temp.setIsAvailable(false);
temp.setIsChangeable(false);
if (clusterModel1.getIsEdit()) {
clusterModel1.postInit();
}
}
};
AsyncDataProvider.getInstance().getClusterServerMemoryOverCommit(_asyncQuery1);
}
};
AsyncDataProvider.getInstance().getClusterDesktopMemoryOverCommit(_asyncQuery);
setDataCenter(new ListModel<StoragePool>());
getDataCenter().getSelectedItemChangedEvent().addListener(this);
getDataCenter().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly);
setArchitecture(new ListModel<ArchitectureType>());
getArchitecture().setIsAvailable(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly));
setManagementNetwork(new ListModel<Network>());
if (isEdit && !isClusterDetached()) {
getManagementNetwork().setChangeProhibitionReason(ConstantsManager.getInstance()
.getConstants()
.prohibitManagementNetworkChangeInEditClusterInfoMessage());
getManagementNetwork().setIsChangeable(false);
}
setCPU(new FilteredListModel<ServerCpu>());
getCPU().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly);
getCPU().getSelectedItemChangedEvent().addListener(this);
setVersion(new ListModel<Version>());
getVersion().getSelectedItemChangedEvent().addListener(this);
setMigrateOnErrorOption(MigrateOnErrorOptions.YES);
getRngRandomSourceRequired().setEntity(false);
getRngHwrngSourceRequired().setEntity(false);
setValidTab(TabName.GENERAL_TAB, true);
setIsResiliencePolicyTabAvailable(true);
setClusterPolicy(new ListModel<ClusterPolicy>());
setCustomPropertySheet(new KeyValueModel());
getClusterPolicy().getSelectedItemChangedEvent().addListener(this);
Frontend.getInstance().runQuery(VdcQueryType.GetAllPolicyUnits, new VdcQueryParametersBase(), new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ArrayList<PolicyUnit> policyUnits =
((VdcQueryReturnValue) returnValue).getReturnValue();
policyUnitMap = new LinkedHashMap<Guid, PolicyUnit>();
for (PolicyUnit policyUnit : policyUnits) {
policyUnitMap.put(policyUnit.getId(), policyUnit);
}
Frontend.getInstance().runQuery(VdcQueryType.GetClusterPolicies,
new VdcQueryParametersBase(),
new AsyncQuery(model,
new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ClusterModel clusterModel = (ClusterModel) model;
ArrayList<ClusterPolicy> list =
((VdcQueryReturnValue) returnValue).getReturnValue();
clusterModel.getClusterPolicy().setItems(list);
ClusterPolicy defaultClusterPolicy = null;
ClusterPolicy selectedClusterPolicy = null;
for (ClusterPolicy clusterPolicy : list) {
if (clusterModel.getIsEdit() && getEntity() != null
&& clusterPolicy.getId()
.equals(getEntity().getClusterPolicyId())) {
selectedClusterPolicy = clusterPolicy;
}
if (clusterPolicy.isDefaultPolicy()) {
defaultClusterPolicy = clusterPolicy;
}
}
if (selectedClusterPolicy != null) {
clusterModel.getClusterPolicy()
.setSelectedItem(selectedClusterPolicy);
} else {
clusterModel.getClusterPolicy()
.setSelectedItem(defaultClusterPolicy);
}
clusterPolicyChanged();
}
}));
}
}));
}
boolean isClusterDetached() {
if (detached == null) {
detached = getEntity().getStoragePoolId() == null;
}
return detached;
}
private void initSpiceProxy() {
String proxy = getEntity().getSpiceProxy();
boolean isProxyAvailable = !StringHelper.isNullOrEmpty(proxy);
getSpiceProxyEnabled().setEntity(isProxyAvailable);
getSpiceProxy().setIsChangeable(isProxyAvailable);
getSpiceProxy().setEntity(proxy);
}
private void initImportCluster(boolean isEdit) {
setGlusterHostAddress(new EntityModel<String>());
getGlusterHostAddress().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
setIsFingerprintVerified(false);
if (getGlusterHostAddress().getEntity() == null
|| (getGlusterHostAddress().getEntity()).trim().length() == 0) {
getGlusterHostFingerprint().setEntity(""); //$NON-NLS-1$
return;
}
fetchFingerprint(getGlusterHostAddress().getEntity());
}
});
setGlusterHostFingerprint(new EntityModel<String>());
getGlusterHostFingerprint().setEntity(""); //$NON-NLS-1$
setIsFingerprintVerified(false);
setGlusterHostPassword(new EntityModel<String>());
setIsImportGlusterConfiguration(new EntityModel<Boolean>());
getIsImportGlusterConfiguration().getEntityChangedEvent().addListener(new IEventListener<EventArgs>() {
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
if (getIsImportGlusterConfiguration().getEntity() != null
&& getIsImportGlusterConfiguration().getEntity()) {
getGlusterHostAddress().setIsChangeable(true);
getGlusterHostPassword().setIsChangeable(true);
}
else {
getGlusterHostAddress().setIsChangeable(false);
getGlusterHostPassword().setIsChangeable(false);
}
}
});
getIsImportGlusterConfiguration().setIsAvailable(false);
getGlusterHostAddress().setIsAvailable(false);
getGlusterHostFingerprint().setIsAvailable(false);
getGlusterHostPassword().setIsAvailable(false);
getIsImportGlusterConfiguration().setEntity(false);
}
private void fetchFingerprint(String hostAddress) {
AsyncQuery aQuery = new AsyncQuery();
aQuery.setModel(this);
aQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
String fingerprint = (String) result;
if (fingerprint != null && fingerprint.length() > 0) {
getGlusterHostFingerprint().setEntity((String) result);
setIsFingerprintVerified(true);
}
else {
getGlusterHostFingerprint().setEntity(ConstantsManager.getInstance()
.getConstants()
.errorLoadingFingerprint());
setIsFingerprintVerified(false);
}
}
};
AsyncDataProvider.getInstance().getHostFingerprint(aQuery, hostAddress);
getGlusterHostFingerprint().setEntity(ConstantsManager.getInstance().getConstants().loadingFingerprint());
}
private void postInit() {
getDescription().setEntity(getEntity().getDescription());
getComment().setEntity(getEntity().getComment());
initSpiceProxy();
getFencingEnabledModel().setEntity(getEntity().getFencingPolicy().isFencingEnabled());
getSkipFencingIfSDActiveEnabled().setEntity(getEntity().getFencingPolicy().isSkipFencingIfSDActive());
getSkipFencingIfConnectivityBrokenEnabled().setEntity(getEntity().getFencingPolicy()
.isSkipFencingIfConnectivityBroken());
getHostsWithBrokenConnectivityThreshold().setSelectedItem(getEntity().getFencingPolicy()
.getHostsWithBrokenConnectivityThreshold());
setMemoryOverCommit(getEntity().getMaxVdsMemoryOverCommit());
getCountThreadsAsCores().setEntity(getEntity().getCountThreadsAsCores());
getEnableBallooning().setEntity(getEntity().isEnableBallooning());
getEnableKsm().setEntity(getEntity().isEnableKsm());
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
ClusterModel clusterModel = (ClusterModel) model;
List<StoragePool> dataCenters = (List<StoragePool>) result;
clusterModel.getDataCenter().setItems(dataCenters);
clusterModel.getDataCenter().setSelectedItem(null);
final Guid dataCenterId = clusterModel.getEntity().getStoragePoolId();
for (StoragePool dataCenter : dataCenters) {
if (dataCenterId != null && dataCenter.getId().equals(dataCenterId)) {
clusterModel.getDataCenter().setSelectedItem(dataCenter);
break;
}
}
final StoragePool selectedDataCenter = clusterModel.getDataCenter().getSelectedItem();
clusterModel.getDataCenter().setIsChangeable(selectedDataCenter == null);
clusterModel.setMigrateOnErrorOption(clusterModel.getEntity().getMigrateOnError());
if (!clusterModel.getManagementNetwork().getIsChangable()) {
loadCurrentClusterManagementNetwork();
}
}
};
AsyncDataProvider.getInstance().getDataCenterList(_asyncQuery);
// inactive KsmPolicyForNuma if KSM disabled
if (getEnableKsm().getEntity() == false)
getKsmPolicyForNumaSelection().setIsChangeable(false);
// hide KsmPolicyForNuma is cluseter version bellow 3.4
Version version = getEntity().getCompatibilityVersion();
if (version.compareTo(Version.v3_4) < 0)
getKsmPolicyForNumaSelection().setIsAvailable(false);
}
private void loadCurrentClusterManagementNetwork() {
final AsyncQuery getManagementNetworkQuery = new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
final ClusterModel clusterModel = (ClusterModel) model;
final Network managementNetwork = (Network) returnValue;
clusterModel.getManagementNetwork().setSelectedItem(managementNetwork);
}
});
AsyncDataProvider.getInstance().getManagementNetwork(getManagementNetworkQuery, getEntity().getId());
}
private void loadDcNetworks(final Guid dataCenterId) {
if (dataCenterId == null) {
return;
}
final AsyncQuery getAllDataCenterNetworksQuery = new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
final ClusterModel clusterModel = (ClusterModel) model;
if (clusterModel.getDataCenter().getSelectedItem() == null) {
return;
}
final List<Network> dcNetworks = (List<Network>) returnValue;
clusterModel.getManagementNetwork().setItems(dcNetworks);
if (defaultManagementNetworkCache.containsKey(dataCenterId)) {
final Network defaultManagementNetwork = defaultManagementNetworkCache.get(dataCenterId);
setSelectedDefaultManagementNetwork(clusterModel, defaultManagementNetwork);
} else {
final AsyncQuery getDefaultManagementNetworkQuery =
new AsyncQuery(clusterModel, new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
final Network defaultManagementNetwork = (Network) returnValue;
defaultManagementNetworkCache.put(dataCenterId, defaultManagementNetwork);
setSelectedDefaultManagementNetwork(clusterModel, defaultManagementNetwork);
}
});
AsyncDataProvider.getInstance()
.getDefaultManagementNetwork(getDefaultManagementNetworkQuery, dataCenterId);
}
}
private void setSelectedDefaultManagementNetwork(ClusterModel clusterModel,
Network defaultManagementNetwork) {
if (defaultManagementNetwork != null) {
clusterModel.getManagementNetwork().setSelectedItem(defaultManagementNetwork);
}
}
});
AsyncDataProvider.getInstance().getManagementNetworkCandidates(getAllDataCenterNetworksQuery, dataCenterId);
}
@Override
public void eventRaised(Event<? extends EventArgs> ev, Object sender, EventArgs args) {
super.eventRaised(ev, sender, args);
if (ev.matchesDefinition(ListModel.selectedItemChangedEventDefinition)) {
if (sender == getDataCenter()) {
storagePool_SelectedItemChanged(args);
}
else if (sender == getVersion()) {
version_SelectedItemChanged(args);
}
else if (sender == getClusterPolicy()) {
clusterPolicyChanged();
}
else if (sender == getCPU()) {
CPU_SelectedItemChanged(args);
}
else if (sender == getArchitecture()) {
architectureSelectedItemChanged(args);
}
}
else if (ev.matchesDefinition(HasEntity.entityChangedEventDefinition)) {
EntityModel senderEntityModel = (EntityModel) sender;
if (senderEntityModel == getSpiceProxyEnabled()) {
getSpiceProxy().setIsChangeable(getSpiceProxyEnabled().getEntity());
} else if ((Boolean) senderEntityModel.getEntity()) {
if (senderEntityModel == getOptimizationNone_IsSelected()) {
getOptimizationForServer_IsSelected().setEntity(false);
getOptimizationForDesktop_IsSelected().setEntity(false);
getOptimizationCustom_IsSelected().setEntity(false);
}
else if (senderEntityModel == getOptimizationForServer_IsSelected()) {
getOptimizationNone_IsSelected().setEntity(false);
getOptimizationForDesktop_IsSelected().setEntity(false);
getOptimizationCustom_IsSelected().setEntity(false);
}
else if (senderEntityModel == getOptimizationForDesktop_IsSelected()) {
getOptimizationNone_IsSelected().setEntity(false);
getOptimizationForServer_IsSelected().setEntity(false);
getOptimizationCustom_IsSelected().setEntity(false);
}
else if (senderEntityModel == getOptimizationCustom_IsSelected()) {
getOptimizationNone_IsSelected().setEntity(false);
getOptimizationForServer_IsSelected().setEntity(false);
getOptimizationForDesktop_IsSelected().setEntity(false);
}
else if (senderEntityModel == getMigrateOnErrorOption_YES()) {
getMigrateOnErrorOption_NO().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
}
else if (senderEntityModel == getMigrateOnErrorOption_NO()) {
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_HA_ONLY().setEntity(false);
}
else if (senderEntityModel == getMigrateOnErrorOption_HA_ONLY()) {
getMigrateOnErrorOption_YES().setEntity(false);
getMigrateOnErrorOption_NO().setEntity(false);
} else if (senderEntityModel == getOptimizeForUtilization()) {
getOptimizeForSpeed().setEntity(false);
} else if (senderEntityModel == getOptimizeForSpeed()) {
getOptimizeForUtilization().setEntity(false);
} else if(senderEntityModel == getGuarantyResources()) {
getAllowOverbooking().setEntity(false);
} else if(senderEntityModel == getAllowOverbooking()) {
getGuarantyResources().setEntity(false);
}
}
}
}
private void architectureSelectedItemChanged(EventArgs args) {
filterCpuTypeByArchitecture();
}
private void filterCpuTypeByArchitecture() {
final ArchitectureType selectedArchitecture = getArchitecture().getSelectedItem();
final FilteredListModel.Filter<ServerCpu> filter = selectedArchitecture == null
|| selectedArchitecture.equals(ArchitectureType.undefined)
? null
: new FilteredListModel.Filter<ServerCpu>() {
@Override
public boolean filter(ServerCpu cpu) {
final ArchitectureType cpuArchitecture = cpu.getArchitecture();
final boolean showCpu = selectedArchitecture.equals(cpuArchitecture);
return showCpu;
}
};
getCPU().filterItems(filter);
}
private void CPU_SelectedItemChanged(EventArgs args) {
updateMigrateOnError();
}
private void version_SelectedItemChanged(EventArgs e) {
Version version;
if (getVersion().getSelectedItem() != null) {
version = getVersion().getSelectedItem();
}
else {
version = getDataCenter().getSelectedItem().getCompatibilityVersion();
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
ClusterModel clusterModel = (ClusterModel) model;
ArrayList<ServerCpu> cpus = (ArrayList<ServerCpu>) result;
if (clusterModel.getIsEdit()) {
AsyncQuery emptyQuery = new AsyncQuery();
emptyQuery.setModel(new Object[] { clusterModel, cpus });
emptyQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
Boolean isEmpty = (Boolean) returnValue;
Object[] objArray = (Object[]) model;
ClusterModel clusterModel = (ClusterModel) objArray[0];
ArrayList<ServerCpu> cpus = (ArrayList<ServerCpu>) objArray[1];
if (isEmpty) {
populateCPUList(clusterModel, cpus, true);
} else {
ArrayList<ServerCpu> filteredCpus = new ArrayList<ServerCpu>();
for (ServerCpu cpu : cpus) {
if (cpu.getArchitecture() == clusterModel.getEntity().getArchitecture()) {
filteredCpus.add(cpu);
}
}
populateCPUList(clusterModel, filteredCpus, false);
}
}
};
AsyncDataProvider.getInstance().isClusterEmpty(emptyQuery, clusterModel.getEntity().getId());
} else {
populateCPUList(clusterModel, cpus, true);
}
}
};
AsyncDataProvider.getInstance().getCPUList(_asyncQuery, version);
// CPU Thread support is only available for clusters of version 3.2 or greater
getVersionSupportsCpuThreads().setEntity(version.compareTo(Version.v3_2) >= 0);
getEnableBallooning().setChangeProhibitionReason(ConstantsManager.getInstance().getConstants().ballooningNotAvailable());
getEnableBallooning().setIsChangeable(version.compareTo(Version.v3_3) >= 0);
setRngSourcesCheckboxes(version);
updateFencingPolicyContent(version);
updateKSMPolicy(version);
updateMigrateOnError();
updateMigrationOptions();
refreshAdditionalClusterFeaturesList();
}
private void updateKSMPolicy(Version version) {
// enable KSM control from version 3.4
boolean isSmallerThanVersion3_4 = version.compareTo(Version.v3_4) < 0;
getEnableKsm().setIsChangeable(!isSmallerThanVersion3_4);
getEnableKsm().setChangeProhibitionReason(ConstantsManager.getInstance().getConstants().ksmNotAvailable());
// for version 3.3 and lower the default is true.
if (isSmallerThanVersion3_4) {
getEnableKsm().setEntity(true);
}
// allow KSM with NUMA awareness only from version 3.4
boolean isLowerVersionThen3_4 = version.compareTo(Version.v3_4) < 0;
getKsmPolicyForNumaSelection().setIsAvailable(!isLowerVersionThen3_4);
getKsmPolicyForNumaSelection().setChangeProhibitionReason(ConstantsManager.getInstance()
.getConstants()
.ksmWithNumaAwarnessNotAvailable());
// enable NUMA aware KSM by default (matching kernel's default)
setKsmPolicyForNuma(true);
}
private void refreshAdditionalClusterFeaturesList() {
if (getVersion() == null || getVersion().getSelectedItem() == null) {
return;
}
Version version = getVersion().getSelectedItem();
ApplicationMode category = null;
if (getEnableGlusterService().getEntity() && getEnableOvirtService().getEntity()) {
category = ApplicationMode.AllModes;
} else if (getEnableGlusterService().getEntity()) {
category = ApplicationMode.GlusterOnly;
} else if (getEnableOvirtService().getEntity()) {
category = ApplicationMode.VirtOnly;
}
AsyncQuery asyncQuery = new AsyncQuery();
asyncQuery.setModel(this);
// Get all the addtional features avaivalble for the cluster
asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
ClusterModel.this.stopProgress();
final Set<AdditionalFeature> features = (Set<AdditionalFeature>) result;
// Get the additional features which are already enabled for cluster. Applicable only in case of edit
// cluster
if (getIsEdit() && !features.isEmpty()) {
AsyncQuery asyncQuery = new AsyncQuery();
asyncQuery.setModel(this);
asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object returnValue) {
ClusterModel.this.stopProgress();
Set<SupportedAdditionalClusterFeature> clusterFeatures =
(Set<SupportedAdditionalClusterFeature>) returnValue;
Set<AdditionalFeature> featuresEnabled = new HashSet<>();
for (SupportedAdditionalClusterFeature feature : clusterFeatures) {
if (feature.isEnabled()) {
featuresEnabled.add(feature.getFeature());
}
}
updateAddtionClusterFeatureList(features, featuresEnabled);
}
};
ClusterModel.this.startProgress(null);
AsyncDataProvider.getInstance().getClusterFeaturesByClusterId(asyncQuery, getEntity().getId());
} else {
updateAddtionClusterFeatureList(features,
Collections.<AdditionalFeature> emptySet());
}
}
};
this.startProgress(null);
AsyncDataProvider.getInstance().getClusterFeaturesByVersionAndCategory(asyncQuery, version, category);
}
private void updateAddtionClusterFeatureList(Set<AdditionalFeature> featuresAvailable,
Set<AdditionalFeature> featuresEnabled) {
List<AdditionalFeature> features = new ArrayList<>();
List<AdditionalFeature> selectedFeatures = new ArrayList<>();
for (AdditionalFeature feature : featuresAvailable) {
features.add(feature);
if (featuresEnabled.contains(feature)) {
selectedFeatures.add(feature);
}
}
List<List<AdditionalFeature>> clusterFeatureList = new ArrayList<>();
clusterFeatureList.add(features);
getAdditionalClusterFeatures().setItems(clusterFeatureList, selectedFeatures);
}
private void updateMigrationOptions() {
Version version = getVersion().getSelectedItem();
if (version == null) {
return;
}
autoConverge.updateChangeability(ConfigurationValues.AutoConvergenceSupported, version);
migrateCompressed.updateChangeability(ConfigurationValues.MigrationCompressionSupported, version);
}
private void updateMigrateOnError() {
ServerCpu cpu = getCPU().getSelectedItem();
Version version = getVersion().getSelectedItem();
if (version == null) {
return;
}
if (cpu == null || cpu.getArchitecture() == null) {
return;
}
getMigrateOnErrorOption_NO().setIsAvailable(true);
if (AsyncDataProvider.getInstance().isMigrationSupported(cpu.getArchitecture(), version)) {
getMigrateOnErrorOption_YES().setIsAvailable(true);
getMigrateOnErrorOption_HA_ONLY().setIsAvailable(true);
} else {
getMigrateOnErrorOption_YES().setIsAvailable(false);
getMigrateOnErrorOption_HA_ONLY().setIsAvailable(false);
setMigrateOnErrorOption(MigrateOnErrorOptions.NO);
}
}
private void setRngSourcesCheckboxes(Version ver) {
boolean rngSupported = isRngSupportedForClusterVersion(ver);
getRngRandomSourceRequired().setIsChangeable(rngSupported);
getRngHwrngSourceRequired().setIsChangeable(rngSupported);
String defaultRequiredRngSourcesCsv = defaultClusterRngSourcesCsv(ver);
if (rngSupported) {
getRngRandomSourceRequired().setEntity(getIsNew()
? defaultRequiredRngSourcesCsv.contains(VmRngDevice.Source.RANDOM.name().toLowerCase())
: getEntity().getRequiredRngSources().contains(VmRngDevice.Source.RANDOM));
getRngHwrngSourceRequired().setEntity(getIsNew()
? defaultRequiredRngSourcesCsv.contains(VmRngDevice.Source.HWRNG.name().toLowerCase())
: getEntity().getRequiredRngSources().contains(VmRngDevice.Source.HWRNG));
} else { // reset
getRngRandomSourceRequired().setEntity(false);
getRngHwrngSourceRequired().setEntity(false);
getRngRandomSourceRequired().setChangeProhibitionReason(ConstantsManager.getInstance().getConstants().rngNotSupportedByClusterCV());
getRngHwrngSourceRequired().setChangeProhibitionReason(ConstantsManager.getInstance().getConstants().rngNotSupportedByClusterCV());
}
}
private void updateFencingPolicyContent(Version ver) {
// skipFencingIfConnectivityBroken option is enabled when fencing is enabled for all cluster versions
getSkipFencingIfConnectivityBrokenEnabled().setIsChangeable(getFencingEnabledModel().getEntity());
getHostsWithBrokenConnectivityThreshold().setIsChangeable(getFencingEnabledModel().getEntity());
if (ver == null) {
if (!getFencingEnabledModel().getEntity()) {
// fencing is disabled and cluster version not selected yet, so disable skipFencingIfSDActive
getSkipFencingIfSDActiveEnabled().setIsChangeable(false);
}
} else {
// skipFencingIfSDActive is enabled for supported cluster level if fencing is not disabled
boolean supported = AsyncDataProvider.getInstance().isSkipFencingIfSDActiveSupported(ver.getValue());
getSkipFencingIfSDActiveEnabled().setIsChangeable(
supported && getFencingEnabledModel().getEntity());
if (supported) {
if (getEntity() == null) {
// this can happen when creating new cluster and cluster dialog is shown
getSkipFencingIfSDActiveEnabled().setEntity(true);
} else {
getSkipFencingIfSDActiveEnabled().setEntity(
getEntity().getFencingPolicy().isSkipFencingIfSDActive());
}
} else {
getSkipFencingIfSDActiveEnabled().setEntity(false);
}
}
}
private void populateCPUList(ClusterModel clusterModel, List<ServerCpu> cpus, boolean canChangeArchitecture) {
// disable CPU Architecture-Type filtering
getArchitecture().getSelectedItemChangedEvent().removeListener(this);
ServerCpu oldSelectedCpu = clusterModel.getCPU().getSelectedItem();
ArchitectureType oldSelectedArch = clusterModel.getArchitecture().getSelectedItem();
clusterModel.getCPU().setItems(cpus);
initSupportedArchitectures(clusterModel);
clusterModel.getCPU().setSelectedItem(oldSelectedCpu != null ?
Linq.firstOrDefault(cpus, new Linq.ServerCpuPredicate(oldSelectedCpu.getCpuName())) : null);
if (clusterModel.getCPU().getSelectedItem() == null || !isCPUinitialized) {
initCPU();
}
if (clusterModel.getIsEdit()) {
if (!canChangeArchitecture) {
getArchitecture().setItems(new ArrayList<ArchitectureType>(
Arrays.asList(clusterModel.getEntity().getArchitecture())));
}
if (oldSelectedArch != null) {
getArchitecture().setSelectedItem(oldSelectedArch);
} else {
if (clusterModel.getEntity() != null) {
getArchitecture().setSelectedItem(clusterModel.getEntity().getArchitecture());
} else {
getArchitecture().setSelectedItem(ArchitectureType.undefined);
}
}
} else {
getArchitecture().setSelectedItem(ArchitectureType.undefined);
}
// enable CPU Architecture-Type filtering
initCpuArchTypeFiltering();
}
private void initCpuArchTypeFiltering() {
filterCpuTypeByArchitecture();
getArchitecture().getSelectedItemChangedEvent().addListener(this);
}
private void initSupportedArchitectures(ClusterModel clusterModel) {
Collection<ArchitectureType> archsWithSupportingCpus = new HashSet<ArchitectureType>();
archsWithSupportingCpus.add(ArchitectureType.undefined);
for (ServerCpu cpu: clusterModel.getCPU().getItems()) {
archsWithSupportingCpus.add(cpu.getArchitecture());
}
clusterModel.getArchitecture().setItems(archsWithSupportingCpus);
}
private void initCPU() {
if (!isCPUinitialized && getIsEdit()) {
isCPUinitialized = true;
getCPU().setSelectedItem(null);
for (ServerCpu a : getCPU().getItems()) {
if (ObjectUtils.objectsEqual(a.getCpuName(), getEntity().getCpuName())) {
getCPU().setSelectedItem(a);
break;
}
}
}
}
private void initHostsWithBrokenConnectivityThreshold() {
ArrayList<Integer> values = new ArrayList<Integer>();
// populating threshold values with {25, 50, 75, 100}
for (int i = 25; i <= 100; i += 25) {
values.add(i);
}
getHostsWithBrokenConnectivityThreshold().setItems(values);
getHostsWithBrokenConnectivityThreshold().setSelectedItem(50);
}
private void storagePool_SelectedItemChanged(EventArgs e) {
// possible versions for new cluster (when editing cluster, this event won't occur)
// are actually the possible versions for the data-center that the cluster is going
// to be attached to.
final StoragePool selectedDataCenter = getDataCenter().getSelectedItem();
if (selectedDataCenter == null) {
getManagementNetwork().setItems(Collections.<Network>emptyList());
return;
}
if (selectedDataCenter.isLocal()) {
setIsResiliencePolicyTabAvailable(false);
}
else {
setIsResiliencePolicyTabAvailable(true);
}
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object result) {
ClusterModel clusterModel = (ClusterModel) model;
ArrayList<Version> versions = (ArrayList<Version>) result;
Version selectedVersion = clusterModel.getVersion().getSelectedItem();
clusterModel.getVersion().setItems(versions);
if (selectedVersion == null ||
!versions.contains(selectedVersion) ||
selectedVersion.compareTo(selectedDataCenter.getCompatibilityVersion()) > 0) {
if(ApplicationModeHelper.getUiMode().equals(ApplicationMode.GlusterOnly)){
clusterModel.getVersion().setSelectedItem(Linq.selectHighestVersion(versions));
}
else {
clusterModel.getVersion().setSelectedItem(selectedDataCenter.getCompatibilityVersion());
}
}
else if (clusterModel.getIsEdit()) {
clusterModel.getVersion().setSelectedItem(Linq.firstOrDefault(versions,
new Linq.VersionPredicate(clusterModel.getEntity().getCompatibilityVersion())));
}
else {
clusterModel.getVersion().setSelectedItem(selectedVersion);
}
}
};
AsyncDataProvider.getInstance().getDataCenterVersions(_asyncQuery, selectedDataCenter.getId());
if (getManagementNetwork().getIsChangable()) {
loadDcNetworks(selectedDataCenter.getId());
}
}
private void clusterPolicyChanged() {
ClusterPolicy clusterPolicy = getClusterPolicy().getSelectedItem();
Map<String, String> policyProperties = new HashMap<String, String>();
Map<Guid, PolicyUnit> allPolicyUnits = new HashMap<Guid, PolicyUnit>();
if (clusterPolicy.getFilters() != null) {
for (Guid policyUnitId : clusterPolicy.getFilters()) {
allPolicyUnits.put(policyUnitId, policyUnitMap.get(policyUnitId));
}
}
if (clusterPolicy.getFunctions() != null) {
for (Pair<Guid, Integer> pair : clusterPolicy.getFunctions()) {
allPolicyUnits.put(pair.getFirst(), policyUnitMap.get(pair.getFirst()));
}
}
if (clusterPolicy.getBalance() != null) {
allPolicyUnits.put(clusterPolicy.getBalance(), policyUnitMap.get(clusterPolicy.getBalance()));
}
for (PolicyUnit policyUnit : allPolicyUnits.values()) {
if (policyUnit.getParameterRegExMap() != null) {
policyProperties.putAll(policyUnit.getParameterRegExMap());
}
}
getCustomPropertySheet().setKeyValueMap(policyProperties);
if (getIsEdit() &&
clusterPolicy.getId().equals(getEntity().getClusterPolicyId())) {
getCustomPropertySheet().deserialize(KeyValueModel.convertProperties(getEntity().getClusterPolicyProperties()));
} else {
getCustomPropertySheet().deserialize(KeyValueModel.convertProperties(clusterPolicy.getParameterMap()));
}
}
public boolean validate(boolean validateCpu) {
return validate(true, validateCpu, true);
}
public boolean validate(boolean validateStoragePool, boolean validateCpu, boolean validateCustomProperties) {
getName().validateEntity(new IValidation[] {
new NotEmptyValidation(),
new LengthValidation(40),
new I18NNameValidation() });
if (validateStoragePool) {
getDataCenter().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
}
if (validateCpu) {
getCPU().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
}
else {
getCPU().validateSelectedItem(new IValidation[] {});
}
if (validateCustomProperties) {
getCustomPropertySheet().setIsValid(getCustomPropertySheet().validate());
}
setValidTab(TabName.CLUSTER_POLICY_TAB, getCustomPropertySheet().getIsValid());
getVersion().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
getManagementNetwork().validateSelectedItem(new IValidation[] { new NotEmptyValidation() });
validateRngRequiredSource();
boolean validService = true;
if (getEnableOvirtService().getIsAvailable() && getEnableGlusterService().getIsAvailable()) {
validService = getEnableOvirtService().getEntity()
|| getEnableGlusterService().getEntity();
}
getGlusterHostAddress().validateEntity(new IValidation[] { new NotEmptyValidation() });
getGlusterHostPassword().validateEntity(new IValidation[] { new NotEmptyValidation() });
if (!validService) {
setMessage(ConstantsManager.getInstance().getConstants().clusterServiceValidationMsg());
}
else if (getIsImportGlusterConfiguration().getEntity() && getGlusterHostAddress().getIsValid()
&& getGlusterHostPassword().getIsValid()
&& !isFingerprintVerified()) {
setMessage(ConstantsManager.getInstance().getConstants().fingerprintNotVerified());
}
else {
setMessage(null);
}
if (getSpiceProxyEnabled().getEntity()) {
getSpiceProxy().validateEntity(new IValidation[] { new HostWithProtocolAndPortAddressValidation() });
} else {
getSpiceProxy().setIsValid(true);
}
setValidTab(TabName.CONSOLE_TAB, getSpiceProxy().getIsValid());
if (getSerialNumberPolicy().getSelectedSerialNumberPolicy() == SerialNumberPolicy.CUSTOM) {
getSerialNumberPolicy().getCustomSerialNumber().validateEntity(new IValidation[] { new NotEmptyValidation() });
} else {
getSerialNumberPolicy().getCustomSerialNumber().setIsValid(true);
}
boolean generalTabValid = getName().getIsValid() && getDataCenter().getIsValid() && getCPU().getIsValid()
&& getManagementNetwork().getIsValid()
&& getVersion().getIsValid() && validService && getGlusterHostAddress().getIsValid()
&& getRngRandomSourceRequired().getIsValid()
&& getRngHwrngSourceRequired().getIsValid()
&& getGlusterHostPassword().getIsValid()
&& (getIsImportGlusterConfiguration().getEntity() ? (getGlusterHostAddress().getIsValid()
&& getGlusterHostPassword().getIsValid()
&& getSerialNumberPolicy().getCustomSerialNumber().getIsValid()
&& isFingerprintVerified()) : true);
setValidTab(TabName.GENERAL_TAB, generalTabValid);
ValidationCompleteEvent.fire(getEventBus(), this);
return generalTabValid && getCustomPropertySheet().getIsValid() && getSpiceProxy().getIsValid();
}
private void validateRngRequiredSource() {
Version clusterVersion = getVersion().getSelectedItem();
boolean rngSupportedForCluster = isRngSupportedForClusterVersion(clusterVersion);
getRngRandomSourceRequired().setIsValid(rngSupportedForCluster || !getRngRandomSourceRequired().getEntity());
getRngHwrngSourceRequired().setIsValid(rngSupportedForCluster || !getRngHwrngSourceRequired().getEntity());
}
private boolean isRngSupportedForClusterVersion(Version version) {
if (version == null) {
return false;
}
Boolean supported = (Boolean) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.VirtIoRngDeviceSupported, version.toString());
return (supported == null)
? false
: supported;
}
private String defaultClusterRngSourcesCsv(Version ver) {
String srcs = (String) AsyncDataProvider.getInstance().getConfigValuePreConverted(ConfigurationValues.ClusterRequiredRngSourcesDefault, ver.toString());
return (srcs == null)
? ""
: srcs;
}
public boolean getKsmPolicyForNuma() {
switch (getKsmPolicyForNumaSelection().getSelectedItem()) {
case shareAcrossNumaNodes:
return true;
case shareInsideEachNumaNode:
return false;
}
return true;
}
public void setKsmPolicyForNuma(Boolean ksmPolicyForNumaFlag) {
if (ksmPolicyForNumaFlag == null)
return;
KsmPolicyForNuma ksmPolicyForNuma = KsmPolicyForNuma.shareAcrossNumaNodes;
if (ksmPolicyForNumaFlag == false)
ksmPolicyForNuma = KsmPolicyForNuma.shareInsideEachNumaNode;
getKsmPolicyForNumaSelection().setSelectedItem(ksmPolicyForNuma);
return;
}
public enum KsmPolicyForNuma {
shareAcrossNumaNodes(ConstantsManager.getInstance().getConstants().shareKsmAcrossNumaNodes()),
shareInsideEachNumaNode(ConstantsManager.getInstance().getConstants().shareKsmInsideEachNumaNode());
private String description;
private KsmPolicyForNuma(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
}
|
package io.spine.examples.todolist.client;
import io.spine.examples.todolist.LabelId;
import io.spine.examples.todolist.TaskId;
import io.spine.examples.todolist.c.commands.CreateBasicLabel;
import io.spine.examples.todolist.c.commands.CreateBasicTask;
import io.spine.examples.todolist.c.commands.CreateDraft;
import io.spine.examples.todolist.client.builder.CommandBuilder;
import io.spine.examples.todolist.context.BoundedContexts;
import io.spine.examples.todolist.q.projection.LabelledTasksView;
import io.spine.examples.todolist.server.Server;
import io.spine.server.BoundedContext;
import io.spine.server.ServerEnvironment;
import io.spine.server.delivery.InProcessSharding;
import io.spine.server.delivery.Sharding;
import io.spine.server.transport.memory.InMemoryTransportFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static io.spine.Identifier.newUuid;
import static io.spine.client.ConnectionConstants.DEFAULT_CLIENT_SERVICE_PORT;
import static io.spine.examples.todolist.client.TodoClientImpl.HOST;
import static io.spine.examples.todolist.server.Server.newServer;
import static io.spine.examples.todolist.testdata.Given.newDescription;
import static io.spine.examples.todolist.testdata.TestLabelCommandFactory.LABEL_TITLE;
import static io.spine.examples.todolist.testdata.TestTaskCommandFactory.DESCRIPTION;
import static io.spine.util.Exceptions.illegalStateWithCauseOf;
/**
* @author Illia Shepilov
*/
abstract class TodoClientTest {
static final String UPDATED_TASK_DESCRIPTION = "Updated.";
static final int PORT = DEFAULT_CLIENT_SERVICE_PORT;
private Server server;
private TodoClient client;
@BeforeEach
void setUp() throws InterruptedException {
final BoundedContext boundedContext = BoundedContexts.create();
server = newServer(PORT, boundedContext);
startServer();
client = TodoClient.instance(HOST, PORT);
}
@AfterEach
public void tearDown() {
server.shutdown();
getClient().shutdown();
final Sharding sharding = new InProcessSharding(InMemoryTransportFactory.newInstance());
ServerEnvironment.getInstance()
.replaceSharding(sharding);
}
private void startServer() throws InterruptedException {
final CountDownLatch serverStartLatch = new CountDownLatch(1);
final Thread serverThread = new Thread(() -> {
try {
server.start();
serverStartLatch.countDown();
} catch (IOException e) {
throw illegalStateWithCauseOf(e);
}
});
serverThread.start();
serverStartLatch.await(100, TimeUnit.MILLISECONDS);
}
static CreateBasicLabel createBasicLabel() {
return CommandBuilder.label()
.createLabel()
.setTitle(LABEL_TITLE)
.build();
}
static CreateDraft createDraft() {
return CommandBuilder.task()
.createDraft()
.build();
}
static CreateBasicTask createBasicTask() {
return CommandBuilder.task()
.createTask()
.setDescription(newDescription(DESCRIPTION))
.build();
}
static TaskId createWrongTaskId() {
return TaskId.newBuilder()
.setValue(newUuid())
.build();
}
static LabelId createWrongTaskLabelId() {
return LabelId.newBuilder()
.setValue(newUuid())
.build();
}
static LabelledTasksView getLabelledTasksView(List<LabelledTasksView> tasksViewList) {
LabelledTasksView result = LabelledTasksView.getDefaultInstance();
for (LabelledTasksView labelledView : tasksViewList) {
final boolean isEmpty = labelledView.getLabelId()
.getValue()
.isEmpty();
if (!isEmpty) {
result = labelledView;
}
}
return result;
}
CreateBasicTask createTask() {
final CreateBasicTask createTask = createBasicTask();
getClient().postCommand(createTask);
return createTask;
}
CreateBasicLabel createLabel() {
final CreateBasicLabel createLabel = createBasicLabel();
getClient().postCommand(createLabel);
return createLabel;
}
public TodoClient getClient() {
return client;
}
}
|
package org.springframework.ide.vscode.commons.java;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BootProjectUtil {
public static final Logger log = LoggerFactory.getLogger(BootProjectUtil.class);
public static boolean isBootProject(IJavaProject jp) {
try {
IClasspath cp = jp.getClasspath();
if (cp!=null) {
return IClasspathUtil.getBinaryRoots(cp, (cpe) -> !cpe.isSystem()).stream().anyMatch(cpe -> isBootEntry(cpe));
}
} catch (Exception e) {
log.error("Failed to determine whether '" + jp.getElementName() + "' is Spring Boot project", e);
}
return false;
}
private static boolean isBootEntry(File cpe) {
String name = cpe.getName();
return name.endsWith(".jar") && name.startsWith("spring-boot");
}
public static Path javaHomeFromLibJar(Path libJar) {
for (Path home = libJar; home.getParent() != null; home = home.getParent()) {
if (Files.exists(home.resolve("release")) || Files.exists(home.resolve("release.txt"))) {
return home;
}
}
return null;
}
public static Path jreSources(Path libJar) {
System.out.println("Lib JAR: " + libJar);
Path home = javaHomeFromLibJar(libJar);
if (home != null) {
Path sources = home.resolve("src.zip");
System.out.println("Trying " + sources);
if (Files.exists(sources)) {
System.out.println("Found " + sources);
return sources;
}
sources = home.resolve("lib/src.zip");
System.out.println("Trying " + sources);
if (Files.exists(sources)) {
System.out.println("Found " + sources);
return sources;
}
}
return null;
}
}
|
package com.newsblur.fragment;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.Toast;
import com.newsblur.R;
import com.newsblur.activity.AllStoriesItemsList;
import com.newsblur.activity.FeedItemsList;
import com.newsblur.activity.ItemsList;
import com.newsblur.activity.NewsBlurApplication;
import com.newsblur.activity.SavedStoriesItemsList;
import com.newsblur.activity.SocialFeedItemsList;
import com.newsblur.database.DatabaseConstants;
import com.newsblur.database.FeedProvider;
import com.newsblur.database.MixedExpandableListAdapter;
import com.newsblur.network.APIManager;
import com.newsblur.network.MarkFeedAsReadTask;
import com.newsblur.network.MarkFolderAsReadTask;
import com.newsblur.util.AppConstants;
import com.newsblur.util.ImageLoader;
import com.newsblur.util.PrefConstants;
import com.newsblur.util.UIUtils;
import com.newsblur.view.FolderTreeViewBinder;
import com.newsblur.view.SocialFeedViewBinder;
public class FolderListFragment extends Fragment implements OnGroupClickListener, OnChildClickListener, OnCreateContextMenuListener {
private ContentResolver resolver;
private MixedExpandableListAdapter folderAdapter;
private FolderTreeViewBinder groupViewBinder;
private APIManager apiManager;
private int currentState = AppConstants.STATE_SOME;
private SocialFeedViewBinder blogViewBinder;
private SharedPreferences sharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// all cursors are initially queried in the "some" unread state to match the default view mode
Cursor folderCursor = resolver.query(FeedProvider.FOLDERS_URI, null, null, new String[] { DatabaseConstants.getFolderSelectionFromState(AppConstants.STATE_SOME) }, null);
Cursor socialFeedCursor = resolver.query(FeedProvider.SOCIAL_FEEDS_URI, null, DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME), null, null);
Cursor countCursor = resolver.query(FeedProvider.FEED_COUNT_URI, null, DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME), null, null);
Cursor sharedCountCursor = resolver.query(FeedProvider.SOCIALCOUNT_URI, null, DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME), null, null);
Cursor savedCountCursor = resolver.query(FeedProvider.STARRED_STORIES_COUNT_URI, null, null, null, null);
ImageLoader imageLoader = ((NewsBlurApplication) getActivity().getApplicationContext()).getImageLoader();
groupViewBinder = new FolderTreeViewBinder(imageLoader);
blogViewBinder = new SocialFeedViewBinder(getActivity());
folderAdapter = new MixedExpandableListAdapter(getActivity(), folderCursor, socialFeedCursor, countCursor, sharedCountCursor, savedCountCursor);
folderAdapter.setViewBinders(groupViewBinder, blogViewBinder);
}
@Override
public void onAttach(Activity activity) {
sharedPreferences = activity.getSharedPreferences(PrefConstants.PREFERENCES, 0);
resolver = activity.getContentResolver();
apiManager = new APIManager(activity);
super.onAttach(activity);
}
@Override
public void onStart() {
super.onStart();
hasUpdated();
}
public void hasUpdated() {
folderAdapter.notifyDataSetChanged();
checkOpenFolderPreferences();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_folderfeedlist, container);
ExpandableListView list = (ExpandableListView) v.findViewById(R.id.folderfeed_list);
list.setGroupIndicator(getResources().getDrawable(R.drawable.transparent));
list.setOnCreateContextMenuListener(this);
Display display = getActivity().getWindowManager().getDefaultDisplay();
list.setIndicatorBounds(
display.getWidth() - UIUtils.convertDPsToPixels(getActivity(), 20),
display.getWidth() - UIUtils.convertDPsToPixels(getActivity(), 10));
list.setChildDivider(getActivity().getResources().getDrawable(R.drawable.divider_light));
list.setAdapter(folderAdapter);
list.setOnGroupClickListener(this);
list.setOnChildClickListener(this);
return v;
}
private ExpandableListView getListView() {
return (ExpandableListView) (this.getView().findViewById(R.id.folderfeed_list));
}
public void checkOpenFolderPreferences() {
if (sharedPreferences == null) {
sharedPreferences = getActivity().getSharedPreferences(PrefConstants.PREFERENCES, 0);
}
for (int i = 0; i < folderAdapter.getGroupCount(); i++) {
String groupName = folderAdapter.getGroupName(i);
if (sharedPreferences.getBoolean(AppConstants.FOLDER_PRE + "_" + groupName, true)) {
this.getListView().expandGroup(i);
} else {
this.getListView().collapseGroup(i);
}
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
MenuInflater inflater = getActivity().getMenuInflater();
ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo;
int type = ExpandableListView.getPackedPositionType(info.packedPosition);
switch(type) {
case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition);
if (! folderAdapter.isRowSavedStories(groupPosition) ) {
inflater.inflate(R.menu.context_folder, menu);
}
break;
case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
inflater.inflate(R.menu.context_feed, menu);
break;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
if (item.getItemId() == R.id.menu_mark_feed_as_read) {
new MarkFeedAsReadTask(getActivity(), apiManager) {
@Override
protected void onPostExecute(Boolean result) {
if (result.booleanValue()) {
ContentValues values = new ContentValues();
values.put(DatabaseConstants.FEED_NEGATIVE_COUNT, 0);
values.put(DatabaseConstants.FEED_NEUTRAL_COUNT, 0);
values.put(DatabaseConstants.FEED_POSITIVE_COUNT, 0);
resolver.update(FeedProvider.FEEDS_URI.buildUpon().appendPath(Long.toString(info.id)).build(), values, null, null);
folderAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), R.string.toast_marked_feed_as_read, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_LONG).show();
}
}
}.execute(Long.toString(info.id));
return true;
} else if (item.getItemId() == R.id.menu_delete_feed) {
int childPosition = ExpandableListView.getPackedPositionChild(info.packedPosition);
int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition);
Cursor childCursor = folderAdapter.getChild(groupPosition, childPosition);
String feedTitle = childCursor.getString(childCursor.getColumnIndex(DatabaseConstants.FEED_TITLE));
// TODO: is there a better way to map group position onto folderName than asking the list adapter?
Cursor folderCursor = ((MixedExpandableListAdapter) this.getListView().getExpandableListAdapter()).getGroup(groupPosition);
String folderName = folderCursor.getString(folderCursor.getColumnIndex(DatabaseConstants.FOLDER_NAME));
DialogFragment deleteFeedFragment = DeleteFeedFragment.newInstance(info.id, feedTitle, folderName);
deleteFeedFragment.show(getFragmentManager(), "dialog");
return true;
} else if (item.getItemId() == R.id.menu_mark_folder_as_read) {
int groupPosition = ExpandableListView.getPackedPositionGroup(info.packedPosition);
// all folder but the root All Stories one use the simple method
if (!folderAdapter.isFolderRoot(groupPosition)) {
// TODO: is there a better way to get the folder ID for a group position that asking the list view?
final Cursor folderCursor = ((MixedExpandableListAdapter) this.getListView().getExpandableListAdapter()).getGroup(groupPosition);
String folderId = folderCursor.getString(folderCursor.getColumnIndex(DatabaseConstants.FOLDER_NAME));
new MarkFolderAsReadTask(apiManager, resolver) {
@Override
protected void onPostExecute(Boolean result) {
if (result) {
folderAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), R.string.toast_marked_folder_as_read, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_SHORT).show();
}
}
}.execute(folderId);
} else {
// TODO is social feed actually all shared stories ? Should this be used for expandable and position == 0 ?
/*final Cursor socialFeedCursor = ((MixedExpandableListAdapter) list.getExpandableListAdapter()).getGroup(groupPosition);
String socialFeedId = socialFeedCursor.getString(socialFeedCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_ID));
new MarkSocialFeedAsReadTask(apiManager, resolver){
@Override
protected void onPostExecute(Boolean result) {
if (result.booleanValue()) {
folderAdapter.notifyDataSetChanged();
Toast.makeText(getActivity(), R.string.toast_marked_socialfeed_as_read, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_LONG).show();
}
}
}.execute(socialFeedId);*/
new AsyncTask<Void, Void, Boolean>() {
private List<String> feedIds = new ArrayList<String>();
@Override
protected Boolean doInBackground(Void... arg) {
return apiManager.markAllAsRead();
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
ContentValues values = new ContentValues();
values.put(DatabaseConstants.FEED_NEGATIVE_COUNT, 0);
values.put(DatabaseConstants.FEED_NEUTRAL_COUNT, 0);
values.put(DatabaseConstants.FEED_POSITIVE_COUNT, 0);
resolver.update(FeedProvider.FEEDS_URI, values, null, null);
folderAdapter.notifyDataSetChanged();
UIUtils.safeToast(getActivity(), R.string.toast_marked_all_stories_as_read, Toast.LENGTH_SHORT);
} else {
UIUtils.safeToast(getActivity(), R.string.toast_error_marking_feed_as_read, Toast.LENGTH_SHORT);
}
};
}.execute();
}
return true;
}
return super.onContextItemSelected(item);
}
public void changeState(int state) {
groupViewBinder.setState(state);
blogViewBinder.setState(state);
currentState = state;
String groupSelection = DatabaseConstants.getFolderSelectionFromState(state);
String blogSelection = DatabaseConstants.getBlogSelectionFromState(state);
// the countCursor always counts neutral/"some" unreads, no matter what mode we are in
String countSelection = DatabaseConstants.getBlogSelectionFromState(AppConstants.STATE_SOME);
folderAdapter.currentState = state;
Cursor cursor = resolver.query(FeedProvider.FOLDERS_URI, null, null, new String[] { groupSelection }, null);
Cursor blogCursor = resolver.query(FeedProvider.SOCIAL_FEEDS_URI, null, blogSelection, null, null);
Cursor countCursor = resolver.query(FeedProvider.FEED_COUNT_URI, null, countSelection, null, null);
folderAdapter.setBlogCursor(blogCursor);
folderAdapter.setGroupCursor(cursor);
folderAdapter.setCountCursor(countCursor);
folderAdapter.notifyDataSetChanged();
checkOpenFolderPreferences();
}
@Override
public boolean onGroupClick(ExpandableListView list, View group, int groupPosition, long id) {
// The root "All Stories" folder goes to a special activity
if (folderAdapter.isFolderRoot(groupPosition)) {
Intent i = new Intent(getActivity(), AllStoriesItemsList.class);
i.putExtra(AllStoriesItemsList.EXTRA_STATE, currentState);
startActivity(i);
return true;
} else if (folderAdapter.isRowSavedStories(groupPosition)) {
Intent i = new Intent(getActivity(), SavedStoriesItemsList.class);
startActivity(i);
return true;
} else {
String groupName = folderAdapter.getGroupName(groupPosition);
if (list.isGroupExpanded(groupPosition)) {
group.findViewById(R.id.row_foldersums).setVisibility(View.VISIBLE);
sharedPreferences.edit().putBoolean(AppConstants.FOLDER_PRE + "_" + groupName, false).commit();
} else {
group.findViewById(R.id.row_foldersums).setVisibility(View.INVISIBLE);
sharedPreferences.edit().putBoolean(AppConstants.FOLDER_PRE + "_" + groupName, true).commit();
}
return false;
}
}
@Override
public boolean onChildClick(ExpandableListView list, View childView, int groupPosition, int childPosition, long id) {
if (groupPosition == 0) {
Cursor blurblogCursor = folderAdapter.getBlogCursor(childPosition);
String username = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_USERNAME));
String userIcon = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_ICON));
String userId = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_ID));
String blurblogTitle = blurblogCursor.getString(blurblogCursor.getColumnIndex(DatabaseConstants.SOCIAL_FEED_TITLE));
final Intent intent = new Intent(getActivity(), SocialFeedItemsList.class);
intent.putExtra(ItemsList.EXTRA_BLURBLOG_USER_ICON, userIcon);
intent.putExtra(ItemsList.EXTRA_BLURBLOG_USERNAME, username);
intent.putExtra(ItemsList.EXTRA_BLURBLOG_TITLE, blurblogTitle);
intent.putExtra(ItemsList.EXTRA_BLURBLOG_USERID, userId);
intent.putExtra(ItemsList.EXTRA_STATE, currentState);
getActivity().startActivity(intent);
} else {
final Intent intent = new Intent(getActivity(), FeedItemsList.class);
Cursor childCursor = folderAdapter.getChild(groupPosition, childPosition);
String feedId = childCursor.getString(childCursor.getColumnIndex(DatabaseConstants.FEED_ID));
String feedTitle = childCursor.getString(childCursor.getColumnIndex(DatabaseConstants.FEED_TITLE));
final Cursor folderCursor = ((MixedExpandableListAdapter) list.getExpandableListAdapter()).getGroup(groupPosition);
String folderName = folderCursor.getString(folderCursor.getColumnIndex(DatabaseConstants.FOLDER_NAME));
intent.putExtra(FeedItemsList.EXTRA_FEED, feedId);
intent.putExtra(FeedItemsList.EXTRA_FEED_TITLE, feedTitle);
intent.putExtra(FeedItemsList.EXTRA_FOLDER_NAME, folderName);
intent.putExtra(ItemsList.EXTRA_STATE, currentState);
getActivity().startActivity(intent);
}
return true;
}
}
|
package org.innovateuk.ifs.testdata.services;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.innovateuk.ifs.BaseBuilder;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.ApplicationState;
import org.innovateuk.ifs.application.resource.FundingDecision;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.finance.resource.OrganisationSize;
import org.innovateuk.ifs.finance.resource.cost.AdditionalCompanyCost;
import org.innovateuk.ifs.finance.resource.cost.FinanceRowType;
import org.innovateuk.ifs.finance.resource.cost.KtpTravelCost;
import org.innovateuk.ifs.form.resource.*;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.innovateuk.ifs.testdata.builders.*;
import org.innovateuk.ifs.testdata.builders.data.ApplicationData;
import org.innovateuk.ifs.testdata.builders.data.ApplicationFinanceData;
import org.innovateuk.ifs.testdata.builders.data.ApplicationQuestionResponseData;
import org.innovateuk.ifs.testdata.builders.data.CompetitionData;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.UnaryOperator;
import static java.lang.Boolean.TRUE;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.innovateuk.ifs.finance.resource.OrganisationSize.SMALL;
import static org.innovateuk.ifs.testdata.builders.ApplicationDataBuilder.newApplicationData;
import static org.innovateuk.ifs.testdata.builders.ApplicationFinanceDataBuilder.newApplicationFinanceData;
import static org.innovateuk.ifs.testdata.builders.CompetitionDataBuilder.newCompetitionData;
import static org.innovateuk.ifs.testdata.builders.QuestionResponseDataBuilder.newApplicationQuestionResponseData;
import static org.innovateuk.ifs.testdata.services.CsvUtils.*;
import static org.innovateuk.ifs.util.CollectionFunctions.*;
/**
* A service that {@link org.innovateuk.ifs.testdata.BaseGenerateTestData} uses to generate Application data. While
* {@link org.innovateuk.ifs.testdata.BaseGenerateTestData} is responsible for gathering CSV information and
* orchestarting the building of it, this service is responsible for taking the CSV data passed to it and using
* the appropriate builders to generate and update entities.
*/
@Component
@Lazy
public class ApplicationDataBuilderService extends BaseDataBuilderService {
@Autowired
private GenericApplicationContext applicationContext;
private ApplicationDataBuilder applicationDataBuilder;
private CompetitionDataBuilder competitionDataBuilder;
private ApplicationFinanceDataBuilder applicationFinanceDataBuilder;
private QuestionResponseDataBuilder questionResponseDataBuilder;
@PostConstruct
public void readCsvs() {
ServiceLocator serviceLocator = new ServiceLocator(applicationContext, COMP_ADMIN_EMAIL, PROJECT_FINANCE_EMAIL);
applicationDataBuilder = newApplicationData(serviceLocator);
competitionDataBuilder = newCompetitionData(serviceLocator);
applicationFinanceDataBuilder = newApplicationFinanceData(serviceLocator);
questionResponseDataBuilder = newApplicationQuestionResponseData(serviceLocator);
}
public List<ApplicationQuestionResponseData> createApplicationQuestionResponses(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationQuestionResponseLine> questionResponseLines) {
QuestionResponseDataBuilder baseBuilder =
questionResponseDataBuilder.withApplication(applicationData.getApplication());
if (!applicationLine.createApplicationResponses) {
return emptyList();
}
List<CsvUtils.ApplicationQuestionResponseLine> responsesForApplication =
simpleFilter(questionResponseLines, r ->
r.competitionName.equals(applicationLine.competitionName) &&
r.applicationName.equals(applicationLine.title));
// if we have specific answers for questions in the application-questions.csv file, fill them in here now
if (!responsesForApplication.isEmpty()) {
List<QuestionResponseDataBuilder> responseBuilders = questionResponsesFromCsv(
baseBuilder,
applicationLine.leadApplicant,
responsesForApplication);
return simpleMap(responseBuilders, BaseBuilder::build);
}
// otherwise provide a default set of marked as complete questions if the application is to be submitted
else if (applicationLine.markQuestionsComplete || applicationLine.submittedDate != null) {
Long competitionId = applicationData.getCompetition().getId();
List<QuestionResource> competitionQuestions = retrieveCachedQuestionsByCompetitionId(competitionId);
List<QuestionResource> questionsToAnswer = simpleFilter(competitionQuestions, q ->
!q.getMultipleStatuses() &&
q.getMarkAsCompletedEnabled() &&
q.getQuestionSetupType().hasFormInputResponses());
List<QuestionResponseDataBuilder> responseBuilders = simpleMap(questionsToAnswer, question -> {
String answerValue = "This is the applicant response for " + question.getName().toLowerCase() + ".";
String leadApplicantEmail = applicationData.getLeadApplicant().getEmail();
QuestionResponseDataBuilder responseBuilder = baseBuilder.
forQuestion(question.getName()).
withAssignee(leadApplicantEmail);
List<FormInputResource> formInputs = retrieveCachedFormInputsByQuestionId(question);
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.TEXTAREA))) {
responseBuilder = responseBuilder.withAnswer(answerValue, leadApplicantEmail);
}
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.MULTIPLE_CHOICE))) {
FormInputResource multipleChoice = formInputs.stream().filter(fi -> fi.getType().equals(FormInputType.MULTIPLE_CHOICE)).findFirst().get();
List<MultipleChoiceOptionResource> choices = multipleChoice.getMultipleChoiceOptions();
String applicationName = applicationData.getApplication().getName();
String questionName = question.getName();
//Pick a choice based on the application name and question name. Ensures we have a random choice, but is the same choice each time generator is ran.
int choice = (applicationName + questionName).length() % choices.size();
responseBuilder = responseBuilder.withChoice(choices.get(choice), leadApplicantEmail);
}
if (formInputs.stream().anyMatch(fi -> fi.getScope().equals(FormInputScope.APPLICATION) && fi.getType().equals(FormInputType.FILEUPLOAD))) {
String applicationName = applicationData.getApplication().getName();
String questionName = question.getShortName().toLowerCase();
String fileUploadName = (applicationName + "-" + questionName + ".pdf")
.toLowerCase().replace(' ', '-') ;
responseBuilder = responseBuilder.
withFileUploads(singletonList(fileUploadName), leadApplicantEmail);
}
return responseBuilder;
});
return simpleMap(responseBuilders, BaseBuilder::build);
}
return emptyList();
}
public List<ApplicationFinanceData> createApplicationFinances(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationOrganisationFinanceBlock> applicationFinanceLines,
List<ExternalUserLine> externalUsers) {
if (!applicationLine.createFinanceResponses) {
return emptyList();
}
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
List<String> applicants = combineLists(applicationLine.leadApplicant, applicationLine.collaborators);
List<Triple<String, String, OrganisationTypeEnum>> organisations = simpleMap(applicants, email -> {
UserResource user = retrieveUserByEmail(email);
OrganisationResource organisation = organisationByName(usersOrganisations.get(email));
return Triple.of(user.getEmail(), organisation.getName(),
OrganisationTypeEnum.getFromId(organisation.getOrganisationType()));
});
List<Triple<String, String, OrganisationTypeEnum>> uniqueOrganisations = simpleFilter(organisations, triple ->
isUniqueOrFirstDuplicateOrganisation(triple, organisations));
List<ApplicationFinanceDataBuilder> builders = simpleMap(uniqueOrganisations, orgDetails -> {
String user = orgDetails.getLeft();
String organisationName = orgDetails.getMiddle();
OrganisationTypeEnum organisationType = orgDetails.getRight();
Optional<CsvUtils.ApplicationOrganisationFinanceBlock> organisationFinances =
simpleFindFirst(applicationFinanceLines, finances ->
finances.competitionName.equals(applicationLine.competitionName) &&
finances.applicationName.equals(applicationLine.title) &&
finances.organisationName.equals(organisationName));
if (applicationData.getCompetition().applicantShouldUseJesFinances(organisationType)) {
return organisationFinances.map(suppliedFinances ->
generateAcademicFinancesFromSuppliedData(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName)
).orElseGet(() ->
generateAcademicFinances(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName)
);
} else {
return organisationFinances.map(suppliedFinances ->
generateIndustrialCostsFromSuppliedData(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName,
suppliedFinances)
).orElseGet(() ->
generateIndustrialCosts(
applicationData.getApplication(),
applicationData.getCompetition(),
user,
organisationName,
organisationType)
);
}
});
return simpleMap(builders, BaseBuilder::build);
}
public void completeApplication(
ApplicationData applicationData,
ApplicationLine applicationLine,
List<ApplicationQuestionResponseData> questionResponseData,
List<ApplicationFinanceData> financeData) {
if (applicationLine.markQuestionsComplete) {
forEachWithIndex(questionResponseData, (i, response) -> {
boolean lastElement = i == questionResponseData.size() - 1;
questionResponseDataBuilder.
withExistingResponse(response).
markAsComplete(lastElement).
build();
});
}
if (applicationLine.markFinancesComplete) {
forEachWithIndex(financeData, (i, finance) -> {
boolean lastElement = i == financeData.size() - 1;
applicationFinanceDataBuilder.
withExistingFinances(
finance.getApplication(),
finance.getCompetition(),
finance.getUser(),
finance.getOrganisation()).
markAsComplete(true, lastElement).
build();
});
}
ApplicationDataBuilder applicationBuilder = this.applicationDataBuilder.
withExistingApplication(applicationData).
markApplicationDetailsComplete(applicationLine.markQuestionsComplete).
markEdiComplete(applicationLine.markQuestionsComplete).
markApplicationTeamComplete(applicationLine.markQuestionsComplete).
markResearchCategoryComplete(applicationLine.markQuestionsComplete);
if (applicationLine.submittedDate != null) {
applicationBuilder = applicationBuilder.submitApplication();
}
if (asLinkedSet(ApplicationState.INELIGIBLE, ApplicationState.INELIGIBLE_INFORMED).
contains(applicationLine.status)) {
applicationBuilder = applicationBuilder.markApplicationIneligible(applicationLine.ineligibleReason);
if (applicationLine.status == ApplicationState.INELIGIBLE_INFORMED) {
applicationBuilder = applicationBuilder.informApplicationIneligible();
}
}
applicationBuilder.build();
}
public void createFundingDecisions(
CompetitionData competition,
CompetitionLine competitionLine,
List<ApplicationLine> applicationLines) {
CompetitionDataBuilder basicCompetitionInformation = competitionDataBuilder.withExistingCompetition(competition);
if (!competition.getCompetition().isKtp() && asList(CompetitionStatus.PROJECT_SETUP, CompetitionStatus.ASSESSOR_FEEDBACK).contains(competitionLine.competitionStatus)) {
basicCompetitionInformation.
moveCompetitionIntoFundersPanelStatus().
sendFundingDecisions(createFundingDecisionsFromCsv(competitionLine.name, applicationLines)).
build();
}
}
private List<Pair<String, FundingDecision>> createFundingDecisionsFromCsv(
String competitionName,
List<ApplicationLine> applicationLines) {
List<CsvUtils.ApplicationLine> matchingApplications = simpleFilter(applicationLines, a ->
a.competitionName.equals(competitionName));
List<CsvUtils.ApplicationLine> applicationsWithDecisions = simpleFilter(matchingApplications, a ->
asList(ApplicationState.APPROVED, ApplicationState.REJECTED).contains(a.status));
return simpleMap(applicationsWithDecisions, ma -> {
FundingDecision fundingDecision = ma.status == ApplicationState.APPROVED ? FundingDecision.FUNDED : FundingDecision.UNFUNDED;
return Pair.of(ma.title, fundingDecision);
});
}
private List<QuestionResponseDataBuilder> questionResponsesFromCsv(
QuestionResponseDataBuilder baseBuilder,
String leadApplicant,
List<CsvUtils.ApplicationQuestionResponseLine> responsesForApplication) {
return simpleMap(responsesForApplication, line -> {
String answeringUser = !isBlank(line.answeredBy) ? line.answeredBy : (!isBlank(line.assignedTo) ? line.assignedTo : leadApplicant);
UnaryOperator<QuestionResponseDataBuilder> withQuestion = builder -> builder.forQuestion(line.questionName);
UnaryOperator<QuestionResponseDataBuilder> answerIfNecessary = builder ->
!isBlank(line.value) ? builder.withAssignee(answeringUser).withAnswer(line.value, answeringUser)
: builder;
UnaryOperator<QuestionResponseDataBuilder> uploadFilesIfNecessary = builder ->
!line.filesUploaded.isEmpty() ?
builder.withAssignee(answeringUser).withFileUploads(line.filesUploaded, answeringUser) :
builder;
UnaryOperator<QuestionResponseDataBuilder> assignIfNecessary = builder ->
!isBlank(line.assignedTo) ? builder.withAssignee(line.assignedTo) : builder;
return withQuestion.
andThen(answerIfNecessary).
andThen(uploadFilesIfNecessary).
andThen(assignIfNecessary).
apply(baseBuilder);
});
}
public ApplicationData createApplication(
CompetitionData competition,
ApplicationLine line,
List<InviteLine> inviteLines,
List<ExternalUserLine> externalUsers) {
UserResource leadApplicant = retrieveUserByEmail(line.leadApplicant);
Map<String, String> usersOrganisations = simpleToMap(externalUsers, user -> user.emailAddress, user -> user.organisationName);
Organisation org = organisationRepository.findOneByName(usersOrganisations.get(line.leadApplicant));
ApplicationDataBuilder baseBuilder = applicationDataBuilder.withCompetition(competition.getCompetition()).
withBasicDetails(leadApplicant, line.title, line.researchCategory, line.resubmission, org.getId()).
withInnovationArea(line.innovationArea).
withStartDate(line.startDate).
withDurationInMonths(line.durationInMonths);
for (String collaborator : line.collaborators) {
baseBuilder = baseBuilder.inviteCollaborator(retrieveUserByEmail(collaborator), organisationRepository.findOneByName(usersOrganisations.get(collaborator)));
}
if (competition.getCompetition().isKtp() && line.submittedDate != null) {
baseBuilder = baseBuilder.inviteKta();
}
List<CsvUtils.InviteLine> pendingInvites = simpleFilter(inviteLines,
invite -> "APPLICATION".equals(invite.type) && line.title.equals(invite.targetName));
for (CsvUtils.InviteLine invite : pendingInvites) {
baseBuilder = baseBuilder.inviteCollaboratorNotYetRegistered(invite.email, invite.hash, invite.name,
invite.ownerName);
}
if (line.status != ApplicationState.CREATED) {
baseBuilder = baseBuilder.beginApplication();
}
return baseBuilder.build();
}
private boolean isUniqueOrFirstDuplicateOrganisation(
Triple<String, String, OrganisationTypeEnum> currentOrganisation,
List<Triple<String, String, OrganisationTypeEnum>> organisationList) {
Triple<String, String, OrganisationTypeEnum> matchingRecord = simpleFindFirstMandatory(organisationList, triple ->
triple.getMiddle().equals(currentOrganisation.getMiddle()));
return matchingRecord.equals(currentOrganisation);
}
private IndustrialCostDataBuilder addFinanceRow(
IndustrialCostDataBuilder builder,
CsvUtils.ApplicationFinanceRow financeRow) {
switch (financeRow.category) {
case "Working days per year":
return builder.withWorkingDaysPerYear(Integer.valueOf(financeRow.metadata.get(0)));
case "Grant claim":
return builder.withGrantClaim(BigDecimal.valueOf(Integer.valueOf(financeRow.metadata.get(0))));
case "Organisation size":
return builder.withOrganisationSize(OrganisationSize.findById(Long.valueOf(financeRow.metadata.get(0))));
case "Work postcode":
return builder.withWorkPostcode(financeRow.metadata.get(0));
case "Labour":
return builder.withLabourEntry(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Overheads":
switch (financeRow.metadata.get(0).toLowerCase()) {
case "total":
return builder.withAdministrationSupportCostsTotalRate(
Integer.valueOf(financeRow.metadata.get(1)));
case "default":
return builder.withAdministrationSupportCostsDefaultRate();
case "none":
return builder.withAdministrationSupportCostsNone();
default:
throw new RuntimeException("Unknown rate type " + financeRow.metadata.get(0).toLowerCase());
}
case "Materials":
return builder.withMaterials(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)),
Integer.valueOf(financeRow.metadata.get(2)));
case "Capital usage":
return builder.withCapitalUsage(
Integer.valueOf(financeRow.metadata.get(4)),
financeRow.metadata.get(0),
Boolean.parseBoolean(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)),
bd(financeRow.metadata.get(3)),
Integer.valueOf(financeRow.metadata.get(5)));
case "Subcontracting":
return builder.withSubcontractingCost(
financeRow.metadata.get(0),
financeRow.metadata.get(1),
financeRow.metadata.get(2),
bd(financeRow.metadata.get(3)));
case "Travel and subsistence":
return builder.withTravelAndSubsistence(
financeRow.metadata.get(0),
Integer.valueOf(financeRow.metadata.get(1)),
bd(financeRow.metadata.get(2)));
case "Other costs":
return builder.withOtherCosts(
financeRow.metadata.get(0),
bd(financeRow.metadata.get(1)));
case "Other funding":
return builder.withOtherFunding(
financeRow.metadata.get(0),
LocalDate.parse(financeRow.metadata.get(1), DATE_PATTERN),
bd(financeRow.metadata.get(2)));
default:
throw new RuntimeException("Unknown category " + financeRow.category);
}
}
private ApplicationFinanceDataBuilder generateIndustrialCostsFromSuppliedData(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName,
CsvUtils.ApplicationOrganisationFinanceBlock organisationFinances) {
ApplicationFinanceDataBuilder finance = this.applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user);
List<CsvUtils.ApplicationFinanceRow> financeRows = organisationFinances.rows;
UnaryOperator<IndustrialCostDataBuilder> costBuilder = costs -> {
IndustrialCostDataBuilder costsWithData = costs;
for (CsvUtils.ApplicationFinanceRow financeRow : financeRows) {
costsWithData = addFinanceRow(costsWithData, financeRow);
}
return costsWithData;
};
return finance.
withIndustrialCosts(costBuilder);
}
private ApplicationFinanceDataBuilder generateIndustrialCosts(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName,
OrganisationTypeEnum organisationType) {
UnaryOperator<IndustrialCostDataBuilder> costBuilder = costs -> {
final IndustrialCostDataBuilder[] builder = {costs};
Consumer<? super FinanceRowType> costPopulator = type -> {
switch(type) {
case LABOUR:
builder[0] = builder[0].withWorkingDaysPerYear(123).
withLabourEntry("Role 1", 200, 200).
withLabourEntry("Role 2", 400, 300).
withLabourEntry("Role 3", 600, 365);
break;
case OVERHEADS:
builder[0] = builder[0].withAdministrationSupportCostsNone();
break;
case PROCUREMENT_OVERHEADS:
builder[0] = builder[0].withProcurementOverheads("procurement overhead" , 1000, 2000);
break;
case MATERIALS:
builder[0] = builder[0].withMaterials("Generator", bd("10020"), 10);
break;
case CAPITAL_USAGE:
builder[0] = builder[0].withCapitalUsage(12, "Depreciating Stuff", true, bd("2120"), bd("1200"), 60);
break;
case SUBCONTRACTING_COSTS:
builder[0] = builder[0].withSubcontractingCost("Developers", "UK", "To develop stuff", bd("90000"));
break;
case TRAVEL:
builder[0] = builder[0].withTravelAndSubsistence("To visit colleagues", 15, bd("398"));
break;
case OTHER_COSTS:
builder[0] = builder[0].withOtherCosts("Some more costs", bd("1100"));
break;
case VAT:
builder[0] = builder[0].withVat(true);
break;
case FINANCE:
builder[0] = builder[0].withGrantClaim(BigDecimal.valueOf(30));
break;
case GRANT_CLAIM_AMOUNT:
builder[0] = builder[0].withGrantClaimAmount(12000);
break;
case OTHER_FUNDING:
builder[0] = builder[0].withOtherFunding("Lottery", LocalDate.of(2016, 4, 1), bd("2468"));
break;
case YOUR_FINANCE:
//none for industrial costs.
break;
case ASSOCIATE_SALARY_COSTS:
builder[0] = builder[0].withAssociateSalaryCosts("role", 4, new BigInteger("6"));
break;
case ASSOCIATE_DEVELOPMENT_COSTS:
builder[0] = builder[0].withAssociateDevelopmentCosts("role", 4, new BigInteger("7"));
break;
case CONSUMABLES:
builder[0] = builder[0].withConsumables("item", new BigInteger("8"), 3);
break;
case ASSOCIATE_SUPPORT:
builder[0] = builder[0].withAssociateSupport("supp", new BigInteger("13"));
break;
case KNOWLEDGE_BASE:
builder[0] = builder[0].withKnowledgeBase("desc", new BigInteger("15"));
break;
case ESTATE_COSTS:
builder[0] = builder[0].withEstateCosts("desc", new BigInteger("16"));
break;
case KTP_TRAVEL:
builder[0] = builder[0].withKtpTravel(KtpTravelCost.KtpTravelCostType.ASSOCIATE, "desc", new BigDecimal("17.00"), 1);
break;
case ADDITIONAL_COMPANY_COSTS:
builder[0] = builder[0].withAdditionalCompanyCosts(AdditionalCompanyCost.AdditionalCompanyCostType.ASSOCIATE_SALARY, "desc", new BigInteger("18"));
break;
case PREVIOUS_FUNDING:
builder[0] = builder[0].withPreviousFunding("a", "b", "c", new BigDecimal("23"));
break;
}
};
if (competition.isKtp()) {
if (OrganisationTypeEnum.KNOWLEDGE_BASE == organisationType) {
competition.getFinanceRowTypes().forEach(costPopulator);
}
} else {
competition.getFinanceRowTypes().forEach(costPopulator);
if (TRUE.equals(competition.getIncludeProjectGrowthTable())) {
builder[0] = builder[0].withProjectGrowthTable(YearMonth.of(2020, 1),
60L,
new BigDecimal("100000"),
new BigDecimal("200000"),
new BigDecimal("300000"),
new BigDecimal("400000"));
} else {
builder[0] = builder[0].withEmployeesAndTurnover(50L,
new BigDecimal("700000"));
}
}
return builder[0].withOrganisationSize(SMALL).
withLocation();
};
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withIndustrialCosts(costBuilder);
}
private ApplicationFinanceDataBuilder generateAcademicFinances(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName) {
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withAcademicCosts(costs -> costs.
withTsbReference("My REF").
withGrantClaim(BigDecimal.valueOf(100)).
withOtherFunding("Lottery", LocalDate.of(2016, 4, 1), bd("2468")).
withDirectlyIncurredStaff(bd("22")).
withDirectlyIncurredTravelAndSubsistence(bd("44")).
withDirectlyIncurredOtherCosts(bd("66")).
withDirectlyAllocatedInvestigators(bd("88")).
withDirectlyAllocatedEstateCosts(bd("110")).
withDirectlyAllocatedOtherCosts(bd("132")).
withIndirectCosts(bd("154")).
withExceptionsStaff(bd("176")).
withExceptionsOtherCosts(bd("198")).
withUploadedJesForm().
withLocation());
}
private ApplicationFinanceDataBuilder generateAcademicFinancesFromSuppliedData(
ApplicationResource application,
CompetitionResource competition,
String user,
String organisationName) {
return applicationFinanceDataBuilder.
withApplication(application).
withCompetition(competition).
withOrganisation(organisationName).
withUser(user).
withAcademicCosts(costs -> costs.
withTsbReference("My REF").
withUploadedJesForm());
}
private BigDecimal bd(String value) {
return new BigDecimal(value);
}
}
|
package it.restart.com.atlassian.jira.plugins.dvcs;
import org.openqa.selenium.By;
import com.atlassian.pageobjects.Page;
import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.query.Poller;
public class DashboardActivityStreamsPage implements Page
{
@ElementBy(xpath = "//h3[text() = 'Activity Stream']")
private PageElement activityStreamsGadgetTitleElm;
@ElementBy(className = "footer")
private PageElement settingsDropdownDiv;
@ElementBy(className = "CommitRowsMore")
private PageElement moreFilesLink;
@ElementBy(linkText = "QA-5")
private PageElement linkIssueQAElm;
@ElementBy(id = "10001")
private PageElement rootElement;
@ElementBy(id = "config-form")
private PageElement configForm;
@Override
public String getUrl()
{
return "/secure/admin/EditDefaultDashboard!default.jspa";
}
public void checkIssueActivityPresentedForQA5()
{
Poller.waitUntilTrue("Expected acitivity at issue QA-5", linkIssueQAElm.timed().isVisible());
}
public void checkIssueActivityNotPresentedForQA5()
{
Poller.waitUntilFalse("Expected acitivity at issue QA-5", linkIssueQAElm.timed().isVisible());
}
public boolean isActivityStreamsGadgetVisible()
{
return activityStreamsGadgetTitleElm.isVisible();
}
public boolean isMoreFilesLinkVisible()
{
return moreFilesLink.isVisible();
}
private void showFilter()
{
PageElement dropdown = settingsDropdownDiv.find(By.className("aui-dd-link"));
dropdown.click();
Poller.waitUntilTrue(settingsDropdownDiv.find(By.linkText("Edit")).timed().isVisible());
PageElement editLink = settingsDropdownDiv.find(By.linkText("Edit"));
editLink.click();
}
public void setIssueKeyFilter(String issueKey)
{
showFilter();
PageElement addFilterLinkElm = rootElement.find(By.className("add-filter-link"));
Poller.waitUntilTrue( rootElement.find(By.className("add-filter-link")).timed().isVisible());
addFilterLinkElm.click();
PageElement ruleSelectkElm = rootElement.find(By.className("rule"));
ruleSelectkElm.find(By.xpath("//option[text() = 'JIRA Issue Key']")).click();
PageElement issueKeyInputElm = rootElement.find(By.name("streams-issue-key-is"));
issueKeyInputElm.clear();
issueKeyInputElm.type(issueKey);
PageElement submitBtnElm = configForm.find(By.className("submit"));
submitBtnElm.click();
}
}
|
package com.archimatetool.editor.utils;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
/**
* HTML Utils
*
* @author Phillip Beauvoir
*/
public class HTMLUtils {
/**
* The reg expression for HTML links
*/
public static final String HTML_LINK_REGEX = "(http|https|ftp|file)://\\S+"; //$NON-NLS-1$
/**
* The compiled pattern to match HTML links
*/
public static final Pattern HTML_LINK_PATTERN = Pattern.compile(HTML_LINK_REGEX);
/**
* The reg expression for HTML tags
*/
public static final String HTML_TAG_REGEX = "<[^>]+>"; //$NON-NLS-1$
/**
* The compiled pattern to match HTML tags
*/
public static final Pattern HTML_TAG_REGEX_PATTERN = Pattern.compile(HTML_TAG_REGEX);
/**
* Strip tags out of a String
* @param str
* @return
*/
public static String stripTags(String str) {
if (str == null || str.indexOf('<') == -1 || str.indexOf('>') == -1) {
return str;
}
str = HTML_TAG_REGEX_PATTERN.matcher(str).replaceAll(""); //$NON-NLS-1$
return str;
}
/**
* Open a link in a Browser
* @param href
* @throws PartInitException
* @throws MalformedURLException
*/
public static void openLinkInBrowser(String href) throws PartInitException, MalformedURLException {
IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
IWebBrowser browser = support.getExternalBrowser();
browser.openURL(new URL(urlEncodeForSpaces(href.toCharArray())));
}
private static String urlEncodeForSpaces(char[] input) {
StringBuffer retu = new StringBuffer(input.length);
for(int i = 0; i < input.length; i++) {
if(input[i] == ' ') {
retu.append("%20"); //$NON-NLS-1$
}
else {
retu.append(input[i]);
}
}
return retu.toString();
}
}
|
package org.safehaus.subutai.core.peer.impl;
public class Timeouts
{
public static final int COMMAND_REQUEST_MESSAGE_TIMEOUT = 30;
public static final int CREATE_CONTAINER_REQUEST_TIMEOUT = 3 * 60;
public static final int CREATE_CONTAINER_RESPONSE_TIMEOUT = 24 * 60 * 60;
public static final int DESTROY_CONTAINER_REQUEST_TIMEOUT = 3 * 60;
public static final int DESTROY_CONTAINER_RESPONSE_TIMEOUT = 60 * 60;
public static final int PEER_MESSAGE_TIMEOUT = 30;
}
|
package io.subutai.core.peer.ui.forms;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.vaadin.ui.Button;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import io.subutai.common.environment.Environment;
import io.subutai.common.peer.ContainerHost;
import io.subutai.common.peer.Peer;
import io.subutai.common.peer.PeerException;
import io.subutai.common.peer.PeerInfo;
import io.subutai.common.peer.RegistrationData;
import io.subutai.common.peer.RegistrationStatus;
import io.subutai.common.peer.ResourceHost;
import io.subutai.core.peer.ui.PeerManagerPortalModule;
import io.subutai.server.ui.component.ConfirmationDialog;
/**
* Registration process should be handled in save manner so no middleware attacks occur. In order to get there peers
* need to exchange with public keys. This will create ssl layer by encrypting all traffic passing through their
* connection. So first initial handshake will be one direction, to pass keys through encrypted channel and register
* them in peers' trust stores. These newly saved keys will be used further for safe communication, with bidirectional
* authentication.
*
*
* TODO here still exists some issues concerned via registration/reject/approve requests. Some of them must pass through
* secure channel such as unregister process. Which already must be in bidirectional auth completed stage.
*/
//TODO: move rest calls to RemotePeer
public class RegistrationForm extends CustomComponent
{
private static final Logger LOG = LoggerFactory.getLogger( PeerRegisterForm.class.getName() );
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
// private AbsoluteLayout mainLayout;
private Table peersTable;
private Button showPeersButton;
private Button doRequestButton;
private TextField hostField;
private TextField keyPhraseField;
private Table requestsTable;
private PeerManagerPortalModule module;
/**
* The constructor should first build the main layout, set the composition root and then do any custom
* initialization. <p/> The constructor will not be automatically regenerated by the visual editor.
*/
public RegistrationForm( final PeerManagerPortalModule module )
{
VerticalLayout layout = buildLayout();
setCompositionRoot( layout );
this.module = module;
updateRequestsTable();
// showPeersButton.click();
}
private VerticalLayout buildLayout()
{
VerticalLayout content = new VerticalLayout();
content.setSpacing( true );
content.setMargin( true );
content.setStyleName( "default" );
content.setSizeFull();
// peerRegistration
final Label peerRegistration = new Label();
peerRegistration.setImmediate( false );
peerRegistration.setValue( "Peer registration" );
content.addComponent( peerRegistration );
FormLayout fl = new FormLayout();
fl.addComponent( new Label( "Host" ) );
// hostField
hostField = new TextField();
hostField.setImmediate( false );
hostField.setMaxLength( 45 );
fl.addComponent( hostField );
// content.addComponent( fl );
// fl = new FormLayout( );
fl.addComponent( new Label( "Secret keyphrase" ) );
// secretKeyphrase
keyPhraseField = new TextField();
keyPhraseField.setImmediate( false );
keyPhraseField.setMaxLength( 45 );
fl.addComponent( keyPhraseField );
content.addComponent( fl );
// doRequestButton
doRequestButton = createRegisterButton();
content.addComponent( doRequestButton );
content.addComponent( createRefreshButton() );
// requestsTable
requestsTable = new Table();
requestsTable.setCaption( "List of remote peers" );
requestsTable.setImmediate( true );
// requestsTable.setHeight( "283px" );
requestsTable.setSizeFull();
requestsTable.addContainerProperty( "ID", String.class, "UNKNOWN" );
requestsTable.addContainerProperty( "Name", String.class, null );
requestsTable.addContainerProperty( "Host", String.class, null );
requestsTable.addContainerProperty( "Key phrase", String.class, null );
requestsTable.addContainerProperty( "Status", RegistrationStatus.class, null );
requestsTable.addContainerProperty( "Action", RequestActionsComponent.class, null );
content.addComponent( requestsTable );
return content;
}
private Button createRefreshButton()
{
showPeersButton = new Button();
showPeersButton.setCaption( "Refresh" );
showPeersButton.setImmediate( false );
showPeersButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
updateRequestsTable();
}
} );
return showPeersButton;
}
private void updateRequestsTable()
{
requestsTable.removeAllItems();
for ( RegistrationData registrationData : module.getPeerManager().getRegistrationRequests() )
{
LOG.debug( registrationData.getPeerInfo().getIp() );
RequestActionsComponent.RequestActionListener listener = new RequestActionsComponent.RequestActionListener()
{
@Override
public void OnPositiveButtonTrigger( final RegistrationData request,
RequestActionsComponent.RequestUpdateViewListener
updateViewListener )
{
positiveActionTrigger( request, updateViewListener );
}
@Override
public void OnNegativeButtonTrigger( final RegistrationData request,
RequestActionsComponent.RequestUpdateViewListener
updateViewListener )
{
negativeActionTrigger( request, updateViewListener );
}
};
RequestActionsComponent actionsComponent =
new RequestActionsComponent( module, registrationData, listener );
requestsTable.addItem( new Object[] {
registrationData.getPeerInfo().getId(), registrationData.getPeerInfo().getName(),
registrationData.getPeerInfo().getIp(), registrationData.getKeyPhrase(),
registrationData.getStatus(), actionsComponent
}, registrationData.getPeerInfo().getId() );
}
}
private void positiveActionTrigger( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
switch ( request.getStatus() )
{
case REQUESTED:
approvePeerRegistration( request, updateViewListener );
break;
case APPROVED:
unregister( request, updateViewListener );
break;
default:
throw new IllegalStateException( request.getStatus().name(), new Throwable( "Invalid case." ) );
}
}
private void negativeActionTrigger( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
PeerInfo selfPeer = module.getPeerManager().getLocalPeerInfo();
switch ( request.getStatus() )
{
case REQUESTED:
rejectRegistration( request, updateViewListener );
break;
case WAIT:
cancelRegistration( request, updateViewListener );
break;
default:
throw new TypeNotPresentException( request.getStatus().name(), new Throwable( "Invalid case." ) );
}
}
private void sendRegistrationRequest( final String destinationHost, final String keyPhrase )
{
try
{
module.getPeerManager().doRegistrationRequest( destinationHost, keyPhrase );
}
catch ( PeerException e )
{
Notification.show( e.getMessage(), Notification.Type.WARNING_MESSAGE );
}
}
private void unregisterMeFromRemote( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
int relationExists = 0;
relationExists = checkEnvironmentExistence( request.getPeerInfo(), relationExists );
relationExists = isRemotePeerContainersHost( request.getPeerInfo(), relationExists );
if ( relationExists != 0 )
{
String msg;
switch ( relationExists )
{
case 1:
msg = "Please destroy all cross peer environments, before you proceed!!!";
break;
case 2:
msg = "You cannot unregister Peer, because you are a carrier of Peer's resources!!!"
+ " Contact with Peer to migrate all his data.";
break;
default:
msg = "Cannot break peer relationship.";
}
ConfirmationDialog alert = new ConfirmationDialog( msg, "Ok", "" );
alert.getOk().addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( Button.ClickEvent clickEvent )
{
}
} );
getUI().addWindow( alert.getAlert() );
}
else
{
unregisterPeerRequestThread( request, updateViewListener );
}
}
private int checkEnvironmentExistence( final PeerInfo remotePeerInfo, final int relationExist )
{
int relationExists = relationExist;
for ( final Iterator<Environment> itEnv = module.getEnvironmentManager().getEnvironments().iterator();
itEnv.hasNext() && relationExists == 0; )
{
Environment environment = itEnv.next();
for ( final Iterator<Peer> itPeer = environment.getPeers().iterator();
itPeer.hasNext() && relationExists == 0; )
{
Peer peer = itPeer.next();
if ( peer.getPeerInfo().equals( remotePeerInfo ) )
{
relationExists = 1;
}
}
}
return relationExists;
}
private int isRemotePeerContainersHost( final PeerInfo remotePeerInfo, final int relationExist )
{
int relationExists = relationExist;
for ( final Iterator<ResourceHost> itResource =
module.getPeerManager().getLocalPeer().getResourceHosts().iterator();
itResource.hasNext() && relationExists == 0; )
{
ResourceHost resourceHost = itResource.next();
for ( final Iterator<ContainerHost> itContainer = resourceHost.getContainerHosts().iterator();
itContainer.hasNext() && relationExists == 0; )
{
ContainerHost containerHost = itContainer.next();
if ( containerHost.getInitiatorPeerId().equals( remotePeerInfo.getId() ) )
{
relationExists = 2;
}
}
}
return relationExists;
}
private void unregisterPeerRequestThread( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener
updateViewListener )
{
new Thread( new Runnable()
{
@Override
public void run()
{
unregister( request, updateViewListener );
updateRequestsTable();
}
} ).start();
}
private void unregister( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
try
{
module.getPeerManager().doUnregisterRequest( request );
updateRequestsTable();
}
catch ( PeerException e )
{
Notification.show( e.getMessage(), Notification.Type.WARNING_MESSAGE );
}
}
private void approvePeerRegistration( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
new Thread( new Runnable()
{
@Override
public void run()
{
approveRegistrationRequest( request, updateViewListener );
updateRequestsTable();
}
} ).start();
}
private void approveRegistrationRequest( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener
updateViewListener )
{
try
{
module.getPeerManager().doApproveRequest( keyPhraseField.getValue(), request );
}
catch ( Exception e )
{
Notification.show( e.getMessage(), Notification.Type.WARNING_MESSAGE );
}
}
/**
* Peer request rejection intented to be handled before they exchange with keys
*
* @param request - registration request
* @param updateViewListener - used to update peers table with relevant buttons captions
*/
private void rejectRegistration( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
new Thread( new Runnable()
{
@Override
public void run()
{
try
{
module.getPeerManager().doRejectRequest( request );
}
catch ( PeerException e )
{
Notification.show( e.getMessage(), Notification.Type.WARNING_MESSAGE );
}
updateRequestsTable();
}
} ).start();
}
private void cancelRegistration( final RegistrationData request,
final RequestActionsComponent.RequestUpdateViewListener updateViewListener )
{
new Thread( new Runnable()
{
@Override
public void run()
{
try
{
module.getPeerManager().doCancelRequest( request );
}
catch ( PeerException e )
{
Notification.show( e.getMessage(), Notification.Type.WARNING_MESSAGE );
}
updateRequestsTable();
}
} ).start();
}
/**
* Send peer registration request for further handshakes.
*
* @return - vaadin button with request initializing click listener
*/
private Button createRegisterButton()
{
doRequestButton = new Button();
doRequestButton.setCaption( "Register" );
doRequestButton.setImmediate( true );
doRequestButton.addClickListener( new Button.ClickListener()
{
@Override
public void buttonClick( final Button.ClickEvent clickEvent )
{
getUI().access( new Runnable()
{
@Override
public void run()
{
if ( Strings.isNullOrEmpty( hostField.getValue() ) || Strings
.isNullOrEmpty( keyPhraseField.getValue() ) )
{
Notification.show( "Please specify host and key phrase." );
}
else
{
sendRegistrationRequest( hostField.getValue(), keyPhraseField.getValue() );
}
updateRequestsTable();
}
} );
}
} );
return doRequestButton;
}
}
|
package org.xcolab.service.contest.utils.promotion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xcolab.client.contest.ContestClientUtil;
import org.xcolab.client.proposals.ProposalClientUtil;
import org.xcolab.client.proposals.ProposalPhaseClientUtil;
import org.xcolab.client.proposals.exceptions.Proposal2PhaseNotFoundException;
import org.xcolab.client.proposals.pojo.Proposal;
import org.xcolab.client.proposals.pojo.phases.Proposal2Phase;
import org.xcolab.entity.utils.email.ContestPhasePromotionEmail;
import org.xcolab.model.tables.pojos.Contest;
import org.xcolab.model.tables.pojos.ContestPhase;
import org.xcolab.model.tables.pojos.ContestPhaseType;
import org.xcolab.service.contest.domain.contest.ContestDao;
import org.xcolab.service.contest.domain.contestphase.ContestPhaseDao;
import org.xcolab.service.contest.domain.contestphasetype.ContestPhaseTypeDao;
import org.xcolab.service.contest.exceptions.NotFoundException;
import org.xcolab.service.contest.service.contest.ContestService;
import org.xcolab.service.contest.service.contestphase.ContestPhaseService;
import org.xcolab.service.contest.utils.email.EmailToAdminDispatcher;
import org.xcolab.util.enums.contest.ProposalContestPhaseAttributeKeys;
import org.xcolab.util.enums.promotion.ContestPhasePromoteType;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* Helper class to automatically promote proposals to the next phase.
*/
@Service
public class PromotionService {
private static final Logger log = LoggerFactory.getLogger(PromotionService.class);
private static final String STATUS_OPEN_FOR_SUBMISSION = "OPEN_FOR_SUBMISSION";
private static final String STATUS_CLOSED = "CLOSED";
private static final long SEMIFINALIST_RIBBON_ID = 3L;
private static final long FINALIST_RIBBON_ID = 1L;
private final ContestPhaseDao contestPhaseDao;
private final ContestDao contestDao;
private final ContestPhaseTypeDao contestPhaseTypeDao;
private final ContestPhaseService contestPhaseService;
private final ContestService contestService;
private Date now;
@Autowired
public PromotionService(ContestPhaseDao contestPhaseDao, ContestDao contestDao,
ContestPhaseService contestPhaseService, ContestPhaseTypeDao contestPhaseTypeDao,
ContestService contestService) {
this.contestPhaseDao = contestPhaseDao;
this.contestDao = contestDao;
this.contestPhaseTypeDao = contestPhaseTypeDao;
this.contestPhaseService = contestPhaseService;
this.contestService = contestService;
}
public synchronized int doPromotion(Date now) {
setNow(now);
int promotedProposals = 0;
promotedProposals += doBasicPromotion();
promotedProposals += doJudgingBasedPromotion();
promotedProposals += distributeRibbons();
return promotedProposals;
}
private int doBasicPromotion() {
int promotedProposals = 0;
final List<ContestPhase> phasesToPromote =
contestPhaseDao.findByPhaseAutopromote(ContestPhasePromoteType.PROMOTE.getValue());
for (ContestPhase phase : phasesToPromote) {
PhasePromotionHelper phasePromotionHelper = new PhasePromotionHelper(phase);
if (phasePromotionHelper.isPhaseContestScheduleTemplatePhase()) {
continue;
}
if (hasNoValidContest(phase)) {
continue;
}
final boolean hasPhaseEnded = phase.getPhaseEndDate() != null
&& phase.getPhaseEndDate().before(now);
if (hasPhaseEnded && !contestPhaseDao.isPhaseActive(phase)) {
// we have a candidate for promotion, find next phase
try {
log.info("promoting phase {}", phase.getContestPhasePK());
Contest contest = contestDao.get(phase.getContestPK());
log.info("promoting contest {}", contest.getContestPK());
ContestPhase nextPhase = contestPhaseService.getNextContestPhase(phase);
final List<Proposal> proposalsInPhase = ProposalClientUtil
.getProposalsInContestPhase(phase.getContestPhasePK());
for (Proposal p : proposalsInPhase) {
if (phasePromotionHelper.isProposalPromoted(p)) {
continue;
}
if (!phasePromotionHelper.isProposalVisible(p)) {
continue;
}
ProposalPhaseClientUtil
.promoteProposal(p.getProposalId(), nextPhase.getContestPhasePK(),
phase.getContestPhasePK());
promotedProposals++;
}
// update phase for which promotion was done (mark it as
// "promotion done")
phase.setContestPhaseAutopromote("PROMOTE_DONE");
contestPhaseDao.update(phase);
if (contestPhaseService.getContestStatus(nextPhase).isCanVote()) {
contestPhaseService.transferSupportsToVote(contest, nextPhase);
}
log.info("done promoting phase {}", phase.getContestPhasePK());
} catch (NotFoundException e) {
log.error("Exception thrown when doing autopromotion for phase {}",
phase.getContestPhasePK(), e);
}
}
}
return promotedProposals;
}
private int doJudgingBasedPromotion() {
int promotedProposals = 0;
final List<ContestPhase> phasesToPromote = contestPhaseDao
.findByPhaseAutopromote(ContestPhasePromoteType.PROMOTE_JUDGED.getValue());
for (ContestPhase phase : phasesToPromote) {
PhasePromotionHelper phasePromotionHelper = new PhasePromotionHelper(phase);
if (phasePromotionHelper.isPhaseContestScheduleTemplatePhase()) {
continue;
}
if (hasNoValidContest(phase)) {
continue;
}
if (phase.getPhaseEndDate() != null && phase.getPhaseEndDate().before(now)
&& !contestPhaseDao.isPhaseActive(phase)) {
log.info("promoting phase {} (judging)", phase.getContestPhasePK());
try {
// Only do the promotion if all proposals have been successfully reviewed
if (phasePromotionHelper.isAllProposalsReviewed()) {
Contest contest = contestDao.get(phase.getContestPK());
log.info("promoting contest {} (judging) ", contest.getContestPK());
ContestPhase nextPhase = contestPhaseService.getNextContestPhase(phase);
for (Proposal p : ProposalClientUtil
.getProposalsInContestPhase(phase.getContestPhasePK())) {
try {
// check if proposal isn't already associated with requested phase
if (ProposalPhaseClientUtil
.getProposal2PhaseByProposalIdContestPhaseId(
p.getProposalId(), nextPhase.getContestPhasePK())
!= null) {
log.warn("Proposal is already associated with given contest "
+ "phase");
continue;
}
} catch (Proposal2PhaseNotFoundException e) {
// no such proposal2phase, we can safely add association
}
//skip already promoted proposal
if (phasePromotionHelper.isProposalPromoted(p)) {
log.trace("Proposal already promoted {}", p.getProposalId());
continue;
}
// Decide about the promotion
if (phasePromotionHelper.didJudgeDecideToPromote(p)) {
log.info("Promote proposal {}", p.getProposalId());
ProposalPhaseClientUtil.promoteProposal(p.getProposalId(),
nextPhase.getContestPhasePK(), phase.getContestPhasePK());
promotedProposals++;
}
// Enable this line to post promotion comment to Evaluation tab comment section
// proposalLocalService.contestPhasePromotionCommentNotifyProposalContributors(p, phase);
// Add this check for extra security to prevent proposal authors from being spammed (see COLAB-500)
if (phasePromotionHelper.isProposalReviewed(p)) {
//TODO COLAB-2603: Migrate logic to send email.
org.xcolab.client.contest.pojo.phases.ContestPhase cp = ContestClientUtil.getContestPhase(phase.getContestPhasePK());
ContestPhasePromotionEmail.contestPhasePromotionEmailNotifyProposalContributors(p, cp);
PhasePromotionHelper.createProposalContestPhasePromotionDoneAttribute(p.getProposalId(), phase.getContestPhasePK());
}
}
if (contestPhaseService.getContestStatus(nextPhase).isCanVote()) {
log.info("Transferring supports to votes in contest {}, phase {} ...",
contest.getContestPK(), nextPhase.getContestPhasePK());
contestPhaseService.transferSupportsToVote(contest, nextPhase);
}
phase.setContestPhaseAutopromote("PROMOTE_DONE");
contestPhaseDao.update(phase);
log.info("done promoting phase {}", phase.getContestPhasePK());
} else {
log.warn("Judge promoting failed for ContestPhase with ID {} - not all "
+ "proposals have been reviewed", phase.getContestPhasePK());
}
} catch (NotFoundException ignored) {
}
}
}
return promotedProposals;
}
private int distributeRibbons() {
int promotedProposals = 0;
final List<ContestPhase> phasesToPromote = contestPhaseDao
.findByPhaseAutopromote(ContestPhasePromoteType.PROMOTE_RIBBONIZE.getValue());
for (ContestPhase phase : phasesToPromote) {
PhasePromotionHelper phasePromotionHelper = new PhasePromotionHelper(phase);
if (phasePromotionHelper.isPhaseContestScheduleTemplatePhase()) {
continue;
}
if (hasNoValidContest(phase)) {
continue;
}
if (phase.getPhaseEndDate() != null && phase.getPhaseEndDate().before(now)
&& !contestPhaseDao.isPhaseActive(phase)) {
log.info("promoting phase {} (ribbonize)", phase.getContestPhasePK());
try {
log.info("promoting phase {}", phase.getContestPhasePK());
Contest contest = contestDao.get(phase.getContestPK());
ContestPhase nextPhase = contestPhaseService.getNextContestPhase(phase);
List<ContestPhase> contestPhases =
contestService.getAllContestPhases(contest.getContestPK());
ContestPhase finalistSelection = null;
ContestPhase semifinalistSelection = null;
Set<ContestPhase> proposalCreationPhases = new HashSet<>();
for (ContestPhase cp : contestPhases) {
final Optional<ContestPhaseType> phaseType =
contestPhaseTypeDao.get(cp.getContestPhaseType());
if (phaseType.isPresent()) {
final String status = phaseType.get().getStatus();
if (status.equals(STATUS_OPEN_FOR_SUBMISSION)) {
proposalCreationPhases.add(cp);
} else if (status.equals(STATUS_CLOSED)) {
if (finalistSelection == null || cp.getPhaseEndDate()
.after(finalistSelection.getPhaseEndDate())) {
semifinalistSelection = finalistSelection;
finalistSelection = cp;
}
}
}
}
Set<Proposal> allProposals = new HashSet<>();
if (!proposalCreationPhases.isEmpty()) {
for (ContestPhase creationPhase : proposalCreationPhases) {
final List<Proposal> proposalsInContestPhase = ProposalClientUtil
.getProposalsInContestPhase(creationPhase.getContestPhasePK());
addAllVisibleProposalsToCollection(proposalsInContestPhase,
allProposals, creationPhase);
}
} else {
log.error("Can't distribute ribbons: No creation phase found in contest {}",
phase.getContestPK());
}
List<Proposal> finalists = null;
List<Proposal> semifinalists = null;
if (finalistSelection != null) {
ContestPhase finalsPhase =
contestPhaseService.getNextContestPhase(finalistSelection);
finalists = ProposalClientUtil
.getProposalsInContestPhase(finalsPhase.getContestPhasePK());
//make sure all finalists are in the set
addAllVisibleProposalsToCollection(finalists, allProposals, finalsPhase);
if (semifinalistSelection != null) {
ContestPhase semifinalsPhase =
contestPhaseService.getNextContestPhase(semifinalistSelection);
semifinalists = ProposalClientUtil.getProposalsInContestPhase(
semifinalsPhase.getContestPhasePK());
semifinalists.removeAll(finalists);
//make sure all semifinalists are in the set
addAllVisibleProposalsToCollection(semifinalists, allProposals,
semifinalsPhase);
} else {
log.warn("No semifinalist phase found in contest {}",
phase.getContestPK());
}
} else {
log.error("Can't distribute ribbons: No finalist phase found in contest {}",
phase.getContestPK());
}
promotedProposals += allProposals.size();
associateProposalsWithCompletedPhase(allProposals, phase, nextPhase);
if (semifinalists != null) {
assignRibbonsToProposals(SEMIFINALIST_RIBBON_ID, semifinalists,
nextPhase.getContestPhasePK());
}
if (finalists != null) {
assignRibbonsToProposals(FINALIST_RIBBON_ID, finalists,
nextPhase.getContestPhasePK());
} else {
log.warn("No finalists found to distribute ribbons to.");
}
// We want to wait showing all ribbons until the winners are determined
contest.setHideRibbons(true);
contestDao.update(contest);
// update phase for which promotion was done (mark it as "promotion done")
phase.setContestPhaseAutopromote("PROMOTE_DONE");
contestPhaseDao.update(phase);
log.info("done promoting phase {}", phase.getContestPhasePK());
} catch (NotFoundException e) {
log.error("Exception thrown when doing auto promotion for phase {}",
phase.getContestPhasePK(), e);
}
}
}
return promotedProposals;
}
private boolean hasNoValidContest(ContestPhase phase) {
try {
contestDao.get(phase.getContestPK());
} catch (NotFoundException e) {
log.warn("promoting phase failed due to invalid contest ", e);
return true;
}
return false;
}
private void addAllVisibleProposalsToCollection(Collection<Proposal> sourceCollection,
Collection<Proposal> toCollection, ContestPhase inPhase) {
PhasePromotionHelper phasePromotionHelper = new PhasePromotionHelper(inPhase);
for (Proposal p : sourceCollection) {
if (!phasePromotionHelper.isProposalVisible(p)) {
continue;
}
toCollection.add(p);
}
}
private void associateProposalsWithCompletedPhase(Set<Proposal> proposals,
ContestPhase previousPhase, ContestPhase completedPhase) throws NotFoundException {
for (Proposal proposal : proposals) {
//update the last phase association - set the end version to the current version
final long proposalId = proposal.getProposalId();
Integer currentProposalVersion = ProposalClientUtil.countProposalVersions(proposalId);
if (currentProposalVersion <= 0) {
log.error("Proposal {} not found: version was {}", proposalId,
currentProposalVersion);
throw new NotFoundException("Proposal not found");
}
try {
//make sure that proposals in the phase directly before have final versions
Proposal2Phase oldP2p = ProposalPhaseClientUtil
.getProposal2PhaseByProposalIdContestPhaseId(proposalId,
previousPhase.getContestPhasePK());
if (oldP2p != null) {
if (oldP2p.getVersionTo() < 0) {
oldP2p.setVersionTo(currentProposalVersion);
ProposalPhaseClientUtil.updateProposal2Phase(oldP2p);
}
}
} catch (Proposal2PhaseNotFoundException ignored) {
}
Proposal2Phase p2p;
final long completedPhasePK = completedPhase.getContestPhasePK();
try {
//This is a workaround for a bug that caused two new p2p's to be created
p2p = ProposalPhaseClientUtil
.getProposal2PhaseByProposalIdContestPhaseId(proposalId, completedPhasePK);
//If this succeeds, we want to log the error to help diagnose the problem
log.error("P2p found while associating proposal {} with phase {}.", proposalId,
completedPhasePK);
new EmailToAdminDispatcher("Duplicate primary key for P2p in auto promotion",
String.format("Unexpectedly found p2p. Setting versionFrom = %d and versionTo = %d: %s",
currentProposalVersion, currentProposalVersion, p2p), 2)
.sendMessage();
} catch (Proposal2PhaseNotFoundException e) {
p2p = new Proposal2Phase();
p2p.setProposalId(proposalId);
p2p.setContestPhaseId(completedPhasePK);
ProposalPhaseClientUtil.createProposal2Phase(p2p);
log.debug("Created new p2p: {}", p2p);
}
p2p.setVersionFrom(currentProposalVersion);
p2p.setVersionTo(currentProposalVersion);
ProposalPhaseClientUtil.updateProposal2Phase(p2p);
}
}
private void assignRibbonsToProposals(Long ribbonId, List<Proposal> proposals, Long phasePK) {
if (ribbonId > 0) {
for (Proposal proposal : proposals) {
//don't overwrite existing ribbons, as they might be manually assigned winner's ribbons!
if (!ProposalPhaseClientUtil.hasProposalContestPhaseAttribute(proposal.getProposalId(), phasePK,
ProposalContestPhaseAttributeKeys.RIBBON)) {
if (ContestClientUtil.getContestPhaseRibbonType(ribbonId) != null) {
ProposalPhaseClientUtil.setProposalContestPhaseAttribute(proposal.getProposalId(), phasePK,
ProposalContestPhaseAttributeKeys.RIBBON, 0L, ribbonId, "");
} else {
ProposalPhaseClientUtil.deleteProposalContestPhaseAttribute(proposal.getProposalId(), phasePK,
ProposalContestPhaseAttributeKeys.RIBBON);
}
} else {
log.error("Skipping ribbon (id = {}) assignment for proposal {}: (already assigned)",
ribbonId, proposal.getProposalId());
}
}
}
}
private void setNow(Date now) {
this.now = now;
}
}
|
package name.abuchen.portfolio.datatransfer.pdf.postfinance;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.assertThat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import name.abuchen.portfolio.datatransfer.Extractor.BuySellEntryItem;
import name.abuchen.portfolio.datatransfer.Extractor.Item;
import name.abuchen.portfolio.datatransfer.Extractor.SecurityItem;
import name.abuchen.portfolio.datatransfer.Extractor.TransactionItem;
import name.abuchen.portfolio.datatransfer.actions.AssertImportActions;
import name.abuchen.portfolio.datatransfer.pdf.PDFInputFile;
import name.abuchen.portfolio.datatransfer.pdf.PostfinancePDFExtractor;
import name.abuchen.portfolio.model.AccountTransaction;
import name.abuchen.portfolio.model.BuySellEntry;
import name.abuchen.portfolio.model.Client;
import name.abuchen.portfolio.model.PortfolioTransaction;
import name.abuchen.portfolio.model.Security;
import name.abuchen.portfolio.model.Transaction.Unit;
import name.abuchen.portfolio.money.CurrencyUnit;
import name.abuchen.portfolio.money.Money;
import name.abuchen.portfolio.money.Values;
@SuppressWarnings("nls")
public class PostfinancePDFExtractorTest
{
@Test
public void testKauf01()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceKauf01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "EUR");
// check security
Optional<Item> item = results.stream().filter(i -> i instanceof SecurityItem).findFirst();
assertThat(item.isPresent(), is(true));
Security security = ((SecurityItem) item.orElseThrow(IllegalArgumentException::new)).getSecurity();
assertThat(security.getIsin(), is("NL0000009355"));
assertThat(security.getCurrencyCode(), is("EUR"));
assertThat(security.getName(), is("UNILEVER DUTCH CERT"));
// check transaction
BuySellEntry entry = (BuySellEntry) results.stream().filter(i -> i instanceof BuySellEntryItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(entry.getPortfolioTransaction().getType(), is(PortfolioTransaction.Type.BUY));
assertThat(entry.getAccountTransaction().getType(), is(AccountTransaction.Type.BUY));
assertThat(entry.getPortfolioTransaction().getDateTime(), is(LocalDateTime.parse("2018-09-27T00:00")));
assertThat(entry.getPortfolioTransaction().getMonetaryAmount(),
is(Money.of("EUR", Values.Amount.factorize(2850.24))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.FEE),
is(Money.of("EUR", Values.Amount.factorize(8.58))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.TAX),
is(Money.of("EUR", Values.Amount.factorize(4.26))));
}
@Test
public void testKauf02()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceKauf02.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
// check security
Optional<Item> item = results.stream().filter(i -> i instanceof SecurityItem).findFirst();
assertThat(item.isPresent(), is(true));
Security security = ((SecurityItem) item.orElseThrow(IllegalArgumentException::new)).getSecurity();
assertThat(security.getIsin(), is("CH0025751329"));
assertThat(security.getCurrencyCode(), is("CHF"));
assertThat(security.getName(), is("LOGITECH N"));
// check transaction
BuySellEntry entry = (BuySellEntry) results.stream().filter(i -> i instanceof BuySellEntryItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(entry.getPortfolioTransaction().getType(), is(PortfolioTransaction.Type.BUY));
assertThat(entry.getAccountTransaction().getType(), is(AccountTransaction.Type.BUY));
assertThat(entry.getPortfolioTransaction().getDateTime(), is(LocalDateTime.parse("2018-10-29T00:00")));
assertThat(entry.getPortfolioTransaction().getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(2998.95))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.FEE),
is(Money.of("CHF", Values.Amount.factorize(26.50))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.TAX),
is(Money.of("CHF", Values.Amount.factorize(2.25))));
}
@Test
public void testKauf03()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceKauf03.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
// check security
Optional<Item> item = results.stream().filter(i -> i instanceof SecurityItem).findFirst();
assertThat(item.isPresent(), is(true));
Security security = ((SecurityItem) item.orElseThrow(IllegalArgumentException::new)).getSecurity();
assertThat(security.getIsin(), is("DE000PAH0038"));
assertThat(security.getCurrencyCode(), is("EUR"));
assertThat(security.getName(), is("PORSCHE AUTOMOBIL HOLDING PRF"));
// check transaction
BuySellEntry entry = (BuySellEntry) results.stream().filter(i -> i instanceof BuySellEntryItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(entry.getPortfolioTransaction().getType(), is(PortfolioTransaction.Type.BUY));
assertThat(entry.getAccountTransaction().getType(), is(AccountTransaction.Type.BUY));
assertThat(entry.getPortfolioTransaction().getDateTime(), is(LocalDateTime.parse("2017-03-29T00:00")));
assertThat(entry.getPortfolioTransaction().getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(2968.50))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.TAX),
is(Money.of("CHF", Values.Amount.factorize(4.45))));
Unit gross = entry.getPortfolioTransaction().getUnit(Unit.Type.GROSS_VALUE)
.orElseThrow(IllegalArgumentException::new);
assertThat(gross.getAmount(), is(Money.of("CHF", Values.Amount.factorize(2964.05))));
assertThat(gross.getForex(), is(Money.of(CurrencyUnit.EUR, Values.Amount.factorize(2737.40))));
}
@Test
public void testVerkauf01()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceVerkauf01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
// check security
Optional<Item> item = results.stream().filter(i -> i instanceof SecurityItem).findFirst();
assertThat(item.isPresent(), is(true));
Security security = ((SecurityItem) item.orElseThrow(IllegalArgumentException::new)).getSecurity();
assertThat(security.getIsin(), is("IE00BD4TYL27"));
assertThat(security.getCurrencyCode(), is("CHF"));
assertThat(security.getName(), is("UBSETF MSCI USA hdg to CHF"));
// check transaction
BuySellEntry entry = (BuySellEntry) results.stream().filter(i -> i instanceof BuySellEntryItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(entry.getPortfolioTransaction().getType(), is(PortfolioTransaction.Type.SELL));
assertThat(entry.getAccountTransaction().getType(), is(AccountTransaction.Type.SELL));
assertThat(entry.getPortfolioTransaction().getDateTime(), is(LocalDateTime.parse("2018-09-24T00:00")));
assertThat(entry.getPortfolioTransaction().getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(7467.50))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.FEE),
is(Money.of("CHF", Values.Amount.factorize(2.60))));
assertThat(entry.getPortfolioTransaction().getUnitSum(Unit.Type.TAX),
is(Money.of("CHF", Values.Amount.factorize(11.20))));
}
@Test
public void testDividende01()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceDividende01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "EUR");
Security security = results.stream().filter(i -> i instanceof SecurityItem).findFirst().get().getSecurity();
assertThat(security.getIsin(), is("NL0000009355"));
assertThat(security.getName(), is("UNILEVER DUTCH CERT"));
AccountTransaction transaction = (AccountTransaction) results.stream().filter(i -> i instanceof TransactionItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(transaction.getType(), is(AccountTransaction.Type.DIVIDENDS));
assertThat(transaction.getMonetaryAmount(),
is(Money.of("EUR", Values.Amount.factorize(20.93))));
assertThat(transaction.getShares(), is(Values.Share.factorize(60)));
assertThat(transaction.getDateTime(), is(LocalDateTime.parse("2019-05-02T00:00")));
assertThat(transaction.getUnitSum(Unit.Type.TAX), is(Money.of("EUR", Values.Amount.factorize(3.69))));
assertThat(transaction.getGrossValue(), is(Money.of("EUR", Values.Amount.factorize(24.62))));
}
@Test
public void testDividende02()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceDividende02.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
Security security = results.stream().filter(i -> i instanceof SecurityItem).findFirst().get().getSecurity();
assertThat(security.getIsin(), is("CH0032912732"));
assertThat(security.getName(), is("UBS ETF CH - SLI CHF A"));
AccountTransaction transaction = (AccountTransaction) results.stream().filter(i -> i instanceof TransactionItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(transaction.getType(), is(AccountTransaction.Type.DIVIDENDS));
assertThat(transaction.getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(36.69))));
assertThat(transaction.getShares(), is(Values.Share.factorize(34)));
assertThat(transaction.getDateTime(), is(LocalDateTime.parse("2017-09-06T00:00")));
assertThat(transaction.getUnitSum(Unit.Type.TAX), is(Money.of("CHF", Values.Amount.factorize(19.75))));
assertThat(transaction.getGrossValue(), is(Money.of("CHF", Values.Amount.factorize(56.44))));
}
@Test
public void testKapitalgewinn01()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceKapitalgewinn01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(2));
new AssertImportActions().check(results, "CHF");
Security security = results.stream().filter(i -> i instanceof SecurityItem).findFirst().get().getSecurity();
assertThat(security.getIsin(), is("CH0019396990"));
assertThat(security.getName(), is("YPSOMED HLDG"));
AccountTransaction transaction = (AccountTransaction) results.stream().filter(i -> i instanceof TransactionItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(transaction.getType(), is(AccountTransaction.Type.DIVIDENDS));
assertThat(transaction.getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(26.60))));
assertThat(transaction.getShares(), is(Values.Share.factorize(19)));
assertThat(transaction.getDateTime(), is(LocalDateTime.parse("2018-07-03T00:00")));
}
@Test
public void testJahresgebuhr01()
{
Client client = new Client();
PostfinancePDFExtractor extractor = new PostfinancePDFExtractor(client);
List<Exception> errors = new ArrayList<>();
List<Item> results = extractor.extract(PDFInputFile.loadTestCase(getClass(), "PostfinanceJahresgebuhr01.txt"), errors);
assertThat(errors, empty());
assertThat(results.size(), is(1));
new AssertImportActions().check(results, "CHF");
AccountTransaction transaction = (AccountTransaction) results.stream().filter(i -> i instanceof TransactionItem).findFirst()
.orElseThrow(IllegalArgumentException::new).getSubject();
assertThat(transaction.getType(), is(AccountTransaction.Type.FEES));
assertThat(transaction.getMonetaryAmount(),
is(Money.of("CHF", Values.Amount.factorize(90.00))));
assertThat(transaction.getDateTime(), is(LocalDateTime.parse("2019-01-03T00:00")));
}
}
|
package org.nuxeo.opensocial.shindig.gadgets;
import java.util.Collections;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.common.JsonSerializer;
import org.apache.shindig.gadgets.FetchResponseUtils;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.http.HttpRequest;
import org.apache.shindig.gadgets.http.HttpResponse;
import org.apache.shindig.gadgets.http.RequestPipeline;
import org.apache.shindig.gadgets.rewrite.RequestRewriterRegistry;
import org.apache.shindig.gadgets.servlet.MakeRequestHandler;
import org.apache.shindig.gadgets.servlet.ProxyBase;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* @author cusgu
*
* Patch FeedProcessor in order to retrieve extra elements from RSS 2.0
* feeds : - enclosure
*
*/
@Singleton
public class NXMakeRequestHandler extends MakeRequestHandler {
public static String AUTH_SESSION_HEADER = "X-NUXEO-INTEGRATED-AUTH";
@Inject
public NXMakeRequestHandler(RequestPipeline requestPipeline,
RequestRewriterRegistry contentRewriterRegistry) {
super(requestPipeline, contentRewriterRegistry);
}
@Override
protected void setRequestHeaders(HttpServletRequest servletRequest,
HttpRequest req) {
super.setRequestHeaders(servletRequest, req);
String sessionId = req.getHeader(AUTH_SESSION_HEADER);
if (sessionId != null) {
req.addHeader("Cookie", "JSESSIONID=" + sessionId);
}
}
/**
* Format a response as JSON, including additional JSON inserted by
* chained content fetchers.
*/
@Override
protected String convertResponseToJson(SecurityToken authToken, HttpServletRequest request,
HttpResponse results) throws GadgetException {
String originalUrl = request.getParameter(ProxyBase.URL_PARAM);
String body = results.getResponseAsString();
if (body.length() > 0) {
if ("FEED".equals(request.getParameter(CONTENT_TYPE_PARAM))) {
body = NXprocessFeed(originalUrl, request, body);
}
}
Map<String, Object> resp = FetchResponseUtils.getResponseAsJson(results, null, body);
if (authToken != null) {
String updatedAuthToken = authToken.getUpdatedToken();
if (updatedAuthToken != null) {
resp.put("st", updatedAuthToken);
}
}
// Use raw param as key as URL may have to be decoded
return JsonSerializer.serialize(Collections.singletonMap(originalUrl, resp));
}
/**
* Processes a feed (RSS or Atom) using FeedProcessor.
*/
private String NXprocessFeed(String url, HttpServletRequest req, String xml)
throws GadgetException {
boolean getSummaries = Boolean.parseBoolean(getParameter(req,
GET_SUMMARIES_PARAM, "false"));
int numEntries = Integer.parseInt(getParameter(req, NUM_ENTRIES_PARAM,
DEFAULT_NUM_ENTRIES));
return new NXFeedProcessor().process(url, xml, getSummaries, numEntries).toString();
}
}
|
package com.x.organization.assemble.control.jaxrs.unit;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.project.bean.WrapCopier;
import com.x.base.core.project.bean.WrapCopierFactory;
import com.x.base.core.project.cache.CacheManager;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WoId;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.organization.assemble.control.Business;
import com.x.organization.assemble.control.message.OrgMessageFactory;
import com.x.organization.core.entity.Identity;
import com.x.organization.core.entity.Identity_;
import com.x.organization.core.entity.Unit;
import com.x.organization.core.entity.Unit_;
class ActionEdit extends BaseAction {
@SuppressWarnings("unused")
private static Logger logger = LoggerFactory.getLogger(ActionEdit.class);
ActionResult<Wo> execute(EffectivePerson effectivePerson, String flag, JsonElement jsonElement) throws Exception {
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
ActionResult<Wo> result = new ActionResult<>();
Business business = new Business(emc);
Wi wi = this.convertToWrapIn(jsonElement, Wi.class);
Unit unit = business.unit().pick(flag);
Unit oldUnit = unit;
boolean checkFlag = false;
if (null == unit) {
throw new ExceptionUnitNotExist(flag);
}
if (!business.editable(effectivePerson, unit)) {
throw new ExceptionDenyEditUnit(effectivePerson, flag);
}
if (StringUtils.isEmpty(wi.getName())) {
throw new ExceptionNameEmpty();
}
/** pick */
emc.beginTransaction(Unit.class);
unit = emc.find(unit.getId(), Unit.class);
Gson gsontool = new Gson();
String strOriginalUnit = gsontool.toJson(unit);
unit.setControllerList(ListTools.extractProperty(
business.person().pick(ListTools.trim(unit.getControllerList(), true, true)),
JpaObject.id_FIELDNAME, String.class, true, true));
Wi.copier.copy(wi, unit);
if (this.duplicateUniqueWhenNotEmpty(business, unit)) {
throw new ExceptionDuplicateUnique(unit.getName(), unit.getUnique());
}
if (this.checkNameInvalid(business, unit)) {
throw new ExceptionNameInvalid(unit.getName());
}
/** name */
if (this.duplicateName(business, unit)) {
throw new ExceptionDuplicateName(unit.getName());
}
//
// checkFlag = this.checkUnitTypeName(oldUnit, unit);
// if (checkFlag) {
// business.unit().adjustInherit(unit);
business.unit().adjustInherit(unit);
emc.check(unit, CheckPersistType.all);
emc.commit();
CacheManager.notify(Unit.class);
checkFlag = this.checkUnitTypeName(oldUnit, unit);
if (checkFlag) {
this.updateIdentityUnitNameAndUnitLevelName(unit, business);
}
/** org */
OrgMessageFactory orgMessageFactory = new OrgMessageFactory();
orgMessageFactory.createMessageCommunicate("modfiy", "unit", strOriginalUnit, unit, effectivePerson);
Wo wo = new Wo();
wo.setId(unit.getId());
result.setData(wo);
return result;
}
}
public static class Wo extends WoId {
}
public static class Wi extends Unit {
private static final long serialVersionUID = -7527954993386512109L;
static WrapCopier<Wi, Unit> copier = WrapCopierFactory.wi(Wi.class, Unit.class, null,
ListTools.toList(JpaObject.FieldsUnmodify, Unit.pinyin_FIELDNAME, Unit.pinyinInitial_FIELDNAME,
Unit.level_FIELDNAME, Unit.levelName_FIELDNAME));
}
/**
*
* @param business
* @param unit
* @return
* @throws Exception
*/
private List<Identity> listIdentityByUnitFlag(Business business, Unit unit) throws Exception {
if (null == unit.getId() || StringUtils.isEmpty(unit.getId()) || null == unit) {
throw new ExceptionUnitNotExist(unit.getId());
}
EntityManager em = business.entityManagerContainer().get(Identity.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Identity> cq = cb.createQuery(Identity.class);
Root<Identity> root = cq.from(Identity.class);
Predicate p = cb.equal(root.get(Identity_.unit), unit.getId());
List<Identity> os = em.createQuery(cq.select(root).where(p)).getResultList();
return os;
}
void updateIdentityUnitNameAndUnitLevelName(Unit unit, Business business) throws Exception {
/*
* unitUnitLevelNameUnitName
*/
List<Unit> unitList = new ArrayList<>();
unitList.add(unit);
unitList.addAll(business.unit().listSubNestedObject(unit));
EntityManagerContainer emc = business.entityManagerContainer();
for (Unit u : unitList) {
List<Identity> identityList = this.listIdentityByUnitFlag(business, u);
if (ListTools.isNotEmpty(identityList)) {
String _unitName = u.getName();
String _unitLevelName = u.getLevelName();
for (Identity i : identityList) {
Identity _identity = emc.find(i.getId(), Identity.class);
_identity.setUnitName(_unitName);
_identity.setUnitLevelName(_unitLevelName);
emc.beginTransaction(Identity.class);
emc.check(_identity, CheckPersistType.all);
emc.commit();
CacheManager.notify(Identity.class);
}
}
}
}
private boolean checkUnitTypeName(Unit oldUnit, Unit unit) throws Exception {
List<String> oldUnitType = oldUnit.getTypeList();
List<String> unitType = unit.getTypeList();
// list
if (oldUnitType.retainAll(unitType) || (!StringUtils.equals(oldUnit.getName(), unit.getName()))
|| (!StringUtils.equals(oldUnit.getSuperior(), unit.getSuperior()))) {
return true;
}
return false;
}
}
|
package org.jkiss.dbeaver.model.impl.data.transformers;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.model.DBUtils;
import org.jkiss.dbeaver.model.data.*;
import org.jkiss.dbeaver.model.exec.DBCSession;
import org.jkiss.dbeaver.model.impl.data.ProxyValueHandler;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Transforms numeric attribute value into epoch time
*/
public class EpochTimeAttributeTransformer implements DBDAttributeTransformer {
@Override
public void transformAttribute(@NotNull DBCSession session, @NotNull DBDAttributeBinding attribute, @NotNull List<Object[]> rows) throws DBException {
// TODO: Change attribute type (to DATETIME)
attribute.setValueHandler(new EpochValueHandler(attribute.getValueHandler()));
}
private class EpochValueHandler extends ProxyValueHandler {
public EpochValueHandler(DBDValueHandler target) {
super(target);
}
@NotNull
@Override
public String getValueDisplayString(@NotNull DBSTypedObject column, @Nullable Object value, @NotNull DBDDisplayFormat format) {
if (value instanceof Number) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH).format(
new Date(((Number) value).longValue()));
}
return DBUtils.getDefaultValueDisplayString(value, format);
}
}
}
|
package org.hisp.dhis.android.core.dataset;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import org.hisp.dhis.android.core.common.ObjectWithUid;
import org.hisp.dhis.android.core.data.api.Fields;
import org.hisp.dhis.android.core.data.api.NestedField;
@AutoValue
public abstract class DataSetElements {
private final static String DATA_ELEMENT = "dataElement";
private final static String CATEGORY_COMBO = "categoryCombo";
public static final NestedField<DataSetElements, ObjectWithUid> dataElement =
NestedField.create(DATA_ELEMENT);
public static final NestedField<DataSetElements, ObjectWithUid> categoryCombo =
NestedField.create(CATEGORY_COMBO);
public static final Fields<DataSetElements> allFields =
Fields.<DataSetElements>builder().fields(dataElement.with(ObjectWithUid.uid),
categoryCombo.with(ObjectWithUid.uid)).build();
@NonNull
@JsonProperty(DATA_ELEMENT)
public abstract ObjectWithUid dataElement();
@Nullable
@JsonProperty(CATEGORY_COMBO)
public abstract ObjectWithUid categoryCombo();
@JsonCreator
public static DataSetElements create(
@JsonProperty(DATA_ELEMENT) ObjectWithUid dataElement,
@JsonProperty(CATEGORY_COMBO) ObjectWithUid categoryCombo) {
return new AutoValue_DataSetElements(dataElement, categoryCombo);
}
}
|
package org.mapfish.print.processor.jasper;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.google.common.collect.Lists;
import com.google.common.io.Closer;
import jsr166y.ForkJoinPool;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.data.JRTableModelDataSource;
import org.mapfish.print.Constants;
import org.mapfish.print.attribute.LegendAttribute.LegendAttributeValue;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.Template;
import org.mapfish.print.http.MfClientHttpRequestFactory;
import org.mapfish.print.processor.AbstractProcessor;
import org.mapfish.print.processor.InternalValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
/**
* <p>Create a legend.</p>
* <p>See also: <a href="attributes.html#!legend">!legend</a> attribute</p>
* [[examples=verboseExample,legend_cropped]]
*/
public final class LegendProcessor extends AbstractProcessor<LegendProcessor.Input, LegendProcessor.Output> {
private static final Logger LOGGER = LoggerFactory.getLogger(LegendProcessor.class);
private static final String NAME_COLUMN = "name";
private static final String ICON_COLUMN = "icon";
private static final String REPORT_COLUMN = "report";
private static final String LEVEL_COLUMN = "level";
@Autowired
private JasperReportBuilder jasperReportBuilder;
@Autowired
private MetricRegistry metricRegistry;
@Resource(name = "requestForkJoinPool")
private ForkJoinPool requestForkJoinPool;
// CSOFF:MagicNumber
private Dimension missingImageSize = new Dimension(24, 24);
// CSON:MagicNumber
private BufferedImage missingImage;
private Color missingImageColor = Color.PINK;
private String template;
private Integer maxWidth = null;
private Double dpi = Constants.PDF_DPI;
/**
* Constructor.
*/
protected LegendProcessor() {
super(Output.class);
}
/**
* The path to the Jasper Report template for rendering the legend data.
*
* @param template path to the template file
*/
public void setTemplate(final String template) {
this.template = template;
}
/**
* The maximum width in pixels for the legend graphics.
* If this parameter is set, the legend graphics are cropped to the given maximum
* width. In this case a sub-report is created containing the graphic.
* For reference see the example `legend_dynamic`.
*
* @param maxWidth The max. width.
*/
public void setMaxWidth(final Integer maxWidth) {
this.maxWidth = maxWidth;
}
/**
* The DPI value that is used for the legend graphics.
* Note: This parameter is only considered when `maxWidth` is set.
*
* @param dpi The DPI value.
*/
public void setDpi(final Double dpi) {
this.dpi = dpi;
}
@Override
public Input createInputParameter() {
return new Input();
}
@Override
public Output execute(final Input values, final ExecutionContext context) throws Exception {
final List<Object[]> legendList = new ArrayList<Object[]>();
final String[] legendColumns = {NAME_COLUMN, ICON_COLUMN, REPORT_COLUMN, LEVEL_COLUMN};
final LegendAttributeValue legendAttributes = values.legend;
fillLegend(values.clientHttpRequestFactory, legendAttributes, legendList, context, values.tempTaskDirectory);
final Object[][] legend = new Object[legendList.size()][];
final JRTableModelDataSource dataSource = new JRTableModelDataSource(new TableDataSource(legendColumns,
legendList.toArray(legend)));
String compiledTemplatePath = compileTemplate(values.template.getConfiguration());
return new Output(dataSource, legendList.size(), compiledTemplatePath);
}
private String compileTemplate(final Configuration configuration) throws JRException {
if (this.template != null) {
final File file = new File(configuration.getDirectory(), this.template);
return this.jasperReportBuilder.compileJasperReport(configuration, file).getAbsolutePath();
}
return null;
}
private class IconTask implements Callable<Object[]> {
private URL icon;
private ExecutionContext context;
private Closer closer;
private MfClientHttpRequestFactory clientHttpRequestFactory;
private int level;
private File tempTaskDirectory;
public IconTask(final URL icon, final ExecutionContext context,
final Closer closer, final int level, final File tempTaskDirectory,
final MfClientHttpRequestFactory clientHttpRequestFactory) {
this.icon = icon;
this.context = context;
this.closer = closer;
this.level = level;
this.clientHttpRequestFactory = clientHttpRequestFactory;
this.tempTaskDirectory = tempTaskDirectory;
}
@Override
public Object[] call() throws IOException, URISyntaxException, JRException {
BufferedImage image = null;
final URI uri = this.icon.toURI();
final String metricName = LegendProcessor.class.getName() + ".read." + uri.getHost();
try {
checkCancelState(this.context);
final ClientHttpRequest request = this.clientHttpRequestFactory.createRequest(uri, HttpMethod.GET);
final Timer.Context timer = LegendProcessor.this.metricRegistry.timer(metricName).time();
final ClientHttpResponse httpResponse = this.closer.register(request.execute());
if (httpResponse.getStatusCode() == HttpStatus.OK) {
image = ImageIO.read(httpResponse.getBody());
if (image == null) {
LOGGER.warn("The URL: " + this.icon + " is NOT an image format that can be decoded");
} else {
timer.stop();
}
} else {
LOGGER.warn("Failed to load image from: " + this.icon
+ " due to server side error.\n\tResponse Code: " + httpResponse.getStatusCode()
+ "\n\tResponse Text: " + httpResponse.getStatusText());
}
} catch (Exception e) {
LOGGER.warn("Failed to load image from: " + this.icon, e);
} finally {
this.closer.close();
}
if (image == null) {
image = getMissingImage();
LegendProcessor.this.metricRegistry.counter(metricName + ".error").inc();
}
String report = null;
if (LegendProcessor.this.maxWidth != null) {
// if a max width is given, create a sub-report containing the cropped graphic
report = createSubReport(image, this.tempTaskDirectory).toString();
}
return new Object[] {null, image, report, this.level};
}
}
private class NameTask implements Callable<Object[]> {
private String name;
private int level;
public NameTask(final String name, final int level) {
this.name = name;
this.level = level;
}
@Override
public Object[] call() {
return new Object[]{this.name, null, null, this.level};
}
}
private void createTasks(final MfClientHttpRequestFactory clientHttpRequestFactory,
final Closer closer, final LegendAttributeValue legendAttributes,
final ExecutionContext context, final File tempTaskDirectory,
final int level, final List<Callable<Object[]>> tasks) {
int insertNameIndex = tasks.size();
final URL[] icons = legendAttributes.icons;
if (icons != null && icons.length > 0) {
for (URL icon : icons) {
tasks.add(new IconTask(icon, context, closer, level, tempTaskDirectory, clientHttpRequestFactory));
}
}
if (legendAttributes.classes != null) {
for (LegendAttributeValue value : legendAttributes.classes) {
createTasks(clientHttpRequestFactory, closer, value, context, tempTaskDirectory, level + 1, tasks);
}
}
if (!tasks.isEmpty()) {
tasks.add(insertNameIndex, new NameTask(legendAttributes.name, level));
}
}
private void fillLegend(final MfClientHttpRequestFactory clientHttpRequestFactory,
final LegendAttributeValue legendAttributes,
final List<Object[]> legendList,
final ExecutionContext context,
final File tempTaskDirectory) throws ExecutionException, JRException, InterruptedException, IOException {
Closer closer = Closer.create();
List<Callable<Object[]>> tasks = new ArrayList<Callable<Object[]>>();
createTasks(clientHttpRequestFactory, closer, legendAttributes, context, tempTaskDirectory, 0, tasks);
List<Future<Object[]>> futures = this.requestForkJoinPool.invokeAll(tasks);
for (Future<Object[]> future : futures) {
legendList.add(future.get());
}
}
private URI createSubReport(final BufferedImage originalImage,
final File tempTaskDirectory) throws IOException, JRException {
assert (this.maxWidth != null);
double scaleFactor = getScaleFactor();
BufferedImage image = originalImage;
if (image.getWidth() * scaleFactor > this.maxWidth) {
image = cropToMaxWidth(image, scaleFactor);
}
URI imageFile = writeToFile(image, tempTaskDirectory);
final ImagesSubReport subReport = new ImagesSubReport(
Lists.newArrayList(imageFile),
new Dimension((int) (image.getWidth() * scaleFactor), (int) (image.getHeight() * scaleFactor)),
this.dpi);
final File compiledReport = File.createTempFile("legend-report-",
JasperReportBuilder.JASPER_REPORT_COMPILED_FILE_EXT, tempTaskDirectory);
subReport.compile(compiledReport);
return compiledReport.toURI();
}
private BufferedImage cropToMaxWidth(final BufferedImage image, final double scaleFactor) {
int width = (int) Math.round(this.maxWidth / scaleFactor);
return image.getSubimage(0, 0, width, image.getHeight());
}
private double getScaleFactor() {
return Constants.PDF_DPI / this.dpi;
}
private URI writeToFile(final BufferedImage image, final File tempTaskDirectory) throws IOException {
File path = File.createTempFile("legend-", ".png", tempTaskDirectory);
ImageIO.write(image, "png", path);
return path.toURI();
}
@Override
protected void extraValidation(final List<Throwable> validationErrors, final Configuration configuration) {
// no checks needed
}
private synchronized BufferedImage getMissingImage() {
if (this.missingImage == null) {
this.missingImage = new BufferedImage(this.missingImageSize.width, this.missingImageSize.height, BufferedImage.TYPE_INT_RGB);
final Graphics2D graphics = this.missingImage.createGraphics();
try {
graphics.setBackground(this.missingImageColor);
graphics.clearRect(0, 0, this.missingImageSize.width, this.missingImageSize.height);
} finally {
graphics.dispose();
}
}
return this.missingImage;
}
/**
* The Input Parameter object for {@link org.mapfish.print.processor.jasper.LegendProcessor}.
*/
public static final class Input {
/**
* The template that contains this processor.
*/
@InternalValue
public Template template;
/**
* A factory for making http requests. This is added to the values by the framework and therefore
* does not need to be set in configuration
*/
@InternalValue
public MfClientHttpRequestFactory clientHttpRequestFactory;
/**
* The path to the temporary directory for the print task.
*/
@InternalValue
public File tempTaskDirectory;
/**
* The data required for creating the legend.
*/
public LegendAttributeValue legend;
}
/**
* The Output object of the legend processor method.
*/
public static final class Output {
/**
* The datasource for the legend object in the report.
*/
public final JRTableModelDataSource legend;
/**
* The path to the compiled subreport.
*/
public final String legendSubReport;
/**
* The number of rows in the legend.
*/
public final int numberOfLegendRows;
Output(final JRTableModelDataSource legend, final int numberOfLegendRows, final String legendSubReport) {
this.legend = legend;
this.numberOfLegendRows = numberOfLegendRows;
this.legendSubReport = legendSubReport;
}
}
}
|
package org.mskcc.cbio.portal.scripts;
import org.mskcc.cbio.portal.dao.*;
import org.mskcc.cbio.portal.util.*;
import org.mskcc.cbio.portal.model.TypeOfCancer;
import java.io.*;
import java.util.*;
/**
* Load all the types of cancer and their names from a file.
*
* @author Arthur Goldberg goldberg@cbio.mskcc.org
*/
public class ImportTypesOfCancers {
public static void main(String[] args) throws IOException, DaoException {
try {
if (args.length < 1) {
System.out.println("command line usage: importTypesOfCancer.pl <types_of_cancer.txt> <clobber>");
// an extra --noprogress option can be given to avoid the messages regarding memory usage and % complete
//use 2 for command line syntax errors:
System.exit(2);
}
ProgressMonitor.setConsoleModeAndParseShowProgress(args);
ProgressMonitor.setCurrentMessage("Loading cancer types...");
File file = new File(args[0]);
// default to clobber = true (existing behavior)
boolean clobber = (args.length > 1 && (args[1].equalsIgnoreCase("f") || args[1].equalsIgnoreCase("false"))) ? false : true;
load(file, clobber);
}
catch (Exception e) {
ConsoleUtil.showWarnings();
//exit with error status:
System.err.println ("\nABORTED! Error: " + e.getMessage());
System.exit(1);
}
}
public static void load(File file, boolean clobber) throws IOException, DaoException {
SpringUtil.initDataSource();
if (clobber) DaoTypeOfCancer.deleteAllRecords(); //TODO - this option should not exist...in a relational DB it basically means the whole DB is cleaned-up...there should be more efficient ways to do this...and here it is probably an unwanted side effect. REMOVE??
TypeOfCancer aTypeOfCancer = new TypeOfCancer();
Scanner scanner = new Scanner(file);
int numNewCancerTypes = 0;
while(scanner.hasNextLine()) {
String[] tokens = scanner.nextLine().split("\t", -1);
if (tokens.length != 5) {
throw new IOException(
"Cancer type file '" + file.getPath() +
"' is not a five-column tab-delimited file");
}
String typeOfCancerId = tokens[0].trim();
//if not clobber, then existing cancer types should be skipped:
if (!clobber && DaoTypeOfCancer.getTypeOfCancerById(typeOfCancerId.toLowerCase()) != null ) {
ProgressMonitor.logWarning("Cancer type with id '" + typeOfCancerId + "' already exists. Skipping.");
}
else {
aTypeOfCancer.setTypeOfCancerId(typeOfCancerId.toLowerCase());
aTypeOfCancer.setName(tokens[1].trim());
aTypeOfCancer.setClinicalTrialKeywords(tokens[2].trim().toLowerCase());
aTypeOfCancer.setDedicatedColor(tokens[3].trim());
aTypeOfCancer.setShortName(typeOfCancerId);
aTypeOfCancer.setParentTypeOfCancerId(tokens[4].trim().toLowerCase());
DaoTypeOfCancer.addTypeOfCancer(aTypeOfCancer);
numNewCancerTypes++;
}
}
ProgressMonitor.setCurrentMessage(" --> Loaded " + numNewCancerTypes + " new cancer types.");
ProgressMonitor.setCurrentMessage("Done.");
ConsoleUtil.showMessages();
}
}
|
package xx.com.geowind;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int c;
int d;
}
}
|
package edu.mit.streamjit.test;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
import edu.mit.streamjit.api.CompiledStream;
import edu.mit.streamjit.api.DuplicateSplitter;
import edu.mit.streamjit.api.Filter;
import edu.mit.streamjit.api.Identity;
import edu.mit.streamjit.api.IllegalStreamGraphException;
import edu.mit.streamjit.api.Input;
import edu.mit.streamjit.api.Joiner;
import edu.mit.streamjit.api.OneToOneElement;
import edu.mit.streamjit.api.Output;
import edu.mit.streamjit.api.Pipeline;
import edu.mit.streamjit.api.Rate;
import edu.mit.streamjit.api.RoundrobinJoiner;
import edu.mit.streamjit.api.RoundrobinSplitter;
import edu.mit.streamjit.api.Splitjoin;
import edu.mit.streamjit.api.Splitter;
import edu.mit.streamjit.api.StreamCompiler;
import edu.mit.streamjit.api.StreamElement;
import edu.mit.streamjit.api.UnbalancedSplitjoinException;
import edu.mit.streamjit.impl.common.CheckVisitor;
import edu.mit.streamjit.impl.common.PrintStreamVisitor;
import edu.mit.streamjit.impl.common.TestFilters;
import edu.mit.streamjit.impl.common.TestFilters.Adder;
import edu.mit.streamjit.impl.common.TestFilters.ArrayHasher;
import edu.mit.streamjit.impl.common.TestFilters.ArrayListHasher;
import edu.mit.streamjit.impl.common.TestFilters.Batcher;
import edu.mit.streamjit.impl.common.TestFilters.Multiplier;
import edu.mit.streamjit.impl.common.TestFilters.PeekingAdder;
import edu.mit.streamjit.impl.common.TestFilters.StatefulAdder;
import edu.mit.streamjit.impl.common.TestFilters.StatefulMultiplier;
import edu.mit.streamjit.impl.compiler.CompilerStreamCompiler;
import edu.mit.streamjit.impl.compiler2.Compiler2StreamCompiler;
import edu.mit.streamjit.impl.interp.DebugStreamCompiler;
import edu.mit.streamjit.impl.interp.InterpreterStreamCompiler;
import edu.mit.streamjit.util.ConstructorSupplier;
import edu.mit.streamjit.util.ReflectionUtils;
import edu.mit.streamjit.util.Template;
import edu.mit.streamjit.util.ilpsolve.InfeasibleSystemException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
/**
* Generates random streams.
*
* TODO: this should verify DrainData, which seems to require working at the
* blob level, or surfacing DrainData somewhere.
* @author Jeffrey Bosboom <jeffreybosboom@gmail.com>
* @since 7/26/2013
*/
public final class StreamFuzzer {
public interface FuzzElement {
public OneToOneElement<Integer, Integer> instantiate();
public String toJava();
@Override
public boolean equals(Object other);
@Override
public int hashCode();
}
private static final int MAX_DEPTH = 5;
public static FuzzElement generate() {
return makeStream(MAX_DEPTH);
}
private static final Random rng = new Random();
private static final int FILTER_PROB = 50, PIPELINE_PROB = 25, SPLITJOIN_PROB = 25;
private static FuzzElement makeStream(int depthLimit) {
int r = rng.nextInt(FILTER_PROB + PIPELINE_PROB + SPLITJOIN_PROB);
if (depthLimit == 0 || r < FILTER_PROB) {
return makeFilter();
} else if (r < FILTER_PROB + PIPELINE_PROB) {
return makePipeline(depthLimit);
} else if (r < FILTER_PROB + PIPELINE_PROB + SPLITJOIN_PROB) {
return makeSplitjoin(depthLimit);
} else
throw new AssertionError(r);
}
private static final ImmutableList<FuzzFilter> FILTERS = ImmutableList.<FuzzFilter>builder()
.add(new FuzzFilter(Identity.class, ImmutableList.of()))
.add(new FuzzFilter(Adder.class, ImmutableList.of(1)))
.add(new FuzzFilter(Adder.class, ImmutableList.of(20)))
.add(new FuzzFilter(Multiplier.class, ImmutableList.of(2)))
.add(new FuzzFilter(Multiplier.class, ImmutableList.of(3)))
.add(new FuzzFilter(Multiplier.class, ImmutableList.of(100)))
.add(new FuzzFilter(Batcher.class, ImmutableList.of(2)))
.add(new FuzzFilter(Batcher.class, ImmutableList.of(10)))
.add(new FuzzFilter(ArrayHasher.class, ImmutableList.of(1)))
.add(new FuzzFilter(ArrayHasher.class, ImmutableList.of(2)))
.add(new FuzzFilter(ArrayHasher.class, ImmutableList.of(3)))
.add(new FuzzFilter(ArrayListHasher.class, ImmutableList.of(1)))
.add(new FuzzFilter(ArrayListHasher.class, ImmutableList.of(2)))
.add(new FuzzFilter(ArrayListHasher.class, ImmutableList.of(3)))
.add(new FuzzFilter(PeekingAdder.class, ImmutableList.of(3)))
.add(new FuzzFilter(PeekingAdder.class, ImmutableList.of(10)))
.add(new FuzzFilter(StatefulAdder.class, ImmutableList.of(1)))
.add(new FuzzFilter(StatefulAdder.class, ImmutableList.of(20)))
.add(new FuzzFilter(StatefulMultiplier.class, ImmutableList.of(2)))
.add(new FuzzFilter(StatefulMultiplier.class, ImmutableList.of(3)))
.add(new FuzzFilter(StatefulMultiplier.class, ImmutableList.of(100)))
.build();
private static FuzzFilter makeFilter() {
return FILTERS.get(rng.nextInt(FILTERS.size()));
}
private static final int MAX_PIPELINE_LENGTH = 5;
private static FuzzPipeline makePipeline(int depthLimit) {
int length = rng.nextInt(MAX_PIPELINE_LENGTH) + 1;
ImmutableList.Builder<FuzzElement> elements = ImmutableList.builder();
for (int i = 0; i < length; ++i)
elements.add(makeStream(depthLimit - 1));
return new FuzzPipeline(elements.build());
}
private static final int MAX_SPLITJOIN_BRANCHES = 5;
private static FuzzSplitjoin makeSplitjoin(int depthLimit) {
CheckVisitor cv = new CheckVisitor();
while (true) {
try {
int numBranches = rng.nextInt(MAX_SPLITJOIN_BRANCHES) + 1;
ImmutableList.Builder<FuzzElement> branches = ImmutableList.builder();
for (int i = 0; i < numBranches; ++i)
branches.add(makeStream(depthLimit - 1));
FuzzSplitjoin sj = new FuzzSplitjoin(makeSplitter(), makeJoiner(), branches.build());
sj.instantiate().visit(cv);
return sj;
} catch (UnbalancedSplitjoinException ex) {}
}
}
private static final ImmutableList<FuzzSplitter> SPLITTERS = ImmutableList.<FuzzSplitter>builder()
.add(new FuzzSplitter(RoundrobinSplitter.class, ImmutableList.of()))
.add(new FuzzSplitter(RoundrobinSplitter.class, ImmutableList.of(2)))
.add(new FuzzSplitter(RoundrobinSplitter.class, ImmutableList.of(3)))
.add(new FuzzSplitter(RoundrobinSplitter.class, ImmutableList.of(4)))
.add(new FuzzSplitter(DuplicateSplitter.class, ImmutableList.of()))
.build();
private static FuzzSplitter makeSplitter() {
return SPLITTERS.get(rng.nextInt(SPLITTERS.size()));
}
private static FuzzJoiner makeJoiner() {
return new FuzzJoiner(RoundrobinJoiner.class, ImmutableList.of());
}
private static final com.google.common.base.Joiner ARG_JOINER = com.google.common.base.Joiner.on(",\n");
private static class FuzzStreamElement<T extends StreamElement<Integer, Integer>> {
private final Class<? extends T> filterClass;
private final ImmutableList<?> arguments;
private final Supplier<? extends T> supplier;
protected FuzzStreamElement(Class<? extends T> filterClass, ImmutableList<? extends Object> arguments) {
this.filterClass = filterClass;
this.arguments = arguments;
this.supplier = new ConstructorSupplier<>(filterClass, arguments);
}
public T instantiate() {
return supplier.get();
}
public String toJava() {
return supplier.toString();
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FuzzStreamElement<?> other = (FuzzStreamElement<?>)obj;
if (!Objects.equals(this.filterClass, other.filterClass))
return false;
if (!Objects.equals(this.arguments, other.arguments))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + Objects.hashCode(this.filterClass);
hash = 41 * hash + Objects.hashCode(this.arguments);
return hash;
}
}
private static final class FuzzFilter extends FuzzStreamElement<Filter<Integer, Integer>> implements FuzzElement {
@SuppressWarnings({"unchecked","rawtypes"})
private FuzzFilter(Class<? extends Filter> filterClass, ImmutableList<? extends Object> arguments) {
super((Class<Filter<Integer, Integer>>)filterClass, arguments);
}
@Override
public Filter<Integer, Integer> instantiate() {
return super.instantiate();
}
//use inherited equals()/hashCode()
}
private static final class FuzzPipeline implements FuzzElement {
private final ImmutableList<FuzzElement> elements;
private FuzzPipeline(ImmutableList<FuzzElement> elements) {
this.elements = elements;
}
@Override
public Pipeline<Integer, Integer> instantiate() {
Pipeline<Integer, Integer> pipeline = new Pipeline<>();
for (FuzzElement e : elements)
pipeline.add(e.instantiate());
return pipeline;
}
@Override
public String toJava() {
List<String> args = new ArrayList<>(elements.size());
for (FuzzElement e : elements)
args.add(e.toJava());
return "new Pipeline(new OneToOneElement[]{\n" + ARG_JOINER.join(args) + "\n})";
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FuzzPipeline other = (FuzzPipeline)obj;
if (!Objects.equals(this.elements, other.elements))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 5;
hash = 59 * hash + Objects.hashCode(this.elements);
return hash;
}
}
/**
* Can't implement FuzzElement because Splitter isn't a OneToOneElement, but
* can still share the instantiation code.
*/
private static final class FuzzSplitter extends FuzzStreamElement<Splitter<Integer, Integer>> {
@SuppressWarnings({"unchecked","rawtypes"})
private FuzzSplitter(Class<? extends Splitter> filterClass, ImmutableList<? extends Object> arguments) {
super((Class<Splitter<Integer, Integer>>)filterClass, arguments);
}
@Override
public Splitter<Integer, Integer> instantiate() {
return super.instantiate();
}
//use inherited equals()/hashCode()
}
/**
* See comments on FuzzSplitter.
*/
private static final class FuzzJoiner extends FuzzStreamElement<Joiner<Integer, Integer>> {
@SuppressWarnings({"unchecked","rawtypes"})
private FuzzJoiner(Class<? extends Joiner> filterClass, ImmutableList<? extends Object> arguments) {
super((Class<Joiner<Integer, Integer>>)filterClass, arguments);
}
@Override
public Joiner<Integer, Integer> instantiate() {
return super.instantiate();
}
//use inherited equals()/hashCode()
}
private static final class FuzzSplitjoin implements FuzzElement {
private final FuzzSplitter splitter;
private final FuzzJoiner joiner;
private final ImmutableList<FuzzElement> branches;
private FuzzSplitjoin(FuzzSplitter splitter, FuzzJoiner joiner, ImmutableList<FuzzElement> branches) {
this.splitter = splitter;
this.joiner = joiner;
this.branches = branches;
}
@Override
public OneToOneElement<Integer, Integer> instantiate() {
Splitjoin<Integer, Integer> splitjoin = new Splitjoin<>(splitter.instantiate(), joiner.instantiate());
for (FuzzElement e : branches)
splitjoin.add(e.instantiate());
return splitjoin;
}
@Override
public String toJava() {
List<String> args = new ArrayList<>(branches.size());
for (FuzzElement e : branches)
args.add(e.toJava());
return "new Splitjoin(" + splitter.toJava() + ", " + joiner.toJava()+", new OneToOneElement[]{\n" + ARG_JOINER.join(args) + "\n})";
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final FuzzSplitjoin other = (FuzzSplitjoin)obj;
if (!Objects.equals(this.splitter, other.splitter))
return false;
if (!Objects.equals(this.joiner, other.joiner))
return false;
if (!Objects.equals(this.branches, other.branches))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 71 * hash + Objects.hashCode(this.splitter);
hash = 71 * hash + Objects.hashCode(this.joiner);
hash = 71 * hash + Objects.hashCode(this.branches);
return hash;
}
}
private static final int INPUT_LENGTH = 1000;
private static List<Integer> run(FuzzElement element, StreamCompiler compiler) throws InterruptedException {
OneToOneElement<Integer, Integer> graph = element.instantiate();
Input<Object> input = Datasets.allIntsInRange(0, INPUT_LENGTH).input();
List<Integer> retval = new ArrayList<>();
Output<Integer> output = Output.toCollection(retval);
@SuppressWarnings("unchecked")
CompiledStream stream = compiler.compile(graph, (Input)input, output);
stream.awaitDrained();
return retval;
}
private static final ImmutableSet<Class<?>> ignoredExceptions = ImmutableSet.<Class<?>>of(
InfeasibleSystemException.class
);
public static void main(String[] args) throws InterruptedException, IOException {
StreamCompiler debugSC = new InterpreterStreamCompiler();
StreamCompiler compilerSC = new Compiler2StreamCompiler();
Set<FuzzElement> completedCases = new HashSet<>();
int generated;
int duplicatesSkipped = 0;
Multiset<Class<?>> ignored = HashMultiset.create(ignoredExceptions.size());
int failures = 0, successes = 0;
next_case: for (generated = 0; true; ++generated) {
FuzzElement fuzz = StreamFuzzer.generate();
if (!completedCases.add(fuzz)) {
++duplicatesSkipped;
continue;
}
try {
fuzz.instantiate().visit(new CheckVisitor());
} catch (IllegalStreamGraphException ex) {
System.out.println("Fuzzer generated bad test case");
ex.printStackTrace(System.out);
fuzz.instantiate().visit(new PrintStreamVisitor(System.out));
}
List<Integer> debugOutput = run(fuzz, debugSC);
List<Integer> compilerOutput = null;
try {
compilerOutput = run(fuzz, compilerSC);
} catch (Throwable ex) {
for (Throwable t : Throwables.getCausalChain(ex))
if (ignoredExceptions.contains(t.getClass())) {
ignored.add(t.getClass());
continue next_case;
}
System.out.println("Compiler failed");
ex.printStackTrace(System.out);
//fall into the if below
}
if (!debugOutput.equals(compilerOutput)) {
++failures;
fuzz.instantiate().visit(new PrintStreamVisitor(System.out));
System.out.println(fuzz.toJava());
//TODO: show only elements where they differ
System.out.println("Debug output: "+debugOutput);
System.out.println("Compiler output: "+compilerOutput);
writeRegressionTest(fuzz);
break;
} else
++successes;
System.out.println(fuzz.hashCode()+" matched");
}
System.out.format("Generated %d cases%n", generated);
System.out.format(" skipped %d duplicates (%f%%)%n", duplicatesSkipped, ((double)duplicatesSkipped)*100/generated);
for (Class<?> c : ignoredExceptions) {
int count = ignored.count(c);
if (count > 0)
System.out.format(" ignored %d due to %s (%f%%)%n", count, c, ((double)count)*100/generated);
}
System.out.format("Ran %d cases (%f%% run rate)%n", successes+failures, ((double)successes+failures)*100/generated);
System.out.format(" %d succeeded (%f%%)%n", successes, ((double)successes)*100/(successes+failures));
System.out.format(" %d failed (%f%%)%n", failures, ((double)failures)*100/(successes+failures));
}
private static final DateFormat SINCE_FORMAT = new SimpleDateFormat("M/d/yyyy h:mma z");
private static final DateFormat NAME_FORMAT = new SimpleDateFormat("yyyyMMdd_hhmmss_SSS");
private static void writeRegressionTest(FuzzElement fuzzTest) throws IOException {
Template template = Template.from(StreamFuzzer.class.getResourceAsStream("RegressionBenchmark.template"));
Date now = new Date();
Map<String, Object> values = new HashMap<>();
values.put("name", "Reg"+NAME_FORMAT.format(now));
values.put("since", SINCE_FORMAT.format(now));
values.put("dataset", "Datasets.allIntsInRange(0, 1000)");
values.put("instantiate", fuzzTest.toJava());
values.put("referenceCompiler", "new "+InterpreterStreamCompiler.class.getCanonicalName()+"()");
values.put("testCompiler", "new "+Compiler2StreamCompiler.class.getCanonicalName()+"()");
StringBuffer sb = new StringBuffer();
template.replace(values, sb);
Path path = Paths.get("src/edu/mit/streamjit/test/regression", values.get("name")+".java");
Files.write(path, ImmutableList.of(sb.toString()), StandardCharsets.UTF_8, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
}
}
|
package edu.wustl.common.hibernate;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.EntityMode;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.type.Type;
public class Metadata {
private static final SessionFactory sessionFactory = DBUtil.getSessionFactory();
private static final EntityMode ENTITY_MODE = EntityMode.POJO;
private final Set<String> primitiveValues;
private final Set<String> collectionsValues;
private final Set<String> associatedValues;
private final ClassMetadata classMetadata;
private final Object obj;
public Metadata(Object obj) {
primitiveValues = new HashSet<String>();
collectionsValues = new HashSet<String>();
associatedValues = new HashSet<String>();
this.obj = obj;
classMetadata = getClassMetadata(obj.getClass());
String[] names = classMetadata.getPropertyNames();
for (int i = 0; i < names.length; i++) {
String name = names[i];
Type type = classMetadata.getPropertyType(name);
Set<String> targetSet;
if (type.isCollectionType()) {
targetSet = collectionsValues;
} else if (type.isEntityType()) {
// TODO check this
targetSet = associatedValues;
} else {
targetSet = primitiveValues;
}
targetSet.add(name);
}
}
private static ClassMetadata getClassMetadata(Class<?> klass) {
return sessionFactory.getClassMetadata(klass);
}
public Set<String> getAssociations() {
return associatedValues;
}
public Set<String> getCollections() {
return collectionsValues;
}
public Set<String> getPrimitives() {
return primitiveValues;
}
public Object getValue(String name) {
return classMetadata.getPropertyValue(obj, name, ENTITY_MODE);
}
public Type getType(String name) {
return classMetadata.getPropertyType(name);
}
public void setValue(String name, Object value) {
classMetadata.setPropertyValue(obj, name, value, ENTITY_MODE);
}
public void nullifyId() {
classMetadata.setIdentifier(obj, null, ENTITY_MODE);
}
}
|
package roart.common.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import roart.common.model.MetaItem;
public class MetaUtil {
public MetaItem findMeta(List<MetaItem> metas, String marketName) {
for (MetaItem meta : metas) {
if (marketName.equals(meta.getMarketid())) {
return meta;
}
}
return null;
}
public List<String> getCategories(MetaItem meta) {
if (meta == null) {
return new ArrayList<>();
}
return Arrays.asList(meta.getPeriod()).stream().filter(Objects::nonNull).collect(Collectors.toList());
}
}
|
package bt;
import ec.gp.GPNode;
import java.awt.*;
import java.util.ArrayList;
public abstract class Task<E> extends GPNode {
private static final long serialVersionUID = 1;
protected Task<E> parent;
protected Task<E> runningTask;
protected ArrayList<Task<E>> childTasks;
protected BehaviourTree<E> tree;
public enum TaskState {
SUCCEEDED(Color.GREEN),
FAILED(Color.RED),
RUNNING(Color.BLUE),
NEUTRAL(Color.WHITE),
CANCELLED(Color.PINK);
public final Color color;
TaskState(Color color) {
this.color = color;
}
}
public TaskState taskState = TaskState.NEUTRAL;
public abstract void start();
public abstract void end();
public abstract void run();
public abstract String humanToString();
/**
* Recursively resets the task so it can restart safely on the next run.
*/
public void reset() {
runningTask = null;
if(taskState == TaskState.RUNNING) cancel();
for(int i=0; i<getChildCount(); i++) {
getChild(i).reset();
}
taskState = TaskState.NEUTRAL;
/*
//TODO hmmm, should I really reset this.. Have to check that
tree = null;
parent = null;
*/
}
public final void cancel() {
cancelFollowingChildren(0);
taskState = TaskState.CANCELLED;
end();
}
protected void cancelFollowingChildren(int index) {
for(int i = index; i<getChildCount(); i++) {
Task<E> child = getChild(i);
if(child.taskState == TaskState.RUNNING)
child.cancel();
}
}
/**
* Get blackboard object
* @return Blackboard Object
*/
public E getBlackboard() {
if(tree == null)
throw new IllegalStateException("bt.Task has never been run");
return tree.getBlackboard();
}
/**
* Set parent task
* @param parent The parent of the task
*/
public void setParent(Task<E> parent) {
this.parent = parent;
this.tree = parent.tree;
}
public Task<E> getParent() {
return parent;
}
/**
* Will be called to signal parent that this task has to run again.
*/
public final void running() {
taskState = TaskState.RUNNING;
if(null != parent)
parent.childRunning(this, this);
}
/**
* Will be called to signal that the task is finished running and have succeeded/failed
*/
public void success() {
taskState = TaskState.SUCCEEDED;
end();
if(parent != null)
parent.childSuccess(this);
}
public void fail() {
taskState = TaskState.FAILED;
end();
if(parent != null)
parent.childFail(this);
}
/**
* Called when one of the childTasks respectively succeed or fail
* @param task task that succeeded/failed
*/
public void childFail(Task<E> task) {
this.runningTask = null;
}
public void childSuccess(Task<E> task) {
this.runningTask = null;
}
/**
* Children uses this method to signal the ancestor that needs to run again.
*
* @param focal the running task (that needs to run again)
* @param nonFocal the reporter task (usually one of its childTasks)
*/
public void childRunning(Task<E> focal, Task<E> nonFocal) {
this.runningTask = focal;
}
// Child handlers
public void addChild(Task<E> child) {
childTasks.add(child);
}
public Task<E> getChild(int i) {
return childTasks.get(i);
}
public int getChildCount() {
return childTasks.size();
}
/**
* Default naming convention, utilizing the
* same algorithm as used by the TreeInterpreter
* @return Leaf-node identifier
**/
protected String getStandardName() {
String sn = getClass().getSimpleName();
return Character.toLowerCase(sn.charAt(0))
+ (sn.length() > 1 ? sn.substring(1): "");
}
}
|
package org.mozartoz.truffle.nodes;
import org.mozartoz.truffle.runtime.OzArguments;
import org.mozartoz.truffle.runtime.OzException;
import org.mozartoz.truffle.runtime.OzLanguage;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.nodes.RootNode;
import com.oracle.truffle.api.source.SourceSection;
public class OzRootNode extends RootNode {
private final int arity;
@Child OzNode body;
public OzRootNode(SourceSection sourceSection, FrameDescriptor frameDescriptor, OzNode body, int arity) {
super(OzLanguage.class, sourceSection, frameDescriptor);
this.body = body;
this.arity = arity;
}
@Override
public Object execute(VirtualFrame frame) {
checkArity(frame);
return body.execute(frame);
}
private void checkArity(VirtualFrame frame) {
int given = OzArguments.getArgumentCount(frame);
if (given != arity) {
CompilerDirectives.transferToInterpreter();
throw new OzException(this, "arity mismatch: " + given + " VS " + arity);
}
}
@Override
public String toString() {
return OzRootNode.class.getSimpleName() + "@" + getSourceSection();
}
}
|
package algorithms.matrix;
import gnu.trove.list.array.TDoubleArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import no.uib.cipr.matrix.DenseMatrix;
import no.uib.cipr.matrix.Matrices;
import no.uib.cipr.matrix.Matrix;
import no.uib.cipr.matrix.MatrixEntry;
import no.uib.cipr.matrix.NotConvergedException;
import no.uib.cipr.matrix.SVD;
/**
* TODO: tidy code for multiply and dot operations
*
* @author nichole
*/
public class MatrixUtil {
/**
* multiply matrix m by vector n
* @param m two dimensional array in row major format
* @param n one dimensional array
* @return the multiplication of matrix m by n
*/
public static double[] multiply(double[][] m, double[] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
int mcols = m[0].length;
int mrows = m.length;
int ncols = n.length;
if (mcols != ncols) {
throw new IllegalArgumentException(
"the number of columns in m must equal the length of n");
}
double[] c = new double[mrows];
int cCol = 0;
for (int row = 0; row < mrows; row++) {
for (int col = 0; col < mcols; col++) {
c[cCol] += (m[row][col] * n[col]);
}
cCol++;
}
return c;
}
/**
* multiply matrix m by vector n
* @param m two dimensional array in row major format
* @param n one dimensional array
* @return the multiplication of matrix m by n
*/
public static float[] multiply(float[][] m, float[] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
int mcols = m[0].length;
int mrows = m.length;
int ncols = n.length;
if (mcols != ncols) {
throw new IllegalArgumentException(
"the number of columns in m must equal the number of rows in n");
}
float[] c = new float[mrows];
int cCol = 0;
for (int row = 0; row < mrows; row++) {
for (int col = 0; col < mcols; col++) {
c[cCol] += (m[row][col] * n[col]);
}
cCol++;
}
return c;
}
/**
* multiply vector m by factor
* @param m one dimensional array that is input and output for result
* @param factor factor to multiply m by
*/
public static void multiply(int[] m, int factor) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
int len = m.length;
for (int i = 0; i < len; i++) {
m[i] *= factor;
}
}
/**
* multiply matrix m by factor
* @param a two dimensional array in that is input and output for result
* @param m factor to multiply m by
*/
public static void multiply(float[][] a, float m) {
if (a == null || a.length == 0) {
throw new IllegalArgumentException("a cannot be null or empty");
}
int mcols = a.length;
int mrows = a[0].length;
for (int col = 0; col < mcols; col++) {
for (int row = 0; row < mrows; row++) {
a[col][row] *= m;
}
}
}
public static void multiply(int[] m, int[] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m must be the same size as n");
}
int len = m.length;
for (int i = 0; i < len; i++) {
m[i] *= n[i];
}
}
/**
* multiply matrix m by matrix n
* @param m tow dimensional array in ro major format
* @param n two dimensional array in row major format
* @return multiplication of m by n
*/
public static double[][] multiply(double[][] m, double[][] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
int mrows = m.length;
int mcols = m[0].length;
int nrows = n.length;
int ncols = n[0].length;
if (mcols != nrows) {
throw new IllegalArgumentException(
"the number of columns in m must equal the number of rows in n");
}
/*
a b c p0 p1 p2
d e f p3 p4 p5
p6 p7 p8
a*p0 + b*p3 + c*p6 a*p1 + b*p4 + c*p7 a*p2 + b*p5 + c*p8
d*p0 + d*p3 + e*p6 d*p1 + d*p4 + e*p7 d*p2 + e*p5 + f*p8
*/
// mrows X ncols
double[][] c = new double[mrows][];
for (int mrow = 0; mrow < mrows; mrow++) {
c[mrow] = new double[ncols];
for (int ncol = 0; ncol < ncols; ncol++) {
double sum = 0;
for (int mcol = 0; mcol < mcols; mcol++) {
sum += (m[mrow][mcol] * n[mcol][ncol]);
}
c[mrow][ncol] = sum;
}
}
return c;
}
public static void multiply(double[] a, double f) {
for (int i = 0; i < a.length; ++i) {
a[i] *= f;
}
}
public static void multiply(double[][] m, double factor) {
int nrows = m.length;
int ncols = m[0].length;
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
m[i][j] = factor*m[i][j];
}
}
}
/**
* perform dot product and return matrix of size mrows X ncols
* @param m
* @param n
* @return
*/
public static DenseMatrix multiply(
Matrix m, Matrix n) {
if (m == null || m.numRows() == 0 || m.numColumns() == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.numRows() == 0 || n.numColumns() == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
int mrows = m.numRows();
int mcols = m.numColumns();
int nrows = n.numRows();
int ncols = n.numColumns();
if (mcols != nrows) {
throw new IllegalArgumentException(
"the number of columns in m must equal the number of rows in n");
}
/*
a b c p0 p1 p2
d e f p3 p4 p5
p6 p7 p8
a*p0+... a*p a*p
d*p0+... d*p d*p
*/
no.uib.cipr.matrix.DenseMatrix c = new DenseMatrix(mrows, ncols);
for (int row = 0; row < mrows; row++) {
for (int ncol = 0; ncol < ncols; ncol++) {
double sum = 0;
for (int mcol = 0; mcol < mcols; mcol++) {
sum += (m.get(row, mcol) * n.get(mcol, ncol));
}
c.set(row, ncol, sum);
}
}
return c;
}
public static double[] multiply(Matrix a, double[] b) {
if (a == null || a.numRows() == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (b == null || b.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
int mrows = a.numRows();
int mcols = a.numColumns();
int nrows = b.length;
if (mcols != nrows) {
throw new IllegalArgumentException(
"the number of cols in a must equal the length of b");
}
double[] c = new double[mrows];
int cCol = 0;
/*
a0 1 2 0
1
2
*/
for (int row = 0; row < mrows; row++) {
for (int col = 0; col < mcols; col++) {
c[cCol] += (a.get(row, col) * b[col]);
}
cCol++;
}
return c;
}
public static void multiply(TDoubleArrayList a, double f) {
for (int i = 0; i < a.size(); ++i) {
a.set(i, f * a.get(i));
}
}
public static void multiply(Matrix a, double b) {
if (a == null || a.numRows() == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
Iterator<MatrixEntry> iter = a.iterator();
while (iter.hasNext()) {
MatrixEntry entry = iter.next();
entry.set(entry.get() * b);
}
}
/**
* perform dot product of m and a diagonalized matrix of diag,
* and return matrix of size mrows X mcols
* @param m
* @param diag
* @return
*/
public static double[][] multiplyByDiagonal(
double[][] m, double[] diag) {
if (m == null || m.length == 0 || m[0].length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (diag == null || diag.length == 0) {
throw new IllegalArgumentException("diag cannot be null or empty");
}
int mrows = m.length;
int mcols = m[0].length;
int nrows = diag.length;
if (mcols != nrows) {
throw new IllegalArgumentException(
"the number of columns in m must equal the number of rows in n");
}
/*
a b c p0 0 0
d e f 0 p1 0
0 0 p2
*/
double[][] c = new double[mrows][mcols];
for (int row = 0; row < mrows; row++) {
c[row] = new double[mcols];
for (int mcol = 0; mcol < mcols; mcol++) {
c[row][mcol] = m[row][mcol] * diag[mcol];
}
}
return c;
}
/**
* perform dot product of m and a diagonalized matrix of diag,
* and return matrix of size mrows X mcols
* @param m
* @param diag
*/
public static void multiplyByDiagonal(DenseMatrix m, double[] diag) {
if (m == null || m.numRows() == 0 || m.numColumns() == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (diag == null || diag.length == 0) {
throw new IllegalArgumentException("diag cannot be null or empty");
}
int mrows = m.numRows();
int mcols = m.numColumns();
int nrows = diag.length;
if (mcols != nrows) {
throw new IllegalArgumentException(
"the number of columns in m must equal the number of rows in n");
}
/*
a b c p0 0 0
d e f 0 p1 0
0 0 p2
*/
for (int row = 0; row < mrows; row++) {
for (int mcol = 0; mcol < mcols; mcol++) {
m.set(row, mcol, m.get(row, mcol) * diag[mcol]);
}
}
}
public static double multiplyByTranspose(TDoubleArrayList a,
TDoubleArrayList b) {
int sz0 = a.size();
int sz1 = b.size();
if (sz0 != sz1) {
throw new IllegalArgumentException(
"a and b must be same size");
}
double s = 0;
for (int i = 0; i < a.size(); ++i) {
s += a.get(i) * b.get(i);
}
return s;
}
public static double multiplyByTranspose(double[] a,
double[] b) {
int sz0 = a.length;
int sz1 = b.length;
if (sz0 != sz1) {
throw new IllegalArgumentException(
"a and b must be same size");
}
double s = 0;
for (int i = 0; i < a.length; ++i) {
s += a[i] * b[i];
}
return s;
}
public static double dot(double[] a, double[] b) {
if (a.length != b.length) {
throw new IllegalArgumentException("a.length must == b.length");
}
double sum = 0;
for (int i = 0; i < a.length; ++i) {
sum += (a[i] * b[i]);
}
return sum;
}
public static double[][] dot(DenseMatrix m1, DenseMatrix m2) {
if (m1 == null) {
throw new IllegalArgumentException("m1 cannot be null");
}
if (m2 == null) {
throw new IllegalArgumentException("m2 cannot be null");
}
int cCols = m2.numColumns();
int cRows = m1.numRows();
if (m1.numColumns() != m2.numRows()) {
throw new IllegalArgumentException(
"the number of columns in m1 != number of rows in m2");
}
// m1 dot m2
double[][] m = new double[cRows][cCols];
for (int i = 0; i < cRows; i++) {
m[i] = new double[cCols];
}
/*
t00 t01 t02 x1 x2 x3 x4
t10 t11 t12 y1 y2 y3 y4
t20 t21 t22 1 1 1 1
row=0, col=0:nCols0 times and plus col=0, row=0:nRows1 --> stored in row, row + (cAdd=0)
row=1, col=0:nCols0 times and plus col=0, row=0:nRows1 --> stored in row, row + (cAdd=0)
row=0, col=0:nCols0 times and plus col=(cAdd=1), row=0:nRows1 --> stored in row, row + (cAdd=0)
*/
for (int colAdd = 0; colAdd < m2.numColumns(); colAdd++) {
for (int row = 0; row < m1.numRows(); ++row) {
for (int col = 0; col < m1.numColumns(); col++) {
double a = m1.get(row, col);
double b = m2.get(col, colAdd);
m[row][colAdd] += (a * b);
}
}
}
return m;
}
/**
* apply dot operator to m1 and m2 which are formatted using same as
* DenseMatrix, that is row major [row][col].
* @param m1
* @param m2
* @return
*/
public static double[][] dot(double[][] m1, double[][] m2) {
if (m1 == null) {
throw new IllegalArgumentException("m1 cannot be null");
}
if (m2 == null) {
throw new IllegalArgumentException("m2 cannot be null");
}
int cCols = m2[0].length;
int cRows = m1.length;
if (m1[0].length != m2.length) {
throw new IllegalArgumentException(
"the number of columns in m1 != number of rows in m2");
}
// m1 dot m2
double[][] m = new double[cRows][cCols];
for (int i = 0; i < cRows; i++) {
m[i] = new double[cCols];
}
for (int colAdd = 0; colAdd < m2[0].length; colAdd++) {
for (int row = 0; row < m1.length; ++row) {
for (int col = 0; col < m1[0].length; col++) {
double a = m1[row][col];
double b = m2[col][colAdd];
m[row][colAdd] += (a * b);
}
}
}
return m;
}
public static TDoubleArrayList subtract(TDoubleArrayList a, TDoubleArrayList b) {
int sz0 = a.size();
int sz1 = b.size();
if (sz0 != sz1) {
throw new IllegalArgumentException(
"a and b must be same size");
}
TDoubleArrayList c = new TDoubleArrayList(sz0);
for (int i = 0; i < a.size(); ++i) {
c.add(a.get(i) - b.get(i));
}
return c;
}
public static double[] subtract(double[] m, double[] n) {
int len = m.length;
double[] c = new double[len];
subtract(m, n, c);
return c;
}
public static void subtract(double[] m, double[] n,
double[] output) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m and n must be same length");
}
int len = m.length;
for (int i = 0; i < len; i++) {
output[i] = m[i] - n[i];
}
}
public static double[] add(double[] m, double[] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m and n must be same length");
}
int len = m.length;
double[] c = new double[len];
for (int i = 0; i < len; i++) {
c[i] = m[i] + n[i];
}
return c;
}
public static float[] add(float[] m, float[] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m and n must be same length");
}
int len = m.length;
float[] c = new float[len];
for (int i = 0; i < len; i++) {
c[i] = m[i] + n[i];
}
return c;
}
public static float[][] subtract(float[][] m, float[][] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m and n must be same length");
}
if (m[0].length != n[0].length) {
throw new IllegalArgumentException("m and n must be same length");
}
float[][] c = new float[m.length][];
for (int i = 0; i < m.length; ++i) {
c[i] = new float[m[0].length];
for (int j = 0; j < m[0].length; ++j) {
c[i][j] -= m[i][j] - n[i][j];
}
}
return c;
}
public static float[][] add(float[][] m, float[][] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m and n must be same length");
}
if (m[0].length != n[0].length) {
throw new IllegalArgumentException("m and n must be same length");
}
float[][] c = new float[m.length][];
for (int i = 0; i < m.length; ++i) {
c[i] = new float[m[0].length];
for (int j = 0; j < m[0].length; ++j) {
c[i][j] = m[i][j] + n[i][j];
}
}
return c;
}
public static float[] subtract(float[] m, float[] n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null || n.length == 0) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.length != n.length) {
throw new IllegalArgumentException("m and n must be same length");
}
int len = m.length;
float[] c = new float[len];
for (int i = 0; i < len; i++) {
c[i] = m[i] - n[i];
}
return c;
}
public static DenseMatrix subtract(DenseMatrix m, DenseMatrix n) {
if (m == null) {
throw new IllegalArgumentException("m cannot be null or empty");
}
if (n == null) {
throw new IllegalArgumentException("n cannot be null or empty");
}
if (m.numRows() != n.numRows() || m.numColumns() != n.numColumns()) {
throw new IllegalArgumentException("m and n must be same length");
}
DenseMatrix output = new DenseMatrix(m.numRows(), m.numColumns());
for (int i = 0; i < m.numRows(); ++i) {
for (int j = 0; j < m.numColumns(); ++j) {
double v0 = m.get(i, j);
double v1 = n.get(i, j);
output.set(i, j, v0 - v1);
}
}
return output;
}
public static void add(int[] m, int n) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
int len = m.length;
for (int i = 0; i < len; i++) {
m[i] += n;
}
}
public static float[][] transpose(float[][] m) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
int mRows = m.length;
int mCols = m[0].length;
float[][] t = new float[mCols][];
for (int i = 0; i < mCols; i++) {
t[i] = new float[mRows];
}
for (int i = 0; i < mRows; i++) {
for (int j = 0; j < mCols; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
public static DenseMatrix transpose(DenseMatrix m) {
int mRows = m.numRows();
int mCols = m.numColumns();
double[][] t = new double[mRows][];
for (int i = 0; i < mRows; i++) {
t[i] = new double[mCols];
for (int j = 0; j < mCols; j++) {
t[i][j] = m.get(i, j);
}
}
double[][] transposed = transpose(t);
DenseMatrix mT = new DenseMatrix(transposed);
return mT;
}
public static double[][] transpose(double[][] m) {
if (m == null || m.length == 0) {
throw new IllegalArgumentException("m cannot be null or empty");
}
int mRows = m.length;
int mCols = m[0].length;
double[][] t = new double[mCols][];
for (int i = 0; i < mCols; i++) {
t[i] = new double[mRows];
}
for (int i = 0; i < mRows; i++) {
for (int j = 0; j < mCols; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
public static double[][] convertToRowMajor(DenseMatrix a) {
int nc = a.numColumns();
int nr = a.numRows();
double[][] out = new double[nr][];
for (int i = 0; i < nr; ++i) {
out[i] = new double[nc];
for (int j = 0; j < nc; ++j) {
out[i][j] = a.get(i, j);
}
}
return out;
}
public static double[][] pseudoinverseRankDeficient(double[][] a) throws NotConvergedException {
int m = a.length;
int n = a[0].length;
// limit for a number to be significant above 0
double eps = 1e-16;
// from Gilbert Strang's "Introduction to Linear Algebra":
// uses SVD:
// A_inverse = V * pseudoinverse(S) * U^T
// where pseudoinverse(S) is simply an empty matrix with the diagonal
// being the reciprocal of each singular value
// NOTE: compare number of ops w/ this factoring:
// V * (pseudoinverse(S) * U^T)
// A_inverse is n X m
// V is n X n
// pseudoinverse(S) is n X m
// U^T is m X m
DenseMatrix aMatrix = new DenseMatrix(a);
SVD svd = SVD.factorize(aMatrix);
//TODO: rewrite to use fewer data structures and multiply in place.
// s is an array of size min(m,n)
double[] s = svd.getS();
int rank = 0;
for (double sv : s) {
if (sv > eps) {
rank++;
}
}
DenseMatrix vTM = svd.getVt();
double[][] vT = MatrixUtil.convertToRowMajor(vTM);
double[][] v = MatrixUtil.transpose(vT);
DenseMatrix uM = svd.getU();
double[][] uT = MatrixUtil.convertToRowMajor(uM);
/*
U is mxn orthonormal columns
S is nxn with non-negative singular values. rank is number of non-zero entries
V is nxn
*/
assert(v.length == n);
assert(v[0].length == n);
assert(uT.length == m);
assert(uT[0].length == m);
double[][] sInverse = new double[n][];
for (int i = 0; i < n; ++i) {
sInverse[i] = new double[m];
}
for (int i = 0; i < s.length; ++i) {
double sI = s[i];
if (sI > eps) {
sInverse[i][i] = 1./sI;
}
}
/*
U is mxn orthonormal columns
S is nxn with non-negative singular values. rank is number of non-zero entries
V is nxn
pseudoinverse(S) is nxm
*/
//A_inverse = V * pseudoinverse(S) * U^T
double[][] inv = MatrixUtil.multiply(v, sInverse);
inv = MatrixUtil.multiply(inv, uT);
return inv;
}
/**
* calculate the pseudo-inverse of matrix a (dimensions mxn) which is a full
* rank matrix, i.e. rank = m, using LUP decomposition
* (inverse(A^T*A) * A^T).
* NOTE that (A^T*A) has to be invertible, that is, the reduced echelon form
* of A has linearly independent columns (rank==n).
* following pseudocode from Cormen et al. Introduction to Algorithms.
* @param a two dimensional array in row major format with dimensions
* m x n. a is a full-rank matrix.
* a is a non-singular matrix(i.e. has exactly one solution).
*
* @return
* @throws NotConvergedException
*/
public static double[][] pseudoinverseFullRank(double[][] a) throws NotConvergedException {
int m = a.length;
int n = a[0].length;
// limit for a number to be significant above 0 (precision of computer)
double eps = 1e-16;
//from cormen et al: A_pseudoinverse = inverse(A^T*A) * A^T
double[][] aT = MatrixUtil.transpose(a);
double[][] aTA = MatrixUtil.multiply(aT, a);
DenseMatrix aTAM = new DenseMatrix(aTA);
//NOTE that (A^T*A) has to be invertible, that is, the reduced echelon form
// of A has linearly independent columns (no free variables, only pivots.
// which also means rank==n).
// could invert (A^T*A) using the cofactor matrix/determinant
// or a convenience method from MTJ Matrix.solve
DenseMatrix I = Matrices.identity(aTA[0].length);
DenseMatrix identity = I.copy();
// A.solve(Matrix B, Matrix X) solves X = A\B.
// A*(A^-1) = I ... identity = aTA / I
DenseMatrix aTAIM = (DenseMatrix)aTAM.solve(I, identity);
double[][] aTAI = MatrixUtil.convertToRowMajor(aTAIM);
double[][] inv = MatrixUtil.multiply(aTAI, aT);
return inv;
}
/**
* given data points xy, want to create a matrix usable to transform
* the data points by scaling and translation so that:
a) points are translated so that their centroid is at the origin.
b) points are scaled so that the average distance from the
origin is sqrt(2).
Can use the transformation matrix with dot operator: Misc.multiply(xy, tMatrix).
* @param xy
* @return a matrix for use for canonical transformation of the points.
* the format of the result is
* <pre>
* t[0] = new double[]{scale, 0, -centroidX*scale};
t[1] = new double[]{0, scale, -centroidY*scale};
</pre>
*/
public static double[][] calculateNormalizationMatrix2X3(double[][] xy) {
int nRows = xy.length;
double cen0 = 0;
double cen1 = 0;
for (int i = 0; i < nRows; ++i) {
cen0 += xy[i][0];
cen1 += xy[i][1];
}
cen0 /= (double)nRows;
cen1 /= (double)nRows;
double mean = 0;
for (int i = 0; i < nRows; ++i) {
double diffX = xy[i][0] - cen0;
double diffY = xy[i][1] - cen1;
double dist = Math.sqrt((diffX * diffX) + (diffY * diffY));
mean += dist;
}
mean /= (double)nRows;
/*
mean * factor = sqrt(2)
*/
double scale = Math.sqrt(2)/mean;
double[][] t = new double[2][];
t[0] = new double[]{scale, 0, -cen0*scale};
t[1] = new double[]{0, scale, -cen1*scale};
return t;
}
public static float[][] copy(float[][] a) {
float[][] c = new float[a.length][a[0].length];
for (int i = 0; i < a.length; ++i) {
c[i] = new float[a[0].length];
System.arraycopy(a[i], 0, c[i], 0, a[0].length);
}
return c;
}
public static double[][] copy(double[][] a) {
double[][] m = new double[a.length][];
for (int i = 0; i < a.length; ++i) {
int n0 = a[i].length;
m[i] = new double[n0];
System.arraycopy(a[i], 0, m[i], 0, n0);
}
return m;
}
}
|
package alignment.alignment_v2;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.Attribute;
import org.jdom2.output.XMLOutputter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Align {
private static final int VERTEX_RETRIES = 2;
private static final int EDGE_RETRIES = 2;
//SEARCH_FOR_DUPLICATE in most cases should always be true, since many STIX components do not have a unique name,
// so to combine we should alway look for duplicates by comparing properties, except cases when graph contains only stucco unique vertices (IP, Port, etc.);
private static boolean SEARCH_FOR_DUPLICATES = true;
private static boolean ALIGN_VERT_PROPS = true;
private Logger logger = null;
private ConfigFileLoader config = null;
private InMemoryDBConnectionJson connection = null;
private Compare compare = null;
private JSONObject newGraphSection = null;
private JSONObject vertsToLoad = null;
private JSONArray edgesToLoad = null;
private Map<String, JSONObject> existingIndicatorsMap = null;
public Align() {
logger = LoggerFactory.getLogger(Align.class);
connection = new InMemoryDBConnectionJson();
config = new ConfigFileLoader();
compare = new Compare();
}
public void setSearchForDuplicates(boolean search) {
SEARCH_FOR_DUPLICATES = search;
}
public void setAlignVertProps(boolean align) {
ALIGN_VERT_PROPS = align;
}
/* for test purpose */
public InMemoryDBConnectionJson getConnection() {
return connection;
}
public boolean load(JSONObject newGraphSection) throws Exception {
this.newGraphSection = newGraphSection;
vertsToLoad = newGraphSection.optJSONObject("vertices");
edgesToLoad = newGraphSection.optJSONArray("edges");
if (vertsToLoad == null) {
vertsToLoad = new JSONObject();
}
if (edgesToLoad == null) {
edgesToLoad = new JSONArray();
}
// removing Indicators, since in most cases they serve as a connector between
// different types of STIX components, and needs to be aligned bases on a subgraph comparison
// and not just by itself
JSONObject indicators = new JSONObject();
Set<String> ids = vertsToLoad.keySet();
List<String> indicatorIds = new ArrayList();
for (String key : vertsToLoad.keySet()) {
String id = key.toString();
JSONObject vertex = vertsToLoad.getJSONObject(id);
if (vertex.getString("vertexType").equals("Indicator")) {
indicators.put(id, vertex);
indicatorIds.add(id);
}
}
for (String id : indicatorIds) {
vertsToLoad.remove(id);
}
boolean loadedVertices = false;
/* loading vertices */
if (vertsToLoad != null) {
for (int currTry = 0; currTry < VERTEX_RETRIES; currTry++) {
vertsToLoad = loadVertices(vertsToLoad);
if (vertsToLoad.length() == 0) {
loadedVertices = true;
break;
} else if (currTry == VERTEX_RETRIES) {
logger.error("Could not add vertex! Vertex is out of retry attempts!");
}
}
}
boolean loadedIndicatorVertices = false;
/* loading indicators */
vertsToLoad = indicators;
if (vertsToLoad != null) {
for (int currTry = 0; currTry < VERTEX_RETRIES; currTry++) {
vertsToLoad = loadVertices(vertsToLoad);
if (vertsToLoad.length() == 0) {
loadedVertices = true;
break;
} else if (currTry == VERTEX_RETRIES) {
logger.error("Could not add Indicator Vertex! Vertex is out of retry attempts!");
}
}
}
boolean loadedEdges = false;
/* loading edges */
if (edgesToLoad != null) {
for (int currTry = 0; currTry < EDGE_RETRIES; currTry++) {
edgesToLoad = loadEdges(edgesToLoad);
if (edgesToLoad.length() == 0) {
loadedEdges = true;
break;
} else if (currTry == EDGE_RETRIES) {
logger.error("Could not add edge! Edge is out of retry attempts!");
}
}
}
return (loadedVertices && loadedEdges) ? true : false;
}
private JSONObject loadVertices(JSONObject vertices) throws Exception {
JSONObject vertsToRetry = new JSONObject();
for (Object id : vertices.keySet()) {
JSONObject newVertex = vertices.getJSONObject(id.toString());
//should always be valid since it is undergoing required properties check while converting to json
String newVertName = newVertex.getString("name");
String vertId = connection.getVertIDByName(newVertName);
boolean newVert = (vertId == null);
if (newVert && SEARCH_FOR_DUPLICATES) {
String vertexType = newVertex.getString("vertexType");
String duplicateId = findDuplicateVertex(newVertex);
newVert = (duplicateId == null);
if (duplicateId != null) {
JSONObject duplicateVertex = connection.getVertByID(duplicateId);
updateEdges(newVertex.getString("name"), duplicateVertex.getString("name"));
updateVertices(newVertex.getString("name"), duplicateVertex.getString("name"));
if (ALIGN_VERT_PROPS) {
// do the aligning of new vert properties
JSONObject existingVert = connection.getVertByID(duplicateId);
alignVertProps(newVertex, duplicateVertex);
connection.updateVertex(duplicateId, duplicateVertex);
} else {
logger.debug("Vertex exists");
logger.debug("Attempted to add vertex when duplicate exists. ALIGN_VERT_PROPS is false, so ignoring new vert. vert was: " + newVertex);
}
}
}
if (newVert) {
String newVertId = connection.addVertex(newVertex);
if (newVertId == null) {
vertsToRetry.put(id.toString(), newVertex);
} else {
List<JSONObject> newEdges = findNewEdges(newVertex);
for (JSONObject newEdge : newEdges) {
edgesToLoad.put(newEdge);
}
}
}
}
return vertsToRetry;
}
private JSONArray loadEdges(JSONArray edges) throws Exception {
JSONArray edgesToRetry = new JSONArray();
for (int i = 0; i < edges.length(); i++) {
JSONObject edge = edges.getJSONObject(i);
String outVertID = edge.getString("outVertID");
String inVertID = edge.getString("inVertID");
String relation = edge.getString("relation");
List<String> edgeIDsByVert = connection.getEdgeIDsByVert(inVertID, outVertID, relation);
// TODO class InMemoryDBConnection returns List of ids for the same outVertID, inVertID, and relation ....
// not sure why ... needs to be double checked.
// if list does not contain a particular relation between two vertices, then we add it ...
if (edgeIDsByVert.size() > 1) {
logger.debug("Multiple edges found with the same outVertID, inVertID, and relation!!!");
}
if (edgeIDsByVert.isEmpty()) {
String edgeId = connection.addEdge(inVertID, outVertID, relation);
if (edgeId == null) {
edgesToRetry.put(edge);
}
}
}
return edgesToRetry;
}
private String findDuplicateVertex(JSONObject vertex) throws Exception {
String vertexType = vertex.getString("vertexType");
if (vertexType.equals("Indicator")) {
return findIndicatorDuplicate(vertex);
}
JSONObject vertexOntology = config.getVertexOntology(vertexType);
List<String> candidateIds = connection.getVertIDsByProperty("vertexType", vertexType);
double threshold = 0.75;
String bestId = null;
double bestScore = 0.0;
for (String candidateId : candidateIds) {
JSONObject candidateVertex = connection.getVertByID(candidateId);
double score = compare.compareVertices(vertex, candidateVertex, vertexOntology);
if (score >= threshold) {
if (bestId == null || (bestId != null && score > bestScore)) {
bestId = candidateId;
bestScore = score;
}
}
}
return bestId;
}
/* to find indicator duplicate we have to compare new subgraph containing new indicator with
existing subgraphs with indicators, since indicator is a connector between multiple stix components */
private String findIndicatorDuplicate(JSONObject indicator) throws Exception {
if (existingIndicatorsMap == null) {
existingIndicatorsMap = new HashMap();
}
loadExistingIndicatorsMap();
double threshold = 0.75;
JSONObject newVerts = newGraphSection.optJSONObject("vertices");
Map<String, List<String>> outVertIDsMap = setOutVertIDsMap(indicator.getString("name"));
Map<String, List<String>> inVertIDsMap = setInVertIDsMap(indicator.getString("name"));
String duplicateId = null;
double bestDuplicateScore = 0.0;
int count = 0;
for (String id : existingIndicatorsMap.keySet()) {
JSONObject existingIndicator = existingIndicatorsMap.get(id);
double totalScore = 0.0;
/* searching for duplicates between vertices that are pointing to existing indicator and new indicator */
if (!inVertIDsMap.isEmpty()) {
for (String relation : inVertIDsMap.keySet()) {
List<String> newInVertIDsList = inVertIDsMap.get(relation);
List<String> existingInVertIDsList = connection.getInVertIDsByRelation(existingIndicator.getString("name"), relation);
double relationTotalScore = 0.0;
for (String newInVertID : newInVertIDsList) {
JSONObject newInVert = newVerts.getJSONObject(newInVertID);
double bestScore = 0.0;
for (String existingInVertID : existingInVertIDsList) {
JSONObject existingInVert = connection.getVertByName(existingInVertID);
double score = compare.compareVertices(newInVert, existingInVert, null);
if (score >= threshold && score > bestScore) {
bestScore = score;
}
}
relationTotalScore = relationTotalScore + bestScore;
}
totalScore = totalScore + ((relationTotalScore == 0.0) ? 0.0 : Math.min(newInVertIDsList.size(), existingInVertIDsList.size())/relationTotalScore);
}
}
/* searching for duplicates between vertices that existing indicator is pointing to and new indicator */
if (outVertIDsMap.isEmpty()) {
for (String relation : outVertIDsMap.keySet()) {
List<String> newOutVertIDsList = outVertIDsMap.get(relation);
List<String> existingOutVertIDsList = connection.getOutVertIDsByRelation(existingIndicator.getString("name"), relation);
double relationTotalScore = 0.0;
for (String newOutVertID : newOutVertIDsList) {
JSONObject newOutVert = newVerts.getJSONObject(newOutVertID);
double bestScore = 0.0;
for (String existingOutVertID : existingOutVertIDsList) {
JSONObject existingOutVert = connection.getVertByName(existingOutVertID);
double score = compare.compareVertices(newOutVert, existingOutVert, null);
if (score >= threshold && score > bestScore) {
bestScore = score;
}
}
relationTotalScore = relationTotalScore + bestScore;
}
totalScore = totalScore + ((relationTotalScore == 0.0) ? 0.0 : Math.min(newOutVertIDsList.size(), existingOutVertIDsList.size())/relationTotalScore);
}
}
totalScore = (compare.compareVertices(indicator, existingIndicator, null) * 0.25) + (totalScore * 0.75);
if (totalScore >= threshold) {
if (totalScore > bestDuplicateScore) {
duplicateId = id;
}
}
}
JSONObject duplicate = connection.getVertByID(duplicateId);
return duplicateId;
}
/* loading all the indicators from existing graph to find duplicate */
private void loadExistingIndicatorsMap() {
List<String> existingIndicatorsIdList = connection.getVertIDsByProperty("vertexType", "Indicator");
for (String id : existingIndicatorsIdList) {
JSONObject existingIndicator = connection.getVertByID(id);
if (existingIndicator != null) {
existingIndicatorsMap.put(id, existingIndicator);
}
}
}
/* mapping relatin between new indicator to related InVertex id from new graph */
private Map<String, List<String>> setInVertIDsMap(String id) {
JSONArray edges = newGraphSection.optJSONArray("edges");
Map<String, List<String>> inVertIDsMap = new HashMap<String, List<String>>();
for (int i = 0; i < edges.length(); i++) {
JSONObject edge = edges.getJSONObject(i);
if (edge.getString("outVertID").equals(id)) {
List<String> inVertIDsList = (inVertIDsMap.containsKey(edge.get("relation"))) ? inVertIDsMap.get(edge.get("relation")) : new ArrayList<String>();
inVertIDsList.add(edge.getString("inVertID"));
inVertIDsMap.put(edge.getString("relation"), inVertIDsList);
}
}
return inVertIDsMap;
}
/* mapping new relatin between new indicator to related outVertex id from new graph */
private Map<String, List<String>> setOutVertIDsMap(String id) {
JSONArray edges = newGraphSection.optJSONArray("edges");
Map<String, List<String>> inVertIDsMap = new HashMap<String, List<String>>();
for (int i = 0; i < edges.length(); i++) {
JSONObject edge = edges.getJSONObject(i);
if (edge.getString("inVertID").equals(id)) {
List<String> inVertIDsList = (inVertIDsMap.containsKey(edge.get("relation"))) ? inVertIDsMap.get(edge.get("relation")) : new ArrayList<String>();
inVertIDsList.add(edge.getString("outVertID"));
inVertIDsMap.put(edge.getString("relation"), inVertIDsList);
}
}
return inVertIDsMap;
}
/* if duplicate vertex found, updating edgesToLoad to match duplicate name,
since in most cases stix element's names are unique UUID */
void updateEdges(String oldID, String newID) {
for (int i = 0; i < edgesToLoad.length(); i++) {
JSONObject edge = edgesToLoad.getJSONObject(i);
String inVertID = edge.getString("inVertID");
String outVertID = edge.getString("outVertID");
if (inVertID.equals(oldID)) {
edge.put("inVertID", newID);
}
if (outVertID.equals(oldID)) {
edge.put("outVertID", newID);
}
}
}
/* if duplicate vertex found, updating vertsToLoad from vertex name duplicate name,
since in most cases stix element's names are unique UUID */
void updateVertices(String oldID, String newID) {
vertsToLoad = newGraphSection.optJSONObject("vertices");
for (Object key : vertsToLoad.keySet()) {
String id = key.toString();
if (id.equals(oldID)) {
JSONObject vert = vertsToLoad.getJSONObject(id);
vert.put("name", newID);
vertsToLoad.put(newID, vert);
vertsToLoad.remove(id);
}
}
}
/* function to set an edges between new IPs and existing AddressRanges */
private List<JSONObject> findNewEdges(JSONObject vert) throws IOException, Exception{
List<JSONObject> edges = new ArrayList();
String vertexType = vert.getString("vertexType");
if (vertexType.equals("AddressRange")) {
long endIpInt = vert.optLong("endIPInt");
long startIpInt = vert.optLong("startIPInt");
if (endIpInt != 0 && startIpInt != 0) {
List<Constraint> constraints = new ArrayList<Constraint>();
Constraint c = new Constraint("vertexType", Constraint.Condition.eq, "IP");
constraints.add(c);
c = new Constraint("ipInt", Constraint.Condition.lte, endIpInt);
constraints.add(c);
c = new Constraint("ipInt", Constraint.Condition.gte, startIpInt);
constraints.add(c);
List<String> matchIDs = connection.getVertIDsByConstraints(constraints);
if (matchIDs != null) {
for (String matchID : matchIDs) {
JSONObject match = connection.getVertByID(matchID);
JSONObject edge = new JSONObject();
edge.put("relation", "Contained_Within");
edge.put("outVertID", match.getString("name"));
edge.put("inVertID", vert.getString("name"));
edges.add(edge);
}
}
} else {
logger.warn("address range vert did not have int addresses: " + vert.toString());
}
} else if (vertexType.equals("IP")) {
List<Constraint> constraints = new ArrayList<Constraint>();
Constraint c = new Constraint("vertexType", Constraint.Condition.eq, "AddressRange");
constraints.add(c);
c = new Constraint("endIPInt", Constraint.Condition.gte, vert.getLong("ipInt"));
constraints.add(c);
c = new Constraint("startIPInt", Constraint.Condition.lte, vert.getLong("ipInt"));
constraints.add(c);
List<String> matchIDs = connection.getVertIDsByConstraints(constraints);
if (matchIDs != null) {
for (String matchID : matchIDs) {
JSONObject match = connection.getVertByID(matchID);
JSONObject edge = new JSONObject();
edge.put("relation", "Contained_Within");
edge.put("outVertID", vert.getString("name"));
edge.put("inVertID", match.getString("name"));
edges.add(edge);
}
}
}
return edges;
}
/* function is adding new properties to existing duplicate vertex;
only new properties can be added, so properties with the same names and different content
cannot be combined for now, unless one of elements contains list of children with this tag,
then we know that list is allowed and we can append new element.
Combination requires more research, and implementation of something like xsld
with set of rules for combination based on schema, otherwise output may be invalid */
private void alignVertProps(JSONObject newVertex, JSONObject existingVertex) {
for (Object keyObject : newVertex.keySet()) {
String key = keyObject.toString();
if (key.equals("sourceDocument")) {
Document newDoc = PreprocessSTIXwithJDOM2.parseXMLText(newVertex.getString("sourceDocument"));
Document existingDoc = PreprocessSTIXwithJDOM2.parseXMLText(existingVertex.getString("sourceDocument"));
combineElements(newDoc.getRootElement(), existingDoc.getRootElement());
existingVertex.put("sourceDocument", new XMLOutputter().outputString(existingDoc));
} else {
JSONArray array1 = newVertex.optJSONArray(key);
if (array1 != null) {
JSONArray array2 = existingVertex.optJSONArray(key);
if (array2 == null) {
//add array1 to existingVertex
existingVertex.put(key, array1);
} else {
//combine arrays
List<Integer> indexToAddList = new ArrayList<Integer>();
for (int i = 0; i < array1.length(); i++) {
String content1 = array1.getString(i);
for (int j = 0; j < array2.length(); j++) {
String content2 = array2.getString(j);
if (!content1.equals(content2)) {
indexToAddList.add(i);
}
}
}
for (Integer index : indexToAddList) {
array2.put(array1.getString(index));
}
existingVertex.put(key, array2);
}
}
}
}
}
/* public for test purpose only */
public void combineElements(Element e1, Element e2) {
double threshold = 0.75;
Map<String, Namespace> elementMap1 = Compare.getTagMap(e1);
Map<String, Namespace> elementMap2 = Compare.getTagMap(e2);
for (String tag : elementMap1.keySet()) {
/* case 1: if e1 contains element with this tag and e2 doesn't,
then adding whole element with this tag from e1 to e2 */
if (!elementMap2.containsKey(tag)) {
List<Element> list1 = e1.getChildren(tag, elementMap1.get(tag));
for (Element elementToAdd : list1) {
e2.addContent(elementToAdd.detach());
}
} else {
List<Element> list1 = e1.getChildren(tag, elementMap1.get(tag));
List<Element> list2 = e2.getChildren(tag, elementMap1.get(tag));
/* case 2: if both elements have children with this tag */
/* case 2.1: if both elements have children with the tag in single appearence; */
if (list1.size() == 1 && list2.size() == 1) {
String text1 = list1.get(0).getTextNormalize();
String text2 = list2.get(0).getTextNormalize();
/* case 2.1.1: if both elements contain text, then rules should be written
based on stix xsd on how to combine them .... if list is allowed ?
if delimiter is allowed ? ... if property shoudl be updated based on timestamp ? */
if (!text1.isEmpty() || !text2.isEmpty()) {
double score = compare.defaultComparison(text1, text2);
if (score < threshold) {
logger.info(" - text1 most likely is new and needs to be combined somehow ... ");
logger.info(" do not know if list is allowed .... or should it be updated based on timestamp?");
logger.info(" or some other rule should be made ...");
}
} else {
/* case 2.1.2: if elements contain children, then continue recursively compare children */
combineElements(list1.get(0), list2.get(0));
}
} else {
/* case 2.2: if eather one of elements have a list of children with this tag means that list is allowed here
and elements should be combined based on list comparison */
combineLists(list1, list2, e2);
}
}
}
}
/* function to combine lists omitting duplicates by using comparison */
private void combineLists(List<Element> list1, List<Element> list2, Element elementToEdit) {
double threshold = 0.75;
PreprocessSTIXwithJDOM2 p = new PreprocessSTIXwithJDOM2();
List<Element> newElementList = new ArrayList<Element>();
for (Element e1 : list1) {
double bestScore = 0.0;
Element bestElement = null;
for (Element e2 : list2) {
double score = compare.compareDocumentElements(e1, e2);
if (score > bestScore) {
bestScore = score;
bestElement = e2;
}
}
/* if duplicate for element from list1 was not found in list2, element should be appended */
if (bestScore < threshold) {
newElementList.add(e1);
}
if (bestScore >= threshold) {
combineElements(e1, bestElement);
}
}
for (Element newElement : newElementList) {
elementToEdit.addContent(newElement.detach());
}
}
}
|
package com.bnade.wow.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
@JsonIgnoreProperties(value = {"auc", "context", "petLevel", "petBreedId"}) // json
public class Auction {
@Id
private Integer auc;
private Integer itemId;
private String owner;
private String ownerRealm;
private Long bid;
private Long buyout;
private Integer quantity;
private String timeLeft;
private Integer petSpeciesId;
private Integer petLevel;
private Integer petBreedId;
private Integer context;
private String bonusList;
@NotNull
private Integer realmId;
public Integer getAuc() {
return auc;
}
public void setAuc(Integer auc) {
this.auc = auc;
}
public Integer getItemId() {
return itemId;
}
public void setItemId(Integer itemId) {
this.itemId = itemId;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getOwnerRealm() {
return ownerRealm;
}
public void setOwnerRealm(String ownerRealm) {
this.ownerRealm = ownerRealm;
}
public Long getBid() {
return bid;
}
public void setBid(Long bid) {
this.bid = bid;
}
public Long getBuyout() {
return buyout;
}
public void setBuyout(Long buyout) {
this.buyout = buyout;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public String getTimeLeft() {
return timeLeft;
}
public void setTimeLeft(String timeLeft) {
this.timeLeft = timeLeft;
}
public Integer getPetSpeciesId() {
return petSpeciesId;
}
public void setPetSpeciesId(Integer petSpeciesId) {
this.petSpeciesId = petSpeciesId;
}
public Integer getPetLevel() {
return petLevel;
}
public void setPetLevel(Integer petLevel) {
this.petLevel = petLevel;
}
public Integer getPetBreedId() {
return petBreedId;
}
public void setPetBreedId(Integer petBreedId) {
this.petBreedId = petBreedId;
}
public Integer getContext() {
return context;
}
public void setContext(Integer context) {
this.context = context;
}
public String getBonusList() {
return bonusList;
}
public void setBonusList(String bonusList) {
this.bonusList = bonusList;
}
public Integer getRealmId() {
return realmId;
}
public void setRealmId(Integer realmId) {
this.realmId = realmId;
}
@Override
public String toString() {
return "Auction{" +
"auc=" + auc +
", itemId=" + itemId +
", owner='" + owner + '\'' +
", ownerRealm='" + ownerRealm + '\'' +
", bid=" + bid +
", buyout=" + buyout +
", quantity=" + quantity +
", timeLeft='" + timeLeft + '\'' +
", petSpeciesId=" + petSpeciesId +
", petLevel=" + petLevel +
", petBreedId=" + petBreedId +
", context=" + context +
", bonusList='" + bonusList + '\'' +
", realmId=" + realmId +
'}';
}
}
|
package com.cjburkey.claimchunk;
import java.text.NumberFormat;
import java.util.UUID;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
public final class Econ {
private Economy econ;
private ClaimChunk instance;
boolean setupEconomy(ClaimChunk instance) {
this.instance = instance;
// Check if Vault is present
if (instance.getServer().getPluginManager().getPlugin("Vault") == null) return false;
// Get the Vault service if it is present
RegisteredServiceProvider<Economy> rsp = instance.getServer().getServicesManager().getRegistration(Economy.class);
// Check if the service is valid
if (rsp == null) return false;
// Update current economy handler
econ = rsp.getProvider();
// Success
return true;
}
public double getMoney(UUID player) {
Player ply = getPlayer(player);
// If the player has joined the server before, return their balance
if (ply != null) {
return econ.getBalance(ply);
}
return -1.0d;
}
@SuppressWarnings("UnusedReturnValue")
public EconomyResponse addMoney(UUID player, double amt) {
Player ply = getPlayer(player);
if (ply != null) {
// Add the (safe) balance to the player
return econ.depositPlayer(ply, Math.abs(amt));
}
return null;
}
@SuppressWarnings("UnusedReturnValue")
private EconomyResponse takeMoney(UUID player, double amt) {
Player ply = getPlayer(player);
if (ply != null) {
// Remove the money from the player's balance
return econ.withdrawPlayer(ply, Math.abs(amt));
}
return null;
}
/**
* Take money from the player.
*
* @param ply Player purchasing.
* @param cost The cost of the purchase.
* @return Whether or not the transaction was successful.
*/
public boolean buy(UUID ply, double cost) {
if (getMoney(ply) >= cost) {
EconomyResponse response = takeMoney(ply, cost);
// Return whether the transaction was completed successfully
return response != null && response.type == EconomyResponse.ResponseType.SUCCESS;
}
return false;
}
public String format(double amt) {
return NumberFormat.getCurrencyInstance().format(amt);
}
private Player getPlayer(UUID id) {
if (instance == null) {
return null;
}
return instance.getServer().getPlayer(id);
}
}
|
package fitnesse.testsystems.slim;
import fitnesse.testsystems.slim.results.ExceptionResult;
import fitnesse.testsystems.slim.results.TestResult;
import fitnesse.testsystems.slim.tables.SyntaxError;
import fitnesse.wikitext.Utils;
import fitnesse.wikitext.parser.Collapsible;
import org.htmlparser.Node;
import org.htmlparser.Tag;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.*;
import org.htmlparser.util.NodeList;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class HtmlTable implements Table {
private List<Row> rows = new ArrayList<Row>();
private TableTag tableNode;
private List<ExceptionResult> exceptions = new ArrayList<ExceptionResult>();
public HtmlTable(TableTag tableNode) {
this.tableNode = tableNode;
NodeList nodeList = tableNode.getChildren();
for (int i = 0; i < nodeList.size(); i++) {
Node node = nodeList.elementAt(i);
if (node instanceof TableRow || node instanceof TableHeader) {
rows.add(new Row((CompositeTag) node));
}
}
tableNode.getChildren().prepend(new ExceptionTextNode());
}
public TableTag getTableNode() {
return tableNode;
}
public String getCellContents(int columnIndex, int rowIndex) {
return rows.get(rowIndex).getColumn(columnIndex).getContent();
}
public String getUnescapedCellContents(int col, int row) {
return Utils.unescapeHTML(getCellContents(col, row));
}
public int getRowCount() {
return rows.size();
}
public int getColumnCountInRow(int rowIndex) {
return rows.get(rowIndex).getColumnCount();
}
public void substitute(int col, int row, String contents) {
Cell cell = rows.get(row).getColumn(col);
// TODO: need escaping here?
cell.setContent(Utils.escapeHTML(contents));
}
public List<List<String>> asList() {
List<List<String>> list = new ArrayList<List<String>>();
for (Row row : rows)
list.add(row.asList());
return list;
}
public String toString() {
return asList().toString();
}
public String toHtml() {
return tableNode.toHtml();
}
public int addRow(List<String> list) {
Row row = new Row();
rows.add(row);
tableNode.getChildren().add(row.getRowNode());
for (String s : list)
row.appendCell(s == null ? "" : Utils.escapeHTML(s));
return rows.size() - 1;
}
public void addColumnToRow(int rowIndex, String contents) {
Row row = rows.get(rowIndex);
row.appendCell(Utils.escapeHTML(contents));
}
/**
* Scenario tables (mainly) are added on the next row. A bit of javascript allows for collapsing and
* expanding.
*
* @see fitnesse.testsystems.slim.Table#appendChildTable(int, fitnesse.testsystems.slim.Table)
*/
public void appendChildTable(int rowIndex, Table childTable) {
Row row = rows.get(rowIndex);
row.rowNode.setAttribute("class", "scenario closed", '"');
Row childRow = new Row();
TableColumn column = (TableColumn) newTag(TableColumn.class);
column.setChildren(new NodeList(((HtmlTable) childTable).getTableNode()));
column.setAttribute("colspan", "" + colspan(row), '"');
childRow.appendCell(new Cell(column));
childRow.rowNode.setAttribute("class", "scenario-detail", '"');
insertRowAfter(row, childRow);
}
private int colspan(Row row) {
NodeList rowNodes = row.rowNode.getChildren();
int colspan = 0;
for (int i = 0; i < rowNodes.size(); i++) {
if (rowNodes.elementAt(i) instanceof TableColumn) {
String s = ((TableColumn)rowNodes.elementAt(i)).getAttribute("colspan");
if (s != null) {
colspan += Integer.parseInt(s);
} else {
colspan++;
}
}
}
return colspan;
}
// It's a bit of work to insert a node with the htmlparser module.
private void insertRowAfter(Row existingRow, Row childRow) {
NodeList rowNodes = tableNode.getChildren();
int index = rowNodes.indexOf(existingRow.rowNode);
Stack<Node> tempStack = new Stack<Node>();
while (rowNodes.size() - 1 > index) {
tempStack.push(rowNodes.elementAt(tableNode.getChildren().size() - 1));
rowNodes.remove(rowNodes.size() - 1);
}
rowNodes.add(childRow.rowNode);
while (tempStack.size() > 0) {
rowNodes.add(tempStack.pop());
}
}
@Override
public void updateContent(int row, TestResult testResult) {
rows.get(row).setTestResult(testResult);
}
@Override
public void updateContent(int col, int row, TestResult testResult) {
Cell cell = rows.get(row).getColumn(col);
cell.setTestResult(testResult);
cell.setContent(cell.formatTestResult());
}
@Override
public void updateContent(int col, int row, ExceptionResult exceptionResult) {
Cell cell = rows.get(row).getColumn(col);
if (cell.exceptionResult == null) {
cell.setExceptionResult(exceptionResult);
cell.setContent(cell.formatExceptionResult());
exceptions.add(exceptionResult);
}
}
private Tag newTag(Class<? extends Tag> klass) {
Tag tag = null;
try {
tag = klass.newInstance();
tag.setTagName(tag.getTagName().toLowerCase());
Tag endTag = klass.newInstance();
endTag.setTagName("/" + tag.getTagName().toLowerCase());
endTag.setParent(tag);
tag.setEndTag(endTag);
} catch (Exception e) {
e.printStackTrace();
}
return tag;
}
class Row {
private List<Cell> cells = new ArrayList<Cell>();
private CompositeTag rowNode;
public Row(CompositeTag rowNode) {
this.rowNode = rowNode;
NodeList nodeList = rowNode.getChildren();
for (int i = 0; i < nodeList.size(); i++) {
Node node = nodeList.elementAt(i);
if (node instanceof TableColumn)
cells.add(new Cell((TableColumn) node));
}
}
public Row() {
rowNode = (TableRow) newTag(TableRow.class);
rowNode.setChildren(new NodeList());
Tag endNode = new TableRow();
endNode.setTagName("/" + rowNode.getTagName().toLowerCase());
rowNode.setEndTag(endNode);
}
public int getColumnCount() {
return cells.size();
}
public Cell getColumn(int columnIndex) {
return cells.get(columnIndex);
}
public void appendCell(String contents) {
Cell newCell = new Cell(contents);
appendCell(newCell);
}
private void appendCell(Cell newCell) {
rowNode.getChildren().add(newCell.getColumnNode());
cells.add(newCell);
}
public CompositeTag getRowNode() {
return rowNode;
}
private List<String> asList() {
List<String> list = new ArrayList<String>();
for (Cell cell : cells) {
// was "colorized"
list.add(cell.getTestResult());
}
return list;
}
private void setTestResult(TestResult testResult) {
NodeList cells = rowNode.getChildren();
for (int i = 0; i < cells.size(); i++) {
Node cell = cells.elementAt(i);
if (cell instanceof Tag) {
Tag tag = (Tag) cell;
tag.setAttribute("class", testResult.getExecutionResult().toString(), '"');
}
}
}
private Tag findById(Node node, String id) {
if (hasId(node, id))
return (Tag) node;
return findChildMatchingId(node, id);
}
private Tag findChildMatchingId(Node node, String id) {
NodeList children = node.getChildren();
if (children != null) {
for (int i = 0; i < children.size(); i++) {
Node child = children.elementAt(i);
Tag found = findById(child, id);
if (found != null)
return found;
}
}
return null;
}
private boolean hasId(Node node, String id) {
if (node instanceof Tag) {
Tag t = (Tag) node;
if (id.equals(t.getAttribute("id")))
return true;
}
return false;
}
}
class Cell {
private final TableColumn columnNode;
private final String originalContent;
private TestResult testResult;
private ExceptionResult exceptionResult;
public Cell(TableColumn tableColumn) {
columnNode = tableColumn;
originalContent = Utils.unescapeHTML(columnNode.getChildrenHTML());
}
public Cell(String contents) {
if (contents == null)
contents = "";
TextNode text = new TextNode(contents);
text.setChildren(new NodeList());
columnNode = (TableColumn) newTag(TableColumn.class);
columnNode.setChildren(new NodeList(text));
originalContent = contents;
}
public String getContent() {
return Utils.unescapeHTML(getEscapedContent());
}
public String getEscapedContent() {
String unescaped = columnNode.getChildrenHTML();
//Some browsers need inside an empty table cell, so we remove it here.
return " ".equals(unescaped) ? "" : unescaped;
}
private void setContent(String s) {
// No HTML escaping here.
TextNode textNode = new TextNode(s);
NodeList nodeList = new NodeList(textNode);
columnNode.setChildren(nodeList);
}
public String getTestResult() {
return testResult != null ? testResult.toString(originalContent) : getContent();
}
public TableColumn getColumnNode() {
return columnNode;
}
public void setTestResult(TestResult testResult) {
this.testResult = testResult;
}
public void setExceptionResult(ExceptionResult exceptionResult) {
this.exceptionResult = exceptionResult;
}
public String formatTestResult() {
if (testResult.getExecutionResult() == null) {
return testResult.getMessage() != null ? testResult.getMessage() : originalContent;
}
final String escapedMessage = testResult.hasMessage() ? Utils.escapeHTML(testResult.getMessage()) : originalContent;
switch (testResult.getExecutionResult()) {
case PASS:
return String.format("<span class=\"pass\">%s</span>", escapedMessage);
case FAIL:
if (testResult.hasActual() && testResult.hasExpected()) {
return String.format("[%s] <span class=\"fail\">expected [%s]</span>",
Utils.escapeHTML(testResult.getActual()),
Utils.escapeHTML(testResult.getExpected()));
}
return String.format("<span class=\"fail\">%s</span>", escapedMessage);
case IGNORE:
return String.format("%s <span class=\"ignore\">%s</span>", originalContent, escapedMessage);
case ERROR:
return String.format("%s <span class=\"error\">%s</span>", originalContent, escapedMessage);
}
return "Should not be here";
}
public String formatExceptionResult() {
if (exceptionResult.hasMessage()) {
return String.format("%s <span class=\"%s\">%s</span>",
originalContent,
exceptionResult.getExecutionResult().toString(),
Utils.escapeHTML(exceptionResult.getMessage()));
} else {
// See below where exception block is formatted
return String.format("%s <span class=\"%s\">Exception: <a href=\"#%s\">%s</a></span>", originalContent, exceptionResult.getExecutionResult().toString(), exceptionResult.getResultKey(), exceptionResult.getResultKey());
}
}
}
@Override
public HtmlTable asTemplate(CellContentSubstitution substitution) throws SyntaxError {
String script = this.toHtml();
// Quick 'n' Dirty
script = substitution.substitute(0, 0, script);
return new HtmlTableScanner(script).getTable(0);
}
// This is not the nicest solution, since the the exceptions are put inside the <table> tag.
class ExceptionTextNode extends TextNode {
public ExceptionTextNode() {
super("");
}
@Override
public String toHtml(boolean verbatim) {
if(!haveExceptionsWithoutMessage()) {
return "";
}
StringBuilder buffer = new StringBuilder(512);
buffer.append("<div class=\"exceptions\"><h3>Exceptions</h3>");
for (ExceptionResult exceptionResult : exceptions) {
if (!exceptionResult.hasMessage()) {
buffer.append(String.format("<a name=\"%s\"></a>", exceptionResult.getResultKey()));
buffer.append(Collapsible.generateHtml(Collapsible.CLOSED, Utils.escapeHTML(exceptionResult.getResultKey()),
"<pre>" + Utils.escapeHTML(exceptionResult.getException()) + "</pre>"));
}
}
buffer.append("</div>");
return buffer.toString();
}
private boolean haveExceptionsWithoutMessage() {
for (ExceptionResult exception : exceptions) {
if (!exception.hasMessage()) {
return true;
}
}
return false;
}
}
}
|
package com.simperium.client;
import java.util.ArrayList;
import java.util.List;
public class Query<T extends Syncable> {
public interface Field {
public String getName();
}
public static class BasicField implements Field {
private String mName;
public BasicField(String name) {
mName = name;
}
@Override
public String getName(){
return mName;
}
}
public static class FullTextSnippet extends BasicField {
private String mColumnName = null;
public FullTextSnippet(String name) {
this(name, null);
}
public FullTextSnippet(String name, String columnName){
super(name);
mColumnName = columnName;
}
public String getColumnName(){
return mColumnName;
}
}
public static class FullTextOffsets extends BasicField {
public FullTextOffsets(String name) {
super(name);
}
}
public interface Condition {
public Object getSubject();
public String getKey();
public ComparisonType getComparisonType();
public Boolean includesNull();
}
public enum ComparisonType {
EQUAL_TO("="), NOT_EQUAL_TO("!=", true),
LESS_THAN("<"), LESS_THAN_OR_EQUAL("<="),
GREATER_THAN(">"), GREATER_THAN_OR_EQUAL(">="),
LIKE("LIKE"), NOT_LIKE("NOT LIKE", true),
MATCH("MATCH");
private final String operator;
private final Boolean includesNull;
private ComparisonType(String operator){
this(operator, false);
}
private ComparisonType(String operator, Boolean includesNull){
this.operator = operator;
this.includesNull = includesNull;
}
public Boolean includesNull(){
return includesNull;
}
@Override
public String toString(){
return operator;
}
}
public static class FullTextMatch implements Condition {
private Object mSubject;
private String mKey;
public FullTextMatch(Object subject) {
this(null, subject);
}
public FullTextMatch(String field, Object subject) {
mKey = field;
mSubject = subject;
}
@Override
public Object getSubject() {
return mSubject;
}
@Override
public String getKey() {
return mKey;
}
@Override
public ComparisonType getComparisonType() {
return ComparisonType.MATCH;
}
@Override
public Boolean includesNull(){
return false;
}
}
public static class BasicCondition implements Condition {
private String key;
private ComparisonType type;
private Object subject;
public BasicCondition(String key, Query.ComparisonType type, Object subject){
this.key = key;
this.type = type;
this.subject = subject;
}
@Override
public Object getSubject(){
return subject;
}
@Override
public String getKey(){
return key;
}
@Override
public ComparisonType getComparisonType(){
return type;
}
@Override
public Boolean includesNull(){
return type.includesNull();
}
@Override
public String toString(){
return String.format("%s %s %s", key, type, subject);
}
}
public enum SortType {
ASCENDING("ASC"), DESCENDING("DESC");
private final String type;
private SortType(String type){
this.type = type;
}
public String getType(){
return type;
}
@Override
public String toString(){
return getType();
}
}
public static class Sorter {
private final String key;
private final SortType type;
public Sorter(String key, SortType type){
this.key = key;
this.type = type;
}
public String getKey(){
return key;
}
public SortType getType(){
return type;
}
}
public static class KeySorter extends Sorter {
public KeySorter(SortType type){
super(null, type);
}
}
private Bucket<T> bucket;
private List<Condition> conditions = new ArrayList<Condition>();
private List<Sorter> sorters = new ArrayList<Sorter>();
private List<Field> mFields = new ArrayList<Field>();
private int mLimit = -1;
private int mOffset = -1;
public Query(Bucket<T> bucket){
this.bucket = bucket;
}
public Query(){
bucket = null;
}
public boolean hasLimit(){
return mLimit != -1;
}
public int getLimit(){
return mLimit;
}
public Query<T> limit(int limit) {
mLimit = limit;
return this;
}
public Query<T> clearLimit() {
return limit(-1);
}
public boolean hasOffset(){
return mOffset != -1;
}
public int getOffset(){
return mOffset;
}
public Query<T> offset(int offset) {
mOffset = offset;
return this;
}
public Query<T> clearOffset() {
return offset(-1);
}
public Query<T> where(Condition condition){
conditions.add(condition);
return this;
}
public Query<T> where(String key, ComparisonType type, Object subject){
where(new BasicCondition(key, type, subject));
return this;
}
public List<Condition> getConditions(){
return conditions;
}
public List<Sorter> getSorters(){
return sorters;
}
public List<Field> getFields(){
return mFields;
}
public Bucket.ObjectCursor<T> execute(){
if (bucket == null) {
throw(new RuntimeException("Tried executing a query without a bucket"));
}
return bucket.searchObjects(this);
}
public int count(){
if (bucket == null){
throw(new RuntimeException("Tried executing a query wihtout a bucket"));
}
return bucket.count(this);
}
public Query<T> orderByKey(){
orderByKey(SortType.ASCENDING);
return this;
}
public Query<T> orderByKey(SortType type){
order(new KeySorter(type));
return this;
}
public Query<T> order(Sorter sort){
sorters.add(sort);
return this;
}
public Query<T> order(String key){
order(key, SortType.ASCENDING);
return this;
}
public Query<T> order(String key, SortType type){
order(new Sorter(key, type));
return this;
}
public Query<T> reorder(){
sorters.clear();
return this;
}
public Query<T> include(String key){
// we want to include some indexed values
mFields.add(new BasicField(key));
return this;
}
public Query<T> include(String ... keys){
for (String key : keys) {
mFields.add(new BasicField(key));
}
return this;
}
public Query<T> include(Field field){
mFields.add(field);
return this;
}
public Query<T> include(Field ... fields){
for(Field field : fields){
mFields.add(field);
}
return this;
}
}
|
package com.mmtc.exam;
import java.io.ByteArrayInputStream;
import static com.mmtc.exam.BuildConfig.DEBUG;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.Future;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
//import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.apache.tomcat.jdbc.pool.DataSource;
//import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jndi.JndiObjectFactoryBean;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.reflect.TypeToken;
import com.mmtc.exam.auth.MMTCJdbcUserDetailsMgr;
import com.mmtc.exam.dao.MMTCUser;
import com.mmtc.exam.dao.Test;
import com.mmtc.exam.dao.TestSuite;
import com.mmtc.exam.dao.TestTaking;
//https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-in-action
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
@Autowired
ServletContext servletCtx;
@Autowired
private JndiObjectFactoryBean jndiObjFactoryBean;
@Autowired
private MMTCJdbcUserDetailsMgr jdbcDaoMgr;
@Autowired
private JavaMailSenderImpl mailSender;
@Autowired
private SimpleMailMessage emailRegMsgTemplate;
private final int DataRows = 5;//Index of last row(tips).
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private final int AES_KEYLENGTH = 128;//change this as desired for the security level.
@RequestMapping(value = {"/","/index"}, method = RequestMethod.GET)
public @ResponseBody ModelAndView root(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
ModelAndView view = new ModelAndView();
view.setViewName("index");
return view;
}
@RequestMapping(value = {"/home"}, method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
int i = dataSource.getPoolSize();
logger.info("Pool size: " + i);
return "home";
}
@RequestMapping(value = "/testsuite", method = RequestMethod.GET)
public @ResponseBody ModelAndView examGET(Locale locale, Model model,
HttpServletRequest request,
HttpServletResponse response) {
logger.info(request.getRequestURL().toString());
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
ModelAndView resultView = new ModelAndView();
ArrayList<String> suites = new ArrayList<String>();
String sql = "SELECT name FROM testsuite";
try{
Connection conn = dataSource.getConnection();
ResultSet s = conn.createStatement().executeQuery(sql);
while(s.next()){
suites.add(s.getString("name"));
}
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[testsuite] " + e.getMessage());
}
resultView.setViewName("testsuite");
resultView.addObject("suites", suites);
//Map<String, Object> resultModel = new HashMap<String, Object>();
//resultModel.put("suites", suites);
//return new ModelAndView("testsuite");//,"model",resultModel);
return resultView;
}
@RequestMapping(value="/addtestsuite", method=RequestMethod.GET)
public String addTestSuiteGET(Locale locale, Model model,
HttpServletRequest request,
HttpServletResponse response){
logger.debug(request.getRequestURL().toString());
return "addsuite";
}
@RequestMapping(value="/adduser", method=RequestMethod.GET)
public @ResponseBody ModelAndView addUserGET(
HttpServletRequest request,
HttpServletResponse response){
logger.info(request.getRequestURL().toString());
MMTCUser user = new MMTCUser();
ModelAndView view = new ModelAndView();
view.setViewName("newuser");
view.addObject("us", user);
return view;
}
@RequestMapping(value="/adduser", method=RequestMethod.POST)
public @ResponseBody ModelAndView addUserPOST(
@ModelAttribute("us") MMTCUser user,
HttpServletRequest request,
HttpServletResponse response){
logger.info(request.getRequestURL().toString());
boolean hasError = false;
ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("STU"));
try {
jdbcDaoMgr.createMMTCUser(new MMTCUser(user.getUsername(),user.getPassword(), authorities));
} catch (SQLException e) {
e.printStackTrace();
logger.error("[adduser] FAILED create NEW user!!!!");
hasError = true;
}
//Send confirmation email.
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
mailSender.setJavaMailProperties(props);
SimpleMailMessage msg = new SimpleMailMessage(this.emailRegMsgTemplate);
msg.setTo(user.getEmail());
msg.setText(
"Dear " + user.getUsername()
+ ", thank you for registering with MMTC! Your user name is your email. ");
try{
this.mailSender.send(msg);
}
catch (MailException ex) {
// simply log it and go on...
logger.error(ex.getMessage());
hasError = true;
}
ModelAndView view = new ModelAndView();
view.setViewName("result");
if(hasError == false)
view.addObject("result", "New user added successfully. Please check you email for confirmation!");
else
view.addObject("result", "Failed adding new user. Please try again.");
return view;
}
@RequestMapping(value="/edittests", method=RequestMethod.GET)
public @ResponseBody ModelAndView editTestSuiteGET(
HttpServletRequest request,
HttpServletResponse response){
logger.info(request.getRequestURL().toString());
TestSuite ts = new TestSuite(null);
ModelAndView resultView = new ModelAndView();
resultView.setViewName("editsuite");
resultView.addObject("ts", ts);
ArrayList<String> suites = getTestSuites();
resultView.addObject("suites", suites);
return resultView;
}
@RequestMapping(value="/listtest", method=RequestMethod.POST)
public @ResponseBody ModelAndView editTestPOST(
@ModelAttribute("ts") TestSuite ts,
HttpServletRequest request,
HttpServletResponse response){
logger.info(request.getRequestURL().toString());
ArrayList<Test> tests = getTestsForDisplayForSuite(ts.getName());
JsonObject jSuite = new JsonObject();
jSuite.addProperty("suite", ts.getName());
Gson gson = new Gson();
JsonArray jTests = (JsonArray)gson.toJsonTree(tests, new TypeToken<ArrayList<Test>>(){}.getType());
jSuite.add("tests", jTests);
String strJ = gson.toJson(jSuite).replace("\\", "\\\\");
request.setAttribute("tests",strJ);
return new ModelAndView("execedit","debug",DEBUG);
}
@RequestMapping(value = "/edittest/{tid}", method = RequestMethod.GET)
public @ResponseBody ModelAndView editTestGET(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@PathVariable String tid) {
logger.info(request.getRequestURL().toString());
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
String suiteAndTest = decryptTestID(curUser + "MendezMasterTrainingCenter6454",tid);
logger.info("[DEcrypted] " + suiteAndTest);
Test ts = new Test();
String[] s_t = suiteAndTest.split("-");
ArrayList<Test> tests = getTestBySuiteAndID(s_t[0],s_t[1]);
if(tests.size() > 1){
//TODO:No good.....duplicated test records. => Delete all of them and keep only 1?
String err = new Throwable().getStackTrace()[0].getMethodName();
err += " => Duplicated test records of suite {} test {}!!!";
logger.error(err,s_t[0],s_t[1]);
}
if(tests.isEmpty() == true){
String msg = "No test found for suite " + s_t[0];
msg += " and test " + s_t[1];
return new ModelAndView("result","result",msg);
}
ModelAndView resultView = new ModelAndView();
resultView.setViewName("edittest");
Test found = tests.get(0);
resultView.addObject("ts", ts);
resultView.addObject("id",tid);
resultView.addObject("ste",found.getSuite());
resultView.addObject("sn",found.getSerialNo());
resultView.addObject("q",found.getQuestion());
resultView.addObject("ans",found.getAnswers());
resultView.addObject("opt",found.getOptions());
resultView.addObject("kwd", found.getKeywords());
String parentDir = File.separator;
parentDir += "mmtcexam";
parentDir += File.separator;
parentDir += "resources" + File.separator;
parentDir += "pic";
parentDir += File.separator;
String pic = found.getPic();
resultView.addObject("pic",pic);
session.setAttribute("uploadFile", parentDir + pic + ".png");
return resultView;
}
@RequestMapping(value = "/getmg/{imgid}", method = RequestMethod.GET)
public @ResponseBody byte[] getImgGET(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@PathVariable String imgid){
byte[] rawImg = null;
return rawImg;
}
@RequestMapping(value = "/newuser",
method = RequestMethod.GET,
produces = "application/json; charset=utf-8")
public @ResponseBody ModelAndView newUserGET(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response){
ModelAndView view = new ModelAndView("newuser");
return view;
}
@Async
public Future<PutObjectResult> uploadS3(File file){
AmazonS3 s3Client = new AmazonS3Client(new InstanceProfileCredentialsProvider());
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType("image/png");
PutObjectResult pr = s3Client.putObject("mmtctestpic",file.getName(),file);
return new AsyncResult<PutObjectResult>(pr);
}
private Boolean updateTest(String suite, Test test){
if(suite.length() == 0 || test.getSerialNo() == null)
return false;
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
String sql = "SELECT pk FROM testsuite WHERE name=?";
long suitePK = -1L;
try {
Connection conn = dataSource.getConnection();
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, suite);
ResultSet rs = prepStmt.executeQuery();
if(rs != null && rs.next()){
suitePK = rs.getLong("pk");
}else{
logger.error("[saveTest]: Could not find suite of " + suite + " !");
rs.close();
prepStmt.close();
conn.close();
return false;
}
rs.close();
prepStmt.close();
sql = "UPDATE test SET ";
String sqlSuffix = "updatedat=NOW() WHERE testsuite_pk = ? AND serial=?";
HashMap<String,String> columns = new HashMap<String,String>();
if(test.getQuestion() != null){
JsonArray quesArr = test.getQuestion();
for(int i = 0; i < quesArr.size(); ++i){
String cur = quesArr.get(i).getAsString();
if(cur.indexOf(".") != -1){
cur = cur.substring(cur.indexOf(".") + 1);
}
quesArr.set(i, new JsonPrimitive(cur));
}
columns.put("question", quesArr.toString());
}
if(test.getOptions() != null){
columns.put("options", test.getOptions().toString());
}
if(test.getAnswers() != null){
columns.put("answer", test.getAnswers().toString());
}
if(test.getKeywords() != null){
columns.put("keywords", test.getKeywords().toString());
}
if(test.getPic() != null){
columns.put("pic", test.getPic().toString());
}else{
columns.put("pic", null);
}
if(test.getWatchword() != null){
columns.put("watchword", test.getWatchword().toString());
}
if(test.getTips() != null){
columns.put("tips", test.getTips().toString());
}
if(columns.size() > 0){
for(String key:columns.keySet()){
sql += key;
sql += "=";
sql += "?,";
}
sql += "testsuite_pk=?,";
}
sql += sqlSuffix;
prepStmt = conn.prepareStatement(sql);
int i = 1;
for(String key:columns.keySet()){
prepStmt.setNString(i, columns.get(key));
++i;
}
prepStmt.setLong(i, suitePK);
++i;
prepStmt.setLong(i, suitePK);
++i;
prepStmt.setInt(i, test.getSerialNo());
logger.debug("[finalPrepStmt]: " + prepStmt.toString());
prepStmt.executeUpdate();
prepStmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
private Boolean addTest(String suite, Test test){
ArrayList<Test> tests = getTestsForSuite(suite);
int i = 0;
for(; i < tests.size(); ++i){
if(tests.get(i).getSerialNo().equals(test.getSerialNo())){
//We'll insert new test before n-th test.
break;
}
}
if(i == tests.size()){
//Not found, we'll append new test at end.
tests.add(test);
}else{
tests.add(i, test);
++i;
for(; i < tests.size(); ++i){
tests.get(i).setSerialNo(i+1);
}
}
//Put tests back to db.
return addTests(suite,tests);
}
private Boolean deleteSuite(String suite, long suitePK){
Boolean result = true;
String sql = null;
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
Connection conn = null;
PreparedStatement prepStmt = null;
if(suitePK == -1L){
sql = "SELECT pk FROM testsuite WHERE name = ?";
try {
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, suite);
ResultSet rs = prepStmt.executeQuery();
if(rs != null && rs.next() == true){
suitePK = rs.getLong(1);
}
prepStmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error("[deleteSuite]: Failed getting PK from testsuite for suite " + suite + ", " + e.toString());
return false;
}
}
try {
sql = "DELETE FROM test WHERE testsuite_pk = ?";
conn = dataSource.getConnection();
prepStmt = conn.prepareStatement(sql);
prepStmt.setLong(1, suitePK);
prepStmt.executeUpdate();
prepStmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
logger.error("[deleteSuite]: " + e.toString());
result = false;
e.printStackTrace();
}
return result;
}
private Boolean addTests(String suite, ArrayList<Test> tests){
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
String sql = "SELECT pk FROM testsuite WHERE name=?";
long suitePK = -1L;
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, suite);
ResultSet rs = prepStmt.executeQuery();
if(rs != null && rs.next()){
suitePK = rs.getLong("pk");
deleteSuite(suite,suitePK);
suitePK = addEmptySuite(suite);
}else{
//suite doesn't exist.
prepStmt.close();
conn.close();
suitePK = addEmptySuite(suite);
}
if(suitePK == -1L){
logger.error("[addTests]: CANNOT FIND suite PK: " + suite);
}else{
sql="INSERT INTO test (testsuite_pk,question,options,answer,"
+ "keywords,pic,serial,watchword,tips,createdat,updatedat)"
+ " VALUES (?,?,?,?,?,?,?,?,?,NOW(),NOW())";
prepStmt = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for(Test t: tests){
prepStmt.setLong(1, suitePK);
prepStmt.setString(2, t.getQuestion().toString());
prepStmt.setString(3, t.getOptions().toString());
prepStmt.setString(4, t.getAnswers().toString());
if(t.getKeywords() == null){
prepStmt.setNString(5, null);//prepStmt.setNull(5, sqlType);
}else{
prepStmt.setNString(5, t.getKeywords().toString());
}
prepStmt.setString(6, t.getPic());
prepStmt.setInt(7, t.getSerialNo());
if(t.getWatchword() == null){
prepStmt.setNString(8, null);
}else{
prepStmt.setNString(8, t.getWatchword().toString());
}
if(t.getTips() == null){
prepStmt.setNString(9, null);
}else{
prepStmt.setNString(9, t.getTips().toString());
}
prepStmt.addBatch();
}
prepStmt.executeBatch();
conn.commit();
conn.setAutoCommit(true);
prepStmt.clearBatch();
prepStmt.close();
conn.close();
}
}catch(SQLException e){
logger.error("[addTests]: " + e.toString());
try {
conn.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
logger.error("[addTests]: " + e1.toString());
e1.printStackTrace();
}
return false;
}
return true;
}
private Long addEmptySuite(String name){
long newSuitePK = -1L;
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
String sql = "INSERT INTO testsuite (name) VALUES (?)";
try {
Connection conn = dataSource.getConnection();
PreparedStatement prepStmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
prepStmt.setString(1, name);
prepStmt.executeUpdate();
ResultSet rs = prepStmt.getGeneratedKeys();
if(rs != null && rs.next()){
newSuitePK = rs.getLong(1);
}else{
logger.error("[saveTest]: Could not get PK of new suite of " + name + " !");
prepStmt.close();
conn.close();
}
prepStmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newSuitePK;
}
@RequestMapping(value = "/oneedit", method = RequestMethod.POST)
public @ResponseBody String oneEditPOST(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@RequestParam ("suite") String suite,
@RequestParam ("test") String test) {
logger.info(request.getRequestURL().toString());
JsonParser jp = new JsonParser();
JsonObject testObj = jp.parse(test).getAsJsonObject();
Test t = new Test();
if(testObj.get("pic") != null
&& testObj.get("pic").isJsonNull() == false){
if(testObj.get("newpic") != null
&& testObj.get("newpic").isJsonNull() == false
&& testObj.get("newpic").getAsBoolean() == true){
String destDir = request.getSession().getServletContext().getRealPath("/");
destDir += "resources";
destDir += File.separator;
destDir += "pic";
destDir += File.separator;
logger.info("[2_save_img_2] " + destDir);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
String encFileName = null;
String strB64Pic = testObj.get("pic").getAsString();
encFileName = encrypt(curUser + "MendezMasterTrainingCenter6454_testpickey",suite + "-" + testObj.get("serialNo").getAsString());
strB64Pic = strB64Pic.substring(strB64Pic.indexOf(",")+1);
byte[] rawPicBytes = Base64.decodeBase64(strB64Pic);
logger.debug("[pic_enc_name]: " + encFileName);
try {
FileOutputStream out = new FileOutputStream(destDir+encFileName);
out.write(rawPicBytes);
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.setPic(encFileName);
//Upload to S3.
if(DEBUG == false){
File outFile = new File(destDir+encFileName);
uploadS3(outFile);
}
}else{
String pic = testObj.get("pic").getAsString();
pic = pic.substring(pic.lastIndexOf("pic/")+4);
if(testObj.get("delpic") != null
&& testObj.get("delpic").getAsBoolean() == true){
String destDir = request.getSession().getServletContext().getRealPath("/");
destDir += "resources";
destDir += File.separator;
destDir += "pic";
destDir += File.separator;
final String file2Del = destDir + pic;
//launch separate thread to delete local picture file.
new Thread(){
public void run(){
try {
Files.delete(Paths.get(file2Del));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error("[oneeditPOST]: Failed deleting local pic, " + e.toString());
}
}
}.start();
}else{
//Prepare file-name-only to return back to client if pic was not edited.
t.setPic(pic);
}
}
}
t.setAnswers(testObj.get("answers").getAsJsonArray());
if(testObj.get("kwds") != null){
t.setKeywords(testObj.get("kwds").getAsJsonArray());
}
t.setOptions(testObj.get("options").getAsJsonArray());
JsonArray quesJArr = testObj.get("question").getAsJsonArray();
JsonElement quesPrefixedBySerial = quesJArr.get(0);
int dotPos = quesJArr.get(0).getAsString().indexOf(".");
if(dotPos != -1){
quesJArr.set(0, new JsonPrimitive(quesJArr.get(0).getAsString().substring(dotPos+1)));
}
t.setQuestion(quesJArr);
if(testObj.get("serialNo") != null){
t.setSerialNo(testObj.get("serialNo").getAsInt());
}
t.setSuite(suite);
JsonElement elm = testObj.get("tips");
if(elm != null){
if(elm.isJsonArray() == true){
t.setTips(testObj.get("tips").getAsJsonArray());
}else{
if(elm.getAsString().length() > 0){
JsonArray tipArr = new JsonArray();
tipArr.add(elm);
t.setTips(tipArr);
}
}
}
elm = testObj.get("watchword");
if(elm != null){
if(elm.isJsonArray() == true){
t.setTips(testObj.get("watchword").getAsJsonArray());
}else{
if(elm.getAsString().length() > 0){
JsonArray tipArr = new JsonArray();
tipArr.add(elm);
t.setWatchword(tipArr);
}
}
}
JsonObject result = new JsonObject();
if(testObj.get("isnew") != null && testObj.get("isnew").getAsBoolean() == true){
logger.info("[oneedit]: Add new test.");
result.add("result", new JsonPrimitive(addTest(suite,t)));
}else{
result.add("result", new JsonPrimitive(updateTest(suite,t)));
}
Gson gson = new Gson();
t.getQuestion().set(0, quesPrefixedBySerial);
result.add("test", gson.toJsonTree(t));
String strJ = gson.toJson(result).replace("\\", "\\\\");
return strJ;
}
@RequestMapping(value = "/submitedit", method = RequestMethod.POST)
public @ResponseBody ModelAndView submitEditPOST(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@RequestParam("testdata") String tests) {
ModelAndView v = new ModelAndView();
logger.info(request.getRequestURL().toString());
JsonParser jsonParser = new JsonParser();
JsonObject jsonTestSuite = jsonParser.parse(tests).getAsJsonObject();
//Check if test editor is authenticated user.
String user = null;
if(request.getUserPrincipal().getName().equals(jsonTestSuite.get("user").getAsString()) == false){
v.setViewName("result");
v.addObject("result","Editing failed: Test taker and logged-in user are different.");
return v;
}else
user = request.getUserPrincipal().getName();
//Check for deleted tests and update to database.
String suite = jsonTestSuite.get("suite").getAsString();
ArrayList<Test> curTests = getTestsForSuite(suite);
JsonArray jsonTests = jsonTestSuite.get("tests").getAsJsonArray();
Boolean hasDeletedTest = false;
for(int i = jsonTests.size() - 1; i > -1; --i){
JsonObject t = jsonTests.get(i).getAsJsonObject();
if(t.get("del") != null && t.get("del").getAsBoolean() == true){
hasDeletedTest = true;
int sn = t.get("serialNo").getAsInt();
curTests.remove(sn-1);
}
}
//Adjust test serial numbers.
for(int j = 0; j < curTests.size(); ++j){
curTests.get(j).setSerialNo(j+1);
}
//Update to DB.
if(hasDeletedTest == true){
if(curTests.size() > 0){
addTests(suite,curTests);
}else{
//remove suite.
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
Connection conn = null;
PreparedStatement prepStmt = null;
try {
conn = dataSource.getConnection();
String sql = "DELETE FROM testsuite WHERE name=?";
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, suite);
prepStmt.executeUpdate();
prepStmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return new ModelAndView("home");
}
@RequestMapping(value = "/edittest/{tid}", method = RequestMethod.POST)
public @ResponseBody ModelAndView editTestPOST(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@PathVariable String tid,
@RequestParam("file") MultipartFile file) {
logger.info(request.getRequestURL().toString());
if(file.getSize() > 0){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
String suiteAndTest = decryptTestID(curUser + "MendezMasterTrainingCenter6454",tid);
logger.info("[DEcrypted] " + suiteAndTest);
//Save image locally.
String destDir = request.getSession().getServletContext().getRealPath("/");//servletCtx.getRealPath("/");
destDir += "resources";
destDir += File.separator;
destDir += "pic";
destDir += File.separator;
logger.info("[2_save_img_2] " + destDir);
String encFileName = encrypt(curUser + "MendezMasterTrainingCenter6454_testpickey",suiteAndTest);
FileInputStream in = null;
try {
in = (FileInputStream) file.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return new ModelAndView("result","result","Failed getting INPUT STREAM.");
}
FileOutputStream out = null;
try {
out = new FileOutputStream(destDir+encFileName+".png");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
File f = new File(destDir);
if(f.mkdir() == false){
logger.error("[VERY BAD] Failed creating picture folder in CATALINA_HOME.");
}
return new ModelAndView("result","result","Failed getting OUTPUT STREAM.");
}
int readBytes = 0;
byte[] buffer = new byte[8192];
try {
while ((readBytes = in.read(buffer, 0, 8192)) != -1) {
logger.info("===ddd=======");
out.write(buffer, 0, readBytes);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
logger.info("[DONE_SAVING_IMG]");
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Save pic dir info to SQL.
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
Connection conn = null;
PreparedStatement preparedSql = null;
String sql = "UPDATE test SET pic=? WHERE testsuite_pk IN (SELECT pk FROM testsuite WHERE name = ?) AND serial = ?";
String[] s_t = suiteAndTest.split("-");
try {
conn = dataSource.getConnection();
preparedSql = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
preparedSql.setString(1, encFileName);
preparedSql.setString(2,s_t[0]);
preparedSql.setInt(3, Integer.valueOf(s_t[1]));
preparedSql.executeUpdate();
ResultSet r = preparedSql.getGeneratedKeys();
r.next();
//rowID = r.getLong(1);
} catch (SQLException e) {
e.printStackTrace();
String err = new Throwable().getStackTrace()[0].getMethodName();
err += " => ";
err += e.getMessage();
logger.error(err);
return new ModelAndView("result","result","Error: " + e.getMessage());
} finally{
sql = null;
try {
preparedSql.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
preparedSql = null;
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
conn = null;
}
}
String parentDir = File.separator;
parentDir += "mmtcexam";
parentDir += File.separator;
parentDir += "resources" + File.separator;
parentDir += "pic";
parentDir += File.separator;
session.setAttribute("uploadFile", parentDir + encFileName + ".png");
//Prepare file to S3.
File outFile = new File(destDir+encFileName);
if(!outFile.exists()){
logger.error(destDir+encFileName + " doesn't exists.");
}else{
uploadS3(outFile);
}
}else{
return new ModelAndView("result","result","Empty file uploaded.");
}
return new ModelAndView("picuploadindex");
}
@RequestMapping(value="/uploadtestsuite", method=RequestMethod.POST)
public @ResponseBody ModelAndView uploadTestSuitePOST(
@RequestParam("name") String suitename,
HttpServletRequest request,
HttpServletResponse response,
@RequestParam("file") MultipartFile file){
logger.info(request.getRequestURL().toString());
if(suitename == null || suitename.length() == 0)
return new ModelAndView("result","result","Error: Missing testsuite name.");
if (!file.isEmpty()) {
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
String sql = "INSERT INTO testsuite (`name`) VALUES (?)";
PreparedStatement preparedSql = null;
Long rowID = null;
Connection conn = null;
try {
conn = dataSource.getConnection();
preparedSql = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
preparedSql.setNString(1, suitename);
preparedSql.executeUpdate();
ResultSet r = preparedSql.getGeneratedKeys();
r.next();
rowID = r.getLong(1);
} catch (SQLException e) {
e.printStackTrace();
logger.error("[uploadtestsuite] " + e.getMessage());
return new ModelAndView("result","result","Error: " + e.getMessage());
} finally{
sql = null;
try {
preparedSql.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
preparedSql = null;
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
conn = null;
}
}
Integer pI = 1;
int r = 0;
int jArrLen = 0;
String prevTestSerial = "0";
String curTestSerial = "0";
XSSFWorkbook parser = null;
try {
byte[] bytes = file.getBytes();
//String decoded = new String(bytes,"UTF-8");
//logger.info("CSV: {}",decoded);
parser = new XSSFWorkbook(new ByteArrayInputStream(bytes));
XSSFSheet sheet1 = parser.getSheetAt(0);
Iterator<Row> rItor = sheet1.iterator();
Boolean isQuestion = true;
String curValue = null;
JsonArray jArr = null;
Boolean isBadQuestion = false;
Boolean isFirstCell = true;
conn = dataSource.getConnection();
sql = "INSERT INTO test (serial, question, answer, keywords, options, watchword, tips, testsuite_pk, " +
"createdat, updatedat) VALUES (?,?,?,?,?,?,?,?,NOW(),NOW())";
preparedSql = conn.prepareStatement(sql);
while(rItor.hasNext()){
Row row = rItor.next();//Row row = sheet1.getRow(i);
if(row.getPhysicalNumberOfCells() > 0){
//logger.info("[pI]: " + pI.toString());
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
cellloop: while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
logger.info("[CELL_TYPE_NUMERIC]!");
curValue = String.valueOf(cell.getNumericCellValue());
if(jArr == null)
jArr = new JsonArray();
jArr.add(curValue);
break;
case Cell.CELL_TYPE_STRING:
curValue = cell.getStringCellValue();
logger.info("{}",curValue);
if(isBadQuestion == false){
if(isQuestion == true){
//boolean isEnglish = curValue.matches("[\\w\\s\\.\\?]+");
//if(isEnglish == true){
if(isFirstCell == true){
isFirstCell = false;
int dotPos = curValue.indexOf('.');
if(dotPos != -1){
curTestSerial = curValue.substring(0, dotPos);
curValue = curValue.substring(dotPos+1);
if(curValue.equals("NOQUESTION")){
isBadQuestion = true;
break cellloop;
}
Integer c = Integer.parseInt(curTestSerial);
Integer p = Integer.parseInt(prevTestSerial);
if(c-p > 1)
c-=1;
preparedSql.setInt(pI, c);
pI++;
prevTestSerial = c.toString();
if(jArr == null)
jArr = new JsonArray();
jArr.add(curValue);
}
}else{
//Error: Question doesn't begin with serial number followed by '.'.
//Check if this cell has chinese translation of question.
//Chinese.
if(jArr == null)
jArr = new JsonArray();
jArr.add(curValue);
}
//break cellloop;//We only allow 1 cell for question.
}else{
if(jArr == null)
jArr = new JsonArray();
jArr.add(cell.getStringCellValue());
}
}
break;
case Cell.CELL_TYPE_BLANK:
logger.info("[CELL_TYPE_BLANK]!");
break;
default:
logger.error("[UNKnown cell type]!!");
break;
}
}
/*
if(jArr != null && isQuestion == false){
curValue = jArr.toString();
preparedSql.setNString(pI, curValue);
if(pI == 5)
pI = 0;
jArr = null;
}
*/
logger.info("[END_ROW]");
}else{
logger.info("[EMPTY_ROW]");
}
if(jArr != null){
if(r != 0 && r % DataRows == 0){
r=0;
if(isQuestion == false){
isQuestion = true;
isBadQuestion = false;
isFirstCell = true;
curValue = jArr.toString();
preparedSql.setNString(pI, curValue);
++pI;
preparedSql.setLong(pI, rowID);
if(pI == 8){
//logger.info("[ROTATE pI].");
pI = 1;
}
preparedSql.addBatch();
jArr.remove(0);
jArr = null;
logger.info("[Done_prepared_batch]: " + preparedSql.toString());
}
}else{
if(isQuestion == true){
curValue = jArr.toString();
preparedSql.setNString(pI, curValue);
++pI;
jArr = null;
isQuestion = false;
}else{
curValue = jArr.toString();
preparedSql.setNString(pI, curValue);
++pI;
jArr = null;
}
++r;
}
}else{
if(isBadQuestion == true){
if(r != 0 && r % 5 == 0){
r = 0;
isQuestion = true;
isBadQuestion = false;
isFirstCell = true;
}else{
++r;
}
}
}
}
//Scoop up last item.
if(jArr != null){
curValue = jArr.toString();
preparedSql.setNString(pI, curValue);
/*++pI;
jArrLen = jArr.size();
for(int i = 0; i < jArrLen; ++i){
jArr.remove(0);
}
jArr.add("NOHIGHLIGHT");
preparedSql.setNString(pI, jArr.toString());
jArr.remove(0);
jArr.add("NOTIPS");
++pI;
preparedSql.setNString(pI, jArr.toString());
++pI;
preparedSql.setLong(pI, rowID);
if(pI == 8){
logger.info("[ROTATE pI].");
pI = 1;
}*/
preparedSql.addBatch();
preparedSql.setLong(8, rowID);
preparedSql.addBatch();
logger.info("[Done_LAST_prepared_batch].");
}
} catch (Exception e) {
e.printStackTrace();
String error = null;
if(curTestSerial != null && curTestSerial.length() > 0)
error = "You failed uploading test suite " + suitename + " because of test " + curTestSerial + " after test " + prevTestSerial;
else
error = "You failed uploading test suite " + suitename;
logger.error(e.getMessage());
//Delete test suite record and any tests already inserted.
try {
preparedSql.clearBatch();
} catch (SQLException e1) {
e1.printStackTrace();
preparedSql = null;
logger.error("[uploadtestsuite] Exception when clearBatch() of preparedSql.");
}
String sql2 = "DELETE FROM testsuite WHERE pk = " + rowID;
try {
conn.createStatement().executeUpdate(sql2);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
logger.error("[uploadtestsuite] Failed deleting testsuite record " + rowID);
error += ". Serious error, PLZ contact nikki.";
}
return new ModelAndView("result","result",error);
}
try {
parser.close();
} catch (IOException e1) {
e1.printStackTrace();
} finally{
parser = null;
}
try {
conn.setAutoCommit(false);
preparedSql.executeBatch();
conn.commit();
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
logger.error("[uploadtestsuite] " + e.getMessage());
new ModelAndView("result","result","Error: " + e.getMessage());
} finally{
try {
preparedSql.close();
} catch (SQLException e) {
e.printStackTrace();
} finally{
preparedSql = null;
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
} finally{
conn = null;
}
}
return new ModelAndView("result","result","Successfully uploaded test suite " + suitename);
} else {
return new ModelAndView("result","result","Server didn't get file.");
}
}
@RequestMapping(value = "/runsuite/{s}", method = RequestMethod.GET)
public @ResponseBody ModelAndView runSuiteGET(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@PathVariable String s) {
logger.info(request.getRequestURL().toString());
TestSuite ts = new TestSuite();
ModelAndView resultView = new ModelAndView("preexecsuite");
resultView.addObject("ts", ts);
resultView.addObject("su", s);
return resultView;
}
@RequestMapping(value = "/runsuite/{s}", method = RequestMethod.POST)
public @ResponseBody ModelAndView runSuitePOST(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@PathVariable String s,
@ModelAttribute("ts") TestSuite suite) {
logger.info(request.getRequestURL().toString());
ArrayList<Test> tests = getTestsForDisplayForSuite(s);
Random random = new Random();
if(suite.getIsQuestionRandom() != null){
Test lastUnStruck = null;
Test randomPickTest = null;
String fullQues = null;
int dotPos = 0;
//Randomize.
int r = 0;
int i = tests.size() - 1;
for(; i >= 1; --i){
r = random.nextInt(i);
lastUnStruck = tests.get(i);
randomPickTest = tests.get(r);
JsonArray jArrQuestion = randomPickTest.getQuestion();
fullQues = jArrQuestion.get(0).getAsString();
dotPos = fullQues.indexOf(".");
if(dotPos != -1){
String ques = fullQues.substring(dotPos);
fullQues = String.valueOf(i+1) + ques;
}else{
logger.error("[runSuitePOST]: Found question not beginning with serial!");
//Make it right: random + "." + question.
fullQues = String.valueOf(i+1) + "." + fullQues;
}
jArrQuestion.set(0, new JsonPrimitive(fullQues));
randomPickTest.setQuestion(jArrQuestion);
tests.set(i, randomPickTest);
tests.set(r, lastUnStruck);
}
//We updated new random picks before, and always
//have to update last i-th item after the loop.
JsonArray jArrQuestion = tests.get(i).getQuestion();
fullQues = jArrQuestion.get(0).getAsString();
dotPos = fullQues.indexOf(".");
if(dotPos != -1){
String ques = fullQues.substring(dotPos);
fullQues = String.valueOf(i+1) + ques;
}else{
logger.error("[runSuitePOST]: Found question not beginning with serial!");
//Make it right: random + "." + question.
fullQues = String.valueOf(i+1) + "." + fullQues;
}
jArrQuestion.set(0, new JsonPrimitive(fullQues));
tests.get(i).setQuestion(jArrQuestion);
}
if(suite.getIsChoiceRandom() != null){
int r = 0;
int dotPos = -1;
String strTemp1;
JsonElement jElemTemp;
JsonElement jElemRandom;
for(int i = 0; i < tests.size(); ++i){
Test curTest = tests.get(i);
JsonArray curOptions = curTest.getOptions();
JsonArray randomOptions = curOptions;
int len = randomOptions.size();
int j = len - 1;
for(; j >= 1; --j){
r = random.nextInt(j);
jElemTemp = randomOptions.get(j);
jElemRandom = randomOptions.get(r);
strTemp1 = jElemRandom.getAsString();
dotPos = strTemp1.indexOf(".");
if(dotPos != -1){
strTemp1 = String.valueOf((char)(j+65)) + strTemp1.substring(dotPos);
}else{
logger.error("[runSuitePOST]: Found bad formatted option without dot between A|B|C|D and rest!Test[" + String.valueOf(i) + "], Option[" + strTemp1 + "]");
strTemp1 = String.valueOf((char)(j+65)) + "." + strTemp1;
}
randomOptions.set(j, new JsonPrimitive(strTemp1));
randomOptions.set(r, jElemTemp);
}
//Adjust A|B|C|D after randomization for j-th value.
strTemp1 = randomOptions.get(j).getAsString();
dotPos = strTemp1.indexOf(".");
if(dotPos != -1){
strTemp1 = String.valueOf((char)(j+65)) + strTemp1.substring(dotPos);
}else{
logger.error("[runSuitePOST]: Found bad formatted option without dot between A|B|C|D and rest! Test[" + String.valueOf(i) + "], Option[" + strTemp1 + "]");
strTemp1 = String.valueOf((char)(j+65)) + "." + strTemp1;
}
randomOptions.set(j, new JsonPrimitive(strTemp1));
curTest.setOptions(randomOptions);
}
}
JsonObject jSuite = new JsonObject();
jSuite.addProperty("suite", s);
Gson gson = new Gson();
JsonArray jTests = (JsonArray)gson.toJsonTree(tests, new TypeToken<ArrayList<Test>>(){}.getType());
jSuite.add("tests", jTests);
//String strJ = gson.toJson(jSuite);
String strJ = gson.toJson(jSuite).replace("\\", "\\\\");
request.setAttribute("tests",strJ);
return new ModelAndView("exectest");
}
@RequestMapping(value = "/timeout", method = RequestMethod.GET)
public @ResponseBody ModelAndView timeoutGET(Locale locale, Model model,
HttpServletRequest request,
HttpServletResponse response) {
logger.info(request.getRequestURL().toString());
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
return new ModelAndView("result","result","Time out!");
}
private ArrayList<String> getTestSuites(){
logger.info("showTestSuites()!");
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
ArrayList<String> suites = new ArrayList<String>();
String sql = "SELECT `name` FROM testsuite";
try{
Connection conn = dataSource.getConnection();
ResultSet s = conn.createStatement().executeQuery(sql);
while(s.next()){
suites.add(s.getString("name"));
}
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[testsuite] " + e.getMessage());
}
return suites;
}
private ArrayList<Test> getTestBySuiteAndID(String suite, String testsn){
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
ArrayList<Test> tests = new ArrayList<Test>();
String sql = "SELECT serial, pic ,updatedat, question, options,answer,keywords,watchword,tips FROM test "
+"WHERE testsuite_pk IN (SELECT pk FROM testsuite WHERE name=?)"
+" AND serial = ?";
PreparedStatement preparedSql = null;
Connection conn = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
try{
conn = dataSource.getConnection();
preparedSql = conn.prepareStatement(sql);
preparedSql.setString(1, suite);
preparedSql.setString(2, testsn);
ResultSet s = preparedSql.executeQuery();
String serial = null;
JsonParser jp = new JsonParser();
Gson gs = new Gson();
String temp;
JsonElement elem = null;
JsonArray jsonArr = null;
Test found = null;
while(s.next()){
found = new Test();
if(s.getString("question").equals("[\"NOQUESTION\"]") == false){
elem = jp.parse(s.getString("question"));
jsonArr = elem.getAsJsonArray();
temp = jsonArr.get(0).getAsString();
temp = serial + "." + temp;
jsonArr.set(0, new JsonPrimitive(temp));
found.setQuestion(jsonArr);
}else{
//Really odd...
logger.error("[getTestBySuiteAndID]: NOQUESTION found!! " + suite + "::" + testsn);
continue;
}
if(s.getString("watchword").equals("[\"NOHIGHLIGHT\"]") == false){
elem = jp.parse(s.getString("watchword"));
jsonArr = elem.getAsJsonArray();
found.setWatchword(jsonArr);
}
if(s.getString("answer").equals("[\"NOANSWER\"]") == false
&& s.getString("answer").equals("[\"NOANS\"]") == false){
elem = jp.parse(s.getString("answer"));
jsonArr = elem.getAsJsonArray();
found.setAnswers(jsonArr);
}
if(s.getString("options").equals("[\"NOOPT\"]") == false){
elem = jp.parse(s.getString("options"));
jsonArr = elem.getAsJsonArray();
found.setOptions(jsonArr);
}
if(s.getString("keywords").equals("[\"NOKEYWORD\"]") == false){
elem = jp.parse(s.getString("keywords"));
jsonArr = elem.getAsJsonArray();
found.setKeywords(jsonArr);
}
//found.setOptions(s.getString("options"));
serial = Integer.toString(s.getInt("serial"));
found.setPic(s.getString("pic"));
if(s.getString("tips").equals("[\"NOTIPS\"]") == false){
elem = jp.parse(s.getString("tips"));
jsonArr = elem.getAsJsonArray();
found.setTips(jsonArr);
}
found.setId(encrypt(curUser + "MendezMasterTrainingCenter6454",suite + "-" + serial));
if(DEBUG == true){
found.setSuite(suite);
}
found.setSerialNo(Integer.valueOf(testsn));
tests.add(found);
}
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[getTestBySuiteAndID()] " + e.getMessage());
}
return tests;
}
private ArrayList<Test> getTestsForSuite(String suite){
logger.info("getTestsForSuite()!");
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
ArrayList<Test> tests = new ArrayList<Test>();
String sql = "SELECT serial, updatedat, question, options,answer,keywords,pic,tips,watchword FROM test WHERE testsuite_pk IN (SELECT pk FROM testsuite WHERE name=?) ORDER BY serial";
PreparedStatement preparedSql = null;
Connection conn = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
try{
conn = dataSource.getConnection();
preparedSql = conn.prepareStatement(sql);
preparedSql.setString(1, suite);
ResultSet s = preparedSql.executeQuery();
String serial = null;
JsonParser jp = new JsonParser();
String temp;
Test found = null;
JsonElement elem = null;
JsonArray jsonArr = null;
while(s.next()){
found = new Test();
serial = Integer.toString(s.getInt("serial"));
if(s.getString("question").equals("[\"NOQUESTION\"]") == false){
//logger.info("[getTestsForDisplayForSuite_Q]: " + s.getString("question"));
elem = jp.parse(s.getString("question"));
jsonArr = elem.getAsJsonArray();
found.setQuestion(jsonArr);
}else{
//Really odd, ought have been filtered out in uploadtestsuite.
logger.error("[getTestsForDisplayForSuite] NOQUESTION found!! TestSuite[" + suite + "][" + serial + "]");
continue;
}
if(s.getString("watchword") != null
&& s.getString("watchword").equals("[\"NOHIGHLIGHT\"]") == false){
elem = jp.parse(s.getString("watchword"));
jsonArr = elem.getAsJsonArray();
found.setWatchword(jsonArr);
}
if(s.getString("answer").equals("[\"NOANSWER\"]") == false
&& s.getString("answer").equals("[\"NOANS\"]") == false){
elem = jp.parse(s.getString("answer"));
jsonArr = elem.getAsJsonArray();
found.setAnswers(jsonArr);
}
if(s.getString("options").equals("[\"NOOPT\"]") == false){
elem = jp.parse(s.getString("options"));
jsonArr = elem.getAsJsonArray();
found.setOptions(jsonArr);
}
if(s.getString("keywords") != null
&& s.getString("keywords").equals("[\"NOKEYWORD\"]") == false){
elem = jp.parse(s.getString("keywords"));
jsonArr = elem.getAsJsonArray();
found.setKeywords(jsonArr);
}
found.setPic(s.getString("pic"));
if(s.getString("tips") != null && s.getString("tips").equals("[\"NOTIPS\"]") == false){
elem = jp.parse(s.getString("tips"));
jsonArr = elem.getAsJsonArray();
found.setTips(jsonArr);
}
found.setId(encrypt(curUser + "MendezMasterTrainingCenter6454",suite + "-" + serial));
if(DEBUG == true){
found.setSuite(suite);
}
found.setSerialNo(Integer.valueOf(serial));
tests.add(found);
}
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[testsuite] " + e.getMessage());
}
return tests;
}
private ArrayList<Test> getTestsForDisplayForSuite(String suite){
logger.info("getTestsForDisplayForSuite()!");
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
ArrayList<Test> tests = new ArrayList<Test>();
String sql = "SELECT serial, updatedat, question, options,answer,keywords,pic,tips,watchword FROM test WHERE testsuite_pk IN (SELECT pk FROM testsuite WHERE name=?) ORDER BY serial";
PreparedStatement preparedSql = null;
Connection conn = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
try{
conn = dataSource.getConnection();
preparedSql = conn.prepareStatement(sql);
preparedSql.setString(1, suite);
ResultSet s = preparedSql.executeQuery();
String serial = null;
JsonParser jp = new JsonParser();
String temp;
Test found = null;
JsonElement elem = null;
JsonArray jsonArr = null;
while(s.next()){
found = new Test();
serial = Integer.toString(s.getInt("serial"));
if(s.getString("question").equals("[\"NOQUESTION\"]") == false){
//logger.info("[getTestsForDisplayForSuite_Q]: " + s.getString("question"));
elem = jp.parse(s.getString("question"));
jsonArr = elem.getAsJsonArray();
temp = jsonArr.get(0).getAsString();
temp = serial + "." + temp;
jsonArr.set(0, new JsonPrimitive(temp));
found.setQuestion(jsonArr);
}else{
//Really odd, ought have been filtered out in uploadtestsuite.
logger.error("[getTestsForDisplayForSuite] NOQUESTION found!! TestSuite[" + suite + "][" + serial + "]");
continue;
}
if(s.getString("watchword") != null
&& s.getString("watchword").equals("[\"NOHIGHLIGHT\"]") == false){
elem = jp.parse(s.getString("watchword"));
jsonArr = elem.getAsJsonArray();
found.setWatchword(jsonArr);
}
if(s.getString("answer").equals("[\"NOANSWER\"]") == false
&& s.getString("answer").equals("[\"NOANS\"]") == false){
elem = jp.parse(s.getString("answer"));
jsonArr = elem.getAsJsonArray();
found.setAnswers(jsonArr);
}
if(s.getString("options").equals("[\"NOOPT\"]") == false){
elem = jp.parse(s.getString("options"));
jsonArr = elem.getAsJsonArray();
found.setOptions(jsonArr);
}
if(s.getString("keywords") != null
&& s.getString("keywords").equals("[\"NOKEYWORD\"]") == false){
elem = jp.parse(s.getString("keywords"));
jsonArr = elem.getAsJsonArray();
found.setKeywords(jsonArr);
}
found.setPic(s.getString("pic"));
if(s.getString("tips") != null && s.getString("tips").equals("[\"NOTIPS\"]") == false){
elem = jp.parse(s.getString("tips"));
jsonArr = elem.getAsJsonArray();
found.setTips(jsonArr);
}
found.setId(encrypt(curUser + "MendezMasterTrainingCenter6454",suite + "-" + serial));
if(DEBUG == true){
found.setSuite(suite);
}
found.setSerialNo(Integer.valueOf(serial));
tests.add(found);
}
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[testsuite] " + e.getMessage());
}
return tests;
}
private String encrypt(String key, String secret2Encrypt){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
MessageDigest md = null;
byte[] iv = new byte[AES_KEYLENGTH / 8]; // Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
logger.error("[DEADLy] SHA not found in security algorithms!!!");
return null;
}
md.update(key.getBytes());
byte[] aesKey = md.digest();
aesKey = Arrays.copyOf(aesKey, 16);
String strKey = new String(aesKey);
//logger.info("[KEY1] " + strKey);
SecretKeySpec keySpec = new SecretKeySpec(aesKey,"AES");
SecureRandom prng = new SecureRandom();
prng.nextBytes(iv);
Cipher aesCipherForEncryption = null;
try {
aesCipherForEncryption = Cipher.getInstance("AES/CBC/PKCS5PADDING");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
try {
aesCipherForEncryption.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
String strIv = new String(iv);//The first 16 bits is iv, followed by suite + serial.
byte[] byteDataToEncrypt = secret2Encrypt.getBytes();
byte[] byteCipherText = null;
try {
byteCipherText = aesCipherForEncryption.doFinal(byteDataToEncrypt);
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
int l = iv.length + byteCipherText.length;
int delta = iv.length;
byte[] finalCipherText = new byte[iv.length + byteCipherText.length];
System.arraycopy(iv, 0, finalCipherText, 0, iv.length);
System.arraycopy(byteCipherText, 0, finalCipherText, iv.length, byteCipherText.length);
String strFinalCipherText = new String(Base64.encodeBase64(finalCipherText,false,true));
return strFinalCipherText;
}
private String decryptTestID(String key, String encryptedData){
byte [] decodeCipherText = Base64.decodeBase64(encryptedData);//16 bit iv + suite + serial.
byte [] iv = Arrays.copyOfRange(decodeCipherText, 0, AES_KEYLENGTH / 8);
byte [] realDecodeCipherText = Arrays.copyOfRange(decodeCipherText, AES_KEYLENGTH / 8, decodeCipherText.length);
Cipher aesCipherForDecryption = null;
try {
aesCipherForDecryption = Cipher.getInstance("AES/CBC/PKCS5PADDING");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
e.printStackTrace();
return null;
}
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String curUser = auth.getName();
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
logger.error("[DEADLy] SHA not found in security algorithms!!!");
return null;
}
md.update(key.getBytes());
byte[] aesKey = md.digest();
aesKey = Arrays.copyOf(aesKey, 16);
String strKey = new String(aesKey);
//logger.info("[KEY2] " + strKey);
//logger.info("[iv len] " + String.valueOf(iv.length));
SecretKeySpec keySpec = new SecretKeySpec(aesKey,"AES");
try {
aesCipherForDecryption.init(Cipher.DECRYPT_MODE, keySpec,new IvParameterSpec(iv));
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
e.printStackTrace();
return null;
}
byte[] byteDecryptedText = null;
try {
byteDecryptedText = aesCipherForDecryption.doFinal(realDecodeCipherText);
} catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String strDecryptedText = new String(byteDecryptedText);
logger.info(" Decrypted Text message is " + strDecryptedText + "/" + encryptedData);
return strDecryptedText;
}
@RequestMapping(value = "/execans", method = RequestMethod.GET)
public @ResponseBody ModelAndView execAnsGET(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response,
@RequestParam("su") String suite,
@RequestParam("u") String user,
@RequestParam("st") Long st,
@RequestParam("et") Long et){
ModelAndView v = new ModelAndView();
logger.info(request.getRequestURL().toString());
String sql = "SELECT pk FROM test_taking WHERE user_username=? "
+ "AND start_time = ? AND end_time=? AND testsuite_name=?";
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
Connection conn = null;
PreparedStatement prepStmt = null;
ArrayList<Test> tests = null;
ArrayList<Test> reorderedTests = null;
try{
long testTakingPK = 0L;
TestTaking taking = null;
JsonArray options = null;
String strOptions;
int serial = 0;
JsonParser jp = new JsonParser();
conn = dataSource.getConnection();
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, user);
prepStmt.setTimestamp(2, new Timestamp(st));
prepStmt.setTimestamp(3, new Timestamp(et));
prepStmt.setString(4, suite);
ResultSet rs = prepStmt.executeQuery();
if(rs != null && rs.next()){
testTakingPK = rs.getLong(1);
}
rs.close();
prepStmt.close();
tests = getTestsForDisplayForSuite(suite);
sql = "SELECT stuans, test_taking_serial,orig_test_serial, test_taking_options "
+ "FROM test_taking_snapshot WHERE test_taking_pk = ? ORDER BY test_taking_serial";
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, String.valueOf(testTakingPK));
rs = prepStmt.executeQuery();
if(rs != null){
if(reorderedTests == null){
reorderedTests = new ArrayList<Test>(tests.size());
}
String strQuestion;
JsonArray questionArr = null;
Test temp = null;
int testTakingSerial = 0;
int origTestSerial = 0;
while(rs.next()){
taking = null;
taking = new TestTaking();
taking.setStuAns(rs.getString("stuans"));
testTakingSerial = rs.getInt("test_taking_serial");
taking.setSerial(String.valueOf(testTakingSerial));
strOptions = rs.getString("test_taking_options");
JsonElement elem = jp.parse(rs.getString("test_taking_options"));
options = elem.getAsJsonArray();
taking.setOptions(options);
origTestSerial = rs.getInt("orig_test_serial");
temp = tests.get(origTestSerial-1);
questionArr = temp.getQuestion();
strQuestion = questionArr.get(0).getAsString();
strQuestion = String.valueOf(testTakingSerial) + strQuestion.substring(strQuestion.indexOf("."));
questionArr.set(0, new JsonPrimitive(strQuestion));
//temp.setQuestion(questionArr);
temp.setTaking(taking);
reorderedTests.add(temp);
}
}
rs.close();
prepStmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[execans] " + e.getMessage());
}
JsonObject jSuite = new JsonObject();
jSuite.addProperty("suite", suite);
Gson gson = new Gson();
JsonArray jTests = (JsonArray)gson.toJsonTree(reorderedTests, new TypeToken<ArrayList<Test>>(){}.getType());
jSuite.add("tests", jTests);
String strJ = gson.toJson(jSuite).replace("\\", "\\\\");
request.setAttribute("tests",strJ);
v.setViewName("execans");
return v;
}
@RequestMapping(value = "/submitans", method = RequestMethod.POST)
public @ResponseBody ModelAndView submitAnsPOST(
Locale locale,
Model model,
HttpSession session,
HttpServletRequest request,
HttpServletResponse response){
ModelAndView v = new ModelAndView();
logger.info(request.getRequestURL().toString());
JsonParser jsonParser = new JsonParser();
JsonObject jsonTestSuite = jsonParser.parse(request.getParameter("tests")).getAsJsonObject();
//Check if test taker is authed user.
String user = null;
if(request.getUserPrincipal().getName().equals(jsonTestSuite.get("user").getAsString()) == false){
v.setViewName("result");
v.addObject("result","Test taker and logged-in user are different.");
return v;
}else
user = request.getUserPrincipal().getName();
//Calculate grade.
JsonArray jArrTests = jsonTestSuite.getAsJsonArray("tests");
Iterator<JsonElement> itor = jArrTests.iterator();
String stuAns;
String correctAns;
Integer grade = 0;
while(itor.hasNext()){
JsonElement cur = itor.next();
if(cur.getAsJsonObject().get("taking") != null){
if(cur.getAsJsonObject().get("taking").getAsJsonObject().get("stuans") != null){
stuAns = cur.getAsJsonObject().get("taking").getAsJsonObject().get("stuans").getAsString();
//TODO: change this if in the future they start to use multi-selection questions.
correctAns = cur.getAsJsonObject().getAsJsonArray("answers").get(0).getAsString();
if(stuAns.equals(correctAns)){
grade += 1;
}
}
}
}
SimpleDateFormat ymdFmt = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat hmFmt = new SimpleDateFormat("HH:mm aaa");
long startTime = jsonTestSuite.get("beg").getAsLong();
long endTime = jsonTestSuite.get("end").getAsLong();
Date sdt = new Date(startTime);
Date edt = new Date(endTime);
String tt = null;
Timestamp stmp = new Timestamp(startTime);
Timestamp etmp = new Timestamp(endTime);
//Integer dur = jsonTestSuite.get("testdur").getAsInt();
JsonObject tempTest = jArrTests.get(0).getAsJsonObject();
String suiteAndTest = decryptTestID(user + "MendezMasterTrainingCenter6454",tempTest.get("id").getAsString());
String[] s_t = suiteAndTest.split("-");
DataSource dataSource = (DataSource) jndiObjFactoryBean.getObject();
String sql = "INSERT INTO test_taking "
+ "(user_username, grade, start_time, end_time, duration_in_sec,testsuite_name) "
+ "VALUES (?,?,?,?,?,"
+ "(SELECT name FROM testsuite WHERE name = '"+ s_t[0] +"'))";
PreparedStatement prepStmt = null;
JsonObject t = null;
long newRowID = -1L;
try{
Connection conn = dataSource.getConnection();
tt = sdf.format(sdt);
prepStmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
prepStmt.setString(1, user);
prepStmt.setInt(2, grade);
prepStmt.setTimestamp(3, stmp);
prepStmt.setTimestamp(4, etmp);
prepStmt.setInt(5,((Long)((endTime - startTime)/1000)).intValue());
prepStmt.executeUpdate();
ResultSet rs = prepStmt.getGeneratedKeys();
if(rs != null && rs.next()){
newRowID = rs.getLong(1);
}
conn.close();
}catch(Exception e){
e.printStackTrace();
logger.error("[submitans] " + e.getMessage());
}
ArrayList<JsonArray> testSplits = splitJsonArray(3,jArrTests);
for(int i = 0; i < testSplits.size(); ++i){
InsertTestAnsThread insertThread = new InsertTestAnsThread(dataSource,testSplits.get(i), newRowID);
insertThread.start();
}
v.setViewName("review");
v.addObject("participant", user);
String ymd = ymdFmt.format(sdt);
String hm = hmFmt.format(sdt);
//v.addObject("date",ymd);
v.addObject("starttime",startTime);//sdt.toString());
v.addObject("endtime",endTime);//edt.toString());
String strElapsedTime;
long elapsedSec = (endTime - startTime);///1000;
String days = String.valueOf(Math.floor(elapsedSec/(1000*60*60*24)));
String hours = String.valueOf(Math.floor((elapsedSec/(1000*60*60)) % 24));
String mins = String.valueOf(Math.floor((elapsedSec/1000/60) % 60));
String seconds = String.valueOf(Math.floor((elapsedSec/1000) % 60));
strElapsedTime = days;
strElapsedTime += " days ";
strElapsedTime += hours;
strElapsedTime += " hours ";
strElapsedTime += mins;
strElapsedTime += " mins ";
strElapsedTime += seconds;
strElapsedTime += " seconds";
v.addObject("elaptime", strElapsedTime);
v.addObject("passscore","630/900");
v.addObject("urscore", String.valueOf(grade * 10) + "/1000");
if(grade >= 70){
v.addObject("grade","Pass");
}else{
v.addObject("grade","Fail");
}
JsonArray scoreRange = new JsonArray();
scoreRange.add(grade*10);
scoreRange.add(700);
scoreRange.add(1000);
v.addObject("scores",scoreRange.toString());
v.addObject("suite",s_t[0]);
return v;
}
private class InsertTestAnsThread extends Thread{
private DataSource dataSource = null;
private JsonArray tests = null;
private Long testTakingPK = null;
public InsertTestAnsThread(
DataSource datasource,
JsonArray tests,
Long testTakingPk){
this.dataSource = datasource;
this.tests = tests;
this.testTakingPK = testTakingPk;
}
@Override
public void run(){
Iterator<JsonElement> itor = tests.iterator();
JsonObject test = null;
String sql = "INSERT INTO test_taking_snapshot (stuans, test_taking_serial,test_taking_options,test_taking_pk,orig_test_serial,marked)"
+ " VALUES (?,?,?," + testTakingPK.toString() + ",?,?)";
PreparedStatement prepStmt = null;
Connection conn = null;
try {
Integer serial = null;
String strSerial;
String strQuestion;
String testOptions;
conn = dataSource.getConnection();
prepStmt = conn.prepareStatement(sql);
conn.setAutoCommit(false);
for(int i = 0; i < tests.size(); ++i){
/*if(conn == null && prepStmt == null){
conn = dataSource.getConnection();
prepStmt = conn.prepareStatement(sql);
conn.setAutoCommit(false);
}*/
test = tests.get(i).getAsJsonObject();
if(test.get("taking") != null
&& test.get("taking").getAsJsonObject().get("stuans") != null){
prepStmt.setString(1, test.get("taking").getAsJsonObject().get("stuans").getAsString());
}else{
prepStmt.setString(1,"");
}
strQuestion = test.getAsJsonArray("question").get(0).getAsString();
strSerial = strQuestion.substring(0, strQuestion.indexOf("."));
prepStmt.setInt(2, Integer.valueOf(strSerial));
testOptions = test.getAsJsonArray("options").toString();
prepStmt.setString(3, testOptions);
prepStmt.setInt(4, test.get("serialNo").getAsInt());
if(test.get("marked") != null){
prepStmt.setInt(5, test.get("marked").getAsBoolean() == true?1:0);
}else{
prepStmt.setInt(5, 0);
}
prepStmt.addBatch();
/*if(i!=0 && i%10 == 0){
prepStmt.executeBatch();
conn.commit();
//conn.setAutoCommit(true);
//conn.close();
prepStmt.clearBatch();
//prepStmt.close();
//prepStmt = null;
//conn = null;
}*/
}
//if(prepStmt != null
// && prepStmt.isClosed() == false){
prepStmt.executeBatch();
conn.commit();
prepStmt.clearBatch();
conn.setAutoCommit(true);
prepStmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
logger.error("ROLLBACK of test taking data failed!");
try {
conn.close();
} catch (SQLException e2) {
e2.printStackTrace();
logger.error("Closing connection failed!");
}
}
}
}
}
private ArrayList<JsonArray> splitJsonArray(int splitCount, JsonArray arr){
if(arr.size() == 0)
return null;
ArrayList<JsonArray> resultArray = new ArrayList<JsonArray>();
int splitLength = arr.size() / splitCount;
int remainder = arr.size() % splitCount;
JsonArray newSubArr = null;
int i = 0;
for(; i < arr.size(); ++i){
if(i == 0){
newSubArr = new JsonArray();
}else if(i % splitLength == 0){
resultArray.add(newSubArr);
newSubArr = new JsonArray();
}
newSubArr.add(arr.get(i));
}
if(remainder > 0 || i % splitLength == 0){
resultArray.add(newSubArr);
}
return resultArray;
}
}
|
package loci.formats.out;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.RandomAccessOutputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.FormatException;
import loci.formats.FormatTools;
import loci.formats.meta.MetadataRetrieve;
import loci.formats.ome.OMEXMLMetadata;
import loci.formats.ome.OMEXMLMetadataImpl;
import loci.formats.services.OMEXMLService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.TiffSaver;
public class OMETiffWriter extends TiffWriter {
// -- Constants --
private static final String WARNING_COMMENT =
"<!-- Warning: this comment is an OME-XML metadata block, which " +
"contains crucial dimensional parameters and other important metadata. " +
"Please edit cautiously (if at all), and back up the original data " +
"before doing so. For more information, see the OME-TIFF web site: " +
FormatTools.URL_OME_TIFF + ".
// -- Fields --
private List<Integer> seriesMap;
private String[][] imageLocations;
private OMEXMLMetadata omeMeta;
private OMEXMLService service;
private Map<String, Integer> ifdCounts = new HashMap<String, Integer>();
private Map<String, String> uuids = new HashMap<String, String>();
// -- Constructor --
public OMETiffWriter() {
super("OME-TIFF", new String[] {"ome.tif", "ome.tiff"});
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#close() */
public void close() throws IOException {
try {
if (currentId != null) {
setupServiceAndMetadata();
// remove any BinData elements from the OME-XML
service.removeBinData(omeMeta);
for (int series=0; series<omeMeta.getImageCount(); series++) {
setSeries(series);
populateImage(omeMeta, series);
}
List<String> files = new ArrayList<String>();
for (String[] s : imageLocations) {
for (String f : s) {
if (!files.contains(f) && f != null) {
files.add(f);
String xml = getOMEXML(f);
// write OME-XML to the first IFD's comment
saveComment(f, xml);
}
}
}
}
}
catch (DependencyException de) {
throw new RuntimeException(de);
}
catch (ServiceException se) {
throw new RuntimeException(se);
}
catch (FormatException fe) {
throw new RuntimeException(fe);
}
catch (IllegalArgumentException iae) {
throw new RuntimeException(iae);
}
finally {
super.close();
boolean canReallyClose =
omeMeta == null || ifdCounts.size() == omeMeta.getImageCount();
if (omeMeta != null && canReallyClose) {
int omePlaneCount = 0;
for (int i=0; i<omeMeta.getImageCount(); i++) {
int sizeZ = omeMeta.getPixelsSizeZ(i).getValue();
int sizeC = omeMeta.getPixelsSizeC(i).getValue();
int sizeT = omeMeta.getPixelsSizeT(i).getValue();
omePlaneCount += sizeZ * sizeC * sizeT;
}
int ifdCount = 0;
for (String key : ifdCounts.keySet()) {
ifdCount += ifdCounts.get(key);
}
canReallyClose = omePlaneCount == ifdCount;
}
if (canReallyClose) {
seriesMap = null;
imageLocations = null;
omeMeta = null;
service = null;
ifdCounts.clear();
}
else {
for(String k : ifdCounts.keySet())
ifdCounts.put(k, 0);
}
}
}
// -- IFormatWriter API methods --
/**
* @see loci.formats.IFormatWriter#saveBytes(int, byte[], int, int, int, int)
*/
public void saveBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
saveBytes(no, buf, null, x, y, w, h);
}
/**
* @see loci.formats.IFormatWriter#saveBytes(int, byte[], IFD, int, int, int, int)
*/
public void saveBytes(int no, byte[] buf, IFD ifd, int x, int y, int w, int h)
throws FormatException, IOException
{
if (seriesMap == null) seriesMap = new ArrayList<Integer>();
if (!seriesMap.contains(series)) {
seriesMap.add(new Integer(series));
}
super.saveBytes(no, buf, ifd, x, y, w, h);
imageLocations[series][no] = currentId;
}
// -- IFormatHandler API methods --
/* @see IFormatHandler#setId(String) */
public void setId(String id) throws FormatException, IOException {
if (id.equals(currentId)) return;
super.setId(id);
if (imageLocations == null) {
MetadataRetrieve r = getMetadataRetrieve();
imageLocations = new String[r.getImageCount()][];
for (int i=0; i<imageLocations.length; i++) {
setSeries(i);
imageLocations[i] = new String[planeCount()];
}
setSeries(0);
}
}
// -- Helper methods --
/** Gets the UUID corresponding to the given filename. */
private String getUUID(String filename) {
String uuid = uuids.get(filename);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
uuids.put(filename, uuid);
}
return uuid;
}
private void setupServiceAndMetadata()
throws DependencyException, ServiceException
{
// extract OME-XML string from metadata object
MetadataRetrieve retrieve = getMetadataRetrieve();
ServiceFactory factory = new ServiceFactory();
service = factory.getInstance(OMEXMLService.class);
OMEXMLMetadata originalOMEMeta = service.getOMEMetadata(retrieve);
originalOMEMeta.resolveReferences();
String omexml = service.getOMEXML(originalOMEMeta);
omeMeta = service.createOMEXMLMetadata(omexml);
}
private String getOMEXML(String file) throws FormatException, IOException {
// generate UUID and add to OME element
String uuid = "urn:uuid:" + getUUID(new Location(file).getName());
omeMeta.setUUID(uuid);
String xml;
try {
xml = service.getOMEXML(omeMeta);
}
catch (ServiceException se) {
throw new FormatException(se);
}
// insert warning comment
String prefix = xml.substring(0, xml.indexOf(">") + 1);
String suffix = xml.substring(xml.indexOf(">") + 1);
return prefix + WARNING_COMMENT + suffix;
}
private void saveComment(String file, String xml) throws IOException {
if (out != null) out.close();
out = new RandomAccessOutputStream(file);
RandomAccessInputStream in = null;
try {
TiffSaver saver = new TiffSaver(out, file);
saver.setBigTiff(isBigTiff);
in = new RandomAccessInputStream(file);
saver.overwriteLastIFDOffset(in);
saver.overwriteComment(in, xml);
in.close();
}
catch (FormatException exc) {
IOException io = new IOException("Unable to append OME-XML comment");
io.initCause(exc);
throw io;
}
finally {
if (out != null) out.close();
if (in != null) in.close();
}
}
private void populateTiffData(OMEXMLMetadata omeMeta, int[] zct,
int ifd, int series, int plane)
{
omeMeta.setTiffDataFirstZ(new NonNegativeInteger(zct[0]), series, plane);
omeMeta.setTiffDataFirstC(new NonNegativeInteger(zct[1]), series, plane);
omeMeta.setTiffDataFirstT(new NonNegativeInteger(zct[2]), series, plane);
omeMeta.setTiffDataIFD(new NonNegativeInteger(ifd), series, plane);
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(1), series, plane);
}
private void populateImage(OMEXMLMetadata omeMeta, int series) {
String dimensionOrder = omeMeta.getPixelsDimensionOrder(series).toString();
int sizeZ = omeMeta.getPixelsSizeZ(series).getValue().intValue();
int sizeC = omeMeta.getPixelsSizeC(series).getValue().intValue();
int sizeT = omeMeta.getPixelsSizeT(series).getValue().intValue();
int imageCount = getPlaneCount();
int ifdCount = seriesMap.size();
if (imageCount == 0) {
omeMeta.setTiffDataPlaneCount(new NonNegativeInteger(0), series, 0);
return;
}
PositiveInteger samplesPerPixel =
new PositiveInteger((sizeZ * sizeC * sizeT) / imageCount);
for (int c=0; c<omeMeta.getChannelCount(series); c++) {
omeMeta.setChannelSamplesPerPixel(samplesPerPixel, series, c);
}
sizeC /= samplesPerPixel.getValue();
int nextPlane = 0;
for (int plane=0; plane<imageCount; plane++) {
int[] zct = FormatTools.getZCTCoords(dimensionOrder,
sizeZ, sizeC, sizeT, imageCount, plane);
int planeIndex = plane;
if (imageLocations[series].length < imageCount) {
planeIndex /= (imageCount / imageLocations[series].length);
}
String filename = imageLocations[series][planeIndex];
if (filename != null) {
filename = new Location(filename).getName();
Integer ifdIndex = ifdCounts.get(filename);
int ifd = ifdIndex == null ? 0 : ifdIndex.intValue();
omeMeta.setUUIDFileName(filename, series, nextPlane);
String uuid = "urn:uuid:" + getUUID(filename);
omeMeta.setUUIDValue(uuid, series, nextPlane);
// fill in any non-default TiffData attributes
populateTiffData(omeMeta, zct, ifd, series, nextPlane);
ifdCounts.put(filename, ifd + 1);
nextPlane++;
}
}
}
private int planeCount() {
MetadataRetrieve r = getMetadataRetrieve();
int z = r.getPixelsSizeZ(series).getValue().intValue();
int t = r.getPixelsSizeT(series).getValue().intValue();
int c = r.getChannelCount(series);
String pixelType = r.getPixelsType(series).getValue();
int bytes = FormatTools.getBytesPerPixel(pixelType);
if (bytes > 1 && c == 1) {
c = r.getChannelSamplesPerPixel(series, 0).getValue();
}
return z * c * t;
}
}
|
package fitnesse.testsystems.slim;
import fitnesse.testsystems.slim.results.ExceptionResult;
import fitnesse.testsystems.slim.results.TestResult;
import fitnesse.testsystems.slim.tables.SyntaxError;
import fitnesse.wikitext.Utils;
import fitnesse.wikitext.parser.Collapsible;
import org.htmlparser.Node;
import org.htmlparser.Tag;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.*;
import org.htmlparser.util.NodeList;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class HtmlTable implements Table {
private List<Row> rows = new ArrayList<Row>();
private TableTag tableNode;
private List<ExceptionResult> exceptions = new ArrayList<ExceptionResult>();
public HtmlTable(TableTag tableNode) {
this.tableNode = tableNode;
NodeList nodeList = tableNode.getChildren();
for (int i = 0; i < nodeList.size(); i++) {
Node node = nodeList.elementAt(i);
if (node instanceof TableRow || node instanceof TableHeader) {
rows.add(new Row((CompositeTag) node));
}
}
tableNode.getChildren().prepend(new ExceptionTextNode());
}
public TableTag getTableNode() {
return tableNode;
}
public String getCellContents(int columnIndex, int rowIndex) {
return rows.get(rowIndex).getColumn(columnIndex).getContent();
}
public String getUnescapedCellContents(int col, int row) {
return Utils.unescapeHTML(getCellContents(col, row));
}
public int getRowCount() {
return rows.size();
}
public int getColumnCountInRow(int rowIndex) {
return rows.get(rowIndex).getColumnCount();
}
public void substitute(int col, int row, String contents) {
Cell cell = rows.get(row).getColumn(col);
// TODO: need escaping here?
cell.setContent(Utils.escapeHTML(contents));
}
public List<List<String>> asList() {
List<List<String>> list = new ArrayList<List<String>>();
for (Row row : rows)
list.add(row.asList());
return list;
}
public String toString() {
return asList().toString();
}
public String toHtml() {
return tableNode.toHtml();
}
public int addRow(List<String> list) {
Row row = new Row();
rows.add(row);
tableNode.getChildren().add(row.getRowNode());
for (String s : list)
row.appendCell(s == null ? "" : Utils.escapeHTML(s));
return rows.size() - 1;
}
public void addColumnToRow(int rowIndex, String contents) {
Row row = rows.get(rowIndex);
row.appendCell(Utils.escapeHTML(contents));
}
/**
* Scenario tables (mainly) are added on the next row. A bit of javascript allows for collapsing and
* expanding.
*
* @see fitnesse.testsystems.slim.Table#appendChildTable(int, fitnesse.testsystems.slim.Table)
*/
public void appendChildTable(int rowIndex, Table childTable) {
Row row = rows.get(rowIndex);
row.rowNode.setAttribute("class", "scenario closed", '"');
Row childRow = new Row();
TableColumn column = (TableColumn) newTag(TableColumn.class);
column.setChildren(new NodeList(((HtmlTable) childTable).getTableNode()));
column.setAttribute("colspan", "" + colspan(row), '"');
childRow.appendCell(new Cell(column));
childRow.rowNode.setAttribute("class", "scenario-detail", '"');
insertRowAfter(row, childRow);
}
private int colspan(Row row) {
NodeList rowNodes = row.rowNode.getChildren();
int colspan = 0;
for (int i = 0; i < rowNodes.size(); i++) {
if (rowNodes.elementAt(i) instanceof TableColumn) {
String s = ((TableColumn)rowNodes.elementAt(i)).getAttribute("colspan");
if (s != null) {
colspan += Integer.parseInt(s);
} else {
colspan++;
}
}
}
return colspan;
}
// It's a bit of work to insert a node with the htmlparser module.
private void insertRowAfter(Row existingRow, Row childRow) {
NodeList rowNodes = tableNode.getChildren();
int index = rowNodes.indexOf(existingRow.rowNode);
Stack<Node> tempStack = new Stack<Node>();
while (rowNodes.size() - 1 > index) {
tempStack.push(rowNodes.elementAt(tableNode.getChildren().size() - 1));
rowNodes.remove(rowNodes.size() - 1);
}
rowNodes.add(childRow.rowNode);
while (tempStack.size() > 0) {
rowNodes.add(tempStack.pop());
}
}
@Override
public void updateContent(int row, TestResult testResult) {
rows.get(row).setTestResult(testResult);
}
@Override
public void updateContent(int col, int row, TestResult testResult) {
Cell cell = rows.get(row).getColumn(col);
cell.setTestResult(testResult);
cell.setContent(cell.formatTestResult());
}
@Override
public void updateContent(int col, int row, ExceptionResult exceptionResult) {
Cell cell = rows.get(row).getColumn(col);
if (cell.exceptionResult == null) {
cell.setExceptionResult(exceptionResult);
cell.setContent(cell.formatExceptionResult());
exceptions.add(exceptionResult);
}
}
private Tag newTag(Class<? extends Tag> klass) {
Tag tag = null;
try {
tag = klass.newInstance();
tag.setTagName(tag.getTagName().toLowerCase());
Tag endTag = klass.newInstance();
endTag.setTagName("/" + tag.getTagName().toLowerCase());
endTag.setParent(tag);
tag.setEndTag(endTag);
} catch (Exception e) {
e.printStackTrace();
}
return tag;
}
class Row {
private List<Cell> cells = new ArrayList<Cell>();
private CompositeTag rowNode;
public Row(CompositeTag rowNode) {
this.rowNode = rowNode;
NodeList nodeList = rowNode.getChildren();
for (int i = 0; i < nodeList.size(); i++) {
Node node = nodeList.elementAt(i);
if (node instanceof TableColumn)
cells.add(new Cell((TableColumn) node));
}
}
public Row() {
rowNode = (TableRow) newTag(TableRow.class);
rowNode.setChildren(new NodeList());
Tag endNode = new TableRow();
endNode.setTagName("/" + rowNode.getTagName().toLowerCase());
rowNode.setEndTag(endNode);
}
public int getColumnCount() {
return cells.size();
}
public Cell getColumn(int columnIndex) {
return cells.get(columnIndex);
}
public void appendCell(String contents) {
Cell newCell = new Cell(contents);
appendCell(newCell);
}
private void appendCell(Cell newCell) {
rowNode.getChildren().add(newCell.getColumnNode());
cells.add(newCell);
}
public CompositeTag getRowNode() {
return rowNode;
}
private List<String> asList() {
List<String> list = new ArrayList<String>();
for (Cell cell : cells) {
// was "colorized"
list.add(cell.getTestResult());
}
return list;
}
private void setTestResult(TestResult testResult) {
NodeList cells = rowNode.getChildren();
for (int i = 0; i < cells.size(); i++) {
Node cell = cells.elementAt(i);
if (cell instanceof Tag) {
Tag tag = (Tag) cell;
tag.setAttribute("class", testResult.getExecutionResult().toString(), '"');
}
}
}
}
class Cell {
private final TableColumn columnNode;
private final String originalContent;
private TestResult testResult;
private ExceptionResult exceptionResult;
public Cell(TableColumn tableColumn) {
columnNode = tableColumn;
originalContent = Utils.unescapeHTML(columnNode.getChildrenHTML());
}
public Cell(String contents) {
if (contents == null)
contents = "";
TextNode text = new TextNode(contents);
text.setChildren(new NodeList());
columnNode = (TableColumn) newTag(TableColumn.class);
columnNode.setChildren(new NodeList(text));
originalContent = contents;
}
public String getContent() {
return Utils.unescapeHTML(getEscapedContent());
}
public String getEscapedContent() {
String unescaped = columnNode.getChildrenHTML();
//Some browsers need inside an empty table cell, so we remove it here.
return " ".equals(unescaped) ? "" : unescaped;
}
private void setContent(String s) {
// No HTML escaping here.
TextNode textNode = new TextNode(s);
NodeList nodeList = new NodeList(textNode);
columnNode.setChildren(nodeList);
}
public String getTestResult() {
return testResult != null ? testResult.toString(originalContent) : getContent();
}
public TableColumn getColumnNode() {
return columnNode;
}
public void setTestResult(TestResult testResult) {
this.testResult = testResult;
}
public void setExceptionResult(ExceptionResult exceptionResult) {
this.exceptionResult = exceptionResult;
}
public String formatTestResult() {
if (testResult.getExecutionResult() == null) {
return testResult.getMessage() != null ? testResult.getMessage() : originalContent;
}
final String escapedMessage = testResult.hasMessage() ? Utils.escapeHTML(testResult.getMessage()) : originalContent;
switch (testResult.getExecutionResult()) {
case PASS:
return String.format("<span class=\"pass\">%s</span>", escapedMessage);
case FAIL:
if (testResult.hasActual() && testResult.hasExpected()) {
return String.format("[%s] <span class=\"fail\">expected [%s]</span>",
Utils.escapeHTML(testResult.getActual()),
Utils.escapeHTML(testResult.getExpected()));
} else if ((testResult.hasActual() || testResult.hasExpected()) && testResult.hasMessage()) {
return String.format("[%s] <span class=\"fail\">%s</span>",
Utils.escapeHTML(testResult.hasActual() ? testResult.getActual() : testResult.getExpected()),
Utils.escapeHTML(testResult.getMessage()));
}
return String.format("<span class=\"fail\">%s</span>", escapedMessage);
case IGNORE:
return String.format("%s <span class=\"ignore\">%s</span>", originalContent, escapedMessage);
case ERROR:
return String.format("%s <span class=\"error\">%s</span>", originalContent, escapedMessage);
}
return "Should not be here";
}
public String formatExceptionResult() {
if (exceptionResult.hasMessage()) {
return String.format("%s <span class=\"%s\">%s</span>",
originalContent,
exceptionResult.getExecutionResult().toString(),
Utils.escapeHTML(exceptionResult.getMessage()));
} else {
// See below where exception block is formatted
return String.format("%s <span class=\"%s\">Exception: <a href=\"#%s\">%s</a></span>", originalContent, exceptionResult.getExecutionResult().toString(), exceptionResult.getResultKey(), exceptionResult.getResultKey());
}
}
}
@Override
public HtmlTable asTemplate(CellContentSubstitution substitution) throws SyntaxError {
String script = this.toHtml();
// Quick 'n' Dirty
script = substitution.substitute(0, 0, script);
return new HtmlTableScanner(script).getTable(0);
}
// This is not the nicest solution, since the the exceptions are put inside the <table> tag.
class ExceptionTextNode extends TextNode {
public ExceptionTextNode() {
super("");
}
@Override
public String toHtml(boolean verbatim) {
if(!haveExceptionsWithoutMessage()) {
return "";
}
StringBuilder buffer = new StringBuilder(512);
buffer.append("<div class=\"exceptions\"><h3>Exceptions</h3>");
for (ExceptionResult exceptionResult : exceptions) {
if (!exceptionResult.hasMessage()) {
buffer.append(String.format("<a name=\"%s\"></a>", exceptionResult.getResultKey()));
buffer.append(Collapsible.generateHtml(Collapsible.CLOSED, Utils.escapeHTML(exceptionResult.getResultKey()),
"<pre>" + Utils.escapeHTML(exceptionResult.getException()) + "</pre>"));
}
}
buffer.append("</div>");
return buffer.toString();
}
private boolean haveExceptionsWithoutMessage() {
for (ExceptionResult exception : exceptions) {
if (!exception.hasMessage()) {
return true;
}
}
return false;
}
}
}
|
package foam.core;
import foam.dao.pg.IndexedPreparedStatement;
import foam.nanos.logger.Logger;
import java.lang.UnsupportedOperationException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public abstract class AbstractArrayPropertyInfo
extends AbstractPropertyInfo
{
@Override
public void setFromString(Object obj, String value) {
if ( value == null ) {
set(obj, value);
}
String[] s = value.split(",", -1);
set(obj, s);
}
public abstract String of();
// NESTED ARRAY
@Override
public Object fromXML(X x, XMLStreamReader reader) {
List objList = new ArrayList();
String startTag = reader.getLocalName();
try {
int eventType;
while ( reader.hasNext() ) {
eventType = reader.next();
switch ( eventType ) {
case XMLStreamConstants.START_ELEMENT:
if ( reader.getLocalName().equals("value") ) {
// TODO: TYPE CASTING FOR PROPER CONVERSION. NEED FURTHER SUPPORT FOR PRIMITIVE TYPES
throw new UnsupportedOperationException("Primitive typed array XML reading is not supported yet");
}
break;
case XMLStreamConstants.END_ELEMENT:
if ( reader.getLocalName() == startTag ) { return objList.toArray(); }
}
}
} catch (XMLStreamException ex) {
Logger logger = (Logger) x.get("logger");
logger.error("Premature end of XML file");
}
return objList.toArray();
}
@Override
public void toXML (FObject obj, Document doc, Element objElement) {
if ( this.f(obj) == null ) return;
Element prop = doc.createElement(this.getName());
objElement.appendChild(prop);
Object[] nestObj = (Object[]) this.f(obj);
for ( int k = 0; k < nestObj.length; k++ ) {
Element nestedProp = doc.createElement("value");
nestedProp.appendChild(doc.createTextNode(nestObj[k].toString()));
prop.appendChild(nestedProp);
}
}
@Override
public void setStatementValue(IndexedPreparedStatement stmt, FObject o) throws java.sql.SQLException {
Object obj = this.get(o);
if ( obj == null ) {
stmt.setObject(null);
return;
}
Object[] os = (Object[]) obj;
java.lang.StringBuilder sb = new java.lang.StringBuilder();
int length = os.length;
for ( int i=0; i < length; i++) {
if( os[i] == null )
sb.append("");
else
sb.append(os[i]);
if ( i < length - 1 ) {
sb.append(",");
}
}
stmt.setObject(sb.toString());
}
}
|
package com.plivo.sdk.client;
//Exceptions
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import com.plivo.sdk.exception.PlivoException;
// Plivo resources
import com.plivo.sdk.response.account.Account;
import com.plivo.sdk.response.account.SubAccount;
import com.plivo.sdk.response.account.SubAccountList;
import com.plivo.sdk.response.application.Application;
import com.plivo.sdk.response.application.ApplicationList;
import com.plivo.sdk.response.call.CDR;
import com.plivo.sdk.response.call.CDRList;
import com.plivo.sdk.response.call.Call;
import com.plivo.sdk.response.call.LiveCall;
import com.plivo.sdk.response.call.LiveCallList;
import com.plivo.sdk.response.conference.Conference;
import com.plivo.sdk.response.conference.LiveConferenceList;
import com.plivo.sdk.response.endpoint.Endpoint;
import com.plivo.sdk.response.endpoint.EndpointList;
import com.plivo.sdk.response.response.GenericResponse;
import com.plivo.sdk.response.response.Record;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ProtocolVersion;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
// Authentication for HTTP resources
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
// Handle HTTP requests
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
// Add pay load to POST request
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class RestAPI {
public String AUTH_ID;
private String AUTH_TOKEN;
private final String PLIVO_URL = "https://api.plivo.com";
public String PLIVO_VERSION = "v1";
private String BaseURI;
private DefaultHttpClient Client;
private Gson gson;
public RestAPI(String auth_id, String auth_token, String version)
{
AUTH_ID = auth_id;
AUTH_TOKEN = auth_token;
PLIVO_VERSION = version;
BaseURI = String.format("%s/%s/Account/%s", PLIVO_URL, PLIVO_VERSION, AUTH_ID);
Client = new DefaultHttpClient();
Client.getCredentialsProvider().setCredentials(
new AuthScope("api.plivo.com", 443),
new UsernamePasswordCredentials(AUTH_ID, AUTH_TOKEN)
);
gson = new Gson();
}
public String request(String resource, LinkedHashMap<String, String> parameters, String method)
throws PlivoException
{
HttpResponse responseBody = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
HttpStatus.SC_OK, "OK");
try {
if ( method == "GET" ) {
// Prepare a String with GET parameters
String getparams = "?";
for ( Entry<String, String> pair : parameters.entrySet() )
getparams += pair.getKey() + "=" + pair.getValue() + "&";
// remove the trailing '&'
getparams = getparams.substring(0, getparams.length() - 1);
HttpGet httpget = new HttpGet(this.BaseURI + getparams);
responseBody = this.Client.execute(httpget);
}
else if ( method == "POST" ) {
HttpPost httpost = new HttpPost(this.BaseURI);
Gson gson = new GsonBuilder().serializeNulls().create();
// Create a String entity with the POST parameters
StringEntity se = new StringEntity(gson.toJson(parameters));
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// Now, attach the pay load to the request
httpost.setEntity(se);
responseBody = this.Client.execute(httpost);
}
else if ( method == "DELETE" ) {
HttpDelete httpdelete = new HttpDelete(this.BaseURI);
responseBody = this.Client.execute(httpdelete);
}
}
catch (ClientProtocolException e) {
throw new PlivoException(e.getLocalizedMessage());
} catch (IOException e) {
throw new PlivoException(e.getLocalizedMessage());
} finally {
this.Client.getConnectionManager().shutdown();
}
if ( responseBody.getStatusLine().getStatusCode() != 200 )
throw new PlivoException(responseBody.getStatusLine().getReasonPhrase());
return responseBody.toString();
}
private String get_key_value(LinkedHashMap<String, String> params, String key) throws PlivoException {
String value = "";
if (params.containsKey(key)) {
value = params.get(key);
params.remove(key);
} else {
throw new PlivoException("Missing mandatory parameter " + key);
}
return value;
}
// Account
public Account get_account() throws PlivoException {
return this.gson.fromJson(request("/", new LinkedHashMap<String, String>(), "GET"), Account.class);
}
public GenericResponse modify_account(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/", parameters, "GET"), GenericResponse.class);
}
public SubAccountList get_subaccounts() throws PlivoException {
return this.gson.fromJson(request("/Subaccount/", new LinkedHashMap<String, String>(), "GET"), SubAccountList.class);
}
public SubAccount get_subaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
String subauth_id = this.get_key_value(parameters, "subauth_id");
return this.gson.fromJson(request(String.format("/Subaccount/%s/", subauth_id), parameters, "GET"), SubAccount.class);
}
public GenericResponse create_subaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Subaccount/", parameters, "POST"), GenericResponse.class);
}
public GenericResponse modify_subaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Subaccount/", parameters, "POST"), GenericResponse.class);
}
public GenericResponse delete_subaccount(LinkedHashMap<String, String> parameters) throws PlivoException {
String subauth_id = this.get_key_value(parameters, "subauth_id");
return this.gson.fromJson(request(String.format("/Subaccount/%s/", subauth_id), parameters, "DELETE"), GenericResponse.class);
}
// Application
public ApplicationList get_applications(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Application/", new LinkedHashMap<String, String>(), "GET"), ApplicationList.class);
}
public Application get_application(LinkedHashMap<String, String> parameters) throws PlivoException {
String app_id = this.get_key_value(parameters, "app_id");
return this.gson.fromJson(request(String.format("/Application/%s/", app_id),
new LinkedHashMap<String, String>(), "GET"), Application.class);
}
public GenericResponse create_application(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Application/", parameters, "POST"), GenericResponse.class);
}
public GenericResponse modify_application(LinkedHashMap<String, String> parameters) throws PlivoException {
String app_id = this.get_key_value(parameters, "app_id");
return this.gson.fromJson(request(String.format("/Application/%s/", app_id), parameters, "POST"), GenericResponse.class);
}
public GenericResponse delete_application(LinkedHashMap<String, String> parameters) throws PlivoException {
String app_id = this.get_key_value(parameters, "app_id");
return this.gson.fromJson(request(String.format("/Application/%s/", app_id), parameters, "DELETE"), GenericResponse.class);
}
// Call
public CDRList get_cdrs(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Call/", parameters, "GET"), CDRList.class);
}
public CDR get_cdr(LinkedHashMap<String, String> parameters) throws PlivoException {
String record_id = get_key_value(parameters, "record_id");
return this.gson.fromJson(request(String.format("/Call/%s/", record_id),
new LinkedHashMap<String, String>(), "GET"), CDR.class);
}
public LiveCallList get_live_calls() throws PlivoException {
LinkedHashMap<String, String> parameters= new LinkedHashMap<String, String>();
parameters.put("status", "live");
return this.gson.fromJson(request("/Call/", parameters, "GET"), LiveCallList.class);
}
public LiveCall get_live_call(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
parameters.put("status", "live");
return this.gson.fromJson(request(String.format("/Call/%s/", call_uuid), parameters, "GET"), LiveCall.class);
}
public Call make_call(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Call/", parameters, "POST"), Call.class);
}
public GenericResponse hangup_all_calls() throws PlivoException {
return this.gson.fromJson(request("/Call/", new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse hangup_call(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/", call_uuid),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse transfer_call(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/", call_uuid), parameters, "POST"), GenericResponse.class);
}
public Record record(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/Record/", call_uuid), parameters, "POST"), Record.class);
}
public GenericResponse stop_record(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/Record/", call_uuid),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse play(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/Play/", call_uuid), parameters, "POST"), GenericResponse.class);
}
public GenericResponse stop_play(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/Play/", call_uuid),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse speak(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/Speak/", call_uuid), parameters, "POST"), GenericResponse.class);
}
public GenericResponse send_digits(LinkedHashMap<String, String> parameters) throws PlivoException {
String call_uuid = get_key_value(parameters, "call_uuid");
return this.gson.fromJson(request(String.format("/Call/%s/DTMF/", call_uuid), parameters, "POST"), GenericResponse.class);
}
// Conference
public LiveConferenceList get_live_conferences() throws PlivoException {
return this.gson.fromJson(request("/Conference/", new LinkedHashMap<String, String>(), "GET"), LiveConferenceList.class);
}
public GenericResponse hangup_all_conferences() throws PlivoException {
return this.gson.fromJson(request("/Conference/", new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public Conference get_live_conference(LinkedHashMap<String, String> parameters) throws PlivoException{
String conference_name = get_key_value(parameters, "conference_name");
return this.gson.fromJson(request(String.format("/Conference/%s/", conference_name),
new LinkedHashMap<String, String>(), "GET"), Conference.class);
}
public GenericResponse hangup_conference(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
return this.gson.fromJson(request(String.format("/Conference/%s/", conference_name),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse hangup_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/", conference_name, member_id),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse play_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Play/", conference_name, member_id),
new LinkedHashMap<String, String>(), "POST"), GenericResponse.class);
}
public GenericResponse stop_play_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Play/", conference_name, member_id),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse speak_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Speak/", conference_name, member_id),
new LinkedHashMap<String, String>(), "POST"), GenericResponse.class);
}
public GenericResponse deaf_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Deaf/", conference_name, member_id),
new LinkedHashMap<String, String>(), "POST"), GenericResponse.class);
}
public GenericResponse undeaf_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Deaf/", conference_name, member_id),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse mute_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Mute/", conference_name, member_id),
new LinkedHashMap<String, String>(), "POST"), GenericResponse.class);
}
public GenericResponse unmute_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Mute/", conference_name, member_id),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
public GenericResponse kick_member(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
String member_id = get_key_value(parameters, "member_id");
return this.gson.fromJson(request(String.format("/Conference/%s/Member/{1}/Kick/", conference_name, member_id),
new LinkedHashMap<String, String>(), "POST"), GenericResponse.class);
}
public Record record_conference(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
return this.gson.fromJson(request(String.format("/Conference/%s/Record/", conference_name), parameters, "POST"), Record.class);
}
public GenericResponse stop_record_conference(LinkedHashMap<String, String> parameters) throws PlivoException {
String conference_name = get_key_value(parameters, "conference_name");
return this.gson.fromJson(request(String.format("/Conference/%s/Record/", conference_name),
new LinkedHashMap<String, String>(), "DELETE"),GenericResponse.class);
}
// Endpoint
public EndpointList get_endpoints(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Endpoint/", parameters, "GET"), EndpointList.class);
}
public GenericResponse create_endpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
return this.gson.fromJson(request("/Endpoint/", parameters, "POST"),GenericResponse.class);
}
public Endpoint get_endpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
String endpoint_id = get_key_value(parameters, "endpoint_id");
return this.gson.fromJson(request(String.format("/Endpoint/%s/", endpoint_id),
new LinkedHashMap<String, String>(), "GET"), Endpoint.class);
}
public GenericResponse modify_endpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
String endpoint_id = get_key_value(parameters, "endpoint_id");
return this.gson.fromJson(request(String.format("/Endpoint/%s/", endpoint_id), parameters, "POST"), GenericResponse.class);
}
public GenericResponse delete_endpoint(LinkedHashMap<String, String> parameters) throws PlivoException {
String endpoint_id = get_key_value(parameters, "endpoint_id");
return this.gson.fromJson(request(String.format("/Endpoint/%s/", endpoint_id),
new LinkedHashMap<String, String>(), "DELETE"), GenericResponse.class);
}
// // Message
// public Message send_message(LinkedHashMap<String, String> parameters) throws PlivoException {
// return this.gson.fromJson(request("/Message/", parameters, "POST"), Message.class);
}
|
package com.thindeck.cockpit;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.rexsl.page.JaxbGroup;
import com.rexsl.page.Link;
import com.rexsl.page.PageBuilder;
import com.thindeck.api.Repo;
import java.io.IOException;
import java.util.logging.Level;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.xembly.Directives;
/**
* List of repositories.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 0.1
*/
@Path("/repos")
public final class ReposRs extends BaseRs {
/**
* Get front page.
* @return The JAX-RS response
*/
@GET
@Path("/")
public Response front() {
return new PageBuilder()
.stylesheet("/xsl/repos.xsl")
.build(TdPage.class)
.init(this)
.link(new Link("add", "./add"))
.append(
JaxbGroup.build(
Collections2.transform(
Lists.newArrayList(this.user().repos().iterate()),
new Function<Repo, JxRepo>() {
@Override
public JxRepo apply(final Repo input) {
return new JxRepo(input, ReposRs.this);
}
}
),
"repos"
)
)
.render()
.build();
}
/**
* Add a new repo.
* @param name Repo name
* @param uri Repo URI
* @return The JAX-RS response
*/
@POST
@Path("/add")
public Response add(@FormParam("name") final String name,
@FormParam("uri") final String uri) {
final Repo repo = this.user().repos().add(name);
try {
repo.memo().update(
new Directives().xpath("/memo").addIf("uri").set(uri)
);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
throw this.flash().redirect(
this.uriInfo().getBaseUriBuilder()
.clone()
.path(ReposRs.class)
.build(),
String.format(
"repo %s added",
repo.name()
),
Level.INFO
);
}
}
|
package org.voltdb.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicLong;
import org.supercsv.exception.SuperCsvException;
import org.supercsv.io.CsvListReader;
import org.supercsv.io.ICsvListReader;
import org.supercsv.prefs.CsvPreference;
import org.supercsv_voltpatches.tokenizer.Tokenizer;
import org.voltcore.logging.VoltLogger;
import org.voltdb.CLIConfig;
import org.voltdb.VoltTable;
import org.voltdb.VoltType;
import org.voltdb.client.Client;
import org.voltdb.client.ClientConfig;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
/**
* CSVLoader is a simple utility to load data from a CSV formatted file to a
* table (or pass it to any stored proc, but ignoring any result other than the
* success code.).
*/
public class CSVLoader {
public static String pathInvalidrowfile = "";
public static String pathReportfile = "csvloaderReport.log";
public static String pathLogfile = "csvloaderLog.log";
protected static final VoltLogger m_log = new VoltLogger("CONSOLE");
private static final AtomicLong inCount = new AtomicLong(0);
private static final AtomicLong outCount = new AtomicLong(0);
private static final AtomicLong totalLineCount = new AtomicLong(0);
private static final AtomicLong totalRowCount = new AtomicLong(0);
private static final int reportEveryNRows = 10000;
private static final int waitSeconds = 10;
private static CSVConfig config = null;
private static long latency = 0;
private static long start = 0;
private static boolean standin = false;
private static BufferedWriter out_invaliderowfile;
private static BufferedWriter out_logfile;
private static BufferedWriter out_reportfile;
private static String insertProcedure = "";
private static Map<Long, String[]> errorInfo = new TreeMap<Long, String[]>();
private static CsvPreference csvPreference = null;
public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE_CHARACTER = '\"';
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
public static final boolean DEFAULT_STRICT_QUOTES = false;
public static final int DEFAULT_SKIP_LINES = 0;
public static final boolean DEFAULT_NO_WHITESPACE = false;
public static final long DEFAULT_COLUMN_LIMIT_SIZE = 16777216;
private static Map <VoltType, String> blankValues = new HashMap<VoltType, String>();
static {
blankValues.put(VoltType.NUMERIC, "0");
blankValues.put(VoltType.TINYINT, "0");
blankValues.put(VoltType.SMALLINT, "0");
blankValues.put(VoltType.INTEGER, "0");
blankValues.put(VoltType.BIGINT, "0");
blankValues.put(VoltType.FLOAT, "0.0");
blankValues.put(VoltType.TIMESTAMP, "0");
blankValues.put(VoltType.STRING, "");
blankValues.put(VoltType.DECIMAL, "0");
blankValues.put(VoltType.VARBINARY, "");
}
private static List <VoltType> typeList = new ArrayList<VoltType>();
private static final class MyCallback implements ProcedureCallback {
private final long m_lineNum;
private final CSVConfig m_config;
private final List<String> m_rowdata;
MyCallback(long lineNumber, CSVConfig cfg, List<String> rowdata) {
m_lineNum = lineNumber;
m_config = cfg;
m_rowdata = rowdata;
}
@Override
public void clientCallback(ClientResponse response) throws Exception {
if (response.getStatus() != ClientResponse.SUCCESS) {
m_log.error( response.getStatusString() );
String[] info = { m_rowdata.toString(), response.getStatusString() };
synchronizeErrorInfo( m_lineNum , info );
return;
}
long currentCount = inCount.incrementAndGet();
if (currentCount % reportEveryNRows == 0) {
m_log.info( "Inserted " + currentCount + " rows" );
}
}
}
private static class CSVConfig extends CLIConfig {
@Option(shortOpt = "f", desc = "location of CSV input file")
String file = "";
@Option(shortOpt = "p", desc = "procedure name to insert the data into the database")
String procedure = "";
@Option(desc = "maximum rows to be read from the CSV file")
int limitrows = Integer.MAX_VALUE;
@Option(shortOpt = "r", desc = "directory path for report files")
String reportdir = System.getProperty("user.dir");
@Option(shortOpt = "m", desc = "maximum errors allowed")
int maxerrors = 100;
@Option(desc = "different ways to handle blank items: {error|null|empty} (default: error)")
String blank = "error";
@Option(desc = "delimiter to use for separating entries")
char separator = DEFAULT_SEPARATOR;
@Option(desc = "character to use for quoted elements (default: \")")
char quotechar = DEFAULT_QUOTE_CHARACTER;
@Option(desc = "character to use for escaping a separator or quote (default: \\)")
char escape = DEFAULT_ESCAPE_CHARACTER;
@Option(desc = "require all input values to be enclosed in quotation marks", hasArg = false)
boolean strictquotes = DEFAULT_STRICT_QUOTES;
@Option(desc = "number of lines to skip before inserting rows into the database")
long skip = DEFAULT_SKIP_LINES;
@Option(desc = "do not allow whitespace between values and separators", hasArg = false)
boolean nowhitespace = DEFAULT_NO_WHITESPACE;
@Option(desc = "max size of a quoted column in bytes(default: 16777216 = 16MB)")
long columnsizelimit = DEFAULT_COLUMN_LIMIT_SIZE;
@Option(shortOpt = "s", desc = "list of servers to connect to (default: localhost)")
String servers = "localhost";
@Option(desc = "username when connecting to the servers")
String user = "";
@Option(desc = "password to use when connecting to servers")
String password = "";
@Option(desc = "port to use when connecting to database (default: 21212)")
int port = Client.VOLTDB_SERVER_PORT;
@Option(desc = "Check CSV Input Data Only.")
boolean check = false;
@AdditionalArgs(desc = "insert the data into database by TABLENAME.insert procedure by default")
String table = "";
@Override
public void validate() {
if (maxerrors < 0)
exitWithMessageAndUsage("abortfailurecount must be >=0");
if (procedure.equals("") && table.equals(""))
exitWithMessageAndUsage("procedure name or a table name required");
if (!procedure.equals("") && !table.equals(""))
exitWithMessageAndUsage("Only a procedure name or a table name required, pass only one please");
if (skip < 0)
exitWithMessageAndUsage("skipline must be >= 0");
if (limitrows > Integer.MAX_VALUE)
exitWithMessageAndUsage("limitrows to read must be < "
+ Integer.MAX_VALUE);
if (port < 0)
exitWithMessageAndUsage("port number must be >= 0");
if ((blank.equalsIgnoreCase("error") ||
blank.equalsIgnoreCase("null") ||
blank.equalsIgnoreCase("empty")) == false)
exitWithMessageAndUsage("blank configuration specified must be one of {error|null|empty}");
}
@Override
public void printUsage() {
System.out
.println("Usage: csvloader [args] tablename");
System.out
.println(" csvloader [args] -p procedurename");
super.printUsage();
}
}
private static boolean isProcedureMp(Client csvClient)
throws IOException, org.voltdb.client.ProcCallException
{
boolean procedure_is_mp = false;
VoltTable procInfo = csvClient.callProcedure("@SystemCatalog",
"PROCEDURES").getResults()[0];
while (procInfo.advanceRow()) {
if (insertProcedure.matches(procInfo.getString("PROCEDURE_NAME"))) {
String remarks = procInfo.getString("REMARKS");
if (remarks.contains("\"singlePartition\":false")) {
procedure_is_mp = true;
}
break;
}
}
return procedure_is_mp;
}
public static void main(String[] args) throws IOException,
InterruptedException {
start = System.currentTimeMillis();
long parsingTimeStart = start;
long parsingTimeEnd = start;
long insertTimeStart = start;
long insertTimeEnd = start;
int waits = 0;
int shortWaits = 0;
CSVConfig cfg = new CSVConfig();
cfg.parse(CSVLoader.class.getName(), args);
config = cfg;
configuration();
Tokenizer tokenizer = null;
ICsvListReader listReader = null;
try {
long st = System.currentTimeMillis();
if (CSVLoader.standin) {
tokenizer = new Tokenizer(new BufferedReader( new InputStreamReader(System.in)), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip) ;
listReader = new CsvListReader(tokenizer, csvPreference);
}
else {
tokenizer = new Tokenizer(new FileReader(config.file), csvPreference,
config.strictquotes, config.escape, config.columnsizelimit,
config.skip) ;
listReader = new CsvListReader(tokenizer, csvPreference);
}
long end = System.currentTimeMillis();
parsingTimeEnd += (end - st);
} catch (FileNotFoundException e) {
m_log.error("CSV file '" + config.file + "' could not be found.");
System.exit(-1);
}
// Split server list
String[] serverlist = config.servers.split(",");
// Create connection
ClientConfig c_config = new ClientConfig(config.user, config.password);
c_config.setProcedureCallTimeout(0); // Set procedure all to infinite
// timeout, see ENG-2670
Client csvClient = null;
if (!config.check) {
try {
csvClient = CSVLoader.getClient(c_config, serverlist, config.port);
} catch (Exception e) {
m_log.error("Error to connect to the servers:"
+ config.servers);
close_cleanup();
System.exit(-1);
}
assert (csvClient != null);
}
try {
int columnCnt = 0;
ProcedureCallback cb = null;
boolean lastOK = true;
if (!cfg.check) {
VoltTable procInfo = null;
boolean isProcExist = false;
try {
procInfo = csvClient.callProcedure("@SystemCatalog",
"PROCEDURECOLUMNS").getResults()[0];
while (procInfo.advanceRow()) {
if (insertProcedure.matches((String) procInfo.get(
"PROCEDURE_NAME", VoltType.STRING))) {
columnCnt++;
isProcExist = true;
String typeStr = (String) procInfo.get("TYPE_NAME", VoltType.STRING);
typeList.add(VoltType.typeFromString(typeStr));
}
}
} catch (Exception e) {
m_log.error(e.getMessage(), e);
close_cleanup();
System.exit(-1);
}
if (isProcExist == false) {
m_log.error("No matching insert procedure available");
close_cleanup();
System.exit(-1);
}
try {
if (isProcedureMp(csvClient)) {
m_log.warn("Using a multi-partitioned procedure to load data will be slow. "
+ "If loading a partitioned table, use a single-partitioned procedure "
+ "for best performance.");
}
} catch (Exception e) {
m_log.fatal(e.getMessage(), e);
close_cleanup();
System.exit(-1);
}
}
List<String> lineList = new ArrayList<String>();
while ((config.limitrows
try{
//Initial setting of totalLineCount
if( listReader.getLineNumber() == 0 )
totalLineCount.set(cfg.skip);
else
totalLineCount.set( listReader.getLineNumber() );
long st = System.currentTimeMillis();
lineList = listReader.read();
long end = System.currentTimeMillis();
parsingTimeEnd += (end - st);
//EOF
if(lineList == null) {
if( totalLineCount.get() > listReader.getLineNumber() )
totalLineCount.set( listReader.getLineNumber() );
break;
}
totalRowCount.getAndIncrement();
boolean queued = false;
while (queued == false) {
String[] correctedLine = lineList.toArray(new String[0]);
if (!config.check) {
cb = new MyCallback(totalLineCount.get() + 1, config,
lineList);
String lineCheckResult;
if ((lineCheckResult = checkparams_trimspace(correctedLine,
columnCnt)) != null) {
String[] info = {lineList.toString(), lineCheckResult};
synchronizeErrorInfo(totalLineCount.get() + 1, info);
break;
}
queued = csvClient.callProcedure(cb, insertProcedure,
(Object[]) correctedLine);
outCount.incrementAndGet();
} else {
queued = true;
}
if (queued == false) {
++waits;
if (lastOK == false) {
++shortWaits;
}
Thread.sleep(waitSeconds);
}
lastOK = queued;
}
}
catch (SuperCsvException e){
//Catch rows that can not be read by superCSV listReader. E.g. items without quotes when strictquotes is enabled.
totalRowCount.getAndIncrement();
String[] info = { e.getMessage(), "" };
synchronizeErrorInfo( totalLineCount.get()+1, info );
}
}
if (csvClient != null) {
csvClient.drain();
}
insertTimeEnd = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
m_log.info("Parsing CSV file took " + (parsingTimeEnd - parsingTimeStart) + " milliseconds.");
if (!config.check) {
m_log.info("Inserting Data took " + ((insertTimeEnd - insertTimeStart) - (parsingTimeEnd - parsingTimeStart)) + " milliseconds.");
m_log.info("Inserted " + outCount.get() + " and acknowledged "
+ inCount.get() + " rows (final)");
} else {
m_log.info("Verification of CSV input completed.");
}
if (waits > 0) {
m_log.info("Waited " + waits + " times");
if (shortWaits > 0) {
m_log.info( "Waited too briefly? " + shortWaits
+ " times" );
}
}
if (!config.check) {
produceFiles();
}
close_cleanup();
listReader.close();
if (csvClient != null) {
csvClient.close();
}
}
private static void synchronizeErrorInfo( long errLineNum, String[] info ) throws IOException, InterruptedException {
synchronized (errorInfo) {
if (!errorInfo.containsKey(errLineNum)) {
errorInfo.put(errLineNum, info);
}
if (errorInfo.size() >= config.maxerrors) {
m_log.error("The number of Failure row data exceeds "
+ config.maxerrors);
produceFiles();
close_cleanup();
System.exit(-1);
}
}
}
private static String checkparams_trimspace(String[] slot, int columnCnt) {
if (slot.length != columnCnt) {
return "Error: Incorrect number of columns. " + slot.length
+ " found, " + columnCnt + " expected.";
}
for (int i = 0; i < slot.length; i++) {
//supercsv read "" to null
if( slot[i] == null )
{
if(config.blank.equalsIgnoreCase("error"))
return "Error: blank item";
else if (config.blank.equalsIgnoreCase("empty"))
slot[i] = blankValues.get(typeList.get(i));
//else config.blank == null which is already the case
}
// trim white space in this line. SuperCSV preserves all the whitespace by default
else {
if( config.nowhitespace &&
( slot[i].charAt(0) == ' ' || slot[i].charAt( slot[i].length() - 1 ) == ' ') ) {
return "Error: White Space Detected in nowhitespace mode.";
}
else
slot[i] = ((String) slot[i]).trim();
// treat NULL, \N and "\N" as actual null value
if ( slot[i].equals("NULL") ||
slot[i].equals(VoltTable.CSV_NULL) ||
slot[i].equals(VoltTable.QUOTED_CSV_NULL) )
slot[i] = null;
}
}
return null;
}
private static void configuration() {
csvPreference = new CsvPreference.Builder(config.quotechar, config.separator, "\n").build();
if (config.file.equals(""))
standin = true;
if (!config.table.equals("")) {
insertProcedure = config.table.toUpperCase() + ".insert";
} else {
insertProcedure = config.procedure;
}
if (!config.reportdir.endsWith("/"))
config.reportdir += "/";
try {
File dir = new File(config.reportdir);
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception x) {
m_log.error(x.getMessage(), x);
System.exit(-1);
}
String myinsert = insertProcedure;
myinsert = myinsert.replaceAll("\\.", "_");
pathInvalidrowfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "invalidrows.csv";
pathLogfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "log.log";
pathReportfile = config.reportdir + "csvloader_" + myinsert + "_"
+ "report.log";
try {
out_invaliderowfile = new BufferedWriter(new FileWriter(
pathInvalidrowfile));
out_logfile = new BufferedWriter(new FileWriter(pathLogfile));
out_reportfile = new BufferedWriter(new FileWriter(pathReportfile));
} catch (IOException e) {
m_log.error(e.getMessage());
System.exit(-1);
}
}
private static Client getClient(ClientConfig config, String[] servers,
int port) throws Exception {
final Client client = ClientFactory.createClient(config);
for (String server : servers)
client.createConnection(server.trim(), port);
return client;
}
private static void produceFiles() {
latency = System.currentTimeMillis() - start;
m_log.info("CSVLoader elapsed: " + latency
+ " seconds");
int bulkflush = 300; // by default right now
try {
long linect = 0;
for (Long irow : errorInfo.keySet()) {
String info[] = errorInfo.get(irow);
if (info.length != 2)
System.out
.println("internal error, information is not enough");
linect++;
out_invaliderowfile.write(info[0] + "\n");
String message = "Invalid input on line " + irow + ".\n Contents:" + info[0];
m_log.error(message);
out_logfile.write(message + "\n " + info[1] + "\n");
if (linect % bulkflush == 0) {
out_invaliderowfile.flush();
out_logfile.flush();
}
}
// Get elapsed time in seconds
float elapsedTimeSec = latency / 1000F;
out_reportfile.write("csvloader elaspsed: " + elapsedTimeSec
+ " seconds\n");
long trueSkip = 0;
//get the actuall number of lines skipped
if( config.skip < totalLineCount.get() )
trueSkip = config.skip;
else
trueSkip = totalLineCount.get();
out_reportfile.write("Number of input lines skipped: "
+ trueSkip + "\n");
out_reportfile.write("Number of lines read from input: "
+ (totalLineCount.get() - trueSkip) + "\n");
if( config.limitrows == -1 ) {
out_reportfile.write("Input stopped after "+ totalRowCount.get() +" rows read"+"\n");
}
out_reportfile.write("Number of rows discovered: "
+ totalRowCount.get() + "\n");
out_reportfile.write("Number of rows successfully inserted: "
+ inCount.get() + "\n");
// if prompted msg changed, change it also for test case
out_reportfile.write("Number of rows that could not be inserted: "
+ errorInfo.size() + "\n");
out_reportfile.write("CSVLoader rate: " + outCount.get()
/ elapsedTimeSec + " row/s\n");
m_log.info("invalid row file is generated to:" + pathInvalidrowfile);
m_log.info("log file is generated to:" + pathLogfile);
m_log.info("report file is generated to:" + pathReportfile);
out_invaliderowfile.flush();
out_logfile.flush();
out_reportfile.flush();
} catch (FileNotFoundException e) {
m_log.error("CSV report directory '" + config.reportdir
+ "' does not exist.");
} catch (Exception x) {
m_log.error(x.getMessage());
}
}
private static void close_cleanup() throws IOException,
InterruptedException {
inCount.set(0);
outCount.set(0);
errorInfo.clear();
typeList.clear();
out_invaliderowfile.close();
out_logfile.close();
out_reportfile.close();
}
}
|
package com.toomasr.sgf4j.gui;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import com.toomasr.sgf4j.Sgf;
import com.toomasr.sgf4j.board.BoardPane;
import com.toomasr.sgf4j.board.BoardStone;
import com.toomasr.sgf4j.board.CoordinateSquare;
import com.toomasr.sgf4j.board.GuiBoardListener;
import com.toomasr.sgf4j.board.StoneState;
import com.toomasr.sgf4j.board.VirtualBoard;
import com.toomasr.sgf4j.filetree.FileTreeView;
import com.toomasr.sgf4j.movetree.EmptyTriangle;
import com.toomasr.sgf4j.movetree.GlueStone;
import com.toomasr.sgf4j.movetree.GlueStoneType;
import com.toomasr.sgf4j.movetree.TreeStone;
import com.toomasr.sgf4j.parser.Game;
import com.toomasr.sgf4j.parser.GameNode;
import com.toomasr.sgf4j.parser.Util;
import com.toomasr.sgf4j.properties.AppState;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.TilePane;
import javafx.scene.layout.VBox;
public class MainUI {
private Button nextButton;
private GameNode currentMove = null;
private GameNode prevMove = null;
private Game game;
private VirtualBoard virtualBoard;
private BoardStone[][] board;
private GridPane movePane;
private GridPane boardPane;
private Map<GameNode, TreeStone> nodeToTreeStone = new HashMap<>();
private TextArea commentArea;
private Button previousButton;
private ScrollPane treePaneScrollPane;
public MainUI() {
board = new BoardStone[19][19];
virtualBoard = new VirtualBoard();
virtualBoard.addBoardListener(new GuiBoardListener(this));
}
public Pane buildUI() throws Exception {
HBox topHBox = new HBox();
enableKeyboardShortcuts(topHBox);
VBox fileTreePane = generateFileTreePane();
fileTreePane.setAlignment(Pos.CENTER);
topHBox.getChildren().add(fileTreePane);
GridPane boardPane = generateBoardPane();
TilePane buttonPane = generateButtonPane();
VBox treePane = generateMoveTreePane();
VBox centerVbox = new VBox();
centerVbox.setMaxWidth(600);
centerVbox.setAlignment(Pos.CENTER);
centerVbox.getChildren().add(boardPane);
centerVbox.getChildren().add(buttonPane);
centerVbox.getChildren().add(treePane);
topHBox.getChildren().add(centerVbox);
VBox mostRightBox = new VBox();
mostRightBox = generateCommentPane();
topHBox.getChildren().add(mostRightBox);
String game = "src/main/resources/game.sgf";
initializeGame(Paths.get(game));
return topHBox;
}
private VBox generateCommentPane() {
VBox rtrn = new VBox();
commentArea = new TextArea();
commentArea.setFocusTraversable(false);
commentArea.setWrapText(true);
commentArea.setPrefSize(300, 600);
rtrn.getChildren().add(commentArea);
return rtrn;
}
private void initializeGame(Path pathToSgf) {
this.game = Sgf.createFromPath(pathToSgf);
currentMove = this.game.getRootNode();
prevMove = null;
// reset our virtual board and actual board
virtualBoard = new VirtualBoard();
virtualBoard.addBoardListener(new GuiBoardListener(this));
boardPane.getChildren().clear();
for (int i = 0; i < 21; i++) {
if (i > 1 && i < 20) {
board[i - 1] = new BoardStone[19];
}
for (int j = 0; j < 21; j++) {
if (i == 0 || j == 0 || i == 20 || j == 20) {
CoordinateSquare btn = new CoordinateSquare(i, j);
boardPane.add(btn, i, j);
}
else {
BoardStone btn = new BoardStone(i, j);
boardPane.add(btn, i, j);
board[i - 1][j - 1] = btn;
}
}
}
placePreGameStones(game);
// construct the tree of the moves
nodeToTreeStone = new HashMap<>();
movePane.getChildren().clear();
movePane.add(new EmptyTriangle(), 1, 0);
GameNode rootNode = game.getRootNode();
populateMoveTreePane(rootNode, 0);
showMarkersForMove(rootNode);
showCommentForMove(rootNode);
}
private void placePreGameStones(Game game) {
// if there are any moves that should already be on the board
// then lets make it so
if (game.getProperty("AB") != null) {
String[] blackStones = game.getProperty("AB").split(",");
for (int i = 0; i < blackStones.length; i++) {
int[] moveCoords = Util.alphaToCoords(blackStones[i]);
virtualBoard.placeStone(StoneState.BLACK, moveCoords[0], moveCoords[1]);
}
}
// and the same story for white
if (game.getProperty("AW") != null) {
String[] blackStones = game.getProperty("AW").split(",");
for (int i = 0; i < blackStones.length; i++) {
int[] moveCoords = Util.alphaToCoords(blackStones[i]);
virtualBoard.placeStone(StoneState.WHITE, moveCoords[0], moveCoords[1]);
}
}
}
private void populateMoveTreePane(GameNode node, int depth) {
// we draw out only actual moves
if (node.isMove()) {
TreeStone treeStone = new TreeStone(node);
movePane.add(treeStone, node.getMoveNo() + 1, node.getVisualDepth());
nodeToTreeStone.put(node, treeStone);
treeStone.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
TreeStone stone = (TreeStone) event.getSource();
fastForwardTo(stone.getMove());
}
});
}
// and draw the next node on this line of play
if (node.getNextNode() != null) {
populateMoveTreePane(node.getNextNode(), depth + node.getVisualDepth());
}
// populate the children also
if (node.hasChildren()) {
Set<GameNode> children = node.getChildren();
// will determine whether the glue stone should be a single
// diagonal or a multiple (diagonal and vertical)
GlueStoneType gStoneType = children.size() > 1 ? GlueStoneType.MULTIPLE : GlueStoneType.DIAGONAL;
for (Iterator<GameNode> ite = children.iterator(); ite.hasNext();) {
GameNode childNode = ite.next();
// the last glue shouldn't be a MULTIPLE
if (GlueStoneType.MULTIPLE.equals(gStoneType) && !ite.hasNext()) {
gStoneType = GlueStoneType.DIAGONAL;
}
// also draw all the "missing" glue stones
for (int i = node.getVisualDepth()+2; i < childNode.getVisualDepth(); i++) {
movePane.add(new GlueStone(GlueStoneType.VERTICAL), node.getMoveNo() + 1, i);
}
// glue stone for the node
movePane.add(new GlueStone(gStoneType), node.getMoveNo() + 1, childNode.getVisualDepth());
// and draw the actual node
populateMoveTreePane(childNode, depth + childNode.getVisualDepth());
}
}
}
/*
* Generates the boilerplate for the move tree pane. The
* pane is actually populated during game initialization.
*/
private VBox generateMoveTreePane() {
VBox rtrn = new VBox();
movePane = new GridPane();
movePane.setPadding(new Insets(0, 0, 0, 0));
movePane.setStyle("-fx-background-color: white");
treePaneScrollPane = new ScrollPane(movePane);
treePaneScrollPane.setPrefHeight(150);
treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.ALWAYS);
treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
rtrn.getChildren().add(treePaneScrollPane);
return rtrn;
}
private void fastForwardTo(GameNode move) {
// clear the board
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j].removeStone();
}
}
placePreGameStones(game);
deHighLightStoneInTree(currentMove);
removeMarkersForNode(currentMove);
virtualBoard.fastForwardTo(move);
highLightStoneOnBoard(move);
}
private VBox generateFileTreePane() {
VBox vbox = new VBox();
vbox.setPrefWidth(200);
TreeView<File> treeView = new FileTreeView();
treeView.setFocusTraversable(false);
vbox.getChildren().add(treeView);
treeView.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
TreeItem<File> item = treeView.getSelectionModel().getSelectedItem();
File file = item.getValue().toPath().toFile();
if (file.isFile()) {
initializeGame(item.getValue().toPath());
}
AppState.getInstance().addProperty(AppState.CURRENT_FILE, file.getAbsolutePath());
}
}
});
return vbox;
}
private TilePane generateButtonPane() {
TilePane pane = new TilePane();
pane.setAlignment(Pos.CENTER);
pane.setMaxWidth(700);
pane.getStyleClass().add("bordered");
TextField moveNoField = new TextField("0");
moveNoField.setFocusTraversable(false);
moveNoField.setMaxWidth(40);
moveNoField.setEditable(false);
nextButton = new Button("Next");
nextButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
handleNextPressed();
}
});
previousButton = new Button("Previous");
previousButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
handlePreviousPressed();
}
});
pane.setPrefColumns(1);
pane.getChildren().add(previousButton);
pane.getChildren().add(moveNoField);
pane.getChildren().add(nextButton);
return pane;
}
private void handleNextPressed() {
if (currentMove.getNextNode() != null) {
prevMove = currentMove;
currentMove = currentMove.getNextNode();
virtualBoard.makeMove(currentMove, prevMove);
// scroll the scrollpane to make
// the highlighted move visible
ensureVisibleForActiveTreeNode(currentMove);
}
}
public void playMove(GameNode move, GameNode prevMove) {
this.currentMove = move;
this.prevMove = prevMove;
// we actually have a previous move!
if (prevMove != null) {
// de-highlight previously highlighted move
if (prevMove.isMove()) {
deHighLightStoneOnBoard(prevMove);
}
// even non moves can haver markers
removeMarkersForNode(prevMove);
}
if (move != null) {
highLightStoneOnBoard(move);
}
// highlight stone in the tree pane
deHighLightStoneInTree(prevMove);
highLightStoneInTree(move);
// show the associated comment
showCommentForMove(move);
// handle the prev and new markers
showMarkersForMove(move);
nextButton.requestFocus();
}
public void handlePreviousPressed() {
if (currentMove.getParentNode() != null) {
prevMove = currentMove;
currentMove = currentMove.getParentNode();
virtualBoard.undoMove(prevMove, currentMove);
}
}
public void undoMove(GameNode move, GameNode prevMove) {
this.currentMove = prevMove;
this.prevMove = move;
if (prevMove != null) {
showMarkersForMove(prevMove);
showCommentForMove(prevMove);
if (prevMove.isMove())
highLightStoneOnBoard(prevMove);
}
deHighLightStoneInTree(move);
highLightStoneInTree(prevMove);
if (move != null) {
removeMarkersForNode(move);
}
ensureVisibleForActiveTreeNode(prevMove);
// rather have previous move button have focus
previousButton.requestFocus();
}
private void ensureVisibleForActiveTreeNode(GameNode move) {
if (move != null && move.isMove()) {
TreeStone stone = nodeToTreeStone.get(move);
// the movetree is not yet fully operational and some
// points don't exist in the map yet
if (stone == null)
return;
double width = treePaneScrollPane.getContent().getBoundsInLocal().getWidth();
double x = stone.getBoundsInParent().getMaxX();
double scrollTo = ((x) - 11 * 30) / (width - 21 * 30);
treePaneScrollPane.setHvalue(scrollTo);
}
}
private void highLightStoneInTree(GameNode move) {
TreeStone stone = nodeToTreeStone.get(move);
// can remove the null check at one point when the
// tree is fully implemented
if (stone != null) {
stone.highLight();
stone.requestFocus();
}
}
private void deHighLightStoneInTree(GameNode node) {
if (node != null && node.isMove()) {
TreeStone stone = nodeToTreeStone.get(node);
if (stone != null) {
stone.deHighLight();
}
else {
throw new RuntimeException("Unable to find node for move " + node);
}
}
}
private void showCommentForMove(GameNode move) {
String comment = move.getProperty("C");
if (comment == null) {
comment = "";
}
// some helpers I used for parsing needs to be undone - see the Parser.java
// in sgf4j project
comment = comment.replaceAll("@@@@@", "\\\\\\[");
comment = comment.replaceAll("
// lets do some replacing - see http://www.red-bean.com/sgf/sgf4.html#text
comment = comment.replaceAll("\\\\\n", "");
comment = comment.replaceAll("\\\\:", ":");
comment = comment.replaceAll("\\\\\\]", "]");
comment = comment.replaceAll("\\\\\\[", "[");
commentArea.setText(comment);
}
private void showMarkersForMove(GameNode move) {
String markerProp = move.getProperty("L");
if (markerProp != null) {
int alphaIdx = 0;
String[] markers = markerProp.split("\\]\\[");
for (int i = 0; i < markers.length; i++) {
int[] coords = Util.alphaToCoords(markers[i]);
board[coords[0]][coords[1]].addOverlayText(Util.alphabet[alphaIdx++]);
}
}
}
private void removeMarkersForNode(GameNode node) {
String markerProp = node.getProperty("L");
if (markerProp != null) {
String[] markers = markerProp.split("\\]\\[");
for (int i = 0; i < markers.length; i++) {
int[] coords = Util.alphaToCoords(markers[i]);
board[coords[0]][coords[1]].removeOverlayText();
}
}
}
private void highLightStoneOnBoard(GameNode move) {
String currentMove = move.getMoveString();
int[] moveCoords = Util.alphaToCoords(currentMove);
board[moveCoords[0]][moveCoords[1]].highLightStone();
}
private void deHighLightStoneOnBoard(GameNode prevMove) {
String prevMoveAsStr = prevMove.getMoveString();
int[] moveCoords = Util.alphaToCoords(prevMoveAsStr);
board[moveCoords[0]][moveCoords[1]].deHighLightStone();
}
private GridPane generateBoardPane() {
boardPane = new BoardPane(19, 19);
for (int i = 0; i < 21; i++) {
if (i > 1 && i < 20) {
board[i - 1] = new BoardStone[19];
}
for (int j = 0; j < 21; j++) {
if (i == 0 || j == 0 || i == 20 || j == 20) {
CoordinateSquare btn = new CoordinateSquare(i, j);
boardPane.add(btn, i, j);
}
else {
BoardStone btn = new BoardStone(i, j);
boardPane.add(btn, i, j);
board[i - 1][j - 1] = btn;
}
}
}
return boardPane;
}
private void enableKeyboardShortcuts(HBox topHBox) {
topHBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getEventType().equals(KeyEvent.KEY_PRESSED)) {
if (event.getCode().equals(KeyCode.LEFT)) {
handlePreviousPressed();
}
else if (event.getCode().equals(KeyCode.RIGHT)) {
handleNextPressed();
}
}
}
});
}
public BoardStone[][] getBoard() {
return this.board;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.